pom文件引入web3j 包
<dependency>
<groupId>com.madgag.spongycastle</groupId>
<artifactId>core</artifactId>
<version>1.58.0.0</version>
</dependency>
<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>
eth 创建钱包
public static void create() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, CipherException {
ECKeyPair ecKeyPair = Keys.createEcKeyPair();
WalletFile walletFile = Wallet.createLight("password", ecKeyPair);
String address = "0x" + walletFile.getAddress();
String privateKey = ecKeyPair.getPrivateKey().toString(16);
String encryptPrivateKey = AesCBC.getInstance().simpleEncrypt(privateKey,
AesCBC.makeKey(1 + "_" + 1));
System.out.println("address:"+ address);
System.out.println("encryptPrivateKey:"+ encryptPrivateKey);
}
eth 转账
public static void trans() throws ExecutionException, InterruptedException, IOException, CipherException{
Web3j web3j = Web3j.build(new HttpService("节点地址"));
String ownAddress = "转账地址";
String toAddress = "收款地址";
String amount = "转账金额";
Credentials credentials = WalletUtils.loadCredentials(
"私钥",
"keystore.store文件地址");
EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
ownAddress, DefaultBlockParameterName.LATEST).sendAsync().get();
BigInteger nonce = ethGetTransactionCount.getTransactionCount();
BigInteger value = Convert.toWei(amount, Convert.Unit.ETHER).toBigInteger();
EthGasPrice gasPrice = web3j.ethGasPrice().send();
RawTransaction rawTransaction = RawTransaction.createEtherTransaction(
nonce, gasPrice.getGasPrice(), GAS_LIMIT, toAddress, value);
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
String hexValue = Numeric.toHexString(signedMessage);
EthSendTransaction ethSendTransaction =
web3j.ethSendRawTransaction(hexValue).sendAsync().get();
String transactionHash = ethSendTransaction.getTransactionHash();
System.out.println(transactionHash);
}
public static BigInteger toWei(String amount) {
return new BigDecimal(amount).multiply(new BigDecimal(Math.pow(10, 18))).toBigInteger();
}