Web3j 实战:一行代码搞定以太坊钱包创建与 ETH 转账

·

关键词:Web3j、ETH钱包、创建钱包、ETH转账、私钥、Gas、Web3、Java、以太坊
应用场景:企业链改、个人 DApp 开发、钱包后端服务
技术门槛:熟悉 Java + Maven,以 Kovan 测试网 为例,5 分钟跑通核心流程。

一、引入 Web3j 依赖

使用 Maven 只需在 pom.xml 中加入以下坐标,目前 3.4.0 及以上版本 与 Java 8+ 兼容性最佳。

<dependencies>
    <!-- 稳定加密库 -->
    <dependency>
        <groupId>com.madgag.spongycastle</groupId>
        <artifactId>core</artifactId>
        <version>1.58.0.0</version>
    </dependency>

    <!-- Web3j 核心工具 -->
    <dependency>
        <groupId>org.web3j</groupId>
        <artifactId>utils</artifactId>
        <version>3.4.0</version>
    </dependency>

    <dependency>
        <groupId>org.web3j</groupId>
        <artifactId>core</artifactId>
        <version>3.4.0</version>
    </dependency>
</dependencies>

安装完成后,IDE 刷新依赖 即自动拉取所有包。

二、创建 ETH 钱包(零成本、零门槛)

Web3j 内置了钱包格式的完整封装,只需一行反射调用即可生成 兼容 Keystore (V3) 的轻量级钱包。示例代码:

ECKeyPair ecKeyPair = Keys.createEcKeyPair();
WalletFile walletFile = Wallet.createLight("password", ecKeyPair);

String address        = "0x" + walletFile.getAddress();
String privateKey     = ecKeyPair.getPrivateKey().toString(16);
String encryptedPriv  = AesCBC.encrypt(privateKey, "自定义盐");

System.out.println("地址:" + address);
System.out.println("加密私钥:" + encryptedPriv);

生成的 walletFile 对象可直接通过 JSON 持久化,过程如下:

  1. 立即将 JSON 写入 .json 文件,用于 Web3j 自动加载
  2. 妥善离线保管私钥;一旦泄漏,链上资产将即刻失控。

👉 想快速上手?一份完整 Java Web3j 工程模板免费下载


FAQ:初学钱包常见疑惑


三、ETH 转账步骤拆解

官方提供两种签名方式:

方式适用场景优势
直接使用原私钥脚本、服务端签名速度最快
使用 Keystore线下钱包文件、硬件隔离符合主流钱包标准

以下采用 第二种(安全性更高):

3.1 建立与链的连接

Web3j web3j = Web3j.build(
    new HttpService("https://kovan.infura.io/v3/YOUR_PROJECT_ID"));
重点:测试网 无需真实 ETH,可从 Kovan 水龙头领取。

3.2 构造交易对象

// 1. 加载凭证
Credentials cred = WalletUtils.loadCredentials("password",
                                               "/path/to/keystore.json");

// 2. 查询最新 nonce
BigInteger nonce = web3j
    .ethGetTransactionCount(cred.getAddress(), DefaultBlockParameterName.LATEST)
    .sendAsync().get().getTransactionCount();

// 3. 设置 1 ETH
BigInteger value = Convert.toWei("1", Convert.Unit.ETHER).toBigInteger();

// 4. 获取实时 Gas Price
BigInteger gasPrice = web3j.ethGasPrice().send().getGasPrice();

3.3 签名 & 广播

RawTransaction raw = RawTransaction.createEtherTransaction(
        nonce, gasPrice, BigInteger.valueOf(21_000), "收款地址", value);

byte[] signed = TransactionEncoder.signMessage(raw, cred);
String rawTx = Numeric.toHexString(signed);

EthSendTransaction resp = web3j
        .ethSendRawTransaction(rawTx).sendAsync().get();

System.out.println("交易哈希:" + resp.getTransactionHash());

大约 5–20 秒 后,可前往 区块浏览器 查看 确认状态


FAQ:转账环节疑难解答

👉 学会进阶技巧:ERC20 一键转发、监听事件、异常重放


四、实战技巧扩展

  1. 离线签名:脱机电脑生成 rawTx,再回到在线机广播,降低私钥暴露风险。
  2. 事件监听:使用 org.web3j.protocol.core.methods.response.EthFilter 轮询 链内转账事件,实现 到账通知
  3. 并发转账:单进程多线程配合同一 Web3j 连接,同步 nonce 保证交易序列。

五、常见坑汇总


总结

至此,你已经掌握 Web3j 两条核心链路

  1. 使用纯 Java 快速创建 ETH 钱包,主流格式 100% 兼容 MetaMask
  2. 从初始化到广播,完整打通 ETH 转账逻辑,可 无摩擦移植到业务系统

下一步挑战是加入 ERC-721、批量签批、Merkle 见证层,持续扩容你的区块链后端能力。