diff --git a/app/src/js/components/Form/Balance.tsx b/app/src/js/components/Form/Balance.tsx index 2d04e73..0ccc5dd 100644 --- a/app/src/js/components/Form/Balance.tsx +++ b/app/src/js/components/Form/Balance.tsx @@ -7,14 +7,39 @@ import { ChainId } from '../MetamaskConnect'; const Balance = () => { const { account, ethereum, chainId } = useConnectedMetaMask(); - const [balance, setBalance] = React.useState(0); + const [balance, setBalance] = React.useState('0'); + const [decimals, setDecimals] = React.useState(0); React.useEffect(() => { const client = new Web3Client(account, ethereum, chainId as ChainId); - client.balanceOf(account).then((balance) => { - setBalance(balance); - }); - }); + client + .balanceOf(account) + .then((accountBalance) => { + console.log('balance', accountBalance); + // put comma in `decimals` position + const balanceStr = accountBalance.toString(); + const balanceArr = balanceStr.split(''); + balanceArr.splice(balanceArr.length - decimals, 0, ','); + console.log(balanceArr); + setBalance(balanceArr.join('')); + }) + .catch((e) => { + console.log('failed to get balance', e); + }); + }, [decimals]); + + React.useEffect(() => { + const client = new Web3Client(account, ethereum, chainId as ChainId); + client + .decimals() + .then((decs) => { + console.log('decimals', decs); + setDecimals(Number(decs)); + }) + .catch((e) => { + console.log('failed to get balance', e); + }); + }, []); return ( diff --git a/app/src/js/web3/Web3Client.ts b/app/src/js/web3/Web3Client.ts index 434e2e4..1717408 100644 --- a/app/src/js/web3/Web3Client.ts +++ b/app/src/js/web3/Web3Client.ts @@ -33,11 +33,16 @@ export default class Web3Client { .send({ from: this.address }); } - async balanceOf(address: string): Promise { + async balanceOf(address: string): Promise { const contract = this.getContract(); return contract.methods.balanceOf(address).call(); } + async decimals(): Promise { + const contract = this.getContract(); + return contract.methods.decimals().call(); + } + private getContract() { return new this.web3.eth.Contract(ABI, CONTRACT_ADDRESS[this.chainId]); }