区块链中文技术社区

web3j.ethCall 测试

package com.example.demo.test;

import com.example.demo.util.Constants;
import org.web3j.abi.FunctionEncoder;
import org.web3j.abi.FunctionReturnDecoder;
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.request.Transaction;
import org.web3j.protocol.core.methods.response.EthCall;
import org.web3j.protocol.http.HttpService;

import java.util.Arrays;
import java.util.List;

public class TransactionGetTest {

    public static void main(String[] args) throws Exception {
        Web3j web3j = Web3j.build(new HttpService()); // defaults to http://localhost:8545/

        /*
         * String name 函数名字
         * List<Type> inputParameters 入口参数
         * List<TypeReference<?>> outputParameters 出口参数
         */
        Function function = new Function("get",
                Arrays.<Type>asList(),
                Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {
                }));

        // encode the function
        String encodedFunction = FunctionEncoder.encode(function);

        /*
         * String from null(optional)
         * String to 合约地址
         * String data ABI
         */
        EthCall response = web3j.ethCall(Transaction.createEthCallTransaction(null, Constants.ADDRESS, encodedFunction), DefaultBlockParameterName.LATEST).send();

        // get result
        List<Type> result = FunctionReturnDecoder.decode(response.getValue(), function.getOutputParameters());
        int data = Integer.parseInt(result.get(0).getValue().toString());
        System.out.println("data = " + data);
    }
}

https://github.com/zhangbincheng1997/Ethereum/blob/dda4509fca76157b28465b8449d8aae9a1ac9ef6/helloworld/src/main/java/com/example/demo/test/TransactionGetTest.java

当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »