Web3js

如何使用 web3.eth 獲取契約公共財產的價值

  • February 5, 2022

使用 web3 javascript 庫如何獲取公共屬性的目前值。例如

contract MyContract {
   address public owner;
   ...
}

這是 abi 的一個片段:

[{
 "constant": true,
 "inputs": [],
 "name": "owner",
 "outputs": [
   {
     "name": "",
     "type": "address"
   }
 ],
 "payable": false,
 "type": "function"
},
...
]

我嘗試了幾種方法,但無濟於事:

   var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
   var contract = new web3.eth.Contract([...], "0x1234...");

   // These don't work:
   var owner = contract.owner;
   console.log(owner); // "undefined"

   contract.methods.owner.call(function(error, result) {
       console.log("This doesn't get called");
   });

   contract.methods.owner(function(error, result) {
       // Displays an error to console:
       // Error: Invalid number of parameters for "owner". Got 1 expected 0!
   });

   var x = contract.methods.owner();
   console.log(x); // Displays the contract object below:

最後一行顯示合約對象。這是一個片段:

{ call: { [Function: bound _executeMethod] request: [Function: bound 
_executeMethod] },
 send: { [Function: bound _executeMethod] request: [Function: bound 
_executeMethod] },
 encodeABI: [Function: bound _encodeMethodABI],
 estimateGas: [Function: bound _executeMethod],
 _method:
 { constant: true,
    inputs: [],
    name: 'owner',
    outputs: [ [Object] ],
    payable: false,
    type: 'function',
    signature: '0x8da5cb5b' },
 _parent:
  Contract {
      // etc...

編輯:使用版本 1.0.0-beta.4 (後來的包沒有正確安裝依賴 lerna)。文件:http ://web3js.readthedocs.io/en/1.0/web3-eth-contract.html

根據Web3 API 文件,獲取合約實例和呼叫方法的方法是:

一、契約定義

var MyContract = web3.eth.contract(abi);

2.獲取該地址的合約實例

var myContractInstance = MyContract .at('0x**********');

3. 執行呼叫

var owner = myContractInstance .owner.call();

完整程式碼:

var abi = [
   {
     "constant": true,
     "inputs": [],
     "name": "owner",
     "outputs": [
       {
         "name": "",
         "type": "address"
       }
     ],
     "payable": false,
     "type": "function"
   },
   {
     "inputs": [],
     "payable": false,
     "type": "constructor"
   }
 ];


var MyContract = web3.eth.contract(abi);

// initiate contract for an address
var myContractInstance = MyContract .at('0xa07ddaff6d8b7aabf91ac6f82bf89455eb9784f4');

// call constant function (synchronous way)
var owner = myContractInstance .owner.call();

console.log("owner="+owner);

工作正常:

所有者=0x13a0674c16f6a5789bff26188c63422a764d9a39

此程式碼是正確的:myContract.methods.owner().call().then(console.log);該錯誤是一個錯誤,將在下一個版本中修復。

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