-
Notifications
You must be signed in to change notification settings - Fork 47
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
adds an
<ObservedBalance/>
component to show the "free" native toke…
…ns of a contract
- Loading branch information
Showing
3 changed files
with
72 additions
and
13 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
// Copyright 2022 @paritytech/contracts-ui authors & contributors | ||
// SPDX-License-Identifier: GPL-3.0-only | ||
|
||
import { useEffect, useState } from 'react'; | ||
import { useApi } from '../../contexts'; | ||
import { Balance } from 'types'; | ||
|
||
const formatBalance = (balance: Balance, decimals = 12, unit?: string) => { | ||
const balanceAsBigInt = balance.toBigInt(); | ||
const prefix = balanceAsBigInt / BigInt(10 ** decimals); | ||
const suffix = balanceAsBigInt - prefix * BigInt(10 ** decimals); | ||
const number = Number(`${prefix.toString()}.${suffix.toString().slice(0, 2)}`); | ||
|
||
return ( | ||
Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format( | ||
number, | ||
) + (unit ? ` ${unit}` : '') | ||
); | ||
}; | ||
|
||
export const ObservedBalance = ({ address }: { address: string }) => { | ||
const { api, tokenDecimals, tokenSymbol } = useApi(); | ||
|
||
const [balance, setBalance] = useState<null | Balance>(null); | ||
useEffect(() => { | ||
const unsubscribePromise = api.query.system.account(address, result => { | ||
setBalance(result.data.free); | ||
}); | ||
|
||
return () => { | ||
unsubscribePromise | ||
.then(unsubscribe => { | ||
unsubscribe(); | ||
}) | ||
.catch(console.error); | ||
}; | ||
}, [address, api]); | ||
|
||
if (!balance) return null; | ||
return formatBalance(balance, tokenDecimals, tokenSymbol); | ||
}; |
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
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