我们在项目里面如果想要得到用户的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 {
/**
* 完成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<EthBlock.TransactionResult> ethGetBlance = web3j.ethGetBlockByNumber(DefaultBlockParameter.valueOf(latestBlock.subtract(new BigInteger("3"))),true).send().getBlock().getTransactions();
//通过hash获取交易
Optional<Transaction> transactions = web3j.ethGetTransactionByHash("hash").send().getTransaction();
} catch (IOException e) {
e.printStackTrace();
}
List<EthBlock.TransactionResult> 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());
});
}
}
下面是项目的相关依赖:
<dependency> <groupId>org.web3j</groupId> <artifactId>core</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>29.0-jre</version> </dependency> <dependency> <groupId>org.bitcoinj</groupId> <artifactId>bitcoinj-core</artifactId> <version>0.15.5</version> </dependency>