当前位置:   article > 正文

Web3j通过合约地址监听transfer事件获取以太坊交易数据_web3怎么监听转账事件 php

web3怎么监听转账事件 php

Web3j通过合约地址监听transfer事件获取以太坊交易数据


We3j

web3j是一个轻量级的Java库,用于在Ethereum网络上集成客户端(节点)。

核心特性

  • 通过Java类型的JSON-RPC与Ethereum客户端进行交互
  • 支持所有的JSON-RPC方法类型
  • 支持所有Geth和Parity方法,用于管理账户和签署交易
  • 同步或异步的发送客户端请求
  • 可从Solidity ABI文件自动生成Java只能合约功能包

业务需求: 分析区块链转账记录,获取交易信息进一步分析。

原创代码,用web3j接入以太坊全节点,通过合约地址监听transfer事件,获取交易记录。

注意:注意版本问题。不同版本event的构造参数列表是不一样的。

	<dependency>
		<groupId>org.web3j</groupId>
		<artifactId>core</artifactId>
		<version>3.4.0</version>
  	</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

GitHub: link. 欢迎star

@Service
public class MonitorTransferService {

    private static final Logger LOG = LoggerFactory.getLogger(MonitorTransferService.class);
    private Web3j web3j;
    private ThreadLocal<Set<BigInteger>> blockNumberSet = ThreadLocal.withInitial(HashSet::new);

    @Value("${ipcSocketPath}")
    private String ipcSocketPath;

    @PostConstruct
    public void init() {
//        web3j = Web3j.build(new HttpService()); //RPC方式
        web3j = Web3j.build(new UnixIpcService(ipcSocketPath)); //IPC方式
    }

    /**
     * 监听合约(分步)
     */
    public void contractFilterOfStep(MonitorTransferRequest monitorTransferRequest) {
        new Thread(() -> {
            try {
                BigInteger blockNumber = getBlockNumber();
                LOG.info("BlockChainNumber={}", blockNumber);
                BigInteger startBlock = new BigInteger(monitorTransferRequest.getFirstBlock());
                BigInteger step = new BigInteger("100");
                assert blockNumber != null;
                int num = Integer.parseInt(String.valueOf(blockNumber.subtract(startBlock).divide(step)));
                for (int i = 0; i < num; i++) {
                    // 监听合约(分步)
                    contractFilterStep(monitorTransferRequest, startBlock, startBlock.add(step));
                    startBlock = startBlock.add(step);
                }
                // 监听合约
                contractFilter(monitorTransferRequest, startBlock);
            } catch (NumberFormatException e) {
                LOG.error("监控合约异常终止,e={}", e.getMessage());
            }
        }).start();
    }

    /**
     * 监听合约
     */
    private void contractFilter(MonitorTransferRequest monitorTransferRequest, BigInteger startBlock) {
        Event event = new Event("Transfer",
                Arrays.asList(
                        new TypeReference<Address>() {
                        },
                        new TypeReference<Address>() {
                        }),
                Collections.singletonList(new TypeReference<Uint256>() {
                }));
        EthFilter filter = new EthFilter(
                DefaultBlockParameter.valueOf(startBlock),
                DefaultBlockParameterName.LATEST,
                monitorTransferRequest.getContractAddress());
        filter.addSingleTopic(EventEncoder.encode(event));
        // 监听并处理
        contractExtract(filter);
    }

    /**
     * 监听并处理
     */
    private void contractExtract(EthFilter filter) {
        Subscription subscription = web3j.ethLogObservable(filter).subscribe(log -> {
            BigInteger blockNumber = log.getBlockNumber();
            // 提取转账记录
            LOG.info("BlockNumber=", blockNumber);
            blockNumberSet.get().add(blockNumber);
            List<String> topics = log.getTopics();
            String fromAddress = topics.get(1);
            String toAddress = topics.get(2);
            String value = log.getData();
            String timestamp = "";

            try {
                EthBlock ethBlock = web3j.ethGetBlockByNumber(DefaultBlockParameter.valueOf(log.getBlockNumber()), false).send();
                timestamp = String.valueOf(ethBlock.getBlock().getTimestamp());
            } catch (IOException e) {
                LOG.warn("Block timestamp get failure,block number is {}", log.getBlockNumber());
                LOG.error("Block timestamp get failure,{}", e);
            }

            TransferRecord transferRecord = new TransferRecord();
            transferRecord.setFromAddress("0x" + fromAddress.substring(26));
            transferRecord.setToAddress("0x" + toAddress.substring(26));
            transferRecord.setValue(new BigDecimal(new BigInteger(value.substring(2), 16)).divide(BigDecimal.valueOf(1000000000000000000.0), 18, BigDecimal.ROUND_HALF_EVEN));
            transferRecord.setTimeStamp(timestamp);
        });
//        subscription.unsubscribe();
    }

    /**
     * 监听合约(分步)
     */
    private void contractFilterStep(MonitorTransferRequest monitorTransferRequest, BigInteger startBlock, BigInteger endBlock) {
        Event event = new Event("Transfer",
                Arrays.asList(
                        new TypeReference<Address>() {
                        },
                        new TypeReference<Address>() {
                        }),
                Collections.singletonList(new TypeReference<Uint256>() {
                }));
        EthFilter filter = new EthFilter(
                DefaultBlockParameter.valueOf(startBlock),
                DefaultBlockParameter.valueOf(endBlock),
                monitorTransferRequest.getContractAddress());
        filter.addSingleTopic(EventEncoder.encode(event));
        // 监听并处理
        contractExtract(filter);
    }

    /**
     * 区块数量
     */
    private BigInteger getBlockNumber() {
        EthBlockNumber send;
        try {
            send = web3j.ethBlockNumber().send();
            return send.getBlockNumber();
        } catch (IOException e) {
            LOG.warn("请求区块链信息异常 >> 区块数量,{}", e);
        }
        return null;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128

GitHub: link. 欢迎star

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/900088
推荐阅读
相关标签
  

闽ICP备14008679号