Web3js

估計具有多個輸入的功能的氣體成本

  • July 3, 2018

我有契約

pragma solidity ^0.4.11;

contract UserBasic {
   struct Record {
       bytes32 _id;
       address _addedBy;
       uint _dateAdded;
       bytes32 _transactionHash;
       bytes32 _type;
       bytes32 _hash;
       bytes32 _signature;
   }
   // Type to records array
   mapping(bytes32 => bytes32[]) typeRecords;
   // Record ID to record
   mapping(bytes32 => Record) idRecord;
   // Search for record
   function searchRecord(bytes32 _id) constant returns (bytes32, address, uint, bytes32, bytes32, bytes32, bytes32) {
       Record storage temp = idRecord[_id];
       return (temp._id, temp._addedBy, temp._dateAdded, temp._transactionHash, temp._type, temp._hash, temp._signature);
   }
   // Add a record
   function addRecord(bytes32 _type, bytes32 _id) {
       typeRecords[_type].push(_id);
       var _new = Record(_id, tx.origin, now, "", _type, "", "");
       idRecord[_id] = _new;
   }
   // Get all records of a given type
   function getRecordsByType(bytes32 _type) constant returns(bytes32[]) {
       return typeRecords[_type];
   }
}

我的addRecord方法不起作用(我認為是因為天然氣成本)。我想估計這種方法的成本是多少,但不確定如何。這個答案解釋了一種帶有一個參數的函式的方法,但它似乎太複雜的過程,我想知道是否有更簡單的方法。

我從節點呼叫它

function addRecord(publicAddress, contractAddress, _type, _id) {
   const contract = contractInstance("UserBasic", contractAddress);
   // Interaction with the contract
   contract.addRecord(_type, _id, {from: publicAddress}, (err, res) => {
       // Log transaction to explore
       if (err) {
           console.log(err);
       } else {
           console.log('tx: ' + res);
           helpers.addTransaction(publicAddress, res);
       }
   });
}

我閱讀了文件,但我不知道的唯一部分是如何將多個參數轉換為data.

如果你有合約地址和abi你可以直接估計方法呼叫

const Web3 = require('web3');

const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

const contractAbi = [.....] ;// Contract abi goes here
const contractAddress = "0x....."; // Contract address goes here

const contract = new web3.eth.Contract(contractAbi, contractAddress);


// Estimate gas for:
//     contractInstance.methods.MethodToCalll(param1, param2, param3);
const gas = contract.methods.MethodToCall.estimateGas(param1, param2, param3);

console.log(`Gas estimated: ${gas}`);

會輸出類似

氣體估算:26818

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