簡體   English   中英

在 ethers.js 中設置合約方法的氣體限制

[英]Set gas limit on contract method in ethers.js

問題

我正在嘗試在測試網絡(ropsten)上使用合約方法,但由於此錯誤而失敗:

原因:'無法估算氣體; 交易可能會失敗或可能需要手動限制氣體”,代碼:“UNPREDICTABLE_GAS_LIMIT”

代碼

我創建了一個智能合約的實例並想調用它的注冊方法:

const registrationContract = new ethers.Contract(ADDRESS, abi, signer);
const hashedDomain = utils.keccak256(utils.toUtf8Bytes(domain));

const register = await registrationContract.register(hashedDomain, walletAddress);

ethers.js是否提供 function 來設置合約限制? 或者這可以通過其他方式完成嗎? 我在文檔中沒有找到。

作為答案的補充,當您手動定義 gasLimit 時,了解以下內容很重要:

  1. 配置的值被保留並在合約調用時發送,因此調用者帳戶必須在他的錢包中至少具有該值;

  2. 當然交易完成后剩余的 Gas 會返還給調用者錢包;

  3. 所以當同一個交易調用時會出現問題,例如取決於 arguments 的數量,你有廣泛的 gas 值可能性,有時值設置非常高並且與小 gas 交易不成比例。

因此,為了解決這個問題並動態設置 gasLimit,使用 function 來估計來自 ETH 的交易氣體(estimateGas),然后給出額外的保證金錯誤百分比。

可能是這樣的,gasMargin() 計算最終要通過 tx 調用的氣體(在這種情況下只增加 10%)。

const gasEstimated = await registrationContract.estimateGas.register(hashedDomain, walletAddress);

const register = await registrationContract.register(hashedDomain, walletAddress), {
      gasLimit: Math.ceil(gasMargin(gasEstimated, 1.1)) 
    });

您可以使用 object 作為最后一個參數來設置氣體限制,對於簡單的轉賬交易,您可以執行以下操作:

const tx = {
  to: toAddress,
  value: ethers.utils.parseEther(value),
  gasLimit: 50000,
  nonce: nonce || undefined,
};
await signer.sendTransaction(tx);

如果您正在對智能合約進行交易,想法是相同的,但請確保在您的 abi 方法之一中設置最后一個參數,例如:

const tx = await contract.safeTransferFrom(from, to, tokenId, amount, [], {
  gasLimit: 100000,
  nonce: nonce || undefined,
});

這可以修復 UNPREDICTABLE_GAS_LIMIT 錯誤,因為手動通知它 ethers 會跳過向提供程序請求計算的 gas_limit 的 rpc 方法調用。

您可以制作一個助手 function 以將氣體限制增加一定量:

const increaseGasLimit = (estimatedGasLimit: BigNumber) => {
  return estimatedGasLimit.mul(130).div(100) // increase by 30%
}

並像這樣使用它:

const estimatedGas = await contract.estimateGas.method(args)
const tx = await contract.method(args, { gasLimit: increaseGasLimit(estimatedGas) })

const gasPrice = signer.gasPrice();

const gasLimit = contract.estimateGas.method(parameter);

const tx = contract. Method(parameter,{gasLimit:gasLimit,gasPrice:gasPrice});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM