100 web3j 使用 javaBean 调用智能合约 或者使用RawTransaction.createTransaction区别

web3j 使用 javaBean 调用智能合约 或者用RawTransaction.createTransaction 自己封装哪个执行速度会快一些, 使用 javaBean 调用智能合约不需要指定nonce,是因为web3j中contract类在执行交易的时候,获取nonce的步骤在封装功能中完成了吗?

请先 登录 后评论

最佳答案 2022-08-25 00:40

通过web3j-client生产的javaBean 在调用合约非 pure view方法是对应的发送交易的代码 org.web3j.tx.RawTransactionManager#sendTransaction

    public EthSendTransaction sendTransaction(
            BigInteger gasPrice,
            BigInteger gasLimit,
            String to,
            String data,
            BigInteger value,
            boolean constructor)
            throws IOException {

        BigInteger nonce = getNonce();

        RawTransaction rawTransaction =
                RawTransaction.createTransaction(nonce, gasPrice, gasLimit, to, value, data);

        return signAndSend(rawTransaction);
    }

可以看到获取nonce的方式是通过该方法 org.web3j.tx.RawTransactionManager#getNonce而该方法时通过调用web3j.ethGetTransactionCount PENDING状态下的交易数量来指定nonce的,及每调用一次合约的方法都会请求一次web3j.ethGetTransactionCount

结论

使用JavaBean 调用在获取nonce的时候会调用一次web3rpc,相比直接使用RawTransaction.createTransaction 多了一次http请求的时间,所以和你的描述很相近,而gasPrice,gasLimit 都是通过新建时给定的gasProvider来给定的基本不消耗时间。除非重载了ContractGasProvider通过ethEstimateGas获取gasLimit,ethGasPrice获取gasPrice这种情况下javaBean就会比直接指定nonce,gasPrice,gasLimit多出3次调用周期

请先 登录 后评论

其它 2 个回答

Tiny熊 - 布道者
  擅长:智能合约,以太坊
请先 登录 后评论
路人乙
请先 登录 后评论