eth钱包开发--java(扫块监听)

扫块监听逻辑

跑定时任务,每隔固定时间执行一次轮询,这里我采用的间隔时间是距上一次执行完后45秒;
定时任务:从上一次轮询的最后区块开始扫描,获取每个区块中所有交易,进行对应查询数据库操作和判断操作,执行完后记录轮询到的区块高度,方便下一次查询;

相关依赖
<dependency>
  <groupId>org.web3j</groupId>
  <artifactId>core</artifactId>
  <version>4.0.3</version>
</dependency>
  • 以下是使用spring管理的定时任务方法案例:
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameter;
import org.web3j.protocol.core.methods.response.EthBlock;
import org.web3j.protocol.http.HttpService;

import java.io.IOException;
import java.math.BigInteger;

@Component
public class TransactionWatcherExample {

    private Web3j web3j = Web3j.build(new HttpService("http://localhost:8545"));

    //上次轮询到的块高度
    private BigInteger lastBlockNumber;

    /**
     * 扫块监听eth交易,每45秒一次轮询
     * @throws IOException
     */
    @Scheduled(fixedDelay = 45 * 1000)
    public void watchEthTransaction() throws IOException {

        //获取当前块高度
        BigInteger currentBlockNumber = web3j.ethBlockNumber().send().getBlockNumber();

        //运行初始化
        if (lastBlockNumber == null || currentBlockNumber.subtract(lastBlockNumber).compareTo(BigInteger.valueOf(100)) > 0) {
            lastBlockNumber = BigInteger.valueOf(currentBlockNumber.longValue());
            return;
        }

        long futureBlockNum = currentBlockNumber.intValue() + 1;

        //遍历区块
        for (int i = lastBlockNumber.intValue(); i < futureBlockNum; i++) {

            //获取block
            EthBlock.Block block = web3j.ethGetBlockByNumber(DefaultBlockParameter.valueOf(BigInteger.valueOf(i)), true).send().getBlock();

            if (block == null) {
                continue;
            }

            // 遍历block中的交易
            for (EthBlock.TransactionResult tx : block.getTransactions()) {
                if (tx instanceof EthBlock.TransactionObject) {

                    //transaction: 块中的单笔交易
                    EthBlock.TransactionObject transaction = (EthBlock.TransactionObject) tx;


                    // todo 交易判断和处理逻辑


                }
            }
        }

        lastBlockNumber = BigInteger.valueOf(futureBlockNum);

    }

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在一个方法内部定义的变量都存储在栈中,当这个函数运行结束后,其对应的栈就会被回收,此时,在其方法体中定义的变量将不...
    Y了个J阅读 4,451评论 1 14
  • http://liuxing.info/2017/06/30/Spring%20AMQP%E4%B8%AD%E6%...
    sherlock_6981阅读 16,062评论 2 11
  • 从三月份找实习到现在,面了一些公司,挂了不少,但最终还是拿到小米、百度、阿里、京东、新浪、CVTE、乐视家的研发岗...
    时芥蓝阅读 42,394评论 11 349
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,161评论 1 32
  • 时间像流水般匆匆流逝,留下的只是回忆。在我的记忆中有许许多多的事,但令我最感动的还是那一件。 记得我读三年级时,因...
    峡溪飞瀑阅读 192评论 0 0