WEB3发送交易扣费

问题描述 投票:0回答:1

我使用的是WEB3版本4.0.3

例如我想发送 0.1 ETH。

所以要发送我需要天然气。

所以我尝试做的是:

当前发送金额减去费用 (例如 0.1 - 0.000003)

但我总是得到:

gas资金不足*价格+价值:地址0xb97170623721F86E7d9756E72668f9A209A4e8Ad有10124457040804150想要11032599524271312

app.post('/send', async (request, response) => {

    const gasPrice = await web3.eth.getGasPrice();
    const gasLimit = 21000;

    const from = 'FROM_ADDRESS';
    const to = 'TO_ADDRESS';
    const amount = utils.toWei('0.1', 'ether').toString() - gasPrice.toString();
    const privateKey = 'PRIVATE_KEY';

    const nonce = await web3.eth.getTransactionCount(from, 'latest');

    const txObject = {
        from: from,
        to: to,
        value: amount,
        gasPrice: gasPrice,
        gas: gasLimit,
        nonce: nonce,
    };

    web3.eth.accounts.signTransaction(txObject, privateKey)
        .then(signedTx => {
            web3.eth.sendSignedTransaction(signedTx.rawTransaction)
                .on('receipt', receipt => {
                    console.log(receipt);
                })
                .catch(err => {
                    console.log(err)
                })
            ;
        })
        .catch(err => {
            console.log(err);
            error('something went wrong', response);
        });
});
javascript ethereum web3js
1个回答
0
投票

如果您想发送金额(例如

0.1 ether
),您的帐户余额必须是:

ACCOUNT_BALANCE <= (VALUE + GAS_PRICE * GAS_LIMIT)
  1. 您减去

    gasPrice
    ,但您必须将 Gas 价格乘以您使用的 Gas 限制,因为价格是 1 个 Gas 单位的价格。

  2. 看起来您没有足够的余额来发送,所以如果您想发送完整的余额,您必须减去将用于gas的金额。

const gasPrice = BigInt(await web3.eth.getGasPrice());
const gasLimit = 21000n;
const balance = BigInt(await web3.eth.getBalance(from));
// send all
const amount = balance - gasPrice * gasLimit;
if (amount <= 0n) {
    throw new Error("Not enough balance to send ${balance}");
}
const value = '0x' + amount.toString(16);
© www.soinside.com 2019 - 2024. All rights reserved.