Truffle

類型錯誤:balance.toNumber 不是函式

  • April 3, 2022

我需要檢查呼叫 selfDestruct 時令牌是否沒有餘額,但顯示錯誤 balance.toNumber 不是測試文件中的函式。

DappTokenSale.sol

function endSale() public {
 //Require Admin (Only Admin can end the Sale)
 require(msg.sender == admin);

 //Transfer remaining dapp tokens to admin
 require(tokenContract.transfer(admin, tokenContract.balanceOf((address(this)))));

 // Destroy contract at the end - transfer remaining token to the admin
 admin.transfer(address(this).balance);

DapptokenSale.js

(此測試程式碼僅用於admin.transfer(address(this).balance);

balance = web3.eth.getBalance(tokenSaleInstance.address);
assert.equal(balance.toNumber(), 0);

web3.eth.getBalance返回一個 Promise,實際餘額為 Wei a 字元串。要獲得餘額,您可以使用Promise.then()or async/await

web3.eth.getBalance(address)
 .then(balance => {
   // You can use balance here
   console.log(balance);
 })
 .catch(console.error);

// or

const getBalance = async () => {
 const balance = await web3.eth.getBalance(address);

 // You can use balance here
 console.log(balance);
}

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