Web3js

使用 fromWei 獲取 Metamask 賬戶餘額

  • August 15, 2020

使用 web3 javascript 程式碼在 Metamask 中獲取所選帳戶的餘額並以 html 顯示,

web3.eth.getCoinbase(function(err, account) {
 if (err === null) { 
   App.account = account;
   $("#account").text(account);
   web3.eth.getBalance(account, function(err, balance) {
     if (err === null) {
       $("#accountBalance").text(web3.fromWei(balance, "ether") + " ETH");
     }
   });
 }
});

現在我正在使用 angular 4 嘗試將上面的程式碼轉換為打字稿。

const Web3 = require('web3');
const contract = require('truffle-contract');
const myBettingArtifact = 
require('../../../build/contracts/Test.json');
declare var window: any;
...
account: any;
accounts: any;
web3: any;
balance: number;

this.web3.eth.getAccounts((err, accs) => {      
 if (err != null || accs.length === 0) {
   return;
 }
 this.accounts = accs;
 this.account = this.accounts[0];

 this.web3.eth.getBalance(this.account, function(err, balance) {
   this.balance = this.web3.fromWei(balance, "ether") + " ETH"        
 });
}); 

但是我收到一個錯誤

> > 未擷取的類型錯誤:無法讀取未定義的屬性“fromWei” > > >

這裡有什麼問題?

顯然,this在您傳遞給getBalance. 嘗試用粗箭頭函式替換它,它將外部值綁定this到內部範圍。

this.web3.eth.getBalance(this.account, (err, balance) => {
 this.balance = this.web3.fromWei(balance, "ether") + " ETH"
});

web3.eth.getBalance(this.userWalletAddress, (err, balance) => { this.userBalance = web3.utils.fromWei (balance, “ether”) + “ETH” });

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