-
Notifications
You must be signed in to change notification settings - Fork 8
/
balance.js
49 lines (38 loc) · 1.14 KB
/
balance.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
window.addEventListener('load', setup)
let account, interval
function render(text) {
console.log('rendering ' + text)
const content = document.querySelector('.content')
content.innerText = text
}
function setup() {
if (typeof window.web3 === 'undefined') {
render('No web3 found, get MetaMask!')
} else {
render('Web3 found, getting balance...')
pollForAccountChange()
}
}
function pollForAccountChange() {
console.log('beginning account change polling...')
if (!interval) {
interval = setInterval(getBalance, 1000)
}
}
function getBalance() {
// console.log('checking balance.')
const newAccount = web3.eth.accounts[0]
if (!newAccount) {
return render('No account selected.')
}
if (newAccount === account) {
return console.log('account unchanged, returning.')
}
account = newAccount
// console.log('getting balance for ' + account)
web3.eth.getBalance(account, (err, balance) => {
if (err) return render(err.message)
const ether = web3.fromWei(balance, 'ether')
render(`Account balance: ${ether.toString()}`)
})
}