ETH原生交易构建,可手动设置手续费
第一种交易方式(无法设置手续费)
这种方式比较简单,不需要一大堆杂七杂八的参数,直接通过私钥完成即可:
/**
* 以太坊交易
*
* @param fromAddress 转账地址
* @param password 密码 userId
* @param toAddress 收款方地址
* @param amount 转账金额,单位:eth
* @return 交易哈希
* @throws Exception
*/
public static String tx(String fromAddress, String password, String toAddress, BigDecimal amount) throws Exception {
Web3j web3j = Web3j.build(new HttpService("https://mainnet.infura.io/v3/df37be688d544933a573b47c1f0ea159"));
String privateKey = EthService.exportPrivateKey(password, fromAddress);
Credentials credentials = Credentials.create(privateKey);
TransactionReceipt transactionReceipt = Transfer.sendFunds(web3j, credentials, toAddress, amount, Convert.Unit.ETHER).send();
return transactionReceipt.getTransactionHash();
}
//获取私钥 keystorePath是keystore文件所在路径
public static String exportPrivateKey(String password, String keystorePath) throws Exception {
Credentials credentials = WalletUtils.loadCredentials(password, keystorePath);
BigInteger privateKey = credentials.getEcKeyPair().getPrivateKey();
return privateKey.toString(16);
}
第二种交易方式(可以设置手续费)
第二种方式,通过私钥签名的方式完成交易。需要进行手动获取nonce,手动设置手续费等操作,相对第一种方式麻烦一些,但是执行速度更快,效率更高。第一种转账方式的本质,其实和第二种转账方式是一样的,只不过是在底层帮我们把这些操作封装好了。
/**
* 构建eth原始交易
*
* @return 交易hash
*/
private String transaction(String fromAddress, String password, String toAddress, BigDecimal amount) throws Exception {
Web3j web3j = Web3j.build(new HttpService("https://mainnet.infura.io/v3/df37be688d544933a573b47c1f0ea159"));
BigInteger nonce;
EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(fromAddress, DefaultBlockParameterName.PENDING).send();
if (ethGetTransactionCount == null) {
return null;
}
nonce = ethGetTransactionCount.getTransactionCount();
//设置手续费 矿工可接受范围之内
BigInteger gasPrice = Convert.toWei(new BigDecimal(PropertiesUtil.getProperty("eth.gasPrice", "3")),
Convert.Unit.GWEI).toBigInteger();
BigInteger gasLimit = new BigInteger(PropertiesUtil.getProperty("eth.gasLimit", "21000"));
toAddress = toAddress.toLowerCase();
BigInteger value = Convert.toWei(amount, Convert.Unit.ETHER).toBigInteger();
String data = "";
byte chainId = ChainId.MAINNET; //主网id
//获取私钥进行交易签名
String privateKey = EthService.exportPrivateKey(password, fromAddress);
if (org.apache.commons.lang3.StringUtils.isBlank(privateKey)) {
return null;
}
String signedData = signTransaction(nonce, gasPrice, gasLimit, toAddress, value, data, chainId, privateKey);
if (signedData != null) {
EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(signedData).send();
String hash = ethSendTransaction.getTransactionHash();
if (hash != null) {
logger.info("eth交易成功,hash={}", hash);
return hash;
}
}
return null;
}
/**
* eth交易签名
*
* @return 签名信息
*/
private String signTransaction(BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, String to,
BigInteger value, String data, byte chainId, String privateKey) {
byte[] signedMessage;
RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit, to, value, data);
if (privateKey.startsWith("0x")) {
privateKey = privateKey.substring(2);
}
ECKeyPair ecKeyPair = ECKeyPair.create(new BigInteger(privateKey, 16));
Credentials credentials = Credentials.create(ecKeyPair);
if (chainId > ChainId.NONE) {
signedMessage = TransactionEncoder.signMessage(rawTransaction, chainId, credentials);
} else {
signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
}
String hexValue = Numeric.toHexString(signedMessage);
logger.info("eth交易签名信息={}", hexValue);
return hexValue;
}
- 说明:手续费 = gasUsed * gasPrice
如果想要手动设置手续费,gasLimit一定要写死21000,这是最低值,设置成了21000意味着每次gasUsed都是21000,不会改变。所以只需要修改gasPrice就相当于设置了手续费。
以上代码复制过去就可以直接使用啦,如果对你有帮助,就点个赞吧 ^ . ^
说明:此处是通过调用infura的节点进行操作的,token可自行去官网免费获取,两种方式本地测试均没有问题。也可以自己同步eth区块,搭建rpc节点进行调用。这样就没有使用限制啦!