Java calls the contract through the smart contract method

1. Call the read-only contract

Note: Generally, the ones copied from the little fox do not have the ID behind them, so we need to register

Ethereum API | IPFS API & Gateway | ETH Nodes as a Service | Infura

Or  click here   , after the registration is complete, we can get a string of IDs, just splicing the IDs behind our main network address.

  1. Call the read-only function of the smart contract
 /**
     * 连接web3 节点 https://mainnet.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161
     */
    private final static Web3j web3j = Web3j.build(new HttpService("https://mainnet.infura.io/v3/这里需要拼接上面方法里面获取的ID"));

    public String signTokenTransaction() throws IOException, ExecutionException, InterruptedException {
        try {
            //方法传入的参数为uint
            List input = Arrays.asList(new Uint256(123));
            //返回的是字符串,如果返回格式错误下面解析将会报错
            List output = Arrays.asList(new TypeReference<Utf8String>() {
            });
            //代币合约地址
            String coinAddress = "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d";
            //传入的合约地址、调取的只读方法、传入参数和返回参数
            List<Type> type = readContract(coinAddress,"tokenURI", input,output);
            return type.get(0).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 读取合约状态
     *
     * @param contractAddress 合约地址
     * @param functionName    合约函数名称
     * @param input           输入参数
     * @param output          返回变量类型
     * @return 合约函数返回值
     * @throws Exception 与节点交互失败
     */
    public List<Type> readContract(String contractAddress, String functionName, List<Type> input, List<TypeReference<?>> output) throws Exception {
        // 生成需要调用函数的data
        Function function = new Function(functionName, input, output);
        String data = FunctionEncoder.encode(function);
        // 组建请求的参数   调用者地址(可以为空),合约地址、参数
        EthCall response = web3j.ethCall(
            Transaction.createEthCallTransaction("0x9175F9EcBbddC078e40C5e037AD31F4abf36628a", contractAddress, data),
            DefaultBlockParameterName.LATEST)
            .send();
        // 解析返回结果
        return FunctionReturnDecoder.decode(response.getValue(), function.getOutputParameters());
    }

The contractAddress parameter represents the address of the smart contract, such as "0x123456789..."
The functionName parameter represents the function name that needs to call the function written in the contract, such as querying the token balance. The "balanceOf"
input parameter of this parameter indicates the parameters that the contract function needs to pass in. The type needs to be consistent with the solidity function parameter type
Example: Arrays.asList(new Address("0x6dF655480F465DC36347a5616E875D155804F0c5"), new Uint256(10000000)); Various variable types of solidity are encapsulated
in the web3j library.
Parameter type, the parameter type needs to be consistent with the return type of the solidity function
Example: Arrays.asList(new TypeReference(){});
The solidity function may return multiple return values ​​of different types


Code example for querying token balance
 

/**
     * 获取某个代币的余额
     *
     * @param contractAddress 代币合约地址
     * @param address         查询用户地址
     * @return 余额:单位ether
     * @throws Exception 与节点交互失败
     */
    public String balanceOf(String contractAddress, String address) throws Exception {
        List input = Arrays.asList(new Address(address));
        List output = Arrays.asList(new TypeReference<Uint256>() {
        });
        List<Type> result = readContract(contractAddress, "balanceOf", input, output);
        Uint256 balance = (Uint256) result.get(0);
        return Convert.fromWei(balance.getValue().toString(), Convert.Unit.ETHER).toString();
    }
  • The length of the output array input determines the length of the return value array of the readContract method
  • 1 ether = 1^18 wei, since the precision of most of the tokens on the chain is 18 decimal places, here we directly do general processing

Guess you like

Origin blog.csdn.net/qq_38935605/article/details/125203291