Truffle

估計 Truffle Console 中的 gas 成本?

  • February 28, 2022

Truffle 控制台中是否有辦法估算將合約部署到主網的 gas 成本?

我正在嘗試truffle migrate --network main簽訂契約,但它的汽油用完了。

我一直在調整 truffle-config 中的gasand gasPrice

// truffle-config.js
main: {
     network_id: 1, // Main's id
     gas: <gas limit>,
     gasPrice: <gas price>

但是知道部署特定合約的氣體是什麼會很有幫助。

@alberto 說得對。

truffle(ropsten)> Migrations.new.estimateGas()
193243

您可以通過以下方式使用 Truffle 進行估算:

PS:您大多數人都安裝了全球最新版本的 Truffle,它使用 Ganache 和氣體精確度。

契約範例

// ./contracts/ContractFactory.sol
pragma solidity ^0.5.0;

contract ContractFactory {
 function createInstance() public {
   new Contract();
 }
}

contract Contract {
 constructor() public {}
}

測試氣體估計:

// ./test/ContractFactory.js
const ContractFactory = artifacts.require("ContractFactory");

contract("ContractFactory", () => {
 it("...should deploy and successfully call createInstance using the method's provided gas estimate", async () => {
   const contractFactoryInstance = await ContractFactory.new();

   const gasEstimate = await contractFactoryInstance.createInstance.estimateGas();

   const tx = await contractFactoryInstance.createInstance({
     gas: gasEstimate
   });
   assert(tx);
 });
});

執行測試命令

$ truffle test
...
...
Contract: ContractFactory

✓ ...should deploy and successfully call createInstance using the method's provided gas estimate (130ms)

1 passing (143ms)

如果 gas 是精確的,你可以這樣做,在發送我們的測試交易之前從 gasEstimate 中減去一個單位的 gas。

// ./test/ContractFactory.js
const ContractFactory = artifacts.require("ContractFactory");

contract("ContractFactory", () => {
 it("...should deploy and successfully call createInstance using the method's provided gas estimate", async () => {
   const contractFactoryInstance = await ContractFactory.new();

const gasEstimate = await contractFactoryInstance.createInstance.estimateGas();

const tx = await contractFactoryInstance.createInstance({
     gas: gasEstimate - 1 // subtract
   });
   assert(tx);
 });
});

測試結果

$ truffle test
...
...
Error: Returned error: VM Exception while processing transaction: revert

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