【问题标题】:Getting "out of gas" when sending whole amount of eth with ethers用以太币发送全部 ETH 时“耗尽气体”
【发布时间】:2022-10-23 17:42:20
【问题描述】:

使用 ethers 库,我想将一个帐户的全部余额发送到我的另一个帐户,但是,它无法为 gas fee 进行一些提款。我怎样才能解决这个问题?

// example.js

const balance = await provider.getBalance(account);
const wei = "1000000000";
const gas = (Number(wei) * Number("21000")).toString();
const value = (BigInt(balance) - BigInt(gas)).toString();

await signer.sendTransaction({
  to: '0x...',
  value: value,
  gasLimit: 21000,
  gasPrice: gas,
})

当我进行上述操作时,我看到metamask弹出窗口中的gas-fee没有从余额中扣除,因此无法继续操作。

【问题讨论】:

  • 您将汽油成本与汽油价格混淆了。
  • @CherryDT,我对 web3 生态系统很陌生。在此示例中我应该在哪里进行更改?

标签: javascript solidity web3js ethers.js


【解决方案1】:

汽油费(即交易费)总是添加在交易value之上。

这是因为 EVM 的设计方式。当矿工/验证者产生交易时,你首先购买gasLimit的gas unit(每一个gas unit为wei的gasPrice),然后执行交易,最后他们将未使用的gas unit卖回给你(同样是gasPrice;当您的gasLimit 高于实际使用的气体单位量时)。这一切都在矿工/验证者机器上自动发生,但了解该机制的工作原理很有用。

例子:

  • value是100亿卫
  • gasLimitgasPrice 产生 50 亿 wei
  • =>你需要至少有150亿wei才能成功发送交易

正如问题评论中指出的那样,您错误地计算了gasPricegasPrice 是市场驱动的,所以它在不断变化,但是当前的通常值是 5 Gwei(50 亿 wei),例如,您可以在 recent transaction 中看到。

因此,您的代码应包含类似于以下的计算:

let gasLimit = 21000;
let gasPrice = 5000000000;
let totalGasInWei = gasLimit * gasPrice;

// ...

{
    value: balanceInWei - totalGasInWei
    gasLimit: gasLimit,
    gasPrice: gasPrice,
}

【讨论】:

  • 谢谢Hejda,我会试试这个。
【解决方案2】:

编辑:这个答案对我很有帮助,但由于 JavaScript 给出了“大数字”错误,我用这样的转换修复了它。


const value = (BigInt(balanceInWei) - BigInt(totalGasInWei)).toString()

{
    value: value,
    gasLimit: gasLimit,
    gasPrice: gasPrice,
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-20
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 2019-11-03
    相关资源
    最近更新 更多