Go-Ethereum

從 geth 命令行與已部署的智能合約互動

  • December 20, 2021

我有一份契約,我希望能夠將任何其他地址送出的數字相加:

contract UnitCounter {
   mapping (address => uint256) public UnitsFrom;
   uint256 public TotalUnits;

   function submitUnits(uint256 Units) {
       UnitsFrom[msg.sender] = Units;
       TotalUnits += Units;
   }
}

以此為粗略指導,我私人網路上按照以下步驟操作:

  1. 使用霧部署合約
  2. 使用霧中的“顯示介面”圖示獲取 JSON 介面程式碼
  3. 0x17d541b8aACFFe473e3dD32eBA83C82B51DB8EF9在我的私有區塊鏈上複製已部署合約的地址。
  4. 在 Geth 控制台上:

var abi=[ { "constant": false, "inputs": [ { "name": "Units", "type": "uint256" } ], "name": "submitUnits", "outputs": [], "type": "function" }, { "constant": true, "inputs": [], "name": "TotalUnits", "outputs": [ { "name": "", "type": "uint256" } ], "type": "function" }, { "constant": true, "inputs": [ { "name": "", "type": "address" } ], "name": "UnitsFrom", "outputs": [ { "name": "", "type": "uint256", "value": "0" } ], "type": "function" } ]

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

var MyContractInstance = MyContract.at('0x17d541b8aACFFe473e3dD32eBA83C82B51DB8EF9');

MyContractInstance.submitUnits('10');

然後我收到以下錯誤:

錯誤:

web3.js:3887:15

at web3.js:3713:20

at web3.js:4939:28

at web3.js:4938:12 at web3.js
:4938:12

at web3.js:3713:20 at web3.js:4964:18

at web3 .js:4989:23

at web3.js:4055:16

at apply ()

at web3.js:4141:16

這些錯誤是什麼意思?

我應該如何從這一點調試?

您需要添加一個交易對象來告訴 geth 使用哪個帳戶進行交易:

MyContractInstance.submitUnits('10', {from: eth.accounts[0], gas:3000000});

您也可以通過設置預設帳戶的方式消除此錯誤,因此您不必在與契約互動時添加選項 {from:…}。

在您的geth 控制台中:-

// default account set to first account in your geth accounts
eth.defaultAccount = eth.accounts[0]
// Note: If eth.accounts is empty, you can create a new account with personal.newAccount()
// default account set to coinbase(Etherbase), the default primary local account in geth
eth.defaultAccount = eth.coinbase

如果您隨後收到此錯誤 -錯誤:需要身份驗證:密碼或解鎖,請解鎖您的帳戶。

在您的geth 控制台中:-

// unlocks your account for calls/transactions after you give password 
personal.unlockAccount(eth.defaultAccount)

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