java中怎么监听以太坊交易

java中怎么监听以太坊交易,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

我们提供的服务有:成都网站设计、成都网站建设、外贸网站建设、微信公众号开发、网站优化、网站认证、涿鹿ssl等。为上千企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的涿鹿网站制作公司

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 getTransferEvents(TransactionReceipt transactionReceipt) {
        ...
        return responses;
    }

    public Observable transferEventObservable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {
		...
	}

	...
	
    public Uint256 balanceOf(Address _owner) throws IOException {
        Function function = new Function("balanceOf", 
                Arrays.asList(_owner), 
                Arrays.>asList(new TypeReference() {}));
        return executeCallSingleValueReturn(function);
    }

	...
	
    public TransactionReceipt transfer(Address _to, Uint256 _amount) throws IOException, TransactionException {
        Function function = new Function("transfer", Arrays.asList(_to, _amount), Collections.>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.
 * Do not modify!
 * Please use the web3j command line tools, or {@link org.web3j.codegen.SolidityFunctionWrapperGenerator} to update.  *  * 

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 getTransferEvents(TransactionReceipt transactionReceipt) {         final Event event = new Event("Transfer",                  Arrays.>asList(new TypeReference

() {}, new TypeReference
() {}),                 Arrays.>asList(new TypeReference() {}));         List valueList = extractEventParameters(event, transactionReceipt);         ArrayList responses = new ArrayList(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 transferEventObservable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {         final Event event = new Event("Transfer",                  Arrays.>asList(new TypeReference
() {}, new TypeReference
() {}),                 Arrays.>asList(new TypeReference() {}));         EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress());         filter.addSingleTopic(EventEncoder.encode(event));         return web3j.ethLogObservable(filter).map(new Func1() {             @Override             public 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 getApprovalEvents(TransactionReceipt transactionReceipt) {         final Event event = new Event("Approval",                  Arrays.>asList(new TypeReference
() {}, new TypeReference
() {}),                 Arrays.>asList(new TypeReference() {}));         List valueList = extractEventParameters(event, transactionReceipt);         ArrayList responses = new ArrayList(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 approvalEventObservable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {         final Event event = new Event("Approval",                  Arrays.>asList(new TypeReference
() {}, new TypeReference
() {}),                 Arrays.>asList(new TypeReference() {}));         EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress());         filter.addSingleTopic(EventEncoder.encode(event));         return web3j.ethLogObservable(filter).map(new Func1() {             @Override             public 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 name() throws IOException {         Function function = new Function("name",                  Arrays.asList(),                  Arrays.>asList(new TypeReference() {}));         return executeCallSingleValueReturn(function);     }     public TransactionReceipt approve(Address _spender, Uint256 _amount) throws IOException, TransactionException {         Function function = new Function("approve", Arrays.asList(_spender, _amount), Collections.>emptyList());         return executeTransaction(function);     }     public Future totalSupply() throws IOException {         Function function = new Function("totalSupply",                  Arrays.asList(),                  Arrays.>asList(new TypeReference() {}));         return executeCallSingleValueReturn(function);     }     public TransactionReceipt transferFrom(Address _from, Address _to, Uint256 _amount) throws IOException, TransactionException {         Function function = new Function("transferFrom", Arrays.asList(_from, _to, _amount), Collections.>emptyList());         return  executeTransaction(function);     }     public Uint8 decimals() throws IOException {         Function function = new Function("decimals",                  Arrays.asList(),                  Arrays.>asList(new TypeReference() {}));         return executeCallSingleValueReturn(function);     }     public Uint256 balanceOf(Address _owner) throws IOException {         Function function = new Function("balanceOf",                  Arrays.asList(_owner),                  Arrays.>asList(new TypeReference() {}));         return executeCallSingleValueReturn(function);     }     public Future
 owner() throws IOException {         Function function = new Function("owner",                  Arrays.asList(),                  Arrays.>asList(new TypeReference
() {}));         return executeCallSingleValueReturn(function);     }     public Future symbol() throws IOException {         Function function = new Function("symbol",                  Arrays.asList(),                  Arrays.>asList(new TypeReference() {}));         return executeCallSingleValueReturn(function);     }     public TransactionReceipt transfer(Address _to, Uint256 _amount) throws IOException, TransactionException {         Function function = new Function("transfer", Arrays.asList(_to, _amount), Collections.>emptyList());         return executeTransaction(function);     }     public Future allowance(Address _owner, Address _spender) throws IOException {         Function function = new Function("allowance",                  Arrays.asList(_owner, _spender),                  Arrays.>asList(new TypeReference() {}));         return executeCallSingleValueReturn(function);     }     public static RemoteCall deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit, BigInteger initialWeiValue, Uint256 totalSupply, Utf8String tokenName, Uint8 decimalUnits, Utf8String tokenSymbol) {         String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.asList(totalSupply, tokenName, decimalUnits, tokenSymbol));         return deployRemoteCall(Erc20TokenWrapper.class, web3j, credentials, gasPrice, gasLimit, BINARY, encodedConstructor, initialWeiValue);     }     public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit, BigInteger initialWeiValue, Uint256 totalSupply, Utf8String tokenName, Uint8 decimalUnits, Utf8String tokenSymbol) {         String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.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;     } }

关于java中怎么监听以太坊交易问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注创新互联行业资讯频道了解更多相关知识。


新闻名称:java中怎么监听以太坊交易
网页网址:http://cdiso.cn/article/gedpej.html

其他资讯