我们在项目里面如果想要得到用户的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;
@Component
public class ETHWeb3jTest {
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.web3j core3.4.0 com.google.guava guava29.0-jre org.bitcoinj bitcoinj-core0.15.5



