【问题标题】:How to calculate gasLimit for token transactions like USDT in BSC (BEP-20) blockchain?如何计算 BSC (BEP-20) 区块链中 USDT 等代币交易的 gasLimit?
【发布时间】:2021-09-20 20:34:12
【问题描述】:

我正在 Binance Smart Chain 中开发一个 DAPP,我想知道如何计算 gasLimit 之类的代币交易,例如 USDT,就像它的 chrome 扩展建议交易 gasLimit 并计算它的 @ 987654324@。我有一个在 BNB 交易中计算 gasLimit 的公式,但这不适用于代币交易。 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

如果我也能像上面那样计算 transactionFee 那就太好了! 任何帮助???

【问题讨论】:

    标签: node.js smartcontracts web3 web3js binance-smart-chain


    【解决方案1】:

    在进行代币交易时,可以在JS中使用web3.eth.Contract实例化合约助手对象。

    然后您可以使用.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

    【讨论】:

    • 非常感谢!你又拯救了我的一天??而且我只是认识到在 TRC20 区块链中进行合约交易所需的能量和带宽也不清楚。你也知道计算它们的方法吗???
    • 如果交易正在执行一个合约函数(在 TRC-20 合约上),你可能可以使用相同的 sn-p。我还没有验证它,但是:Tron 网络使用 EVM 的一个分支,并且大多数 RPC 命令是相同的(与以太坊中一样),所以web3 应该也可以在 Tron 网络上执行estimateGas()。您只需要使用 Tron 提供程序(在 new Web3(provider) 构造函数中)。
    • 我已经测试过了,但是当我在 TRON 网络中使用 usdt 合约地址时。它会给我这个错误Provided address TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t is invalid, the capitalization checksum test failed, or it's an indirect IBAN address which can't be converted。我已将地址转换为十六进制并重试,但没有任何反应。但至少我发现 TRC20 中的交易有两个选项 29,63114,631 用于能源和 345 用于带宽。
    • Web3.toChecksumAddress 可能会有所帮助
    【解决方案2】:

    使用 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();
    

    【讨论】:

      猜你喜欢
      • 2021-08-30
      • 2021-09-23
      • 2022-01-15
      • 2021-07-27
      • 1970-01-01
      • 2021-09-01
      • 1970-01-01
      • 2018-01-12
      • 2016-01-09
      相关资源
      最近更新 更多