以太坊或ERC20转账查询(Java版本)
生活随笔
收集整理的這篇文章主要介紹了
以太坊或ERC20转账查询(Java版本)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
表現效果
測試用例 EthTestData.java
/*** 測試數據** @Autor Tricky* @Date 2021-04-01 22:06:36*/public class EthTestData { // {"address":"0xe81128942ed67a3b453576cad44fa9fb7f0b2098","privateKey":"8ca3edaabc0567d9555ade455bab24a27bea6ee0524e96ffac9a3cfc2b841214"}private String privateKey="8ca3edaabc0567d9555ade455bab24a27bea6ee0524e96ffac9a3cfc2b841214";private String myAddress = "0xab8ba39195bFF4D406FC62A776ce41dBA6FCf1fD";//rinkeby上面的測試幣 erc20-usdt同款private String contract="0xf805ed280cadeadc2aa135808688e06fef5a9b71";private Web3j web3j ;{try{//如果這個地址不知道怎么獲取 可以參考 https://blog.csdn.net/sail331x/article/details/115395131web3j = Web3j.build(new HttpService("https://rinkeby.infura.io/v3/dddddddddda74486b59041e5d83f4af1"));}catch (Throwable t){t.printStackTrace();}}/*** 創建地址*/@Testpublic void createAddress(){System.out.println("創建地址:"+JSONUtil.toJsonStr(EthUtils.createAddress()));}/*** 查詢eth數量*/@Testpublic void balanceOf(){System.out.println("查詢ETH:"+EthUtils.balanceOf(web3j,myAddress));}/*** 查詢ERC20數量*/@Testpublic void balanceOfErc20(){System.out.println("查詢ERC20:"+EthUtils.balanceOfErc20(web3j,contract,myAddress));}/*** 發送ERC20*/@Testpublic void sendErc20(){String txid = EthUtils.sendErc20(web3j, contract, privateKey, myAddress, BigInteger.valueOf(10000000));System.out.println("發送ERC20:"+txid);}/*** 發送以太坊*/@Testpublic void sendEth(){String txid = EthUtils.sendEth(web3j, privateKey, myAddress, new BigDecimal("0.001"));System.out.println("發送ETH:"+txid);}@Testpublic void getTransaction(){//合約String txid="0x29d96b351be4ab1c29912a1c26c1c8f9205fc35fb9ea2395c53c5c2e1884c421";//ethString txid2="0xef3c06f56085187d6a43edec2bb399a7fe98572aad63bcd5bd80e5e5dab153b3";EthTransaction tx = EthUtils.getTransaction(web3j, txid2);System.out.println("查詢交易:"+JSONUtil.toJsonStr(tx));} }運行結果
工具類
EthUtils.java工具類
/*** 以太坊工具類** @Autor Tricky* @Date 2021-04-01 21:02:11*/ @Slf4j public class EthUtils {public static final BigDecimal ETH_DECIMALS = new BigDecimal(1_000_000_000_000_000_000L);public static final BigInteger ETH_GAS_LIMIT = new BigInteger("100000");/*** 獲取區塊數據** @param web3j* @param block 塊高* @param fullTransactionObjects 是否需要交易數據* @return*/public static EthBlock getBlock(Web3j web3j, long block, boolean fullTransactionObjects) {try {return web3j.ethGetBlockByNumber(new DefaultBlockParameterNumber(block), fullTransactionObjects).send();} catch (Throwable t) {logger.error(String.format("Get Block Error %d", block), t);}return null;}/*** 獲取當前塊高** @param web3j* @return*/public static long getNowBlockNumber(Web3j web3j) {try {EthBlockNumber send = web3j.ethBlockNumber().send();return send.getBlockNumber().longValue();} catch (Throwable t) {logger.error("GetBlockNumberError", t);}return -1;}/*** 發送erc20** @param web3j* @param contractAddress 合約地址* @param privateKey 私鑰* @param to 收款地址* @param value 額度* @return*/public static String sendErc20(Web3j web3j, String contractAddress, String privateKey,String to, BigInteger value) {String from = getAddressByPrivateKey(privateKey);logger.info(String.format("Start:SendErc20 from:%s to:%s amount:%s erc20:%s", from, to, value.toString(), contractAddress));try {//加載轉賬所需的憑證,用私鑰Credentials credentials = Credentials.create(privateKey);//獲取nonce,交易筆數BigInteger nonce = getNonce(web3j, from);if (nonce == null) {logger.error(String.format("END:GetNonceError from:%s to:%s amount:%s erc20:%s", from, to, value.toString(), contractAddress));return null;}//gasPrice和gasLimit 都可以手動設置BigInteger gasPrice = getGasPrice(web3j);if (gasPrice == null) {logger.error(String.format("END:GetGasPriceError from:%s to:%s amount:%s erc20:%s", from, to, value.toString(), contractAddress));return null;}//BigInteger.valueOf(4300000L) 如果交易失敗 很可能是手續費的設置問題BigInteger gasLimit = BigInteger.valueOf(60000L);//ERC20代幣合約方法Function function = new Function("transfer",Arrays.asList(new Address(to), new Uint256(value)),Collections.singletonList(new TypeReference<Type>() {}));//創建RawTransaction交易對象String encodedFunction = FunctionEncoder.encode(function);RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit,contractAddress, encodedFunction);//簽名Transactionbyte[] signMessage = TransactionEncoder.signMessage(rawTransaction, credentials);String hexValue = Numeric.toHexString(signMessage);//發送交易EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();String hash = ethSendTransaction.getTransactionHash();if (hash != null) {return hash;}logger.error(String.format("END:HashIsNull from:%s to:%s amount:%s erc20:%s", from, to, value.toString(), contractAddress));} catch (Throwable t) {logger.error(String.format("發送ERC20失敗 from=%s to=%s erc20=%s amount=%s",from, to, contractAddress, value.toString()), t);}return null;}/*** 列出交易信息** @param block 區塊高度* @param filter 過濾器* @return*/public static List<EthBlock.TransactionResult> getTransactions(Web3j web3j, long block, java.util.function.Function<EthBlock.TransactionResult, Boolean> filter) {EthBlock send = getBlock(web3j, block, true);if (send == null) {logger.error(String.format("GetBlockDataError:%d", block));return Collections.emptyList();}List<EthBlock.TransactionResult> transactions = send.getBlock().getTransactions();if (filter != null) {List<EthBlock.TransactionResult> result = new ArrayList<>();for (EthBlock.TransactionResult e : transactions) {try {if (filter.apply(e)) {result.add(e);}} catch (Throwable t) {logger.error(t.getMessage(), t);}}return result;}return transactions;}/*** 根據私鑰獲取地址** @param privateKey* @return*/public static String getAddressByPrivateKey(String privateKey) {ECKeyPair ecKeyPair = ECKeyPair.create(new BigInteger(privateKey, 16));return "0x" + Keys.getAddress(ecKeyPair).toLowerCase();}/*** 創建地址** @return*/public static EthAddress createAddress() {try {String seed = UUID.randomUUID().toString();ECKeyPair ecKeyPair = Keys.createEcKeyPair();BigInteger privateKeyInDec = ecKeyPair.getPrivateKey();String sPrivatekeyInHex = privateKeyInDec.toString(16);WalletFile aWallet = Wallet.createLight(seed, ecKeyPair);String sAddress = aWallet.getAddress();EthAddress address = new EthAddress();address.setAddress("0x" + sAddress);address.setPrivateKey(sPrivatekeyInHex);return address;} catch (Throwable t) {logger.error("創建地址失敗", t);}return null;}/*** 查詢地址以太坊數量** @param web3j* @param address 查詢地址* @return*/public static BigDecimal balanceOf(Web3j web3j, String address) {try {EthGetBalance balance = web3j.ethGetBalance(address, DefaultBlockParameterName.LATEST).send();BigInteger amount = balance.getBalance();if (amount == null || amount.compareTo(BigInteger.ZERO) <= 0) {return BigDecimal.ZERO;}return new BigDecimal(amount).divide(ETH_DECIMALS, 18, RoundingMode.FLOOR);} catch (Throwable t) {logger.error(String.format("獲取以太坊數量出錯 %s", address), t);}return BigDecimal.ZERO;}/*** 轉換成最小單位 Wei** @param ethAmount* @return*/public static BigInteger toWei(BigDecimal ethAmount) {return ethAmount.multiply(ETH_DECIMALS).toBigInteger();}/*** wei to eth** @param wei* @return*/public static BigDecimal toEth(BigInteger wei) {return new BigDecimal(wei).divide(ETH_DECIMALS, 18, RoundingMode.FLOOR);}/*** 查詢erc20的余額** @param web3j* @param contract 合約地址* @param address 查詢地址* @return*/public static BigInteger balanceOfErc20(Web3j web3j, String contract, String address) {try {final String DATA_PREFIX = "0x70a08231000000000000000000000000";String value = web3j.ethCall(org.web3j.protocol.core.methods.request.Transaction.createEthCallTransaction(address,contract, DATA_PREFIX + address.substring(2)), DefaultBlockParameterName.PENDING).send().getValue();if (StrUtil.isEmptyIfStr(value)) {return BigInteger.ZERO;}return new BigInteger(value.substring(2), 16);} catch (Throwable t) {logger.error(String.format("查詢ERC20失敗 contract:%s address:%s", contract, address), t);}return BigInteger.ZERO;}/*** 獲取gas-price** @param web3j* @return*/public static BigInteger getGasPrice(Web3j web3j) {try {EthGasPrice ethGasPrice = web3j.ethGasPrice().sendAsync().get();if (ethGasPrice == null) {logger.error("GetGasPriceError");return null;}return ethGasPrice.getGasPrice();} catch (Throwable t) {logger.error(t.getMessage(), t);}return null;}/*** 獲取nonce** @param web3j* @param address* @return*/public static BigInteger getNonce(Web3j web3j, String address) {try {EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(address, DefaultBlockParameterName.PENDING).send();if (ethGetTransactionCount == null) {logger.error("GetNonceError:" + address);return null;}return ethGetTransactionCount.getTransactionCount();} catch (Throwable t) {logger.error("GetNonceError:" + address);}return null;}/*** 發送以太坊** @param web3j* @param privateKey 發送者私鑰* @param to 收款地址* @param wei wei為單位的數量* @param gasPrice gas-price* @param gasLimit gas-limit* @return*/public static String sendEth(Web3j web3j, String privateKey, String to, BigInteger wei, BigInteger gasPrice, BigInteger gasLimit) {String from = getAddressByPrivateKey(privateKey);try {//加載轉賬所需的憑證,用私鑰Credentials credentials = Credentials.create(privateKey);//獲取nonce,交易筆數BigInteger nonce = getNonce(web3j, from);//創建RawTransaction交易對象RawTransaction rawTransaction = RawTransaction.createEtherTransaction(nonce, gasPrice, gasLimit, to, wei);//簽名Transaction,這里要對交易做簽名byte[] signMessage = TransactionEncoder.signMessage(rawTransaction, credentials);String hexValue = Numeric.toHexString(signMessage);//發送交易EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();return ethSendTransaction.getTransactionHash();} catch (Throwable t) {logger.error(String.format("發送ETH失敗 from:%s to:%s amount-eth:%s", from, to, toEth(wei).toString()));}return null;}/*** 發送以太坊** @param web3j* @param privateKey 發送者私鑰* @param to 收款地址* @param wei wei為單位的數量* @return*/public static String sendEth(Web3j web3j, String privateKey, String to, BigInteger wei) {return sendEth(web3j, privateKey, to, wei, getGasPrice(web3j), ETH_GAS_LIMIT);}/*** 發送以太坊** @param web3j* @param privateKey 發送者私鑰* @param to 收款地址* @param eth wei為單位的數量* @param gasPrice gas-price* @param gasLimit gas-limit* @return*/public static String sendEth(Web3j web3j, String privateKey, String to, BigDecimal eth, BigInteger gasPrice, BigInteger gasLimit) {return sendEth(web3j, privateKey, to, toWei(eth), gasPrice, gasLimit);}/*** 發送以太坊** @param web3j* @param privateKey 發送者私鑰* @param to 收款地址* @param eth wei為單位的數量* @return*/public static String sendEth(Web3j web3j, String privateKey, String to, BigDecimal eth) {return sendEth(web3j, privateKey, to, toWei(eth), getGasPrice(web3j), ETH_GAS_LIMIT);}/*** 根據hash獲取交易信息* @param web3j* @param hash* @return*/public static EthTransaction getTransaction(Web3j web3j, String hash) {try {EthTransaction tx = web3j.ethGetTransactionByHash(hash).send();return tx;} catch (Throwable t) {logger.error("GetTransactionError:" + hash, t);}return null;} }寫在最后
注意 這里的Web3j初始化用的url 可以到 https://infura.io/ 中去申請。
以太坊(ETH)發行ERC20代幣(Rinkeby演示)
波場歸集充值回調(trx/trc10/trc20版本整合)
tron(波場)trc20離線簽名廣播交易(Java版本)
如有任何問題或者寫得不對的地方 歡迎留言評論指點下哦
總結
以上是生活随笔為你收集整理的以太坊或ERC20转账查询(Java版本)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php学习日志(5)-解决Windows
- 下一篇: Java 输入两个日期,计算出期间的周