Truffle

未擷取的類型錯誤:contract.name 不是函式

  • December 14, 2021

我正在嘗試檢查我是否正確部署了帶有鬆露和甘納許的契約。我跑truffle console,然後contract = await Kryptobird.deployed()。但是當我嘗試獲取契約的名稱時,我遇到了這個錯誤

truffle(development)> contract.name()
evalmachine.<anonymous>:0
contract.name()
        ^

Uncaught TypeError: contract.name is not a function
   at evalmachine.<anonymous>
   at sigintHandlersWrap (node:vm:268:12)
   at Script.runInContext (node:vm:137:14)
   at runScript (C:\Users\Марія\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\console.js:364:1)
   at Console.interpret (C:\Users\Марія\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\console.js:379:1)
   at bound (node:domain:421:15)
   at REPLServer.runBound [as eval] (node:domain:432:12)
   at REPLServer.onLine (node:repl:889:10)
   at REPLServer.emit (node:events:390:28)
   at REPLServer.emit (node:domain:475:12)

合約程式碼

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;


contract Kryptobird{

   string private name;
   string private symbol;

   constructor() {

       name = 'Kryptobirdz';
       symbol = 'KBIRDZ';
   }
}    
string private name;

它被明確設置為私有可見性,這意味著它不可見……意味著沒有name()功能。

如果能見度是,將生成一個大致如下的函式public

function name() public view returns(string memory) {
 return name;
}

但它不是,所以沒有功能。

希望能幫助到你。

解決方案程式碼是

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;


contract Kryptobird{

   string private _name;
   string private _symbol;

   constructor() {

       _name = 'Kryptobirdz';
       _symbol = 'KBIRDZ';
   }

   function name() public view returns(string memory) {
       return _name;
   }

   function symbol() public view returns(string memory) {
       return _symbol;
   }

}    

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