Skip to Content
dApps

eth_estimateGas

Génère et renvoie une estimation du gas nécessaire pour terminer la transaction. La transaction ne sera pas ajoutée à la blockchain.


Paramètres

IndiceTypeDescription
0objectObjet de transaction
1stringNuméro ou balise de bloc (facultatif)

Objet de transaction

ChampTypeObligatoireDescription
fromstringNonAdresse de l’expéditeur
tostringNonAdresse du destinataire
datastringNonDonnées d’appel du contrat
valuestringNonValeur en wei (hex)
gasstringNonLimite de gas (hex)
gasPricestringNonPrix du gas (hex)

Valeur de retour

string - Quantité de gas estimée (hex)


Exemple

Estimer un transfert 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

Estimer un appel de contrat

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))

Ajouter une marge de sécurité

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 })

Erreurs

CodeMessageDescription
-32000Exécution annuléeLa transaction échouerait
-32000Fonds insuffisantsSolde insuffisant
-32602Paramètres non validesParamètres de transaction non valides

Remarques

  • L’estimation peut être inexacte ; les transactions peuvent utiliser plus ou moins de gas
  • Ajoutez une marge (10-20%) à l’estimation par sécurité
  • Si l’estimation échoue, la transaction échouerait probablement aussi
  • L’estimation tient compte de l’état actuel de la blockchain
Dernière mise à jour le