web3.js:估算usdt智能合约转账的gas费

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

我正在尝试估算 eth 中的 gas 价值,用于 USDT 转账,但 we3.js 只给我 IVALID OPCODE 错误...

代码示例

const Web3 = require('web3');

const web3 = new Web3('https://cloudflare-eth.com/');

const token = new web3.eth.Contract([{
    'constant': false,
    'inputs': [{
        'internalType': 'address',
        'name': 'recipient',
        'type': 'address',
    }, {
        'internalType': 'uint256',
        'name': 'amount',
        'type': 'uint256',
    }],
    'name': 'transfer',
    'outputs': [{
        'internalType': 'bool',
        'name': '',
        'type': 'bool',
    }],
    'payable': false,
    'stateMutability': 'nonpayable',
    'type': 'function',
}], '0xdac17f958d2ee523a2206206994597c13d831ec7');


const to = '0x....';
const from = '0x.....'
token
    .methods
    .transfer(to, web3.utils.toWei('1'))
    .estimateGas({from})
    .then(res=>{
        console.log(res);
    })
;

错误:

找不到任何工作示例。最后,我想获得与 metamask 给我的价值接近的价值......

Petr Hejda 回答后更新

const Web3 = require('web3');

const web3 = new Web3('https://cloudflare-eth.com/');

const token = new web3.eth.Contract([{
    'constant': false,
    'inputs': [{
        'internalType': 'address',
        'name': 'recipient',
        'type': 'address',
    }, {
        'internalType': 'uint256',
        'name': 'amount',
        'type': 'uint256',
    }],
    'name': 'transfer',
    'outputs': [{
        'internalType': 'bool',
        'name': '',
        'type': 'bool',
    }],
    'payable': false,
    'stateMutability': 'nonpayable',
    'type': 'function',
}], '0xdac17f958d2ee523a2206206994597c13d831ec7');


const to = '0x..';
const from = '0x..'
const value = web3.utils.toWei('1', 'mwei');

web3.eth.getGasPrice()
    .then(gasPrice => {
        token
            .methods
            .transfer(to, value)
            .estimateGas({from})
            .then(estimatedGas=>{
                const txPriceWei = estimatedGas * gasPrice;
                const txPriceEth = web3.utils.fromWei(txPriceWei.toString(), 'ether');
                const txPriceUSD = txPriceEth * 1800;
                console.log({
                    estimatedGas, txPriceWei, txPriceEth, txPriceUSD
                });
            })
        ;
    })
;

现在它起作用了,并且估计.. 东西。它接近元掩码值,但大约低 30%。我哪里可以错过这30%? 谢谢。

javascript node.js web3js
2个回答
2
投票

根据代码中提供的值,我假设您正在尝试计算在以太坊主网上转账 1 USDT 的汽油费。

web3js

toWei()
函数将数字转换为具有 18 位小数的 EVM 兼容值。然而,USDT 代币 只使用 6 位小数。

由于这种差异,您的代码有效地绑定到计算转移

1.000.000.000.000
代币 (
10^18 / 10^6 = 10^12
) 的 gas 成本。

由于

from
地址没有一万亿美元的USDT,交易预计会回滚。并且,在底层的低级 EVM 字节码中,还原由
IVALID
操作码触发。


-1
投票

我使用代码并且我已经恢复了错误任何人都可以帮助我

© www.soinside.com 2019 - 2024. All rights reserved.