ETH java 扫块开发
顾名思义,就是根据区块号扫描该区块的交易信息,从中找到我们关心的from地址和to地址
那么应该怎么扫块呢
1.pom文件引入
<dependency>
<groupId>org.web3j</groupId>
<artifactId>core</artifactId>
<version>4.8.4</version>
</dependency>
2.java代码
// 当然要使用web3j了,web3j的java版本
// 以下是源码
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.web3j.protocol.ObjectMapperFactory;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameter;
import org.web3j.protocol.core.methods.response.EthBlock;
import org.web3j.protocol.core.methods.response.EthTransaction;
import org.web3j.protocol.core.methods.response.Transaction;
import org.web3j.protocol.websocket.WebSocketService;
import java.math.BigInteger;
import java.util.List;
public class EthWsTest {
@Test
public void testEthWsClient() {
try {
// 找个infra链接
String apiServerUrl = "";
Web3j web3j = Web3j.build(new HttpService(apiServerUrl));
ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper(false);
// 先调用获取区块号接口,拿到区块号
String reqString = objectMapper.writeValueAsString(web3j.ethBlockNumber());
System.out.println(reqString);
BigInteger blockNumber = web3j.ethBlockNumber().sendAsync().get().getBlockNumber();
System.out.println(blockNumber);
// 这里是根据交易hash,获取交易详情
EthTransaction send = web3j.ethGetTransactionByHash("0x7528078a2725300b298aad6fd86e77fb1efd2c0e909847d597f4829f0a559499").send();
BigInteger big = new BigInteger("6285815");
DefaultBlockParameter parameter = DefaultBlockParameter.valueOf(big);
// 这里是根据区块号获取区块的交易hash
EthBlock ethBlock = web3j.ethGetBlockByNumber(parameter, true).sendAsync().get();
String x = JSONObject.toJSONString(ethBlock, SerializerFeature.DisableCircularReferenceDetect);
System.out.println(x);
JSONObject obj = JSON.parseObject(x);
for (int i = 0; i < 1000; i++) {
EthBlock ethBlock1 = JSON.toJavaObject(obj, EthBlock.class);
EthBlock ethBlock2 = JSON.toJavaObject(x, EthBlock.class);
List<EthBlock.TransactionResult> transactions2 = ethBlock2.getBlock().getTransactions();
System.out.println(transactions2);
List<EthBlock.TransactionResult> transactions = ethBlock1.getBlock().getTransactions();
System.out.println(transactions);
}
Transaction transaction = send.getTransaction().get();
System.out.println(transaction.getBlockNumber());
System.out.println(JSONObject.toJSON(transaction));
} catch (Exception e) {
e.printStackTrace();
}
// System.out.println(newBlockNum);
}
}
// 根据区块号拿到信息就开始遍历吧。
需要一点点基础,不是傻瓜式教程,这里是给自己做一个笔记
里面有很多判断要做,比如只解析你关心的合约,你关心的from地址和to地址
erc20解析
解析关键字,区块号,交易hash,from ,to
步骤是: 获取区块号=>根据区块号查询交易hash集合=>
根据交易hash查询交易详情=>解析交易详情,得到关心的from地址和to地址,还有金额
3.节点链接
infura的节点提供商:https://infura.io/zh
或者使用ankr
4.测试币领取地址
领水地址:https://faucet.paradigm.xyz/?continueFlag=cf030efc93fc955252497e163e22ab63