2019独角兽企业重金招聘Python工程师标准>>>

你可以在web3j库的帮助下使用java轻松监听以太坊交易,但此库无法监听Erc20 Token交易。

要监听Erc20Token交易,你必须使用在合约(token)创建时的token封装类。我假设你已经使用最少的功能部署了合约,因此你的封装类看起来像这样:

package com.bolenum.util;import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util...;import org.web3j.abi.EventEncoder;
import org.web3j.abi...
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol...;
import org.web3j.tx.Contract;
import org.web3j.tx.TransactionManager;import rx.Observable;
import rx.functions.Func1;...public final class Erc20TokenWrapper extends Contract {private static final String BINARY = "contract binary key";private Erc20TokenWrapper(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit);}private Erc20TokenWrapper(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit);}public List<TransferEventResponse> getTransferEvents(TransactionReceipt transactionReceipt) {...return responses;}public Observable<TransferEventResponse> transferEventObservable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {...}...public Uint256 balanceOf(Address _owner) throws IOException {Function function = new Function("balanceOf", Arrays.<Type>asList(_owner), Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}));return executeCallSingleValueReturn(function);}...public TransactionReceipt transfer(Address _to, Uint256 _amount) throws IOException, TransactionException {Function function = new Function("transfer", Arrays.<Type>asList(_to, _amount), Collections.<TypeReference<?>>emptyList());return executeTransaction(function);}...public static Erc20TokenWrapper load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {return new Erc20TokenWrapper(contractAddress, web3j, transactionManager, gasPrice, gasLimit);}public static class TransferEventResponse {public Address _from;public Address _to;public Uint256 _value;public String _transactionHash;}...
}

现在你必须使用这个类函数来加载合约然后监听交易。使用下面的代码加载和监听交易:

Web3j web3j = Web3j.build(new HttpService("url of your ethereum blockchain"))
ClientTransactionManager transactionManager = new ClientTransactionManager(web3j,"your deployed contract addess");Erc20TokenWrapper token = Erc20TokenWrapper.load("your deployed contract addess", web3j, transactionManager,Contract.GAS_PRICE, Contract.GAS_LIMIT);token.transferEventObservable(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST).subscribe(tx -> {String toAddress = tx._to.getValue();String fromAddress = tx._from.getValue();String txHash = tx._transactionHash.getValue();}

如果你已经部署了合约,它由第三人部署,那么你可以直接使用我的包装类,只需更改你可以从https://etherscan.io/tokens很容易获得的二进制密钥。

结论:因此你可以将此代码用于任何token的监听交易。此代码为你提供addressfromAddresstransactionHash。所以这些东西你可以根据你的要求使用,你可以将它们保存在你的数据库中,或者你只保存地址是你的钱包地址的交易。

谢谢,我希望这会有所帮助。

如果希望快速进行web3j、java、以太坊开发,那请看我们精心打造的教程: java以太坊开发教程,主要是针对java和android程序员进行区块链以太坊开发的web3j详解。

这里是原文

完整代码如下:

package com.bolenum.util;import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Future;import org.web3j.abi.EventEncoder;
import org.web3j.abi.EventValues;
import org.web3j.abi.FunctionEncoder;
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.Event;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.Utf8String;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.abi.datatypes.generated.Uint8;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameter;
import org.web3j.protocol.core.RemoteCall;
import org.web3j.protocol.core.methods.request.EthFilter;
import org.web3j.protocol.core.methods.response.Log;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.exceptions.TransactionException;
import org.web3j.tx.Contract;
import org.web3j.tx.TransactionManager;import rx.Observable;
import rx.functions.Func1;/*** Auto generated code.<br>* <strong>Do not modify!</strong><br>* Please use the <a href="https://docs.web3j.io/command_line.html">web3j command line tools</a>, or {@link org.web3j.codegen.SolidityFunctionWrapperGenerator} to update.** <p>Generated with web3j version 2.3.1.*/
public final class Erc20TokenWrapper extends Contract {private static final String BINARY = "contract binary key";private Erc20TokenWrapper(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit);}private Erc20TokenWrapper(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit);}public List<TransferEventResponse> getTransferEvents(TransactionReceipt transactionReceipt) {final Event event = new Event("Transfer", Arrays.<TypeReference<?>>asList(new TypeReference<Address>() {}, new TypeReference<Address>() {}),Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}));List<EventValues> valueList = extractEventParameters(event, transactionReceipt);ArrayList<TransferEventResponse> responses = new ArrayList<TransferEventResponse>(valueList.size());for (EventValues eventValues : valueList) {TransferEventResponse typedResponse = new TransferEventResponse();typedResponse._from = (Address) eventValues.getIndexedValues().get(0);typedResponse._to = (Address) eventValues.getIndexedValues().get(1);typedResponse._value = (Uint256) eventValues.getNonIndexedValues().get(0);responses.add(typedResponse);}return responses;}public Observable<TransferEventResponse> transferEventObservable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {final Event event = new Event("Transfer", Arrays.<TypeReference<?>>asList(new TypeReference<Address>() {}, new TypeReference<Address>() {}),Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}));EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress());filter.addSingleTopic(EventEncoder.encode(event));return web3j.ethLogObservable(filter).map(new Func1<Log, TransferEventResponse>() {@Overridepublic TransferEventResponse call(Log log) {EventValues eventValues = extractEventParameters(event, log);TransferEventResponse typedResponse = new TransferEventResponse();typedResponse._from = (Address) eventValues.getIndexedValues().get(0);typedResponse._to = (Address) eventValues.getIndexedValues().get(1);typedResponse._value = (Uint256) eventValues.getNonIndexedValues().get(0);typedResponse._transactionHash = log.getTransactionHash();return typedResponse;}});}public List<ApprovalEventResponse> getApprovalEvents(TransactionReceipt transactionReceipt) {final Event event = new Event("Approval", Arrays.<TypeReference<?>>asList(new TypeReference<Address>() {}, new TypeReference<Address>() {}),Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}));List<EventValues> valueList = extractEventParameters(event, transactionReceipt);ArrayList<ApprovalEventResponse> responses = new ArrayList<ApprovalEventResponse>(valueList.size());for (EventValues eventValues : valueList) {ApprovalEventResponse typedResponse = new ApprovalEventResponse();typedResponse._owner = (Address) eventValues.getIndexedValues().get(0);typedResponse._spender = (Address) eventValues.getIndexedValues().get(1);typedResponse._value = (Uint256) eventValues.getNonIndexedValues().get(0);responses.add(typedResponse);}return responses;}public Observable<ApprovalEventResponse> approvalEventObservable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {final Event event = new Event("Approval", Arrays.<TypeReference<?>>asList(new TypeReference<Address>() {}, new TypeReference<Address>() {}),Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}));EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress());filter.addSingleTopic(EventEncoder.encode(event));return web3j.ethLogObservable(filter).map(new Func1<Log, ApprovalEventResponse>() {@Overridepublic ApprovalEventResponse call(Log log) {EventValues eventValues = extractEventParameters(event, log);ApprovalEventResponse typedResponse = new ApprovalEventResponse();typedResponse._owner = (Address) eventValues.getIndexedValues().get(0);typedResponse._spender = (Address) eventValues.getIndexedValues().get(1);typedResponse._value = (Uint256) eventValues.getNonIndexedValues().get(0);typedResponse._transactionHash = log.getTransactionHash();return typedResponse;}});}public Future<Utf8String> name() throws IOException {Function function = new Function("name", Arrays.<Type>asList(), Arrays.<TypeReference<?>>asList(new TypeReference<Utf8String>() {}));return executeCallSingleValueReturn(function);}public TransactionReceipt approve(Address _spender, Uint256 _amount) throws IOException, TransactionException {Function function = new Function("approve", Arrays.<Type>asList(_spender, _amount), Collections.<TypeReference<?>>emptyList());return executeTransaction(function);}public Future<Uint256> totalSupply() throws IOException {Function function = new Function("totalSupply", Arrays.<Type>asList(), Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}));return executeCallSingleValueReturn(function);}public TransactionReceipt transferFrom(Address _from, Address _to, Uint256 _amount) throws IOException, TransactionException {Function function = new Function("transferFrom", Arrays.<Type>asList(_from, _to, _amount), Collections.<TypeReference<?>>emptyList());return  executeTransaction(function);}public Uint8 decimals() throws IOException {Function function = new Function("decimals", Arrays.<Type>asList(), Arrays.<TypeReference<?>>asList(new TypeReference<Uint8>() {}));return executeCallSingleValueReturn(function);}public Uint256 balanceOf(Address _owner) throws IOException {Function function = new Function("balanceOf", Arrays.<Type>asList(_owner), Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}));return executeCallSingleValueReturn(function);}public Future<Address> owner() throws IOException {Function function = new Function("owner", Arrays.<Type>asList(), Arrays.<TypeReference<?>>asList(new TypeReference<Address>() {}));return executeCallSingleValueReturn(function);}public Future<Utf8String> symbol() throws IOException {Function function = new Function("symbol", Arrays.<Type>asList(), Arrays.<TypeReference<?>>asList(new TypeReference<Utf8String>() {}));return executeCallSingleValueReturn(function);}public TransactionReceipt transfer(Address _to, Uint256 _amount) throws IOException, TransactionException {Function function = new Function("transfer", Arrays.<Type>asList(_to, _amount), Collections.<TypeReference<?>>emptyList());return executeTransaction(function);}public Future<Uint256> allowance(Address _owner, Address _spender) throws IOException {Function function = new Function("allowance", Arrays.<Type>asList(_owner, _spender), Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}));return executeCallSingleValueReturn(function);}public static RemoteCall<Erc20TokenWrapper> deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit, BigInteger initialWeiValue, Uint256 totalSupply, Utf8String tokenName, Uint8 decimalUnits, Utf8String tokenSymbol) {String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.<Type>asList(totalSupply, tokenName, decimalUnits, tokenSymbol));return deployRemoteCall(Erc20TokenWrapper.class, web3j, credentials, gasPrice, gasLimit, BINARY, encodedConstructor, initialWeiValue);}public static RemoteCall<Erc20TokenWrapper> deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit, BigInteger initialWeiValue, Uint256 totalSupply, Utf8String tokenName, Uint8 decimalUnits, Utf8String tokenSymbol) {String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.<Type>asList(totalSupply, tokenName, decimalUnits, tokenSymbol));return deployRemoteCall(Erc20TokenWrapper.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, encodedConstructor, initialWeiValue);}public static Erc20TokenWrapper load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {return new Erc20TokenWrapper(contractAddress, web3j, credentials, gasPrice, gasLimit);}public static Erc20TokenWrapper load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {return new Erc20TokenWrapper(contractAddress, web3j, transactionManager, gasPrice, gasLimit);}public static class TransferEventResponse {public Address _from;public Address _to;public Uint256 _value;public String _transactionHash;}public static class ApprovalEventResponse {public Address _owner;public Address _spender;public Uint256 _value;public String _transactionHash;}
}

转载于:https://my.oschina.net/u/2472105/blog/1935171

java如何监听以太坊交易相关推荐

  1. java erc 2.0_java 监听 ERC20 Token 交易

    你可以在web3j库的帮助下使用java轻松监听以太坊交易,但此库无法监听Erc20 Token交易. 要监听Erc20Token交易,你必须使用在合约(token)创建时的token封装类.我假设你 ...

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

    Web3j通过合约地址监听transfer事件获取以太坊交易数据 We3j web3j是一个轻量级的Java库,用于在Ethereum网络上集成客户端(节点). 核心特性 通过Java类型的JSON- ...

  3. java 以太坊 智能合约_web3j教程:java使用web3j开发以太坊智能合约交易

    从广义上讲,有web3j支持三种类型的以太坊交易: 1.以太币从一方交易到另一方 2.创建一个智能合约 3.与智能合约交易 为了进行这些交易,必须有以太币(以太坊区块链的代币)存在于交易发生的以太坊账 ...

  4. JAVA使用web3j开发以太坊实战案例

    JAVA使用web3j开发以太坊实战案例 必读 1.前言 2.基础(必看) 3.web3j引入 4.创建账户(离线创建) 5.geth节点搭建.基本使用及一般问题 6.常量类 后面内容都要用到(必备! ...

  5. Infura Http 客户端 以太坊 交易

    web3j Infura 模块提供了一个Infura Http 客户端(InfuraHttpService),它为Infura特定的Infura-Ethereum-Preferred-Client提供 ...

  6. 以太坊java开发指南_java以太坊开发库ethereumj

    EthereumJ是以太坊协议的纯Java实现.有关以太坊及其目标的高级信息,请访问ethereum.org,其 白皮书 提供了一个完整的概念的概述,和 黄皮书 一起提供了协议的正式定义. 我们尽可能 ...

  7. 以太坊地址和公钥_以太坊交易签名解析源码解读

    上篇文章<以太坊交易签名过程源码解析[1]>从源码角度分析了一个合约调用的的签名过程,签名后的交易发送到以太坊节点后,节点需要从签名交易中还原出公钥(从公钥中单向计算出账号地址),进而将交 ...

  8. java jmenu 监听_Java中用得比较顺手的事件监听

    第一次听说监听是三年前,做一个webGIS的项目,当时对Listener的印象就是个"监视器",监视着界面的一举一动,一有动静就触发对应的响应. 一.概述 通过对界面的某一或某些操 ...

  9. 以太坊交易信息及event、input、logs、topics等概念机制

    文章目录 一.交易信息获取 1.1 合约事件例子定义 1.2 以太坊交易获取 二.input解析 2.1 input内容解析 2.2 input处理逻辑 三.logs解析 3.1 logs解析代码 四 ...

最新文章

  1. 设计模式学习(二): 观察者模式 (C#)
  2. formatnumber js_javascript js format number 数字格式化
  3. spring加载顺序
  4. sqlhelper中事务的简单用法(初学者)
  5. oracle查询相同想,返回相同总和的查询-Oracle SQL
  6. RocketMQ的安装与启动
  7. java socket 缓冲_关于socket的发送缓冲区网上有诸多的讨论,这里个人小结一下,希望对以后有些帮助。首先,看下面一段代码,...
  8. shell date cal
  9. 从零开始一起学习SLAM | 相机成像模型
  10. Prototype使用Template
  11. 利用Brettle.Web.NeatUpload控件对打文件进行上传(转)
  12. matlab中怎么看电压和电流值,matlab计算电压有效值
  13. 中国移动的固网宽带不再免费,该项业务收入已与中国电信相当
  14. NTRIP传输相关,上篇SNIP NTRIP Caster学习笔记扫盲补充
  15. 英语微课-Speaking Confidently
  16. python api文档生成二维码_使用Python第三方库生成二维码
  17. 【http-flv】zlmedia http 客户端拉取 http-flv 流程
  18. spring源码解析之IOC核心体系结构
  19. 冯扬文:船用燃料油价格大涨对我省航运企业的影响
  20. 劲乐园合歌(幽灵圣典+飞吧喜鹊+唯一+v3+幽灵圣典2)铃声 劲乐园...

热门文章

  1. vscode snippet利器
  2. 深入剖析iLBC的丢包补偿技术(PLC)
  3. Linux/CentOS优化配置 汇总
  4. SQL Server 2008 远程过程调用失败
  5. 关于ngOptions的键值对
  6. rsync 模块同步失败
  7. perl:正则表达式部分
  8. Android自定义View:MeasureSpec的真正意义与View大小控制
  9. Python多进程编程
  10. Linux监控工具介绍系列——free`