Created
September 6, 2019 19:40
-
-
Save ryanio/131d5ddd47a8c8d21c8137167b352d0f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { gql } from 'apollo-boost'; | |
import { useQuery } from '@apollo/react-hooks'; | |
import web3 from '../lib/web3'; | |
export const GET_TOKEN_BALANCE = gql` | |
query TokenBalance($tokenAddress: Address!, $callData: Bytes!) { | |
block { | |
call(data: { to: $tokenAddress, data: $callData }) { | |
data | |
} | |
} | |
} | |
`; | |
export default function TokenBalance({ forAddress, token }) { | |
const callData = | |
'0x70a08231000000000000000000000000' + forAddress.substring(2); // balanceOf(address) | |
const { loading, error, data } = useQuery(GET_TOKEN_BALANCE, { | |
variables: { tokenAddress: token.address, callData } | |
}); | |
if (loading) return 'Loading balance'; | |
if (error) return error.toString(); | |
const balance = web3.utils.toBN(data.block.call.data); | |
let balanceDecimal = balance; | |
if (token.decimal) { | |
balanceDecimal = balance.div(token.decimal); | |
} | |
return `${balanceDecimal.toLocaleString()} ${token.symbol}`; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment