@polkadot/types/interfaces#Balance TypeScript Examples
The following examples show how to use
@polkadot/types/interfaces#Balance.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.ts From metamask-snap-polkadot with Apache License 2.0 | 6 votes |
export async function updateAsset(
wallet: Wallet, origin: string, balance: number|string|Balance
): Promise<void> {
const configuration = getConfiguration(wallet);
const asset = getPolkadotAssetDescription(balance, await getAddress(wallet), configuration);
if (!assetState) {
// create polkadot snap asset
await executeAssetOperation(asset, wallet, "add");
} else if (assetState.balance !== asset.balance || assetState.network !== configuration.networkName) {
// update if balance or network changed
await executeAssetOperation(asset, wallet, "update");
}
assetState = {balance: asset.balance, network: configuration.networkName};
}
Example #2
Source File: AvailableCandy.tsx From crust-apps with Apache License 2.0 | 6 votes |
function AvailableDisplay ({ children, className = '', label, params }: Props): React.ReactElement<Props> {
const { api } = useApi();
const allBalances = useCall<Balance>(api.query.candy?.balances, [params]);
return (
<FormatCandy
className={className}
label={label}
value={allBalances}
>
{children}
</FormatCandy>
);
}
Example #3
Source File: Tip.tsx From crust-apps with Apache License 2.0 | 6 votes |
function extractTipState (tip: OpenTip | OpenTipTo225, allAccounts: string[]): TipState {
const closesAt = tip.closes.unwrapOr(null);
let finder: AccountId | null = null;
let deposit: Balance | null = null;
if (isCurrentTip(tip)) {
finder = tip.finder;
deposit = tip.deposit;
} else if (tip.finder.isSome) {
const finderInfo = tip.finder.unwrap();
finder = finderInfo[0];
deposit = finderInfo[1];
}
const values = tip.tips.map(([, value]) => value).sort((a, b) => a.cmp(b));
const midIndex = Math.floor(values.length / 2);
const median = values.length
? values[midIndex]
: BN_ZERO;
return {
closesAt,
deposit,
finder,
isFinder: !!finder && allAccounts.includes(finder.toString()),
isTipped: !!values.length,
isTipper: tip.tips.some(([address]) => allAccounts.includes(address.toString())),
median
};
}
Example #4
Source File: index.tsx From crust-apps with Apache License 2.0 | 6 votes |
function useAddressCalls (api: ApiPromise, address: string, isMain?: boolean) {
const params = useMemo(() => [address], [address]);
const stakeLimit = useCall<BN>(api.query.staking.stakeLimit, params);
const accountInfo = useCall<DeriveAccountInfo>(api.derive.accounts.info, params);
const slashingSpans = useCall<SlashingSpans | null>(!isMain && api.query.staking.slashingSpans, params, transformSlashes);
const activeEraInfo = useCall<ActiveEraInfo>(api.query.staking.activeEra);
const activeEra = activeEraInfo && (JSON.parse(JSON.stringify(activeEraInfo)).index);
const erasStakersStashExposure = useCall<Exposure>(api.query.staking.erasStakers, [activeEra, address]);
const accountIdBonded = useCall<string | null>(api.query.staking.bonded, params, transformBonded);
const controllerActive = useCall<Balance | null>(api.query.staking.ledger, [accountIdBonded], transformLedger);
const erasStakersStash = erasStakersStashExposure && (parseObj(erasStakersStashExposure).others.map((e: { who: any; }) => e.who));
const stakersGuarantees = useCall<Guarantee[]>(api.query.staking.guarantors.multi, [erasStakersStash]);
let totalStaked = new BN(Number(controllerActive).toString());
if (stakersGuarantees) {
for (const stakersGuarantee of stakersGuarantees) {
if (parseObj(stakersGuarantee)) {
for (const target of parseObj(stakersGuarantee)?.targets) {
if (target.who.toString() == address) {
totalStaked = totalStaked?.add(new BN(Number(target.value).toString()));
}
}
}
}
}
return { accountInfo, slashingSpans, totalStaked, stakeLimit, activeEra };
}
Example #5
Source File: Account.tsx From gear-js with GNU General Public License v3.0 | 6 votes |
function AccountProvider({ children }: Props) {
const { api } = useApi();
const [account, setAccount] = useState<Account>();
const getBalance = (balance: Balance) => {
const [value, unit] = balance.toHuman().split(' ');
return { value, unit };
};
const getAccount = (_account: InjectedAccountWithMeta, balance: Balance) => ({
..._account,
balance: getBalance(balance),
decodedAddress: GearKeyring.decodeAddress(_account.address),
});
const switchAccount = (_account: InjectedAccountWithMeta) => {
api?.balance
.findOut(_account.address)
.then((balance) => getAccount(_account, balance))
.then(setAccount);
};
const updateBalance = (balance: Balance) => {
setAccount((prevAccount) => (prevAccount ? { ...prevAccount, balance: getBalance(balance) } : prevAccount));
};
const logout = () => {
setAccount(undefined);
};
const { Provider } = AccountContext;
const value = { account, switchAccount, updateBalance, logout };
return <Provider value={value}>{children}</Provider>;
}
Example #6
Source File: Guaranteeable.tsx From crust-apps with Apache License 2.0 | 6 votes |
function GuaranteeableDisplay ({ params }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const stakeLimit = useCall<Option<Balance>>(api.query.staking.stakeLimit, [params]);
const activeEraInfo = useCall<ActiveEraInfo>(api.query.staking.activeEra);
const activeEra = activeEraInfo && (JSON.parse(JSON.stringify(activeEraInfo)).index);
const accountIdBonded = useCall<string | null>(api.query.staking.bonded, [params], transformBonded);
const controllerActive = useCall<Balance | null>(api.query.staking.ledger, [accountIdBonded], transformLedger);
const erasStakersStashExposure = useCall<Option<Exposure>>(api.query.staking.erasStakers, [activeEra, params]);
const erasStakersStash = erasStakersStashExposure && (parseObj(erasStakersStashExposure).others.map((e: { who: any; }) => e.who));
const stakersGuarantees = useCall<Guarantee[]>(api.query.staking.guarantors.multi, [erasStakersStash]);
let totalStaked = new BN(Number(controllerActive).toString());
if (stakersGuarantees) {
for (const stakersGuarantee of stakersGuarantees) {
if (parseObj(stakersGuarantee)) {
for (const target of parseObj(stakersGuarantee)?.targets) {
if (target.who.toString() == params?.toString()) {
totalStaked = totalStaked?.add(new BN(Number(target.value).toString()));
}
}
}
}
}
return (
<>
<span className='highlight'>{t<string>('total stakes')} {formatBalance(totalStaked, { withUnit: true })} / {t<string>('stake limit')} { formatBalance(new BN(Number(stakeLimit).toString()))}</span>
</>
);
}
Example #7
Source File: Member.tsx From crust-apps with Apache License 2.0 | 6 votes |
function renderJSXPayouts (bestNumber: BN, payouts: [BlockNumber, Balance][]): JSX.Element[] { return payouts.map(([bn, value], index) => ( <div className='payout' key={index} > <Columar> <Columar.Column> <FormatBalance value={value} /> </Columar.Column> <Columar.Column> <div>#{formatNumber(bn)}</div> {bn.gt(bestNumber) && ( <BlockToTime key={index} value={bn.sub(bestNumber)} /> )} </Columar.Column> </Columar> </div> )); }
Example #8
Source File: Account.tsx From gear-js with GNU General Public License v3.0 | 6 votes |
function AccountProvider({ children }: ProviderProps) {
const { api } = useContext(ApiContext); // сircular dependency fix
const [account, setAccount] = useState<Account>();
const login = (_account: Account) => {
localStorage.setItem(LOCAL_STORAGE.ACCOUNT, _account.address);
setAccount(_account);
};
const switchAccount = (_account: InjectedAccountWithMeta) => {
api?.balance
.findOut(_account.address)
.then((balance) => getAccount(_account, balance))
.then(login);
};
const updateBalance = (balance: Balance) => {
setAccount((prevAccount) => (prevAccount ? { ...prevAccount, balance: getBalance(balance) } : prevAccount));
};
const logout = () => {
localStorage.removeItem(LOCAL_STORAGE.ACCOUNT);
setAccount(undefined);
};
const { Provider } = AccountContext;
const value = { account, switchAccount, updateBalance, logout };
return <Provider value={value}>{children}</Provider>;
}
Example #9
Source File: Provider.tsx From gear-js with GNU General Public License v3.0 | 6 votes |
function AccountProvider({ children }: Props) {
const { api } = useApi();
const [account, setAccount] = useState<Account>();
const getBalance = (balance: Balance) => {
const [value, unit] = balance.toHuman().split(' ');
return { value, unit };
};
const getAccount = (_account: InjectedAccountWithMeta, balance: Balance) => ({
..._account,
balance: getBalance(balance),
decodedAddress: GearKeyring.decodeAddress(_account.address),
});
const switchAccount = (_account: InjectedAccountWithMeta) => {
api?.balance
.findOut(_account.address)
.then((balance) => getAccount(_account, balance))
.then(setAccount);
};
const updateBalance = (balance: Balance) => {
setAccount((prevAccount) => (prevAccount ? { ...prevAccount, balance: getBalance(balance) } : prevAccount));
};
const logout = () => {
setAccount(undefined);
};
const { Provider } = AccountContext;
const value = { account, switchAccount, updateBalance, logout };
return <Provider value={value}>{children}</Provider>;
}
Example #10
Source File: mappingHandlers.ts From tutorials-simple-aggregation_v2 with MIT License | 6 votes |
export async function handleStakingRewarded(event: SubstrateEvent): Promise<void> {
const {event: {data: [account, newReward]}} = event;
const entity = new StakingReward(`${event.block.block.header.number}-${event.idx.toString()}`);
entity.accountId = account.toString();
entity.balance = (newReward as Balance).toBigInt();
entity.date = event.block.timestamp;
entity.blockHeight = event.block.block.header.number.toNumber();
await entity.save();
}
Example #11
Source File: mappingHandlers.ts From tutorials-simple-aggregation_v2 with MIT License | 6 votes |
export async function handleSumRewarded(event: SubstrateEvent): Promise<void> {
const {event: {data: [account, newReward]}} = event;
let entity = await SumReward.get(account.toString());
if (entity === undefined){
entity = createSumReward(account.toString());
}
entity.totalReward = entity.totalReward + (newReward as Balance).toBigInt();
entity.blockheight = event.block.block.header.number.toNumber();
await entity.save();
}
Example #12
Source File: index.ts From metamask-snap-polkadot with Apache License 2.0 | 6 votes |
export function getPolkadotAssetDescription(
balance: number|string|Balance, address: string, configuration: SnapConfig
): Asset {
return {
balance: formatBalance(balance, {decimals: configuration.unit.decimals, withSi: true, withUnit: false}),
customViewUrl: configuration.unit.customViewUrl || "",
decimals: 0,
identifier: POLKADOT_SNAP_ASSET_IDENTIFIER,
image: configuration.unit.image || "",
symbol: configuration.unit.symbol,
};
}
Example #13
Source File: democracy_proposals.ts From commonwealth with GNU General Public License v3.0 | 5 votes |
// Loads all proposals and referendums currently present in the democracy module
public async init(ChainInfo: SubstrateChain, Accounts: SubstrateAccounts): Promise<void> {
this._disabled = !ChainInfo.api.query.democracy;
if (this._initializing || this._initialized || this.disabled) return;
this._initializing = true;
this._Chain = ChainInfo;
this._Accounts = Accounts;
// load server proposals
const entities = this.app.chain.chainEntities.store.getByType(SubstrateTypes.EntityKind.DemocracyProposal);
entities.forEach((e) => this._entityConstructor(e));
// save parameters
this._minimumDeposit = this._Chain.coins(ChainInfo.api.consts.democracy.minimumDeposit as Balance);
this._launchPeriod = +(ChainInfo.api.consts.democracy.launchPeriod as BlockNumber);
this._cooloffPeriod = +(ChainInfo.api.consts.democracy.cooloffPeriod as BlockNumber);
// register new chain-event handlers
this.app.chain.chainEntities.registerEntityHandler(
SubstrateTypes.EntityKind.DemocracyProposal, (entity, event) => {
this.updateProposal(entity, event);
}
);
this.app.chain.chainEntities.registerEntityHandler(
SubstrateTypes.EntityKind.DemocracyPreimage, (entity, event) => {
if (event.data.kind === SubstrateTypes.EventKind.PreimageNoted) {
const proposal = this.getByHash(entity.typeId);
if (proposal) proposal.update(event);
}
}
);
// fetch proposals from chain
const events = await this.app.chain.chainEntities.fetchEntities(
this.app.chain.id,
chainToEventNetwork(this.app.chain.meta),
() => this._Chain.fetcher.fetchDemocracyProposals(this.app.chain.block.height)
);
const hashes = events.map((e) => e.data.proposalHash);
await this.app.chain.chainEntities.fetchEntities(
this.app.chain.id,
chainToEventNetwork(this.app.chain.meta),
() => this._Chain.fetcher.fetchDemocracyPreimages(hashes)
);
const lastTabledWasExternal = await ChainInfo.api.query.democracy.lastTabledWasExternal();
const nextExternal = await ChainInfo.api.query.democracy.nextExternal();
this._lastTabledWasExternal = lastTabledWasExternal.valueOf();
this._nextExternal = nextExternal.unwrapOr(null);
this._initialized = true;
this._initializing = false;
}
Example #14
Source File: index.ts From gear-js with GNU General Public License v3.0 | 5 votes |
getAccount = (_account: InjectedAccountWithMeta, balance: Balance) => ({
..._account,
balance: getBalance(balance),
decodedAddress: GearKeyring.decodeAddress(_account.address),
})
Example #15
Source File: index.ts From gear-js with GNU General Public License v3.0 | 5 votes |
getBalance = (balance: Balance) => {
const [value, unit] = balance.toHuman().split(' ');
return { value, unit };
}
Example #16
Source File: migrateCouncillorValidatorFlags.ts From commonwealth with GNU General Public License v3.0 | 5 votes |
export default async function (models, chain?: string): Promise<void> {
// 1. fetch the node and url of supported/selected chains
log.info('Fetching node info for chain entity migrations...');
const whereOption = chain ? { chain } : {};
const nodes = await models.ChainNode.findAll({
where: whereOption,
include: [
{
model: models.Chain,
where: {
active: true,
has_chain_events_listener: true,
base: ChainBase.Substrate,
},
required: true,
},
],
});
if (!nodes) {
throw new Error('no nodes found for chain entity migration');
}
// 2. for each node, fetch councillors and validators
for (const node of nodes) {
log.info(`Fetching and migrating councillor/validator flags for ${node.chain}.`);
const flagsHandler = new UserFlagsHandler(models, node.chain);
const nodeUrl = constructSubstrateUrl(node.url);
try {
const api = await SubstrateEvents.createApi(nodeUrl, node.Chain.substrate_spec);
log.info('Fetching councillor and validator lists...');
const validators = await api.derive.staking?.validators();
const section = api.query.electionsPhragmen ? 'electionsPhragmen' : 'elections';
const councillors = await api.query[section].members<Vec<[ AccountId, Balance ] & Codec>>();
await flagsHandler.forceSync(
councillors.map(([ who ]) => who.toString()),
validators ? validators.validators.map((v) => v.toString()) : [],
);
} catch (e) {
log.error(`Failed to migrate flags for ${node.chain}: ${e.message}`);
}
}
}
Example #17
Source File: useBalance.ts From parity-bridges-ui with GNU General Public License v3.0 | 5 votes |
initValues = {
chainTokens: '-',
formattedBalance: '0',
free: new BN(ZERO) as Balance
}
Example #18
Source File: DemocracyLocks.tsx From subscan-multisig-react with Apache License 2.0 | 5 votes |
// group by header & details
// - all unlockable together
// - all ongoing together
// - unlocks are displayed individually
function groupLocks(t: TFunction, bestNumber: BN, locks: Partial<DeriveDemocracyLock>[] = []): State {
return {
maxBalance: bnMax(...locks.map(({ balance }) => balance).filter((b): b is Balance => !!b)),
sorted: locks
.map((info): [Partial<DeriveDemocracyLock>, BN] => [
info,
info.unlockAt && info.unlockAt.gt(bestNumber) ? info.unlockAt.sub(bestNumber) : BN_ZERO,
])
.sort((a, b) => (a[0].referendumId || BN_ZERO).cmp(b[0].referendumId || BN_ZERO))
.sort((a, b) => a[1].cmp(b[1]))
.sort((a, b) => (a[0].isFinished === b[0].isFinished ? 0 : a[0].isFinished ? -1 : 1))
.reduce(
(sorted: Entry[], [{ balance, isDelegated, isFinished = false, referendumId, vote }, blocks]): Entry[] => {
const isCountdown = blocks.gt(BN_ZERO);
const header =
referendumId && vote ? (
<div>
#{referendumId.toString()} {formatBalance(balance, { forceUnit: '-' })} {vote.conviction.toString()}
{isDelegated && '/d'}
</div>
) : (
<div>{t('Prior locked voting')}</div>
);
const prev = sorted.length ? sorted[sorted.length - 1] : null;
if (!prev || isCountdown || isFinished !== prev.isFinished) {
sorted.push({
details: (
<div className="faded">
{isCountdown ? (
<BlockToTime
label={`${t<string>('{{blocks}} blocks', { replace: { blocks: formatNumber(blocks) } })}, `}
value={blocks}
/>
) : isFinished ? (
t<string>('lock expired')
) : (
t<string>('ongoing referendum')
)}
</div>
),
headers: [header],
isCountdown,
isFinished,
});
} else {
prev.headers.push(header);
}
return sorted;
},
[]
),
};
}
Example #19
Source File: Account.tsx From gear-js with GNU General Public License v3.0 | 5 votes |
function AccountProvider({ children }: Props) {
const { api } = useApi();
const [accounts, setAccounts] = useState<InjectedAccountWithMeta[]>();
const [account, setAccount] = useState<Account>();
const getAccounts = (extensions: InjectedExtension[]) => (extensions.length > 0 ? web3Accounts() : undefined);
useEffect(() => {
setTimeout(() => {
web3Enable('Gear App').then(getAccounts).then(setAccounts);
}, 300);
}, []);
const getBalance = (balance: Balance) => {
const [value, unit] = balance.toHuman().split(' ');
return { value, unit };
};
const getAccount = (_account: InjectedAccountWithMeta, balance: Balance) => ({
..._account,
balance: getBalance(balance),
decodedAddress: GearKeyring.decodeAddress(_account.address),
});
const switchAccount = (_account: InjectedAccountWithMeta) => {
api?.balance
.findOut(_account.address)
.then((balance) => getAccount(_account, balance))
.then(setAccount);
};
const logout = () => {
setAccount(undefined);
};
useEffect(() => {
const loggedInAccount = accounts?.find(isLoggedIn);
if (loggedInAccount) switchAccount(loggedInAccount);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [api, accounts]);
const updateBalance = (balance: Balance) => {
setAccount((prevAccount) => ({ ...prevAccount!, balance: getBalance(balance) }));
};
useEffect(() => {
let unsub: UnsubscribePromise | undefined;
if (account) {
unsub = api?.gearEvents.subscribeToBalanceChange(account.address, updateBalance);
}
return () => {
if (unsub) unsub.then((callback) => callback());
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [api, account]);
const { Provider } = AccountContext;
const value = { accounts, account, switchAccount, logout };
return <Provider value={value}>{children}</Provider>;
}
Example #20
Source File: Balance.ts From gear-js with GNU General Public License v3.0 | 5 votes |
async findOut(publicKey: string): Promise<Balance> {
const { data: balance } = (await this.api.query.system.account(publicKey)) as ISystemAccountInfo;
return this.api.createType('Balance', balance.free) as Balance;
}
Example #21
Source File: useOwnEraRewards.ts From subscan-multisig-react with Apache License 2.0 | 5 votes |
function getValRewards(
api: ApiPromise,
validatorEras: ValidatorWithEras[],
erasPoints: DeriveEraPoints[],
erasRewards: DeriveEraRewards[]
): State {
const allRewards: Record<string, DeriveStakerReward[]> = {};
validatorEras.forEach(({ eras, stashId }): void => {
eras.forEach((era): void => {
const eraPoints = erasPoints.find((p) => p.era.eq(era));
const eraRewards = erasRewards.find((r) => r.era.eq(era));
if (eraPoints?.eraPoints.gt(BN_ZERO) && eraPoints?.validators[stashId] && eraRewards) {
const reward = eraPoints.validators[stashId].mul(eraRewards.eraReward).div(eraPoints.eraPoints);
if (!reward.isZero()) {
const total = api.createType<Balance>('Balance', reward);
if (!allRewards[stashId]) {
allRewards[stashId] = [];
}
allRewards[stashId].push({
era,
eraReward: eraRewards.eraReward,
isEmpty: false,
isValidator: true,
nominating: [],
validators: {
[stashId]: {
total,
value: total,
},
},
});
}
}
});
});
return {
allRewards,
isLoadingRewards: false,
rewardCount: Object.values(allRewards).filter((rewards) => rewards.length !== 0).length,
};
}
Example #22
Source File: balance.ts From crust-apps with Apache License 2.0 | 5 votes |
export function balanceOf (number: number): Balance {
return new TypeRegistry().createType('Balance', new BN(number));
}
Example #23
Source File: Summary.tsx From crust-apps with Apache License 2.0 | 5 votes |
transformReward = {
transform: (optBalance: Option<Balance>) => optBalance.unwrapOrDefault()
}
Example #24
Source File: index.tsx From crust-apps with Apache License 2.0 | 5 votes |
transformLedger = {
transform: (value: Option<StakingLedger>): Balance | null =>
value.isSome
? value.unwrap().active.unwrap()
: null
}
Example #25
Source File: Guaranteeable.tsx From crust-apps with Apache License 2.0 | 5 votes |
transformLedger = {
transform: (value: Option<StakingLedger>): Balance | null =>
value.isSome
? value.unwrap().active.unwrap()
: null
}
Example #26
Source File: Summary.tsx From crust-apps with Apache License 2.0 | 5 votes |
function Summary ({ auctionInfo, className, lastWinner, numAuctions }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const bestNumber = useBestNumber();
const totalIssuance = useCall<Balance>(api.query.balances?.totalIssuance);
const [period, ending] = auctionInfo || [];
return (
<SummaryBox className={className}>
<section>
<CardSummary label={t<string>('auctions')}>
{formatNumber(numAuctions)}
</CardSummary>
{period && (
<CardSummary label={t<string>('period')}>
{formatNumber(period)}
</CardSummary>
)}
</section>
{auctionInfo && (
<>
{totalIssuance && lastWinner && (
<CardSummary
label={t<string>('total')}
progress={{
hideValue: true,
total: totalIssuance,
value: lastWinner.total,
withTime: true
}}
>
<FormatBalance
value={lastWinner.total}
withSi
/>
</CardSummary>
)}
<section>
{bestNumber && ending && (
bestNumber.lt(ending)
? (
<CardSummary
label={t<string>('end period at')}
progress={{
hideGraph: true,
total: ending,
value: bestNumber,
withTime: true
}}
>
#{formatNumber(ending)}
</CardSummary>
)
: (
<CardSummary
label={t<string>('ending period')}
progress={{
total: api.consts.auctions.endingPeriod as BlockNumber,
value: bestNumber.sub(ending),
withTime: true
}}
></CardSummary>
)
)}
</section>
</>
)}
</SummaryBox>
);
}
Example #27
Source File: useBalance.ts From crust-apps with Apache License 2.0 | 5 votes |
export function useBalance (accountId: string | null): Balance | undefined {
const { api } = useApi();
return useCall<DeriveBalancesAll>(api.derive.balances.all, [accountId])?.availableBalance;
}
Example #28
Source File: IdentitySub.tsx From crust-apps with Apache License 2.0 | 5 votes |
transformIds = {
transform: ([, ids]: ITuple<[Balance, Vec<AccountId>]>) => ids.map((a) => a.toString())
}
Example #29
Source File: api.ts From community-repo with GNU General Public License v3.0 | 5 votes |
getCouncilPayout = (
api: ApiPromise,
hash: Hash
): Promise<Balance> => api.query.council.amountPerPayout.at(hash)