Skip to Content
dApp 接入

eth_estimateGas

生成并返回完成交易所需的 Gas 估算值。交易不会被添加到区块链。


参数

索引类型说明
0object交易对象
1string区块号或标签(可选)

交易对象

字段类型必填说明
fromstring否发送方地址
tostring否接收方地址
datastring否合约调用数据
valuestring否金额,单位 wei(十六进制)
gasstring否Gas 限制(十六进制)
gasPricestring否Gas 价格(十六进制)

返回值

string - 估算的 Gas 数量(十六进制)


示例

估算 ETH 转账

const gasEstimate = await window.$onekey.ethereum.request({ method: 'eth_estimateGas', params: [{ from: '0xYourAddress...', to: '0xRecipientAddress...', value: '0xDE0B6B3A7640000' // 1 ETH }] }) console.log('Estimated gas:', parseInt(gasEstimate, 16)) // Simple ETH transfer: ~21000

估算合约调用

const gasEstimate = await window.$onekey.ethereum.request({ method: 'eth_estimateGas', params: [{ from: '0xYourAddress...', to: '0xContractAddress...', data: '0xa9059cbb...' // transfer(address,uint256) }] }) console.log('Estimated gas:', parseInt(gasEstimate, 16))

添加安全缓冲

async function estimateGasWithBuffer(tx, bufferPercent = 20) { const estimate = await window.$onekey.ethereum.request({ method: 'eth_estimateGas', params: [tx] }) const gas = parseInt(estimate, 16) const bufferedGas = Math.ceil(gas * (1 + bufferPercent / 100)) return '0x' + bufferedGas.toString(16) } const safeGasLimit = await estimateGasWithBuffer({ from: accounts[0], to: contractAddress, data: encodedData })

错误码

错误码消息说明
-32000Execution reverted交易会失败
-32000Insufficient funds余额不足
-32602Invalid params交易参数无效

说明

  • 估算值可能不准确;交易可能使用更多或更少的 Gas
  • 建议在估算值基础上增加 10-20% 的缓冲
  • 如果估算失败,交易很可能也会失败
  • 估算基于当前区块链状态
最后更新于