我们在项目里面如果想要得到用户的ETH交易明细怎么做呢?有两种方式:
1、直接获取ETH最新块的交易明细。
2、通过块获取用户的交易明细。
废话不多说,直接贴代码看了
package com.example.demo.web3jLog;import org.springframework.stereotype.Component;import org.web3j.protocol.Web3j;import org.web3j.protocol.core.DefaultBlockParameter;import org.web3j.protocol.core.DefaultBlockParameterName;import org.web3j.protocol.core.methods.request.EthFilter;import org.web3j.protocol.core.methods.response.*;import org.web3j.protocol.core.methods.response.Transaction;import org.web3j.protocol.http.HttpService;import org.web3j.utils.Convert;import java.io.IOException;import java.math.BigDecimal;import java.math.BigInteger;import java.util.Arrays;import java.util.List;import java.util.Optional;import java.util.concurrent.ExecutionException;@Componentpublic class ETHWeb3jTest {/** * 完成web3的初始化 下面的地址引入区块链节点地址 */public static Web3j web3j = Web3j.build(new HttpService("https://org:8545/"));public static void main(String[] args) {BigInteger latestBlock;try {//获取ETH的最新区块号latestBlock = web3j.ethBlockNumber().send().getBlockNumber();//通过区块号获取交易List ethGetBlance = web3j.ethGetBlockByNumber(DefaultBlockParameter.valueOf(latestBlock.subtract(new BigInteger("3"))),true).send().getBlock().getTransactions();//通过hash获取交易Optional transactions = web3j.ethGetTransactionByHash("hash").send().getTransaction();} catch (IOException e) {e.printStackTrace();}List txs = null;try {//也可以直接获取最新交易txs = web3j.ethGetBlockByNumber(DefaultBlockParameterName.LATEST, true).send().getBlock().getTransactions();} catch (IOException e) {e.printStackTrace();}txs.forEach(tx -> {EthBlock.TransactionObject transaction = (EthBlock.TransactionObject) tx.get();System.out.println(transaction.getFrom());});}}
下面是项目的相关依赖:
org.web3jcore3.4.0com.google.guavaguava29.0-jreorg.bitcoinjbitcoinj-core0.15.5