NodeJS 如何在BSC(BEP-20)区块链中计算像USDT这样的令牌交易的gasLimit?

k4ymrczo  于 2022-11-04  发布在  Node.js
关注(0)|答案(2)|浏览(274)

我正在Binance Smart Chain中开发一个DAPP,我想知道我如何计算像USDT这样的代币交易的气体限额,就像它的Chrome扩展一样,它会建议交易气体限额并计算其transactionFee。我有一个计算BNB交易中气体限额的公式,但这对代币交易不起作用。
用于计算BNB事务处理的公式:

const gasPrice = await web3.eth.getGasPrice(); // estimate the gas price

const transactionObject = {
  from: SENDER_WALLET_ADDRESS,
  to: RECIEVER_WALLET_ADDRESS,
  gasPrice
}

const gasLimit = await web3.eth.estimateGas(transactionObject); // estimate the gas limit for this transaction
const transactionFee = gasPrice * gasLimit; // calculate the transaction fee

如果我也能像上面那样计算交易费就太好了。

hkmswyz6

hkmswyz61#

在执行令牌事务时,可以使用web3.eth.Contract示例化JS中的合约助手对象。
然后,您可以使用.methods属性,该属性包含基于协定ABI的帮助器函数和公共函数。
然后,您可以将.estimateGas()函数链接到契约函数。

const myContract = new web3.eth.Contract(abiJson, contractAddress);
const gasLimit = await myContract.methods
    .transfer(to, amount)       // the contract function
    .estimateGas({from: ...});  // the transaction object

文件:https://web3js.readthedocs.io/en/v1.3.4/web3-eth-contract.html#methods-mymethod-estimategas

vsdwdz23

vsdwdz232#

使用Ethers.js库

const ethers = require("ethers");

let wallet = new ethers.Wallet(privateKey, provider);

let walletSigner = wallet.connect(provider);

let contractAddress = "";

const token = new ethers.Contract(
  contractAddress,
  contract_abi,
  walletSigner
);

let token_decimal = await token.decimals();

let token_amount = await ethers.utils.parseUnits(amount, token_decimal);

let gasPrice = await provider.getGasPrice();

gasPrice = await ethers.utils.formatEther(gasPrice);

let gasLimit = await token.estimateGas.transfer(
  receiver,
  token_amount
);

let transactionFee = gasPrice * gasLimit.toNumber();

相关问题