estimateGas - 估算合约方法gas用量

优质
小牛编辑
141浏览
2023-12-01

通过在EVM中执行方法来估算链上执行是需要的gas用量。得到的估算值可能与之后实际发送 交易的gas用量有差异,因为合约的状态可能在两个时刻存在差异。

调用:

myContract.methods.myMethod([param1[, param2[, ...]]]).estimateGas(options[, callback])

参数:

  • options - Object : 选项,包括以下字段:
    • from - String : 可选,交易发送方地址
    • gas - Number : 可选,本次交易gas用量上限
    • value - Number|String|BN|BigNumber: 可选,交易转账金额,单位:wei
    • callback - Function : 可选的回调函数,触发时其第二个参数为gas估算量,第一个参数为错误对象。

返回值:

一个Promise对象,其解析值为估算的gas用量。

示例代码:

// 使用回调函数
myContract.methods.myMethod(123).estimateGas({gas: 5000000}, function(error, gasAmount){
    if(gasAmount == 5000000)
        console.log('Method ran out of gas');
});

// 使用promise
myContract.methods.myMethod(123).estimateGas({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
.then(function(gasAmount){
    ...
})
.catch(function(error){
    ...
});