这里使用的是maven项目,第一步要引入web3j的包
<dependency>
<groupId>org.web3j</groupId>
<artifactId>core</artifactId>
<version>3.4.0</version>
</dependency>
public static void transfer() throws Exception {
Web3j web3j = Web3j.build(new HttpService("infura节点链接"));
BigInteger bigInteger = new BigInteger("钱包私钥", 16);
ECKeyPair ecKeyPair = ECKeyPair.create(bigInteger);
Credentials credentials = Credentials.create(ecKeyPair);
TransactionReceipt transactionReceipt = Transfer.sendFunds(web3j, credentials, "目标地址", BigDecimal.valueOf(0.001), Convert.Unit.ETHER).send();
System.out.println(transactionReceipt);
}
public static void transferToken() throws Exception {
Web3j web3j = Web3j.build(new HttpService("infura节点链接"));
BigInteger bigInteger = new BigInteger("私钥", 16);
ECKeyPair ecKeyPair = ECKeyPair.create(bigInteger);
Credentials credentials = Credentials.create(ecKeyPair);
String fromAddress = credentials.getAddress();
EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
fromAddress, DefaultBlockParameterName.LATEST).sendAsync().get();
BigInteger nonce = ethGetTransactionCount.getTransactionCount();
Address address = new Address("目标地址");
Uint256 value = new Uint256(new BigInteger("数量 单位wei"));
List<Type> parametersList = new ArrayList<>();
parametersList.add(address);
parametersList.add(value);
List<TypeReference<?>> outList = new ArrayList<>();
Function function = new Function("transfer", parametersList, outList);
String encodedFunction = FunctionEncoder.encode(function);
System.out.println( DefaultGasProvider.GAS_PRICE);
System.out.println(DefaultGasProvider.GAS_LIMIT);
RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, DefaultGasProvider.GAS_PRICE,
new BigInteger("210000"), "合约地址", encodedFunction);
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
String hexValue = Numeric.toHexString(signedMessage);
EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
Object transactionHash = ethSendTransaction.getTransactionHash();
System.out.println(transactionHash.toString());
}