Web3js

ethers.js 會自動計算 gas 成本嗎?

  • November 22, 2022
const contractAddress = "Contract Address";
const ABI = "ABI data JSON"

const Web3 = require("web3");
const transaction = {
   'from' :account.address, 
   'gas': 95000,
   'gasPrice' : web3.utils.toWei("35", "gwei"),
};
const contract = new web3.eth.Contract(abi,contractAddress)
let result = await contract.methods.mint(to,amount).send(transaction); // require transaction data

web3JS 模組的情況下,呼叫智能合約函式時,gas fee 必須寫入交易數據。

const contractAddress = "Contract Address";
const ABI = "ABI data JSON"

const { ethers,Contract } = require("ethers");
const contract = new Contract(contractAddress,ABI,signer);
let result = await contract.connect(signer).mint(to,amount); // no transaction data

使用ethersJS 模組時,交易是通過預測 gas fee 來發送的,而不指定要使用的 gas fee。

EthersJS 會自動估算和計算 gas 成本嗎?

+用EthersJS發送交易時,如何寫程式碼像web3一樣直接輸入gas fee?

在 EthersJS 中,在估算交易所需的氣體量時,會查詢節點的最佳猜測。如果節點不能(或不願意)預測成本,UNPREDICTABLE_GAS_LIMIT就會發生錯誤。

請參閱:https ://docs.ethers.io/v5/api/utils/logger/#errors–unpredicatable-gas-limit

您可以按照下面的範例編寫程式碼,在使用 EthersJS 發送交易時像 web3 一樣直接輸入 gas 費用。

const url = `provider url`
const provider = new ethers.providers.JsonRpcProvider(url)
const wallet = new ethers.Wallet(privKey, provider)

const tx = await wallet.sendTransaction({
      to: account,
      value: 90000000000,
      gasPrice: 250000000000,
      gasLimit: 21000,
  })

const receipt = await tx.wait()

請參閱:https ://medium.com/klaytn/using-ethereum-tools-in-klaytn-dc068d48de04

引用自:https://ethereum.stackexchange.com/questions/139798