ETH原生交易构建,可手动设置手续费

编程入门 行业动态 更新时间:2024-10-24 15:17:11

ETH原生交易构建,可手动设置<a href=https://www.elefans.com/category/jswz/34/1739473.html style=手续费"/>

ETH原生交易构建,可手动设置手续费

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(""));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(""));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.apachemons.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节点进行调用。这样就没有使用限制啦!

更多推荐

ETH原生交易构建,可手动设置手续费

本文发布于:2024-02-12 14:26:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1688160.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:手续费   ETH

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!