Solidity

無法呼叫合約函式

  • November 12, 2019

我想訪問契約的餘額(即 0x552F3AfaA0394632f4aEfa9E923fA3e2bbDAF5FE)及其 totalSupply(狀態變數)。我可以訪問這個合約的 balancec ,但是為什麼我不能呼叫它的函式,即getTotalSupply()我有以下程式碼;

async function myContractAddress() {
   myContAddr = '0x552F3AfaA0394632f4aEfa9E923fA3e2bbDAF5FE';
   web3.eth.getBalance(myContAddr).then(console.log);
   tokens = await myContAddr.methods.getTotalSupply().call();
   tokens = tokens.toString(10);
   console.log("Toten supply is : ",tokens);

 }
 myContractAddress();

這是我的錯誤;

(node:6028) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'getTotalSupply' of undefined
   at myContractAddress (C:\Users\jj\Desktop\temp\deploy.js:36:39)
   at C:\Users\jj\Desktop\temp\deploy.js:26:1
   at process._tickCallback (internal/process/next_tick.js:68:7)
(node:6028) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function without a catch
block, or by rejecting a promise which was not handled with .catch(). (rejectio
id: 1)
(node:6028) [DEP0018] DeprecationWarning: Unhandled promise rejections are depr
cated. In the future, promise rejections that are not handled will terminate th
Node.js process with a non-zero exit code.
0 // actually this is my contract balance , which have shown

你做錯了什麼在你的程式碼中myContAddr是字元串,你正在嘗試訪問這個變數的參數。要訪問 .methods.getTotalSupply().call() 您需要使用以下程式碼創建合約實例:

async function myContractAddress() {
   var myContAddr = '0x552F3AfaA0394632f4aEfa9E923fA3e2bbDAF5FE';
   var myContractAbiDefenition = 'CONTRACT_ABI';
   var myContractInstance = new web3.eth.Contract(myContractAbiDefenition, myContAddr);
   tokens = await myContractInstance.methods.getTotalSupply().call();
   console.log("Tokens: ",tokens);
}
myContractAddress();

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