import JSBI from 'jsbi' ; import { useState , useEffect } from 'react' ; import { Account , EthereumProvider , Balance } from '../types' ; import { pollEvery , getAccountBalance } from '../utils' ; const NO_BALANCE = '-1' ; export function useWalletBalance ( { account , ethereum , pollBalanceInterval , } ) { const [ balance , setBalance ] = useState < Balance > ( NO_BALANCE ) ; useEffect ( ( ) => { if ( ! account || ! ethereum ) { return ; } let cancel = false ; const pollBalance = pollEvery < Balance , any > ( ( account , ethereum , onUpdate ) => { let lastBalance = NO_BALANCE ; return { async request ( ) { return getAccountBalance ( ethereum , account ) . then ( ( value ) => { return value ? JSBI . BigInt ( value ) . toString ( ) : NO_BALANCE ; } ) . catch ( ( ) => NO_BALANCE ) ; } , onResult ( balance ) { if ( ! cancel && balance !== lastBalance ) { lastBalance = balance ; onUpdate ( balance ) ; } } } ; } , pollBalanceInterval ) ; const stopPollingBalance = pollBalance ( account , ethereum , setBalance ) ; return ( ) => { cancel = true ; stopPollingBalance ( ) ; setBalance ( NO_BALANCE ) ; } ; } , [ account , ethereum , pollBalanceInterval ] ) ; return balance ; }