Use BN_{BILLION, MILLION} constants (#4577)

* Use BN_{BILLIN, MILLION} constants

* BN_ONE

* Update packages/page-treasury/src/Overview/ProposalCreate.tsx

* Update packages/page-staking/src/Payouts/useStakerPayouts.ts

* Additional

* Update packages/page-democracy/src/Overview/Summary.tsx

* Additional

* Additional

* Re-apply

* Cleanups

* Apply suggestions from code review
This commit is contained in:
Jaco Greeff 2021-02-03 10:59:37 +01:00 committed by GitHub
parent 559df52d7b
commit fd0ceaff0d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
31 changed files with 68 additions and 65 deletions

View File

@ -12,7 +12,7 @@ import { checkAddress } from '@polkadot/phishing';
import { InputAddress, InputBalance, MarkError, MarkWarning, Modal, Toggle, TxButton } from '@polkadot/react-components';
import { useApi, useCall } from '@polkadot/react-hooks';
import { Available } from '@polkadot/react-query';
import { BN_ZERO, isFunction } from '@polkadot/util';
import { BN_HUNDRED, BN_ZERO, isFunction } from '@polkadot/util';
import { useTranslation } from '../translate';
@ -65,7 +65,7 @@ function Transfer ({ className = '', onClose, recipientId: propRecipientId, send
.transfer(toId, balances.availableBalance)
.paymentInfo(fromId)
.then(({ partialFee }): void => {
const adjFee = partialFee.muln(110).divn(100);
const adjFee = partialFee.muln(110).div(BN_HUNDRED);
const maxTransfer = balances.availableBalance.sub(adjFee);
setMaxTransfer(

View File

@ -8,6 +8,7 @@ import BN from 'bn.js';
import React from 'react';
import { AddressSmall } from '@polkadot/react-components';
import { BN_HUNDRED } from '@polkadot/util';
import VotingSummary from './Voting/VotingSummary';
import BountyInfo from './BountyInfo';
@ -30,7 +31,7 @@ function BountyInfos ({ beneficiary, blocksUntilUpdate, proposals, status }: Pro
const { bountyUpdatePeriod } = useBounties();
const blocksPercentageLeftToShowWarning = bountyUpdatePeriod?.muln(BLOCKS_PERCENTAGE_LEFT_TO_SHOW_WARNING).divn(100);
const blocksPercentageLeftToShowWarning = bountyUpdatePeriod?.muln(BLOCKS_PERCENTAGE_LEFT_TO_SHOW_WARNING).div(BN_HUNDRED);
const blocksToShowWarning = blocksPercentageLeftToShowWarning ?? BLOCKS_LEFT_TO_SHOW_WARNING;
return (

View File

@ -3,6 +3,8 @@
import BN from 'bn.js';
import { BN_MILLION } from '@polkadot/util';
export function permillOf (value: BN, perMill: BN): BN {
return value.mul(perMill).div(new BN(1_000_000));
return value.mul(perMill).div(BN_MILLION);
}

View File

@ -81,7 +81,7 @@ function createDispatches (bestNumber: BlockNumber, blockTime: number, dispatche
function createReferendums (bestNumber: BlockNumber, blockTime: number, referendums: DeriveReferendumExt[]): [EntryType, EntryInfo[]][] {
return referendums.reduce((result: [EntryType, EntryInfo[]][], { index, status }): [EntryType, EntryInfo[]][] => {
const enactBlocks = status.end.add(status.delay).sub(bestNumber);
const voteBlocks = status.end.sub(bestNumber).subn(1);
const voteBlocks = status.end.sub(bestNumber).isub(BN_ONE);
result.push(['referendumVote', [{
...newDate(voteBlocks, blockTime),
@ -110,7 +110,7 @@ function createStakingInfo (bestNumber: BlockNumber, blockTime: number, sessionI
.filter(([, values]) => values.length)
.map(([key]): EntryInfo => {
const eraIndex = key.args[0];
const blockProgress = sessionInfo.activeEra.sub(eraIndex).subn(1).mul(sessionInfo.eraLength).add(sessionInfo.eraProgress);
const blockProgress = sessionInfo.activeEra.sub(eraIndex).isub(BN_ONE).imul(sessionInfo.eraLength).iadd(sessionInfo.eraProgress);
const blocks = slashDuration.sub(blockProgress);
return {

View File

@ -13,7 +13,7 @@ import { ContractPromise } from '@polkadot/api-contract';
import { Button, Dropdown, Expander, InputAddress, InputBalance, Modal, Toggle, TxButton } from '@polkadot/react-components';
import { useAccountId, useDebounce, useFormField, useToggle } from '@polkadot/react-hooks';
import { Available } from '@polkadot/react-query';
import { BN_ZERO } from '@polkadot/util';
import { BN_ONE, BN_ZERO } from '@polkadot/util';
import { InputMegaGas, Params } from '../shared';
import { useTranslation } from '../translate';
@ -30,7 +30,7 @@ interface Props {
onClose: () => void;
}
const MAX_CALL_WEIGHT = new BN(5_000_000_000_000).subn(1);
const MAX_CALL_WEIGHT = new BN(5_000_000_000_000).isub(BN_ONE);
function Call ({ className = '', contract, messageIndex, onCallResult, onChangeMessage, onClose }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();

View File

@ -8,7 +8,7 @@ import React, { useEffect, useMemo, useState } from 'react';
import styled from 'styled-components';
import { InputNumber, Toggle } from '@polkadot/react-components';
import { BN_ZERO } from '@polkadot/util';
import { BN_MILLION, BN_ONE, BN_ZERO } from '@polkadot/util';
import { useTranslation } from '../translate';
@ -20,15 +20,13 @@ interface Props {
weight: UseWeight;
}
const MEGA = new BN(1_000_000);
function InputMegaGas ({ className, estimatedWeight, help, isCall, weight: { executionTime, isValid, megaGas, percentage, setIsEmpty, setMegaGas } }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const [withEstimate, setWithEstimate] = useState(true);
const estimatedMg = useMemo(
() => estimatedWeight
? estimatedWeight.div(MEGA).iaddn(1)
? estimatedWeight.div(BN_MILLION).iadd(BN_ONE)
: null,
[estimatedWeight]
);

View File

@ -8,9 +8,7 @@ import BN from 'bn.js';
import { useCallback, useMemo, useState } from 'react';
import { useApi, useBlockTime } from '@polkadot/react-hooks';
import { BN_TEN, BN_ZERO } from '@polkadot/util';
const BN_MILLION = new BN(1_000_000);
import { BN_MILLION, BN_TEN, BN_ZERO } from '@polkadot/util';
export default function useWeight (): UseWeight {
const { api } = useApi();

View File

@ -11,7 +11,7 @@ import styled from 'styled-components';
import { Badge, Button, Icon, LinkExternal } from '@polkadot/react-components';
import { useAccounts, useApi, useCall } from '@polkadot/react-hooks';
import { BlockToTime } from '@polkadot/react-query';
import { formatNumber, isBoolean } from '@polkadot/util';
import { BN_ONE, formatNumber, isBoolean } from '@polkadot/util';
import { useTranslation } from '../translate';
import useChangeCalc from '../useChangeCalc';
@ -82,7 +82,7 @@ function Referendum ({ className = '', value: { allAye, allNay, image, imageHash
}
const enactBlock = status.end.add(status.delay);
const remainBlock = status.end.sub(bestNumber).subn(1);
const remainBlock = status.end.sub(bestNumber).isub(BN_ONE);
return (
<tr className={className}>

View File

@ -8,7 +8,7 @@ import React, { useMemo } from 'react';
import { Expander } from '@polkadot/react-components';
import { FormatBalance } from '@polkadot/react-query';
import { formatNumber } from '@polkadot/util';
import { BN_TEN, formatNumber } from '@polkadot/util';
import { useTranslation } from '../translate';
import ReferendumVote from './ReferendumVote';
@ -30,8 +30,8 @@ function ReferendumVotes ({ change, className, count, isAye, isWinning, total, v
const sorted = useMemo(
() => votes.sort((a, b) => {
const ta = a.balance.muln(LOCKS[a.vote.conviction.toNumber()]).divn(10);
const tb = b.balance.muln(LOCKS[b.vote.conviction.toNumber()]).divn(10);
const ta = a.balance.muln(LOCKS[a.vote.conviction.toNumber()]).div(BN_TEN);
const tb = b.balance.muln(LOCKS[b.vote.conviction.toNumber()]).div(BN_TEN);
return tb.cmp(ta);
}),

View File

@ -6,7 +6,7 @@ import React from 'react';
import { CardSummary, SummaryBox } from '@polkadot/react-components';
import { useApi, useCall } from '@polkadot/react-hooks';
import { formatNumber } from '@polkadot/util';
import { BN_ONE, formatNumber } from '@polkadot/util';
import { useTranslation } from '../translate';
@ -46,7 +46,7 @@ function Summary ({ referendumCount }: Props): React.ReactElement<Props> {
label={t<string>('launch period')}
progress={{
total: api.consts.democracy.launchPeriod,
value: bestNumber.mod(api.consts.democracy.launchPeriod).addn(1),
value: bestNumber.mod(api.consts.democracy.launchPeriod).iadd(BN_ONE),
withTime: true
}}
/>

View File

@ -9,7 +9,7 @@ import React from 'react';
import { CardSummary } from '@polkadot/react-components';
import { useApi, useCall } from '@polkadot/react-hooks';
import { Elapsed } from '@polkadot/react-query';
import { formatNumber } from '@polkadot/util';
import { BN_ONE, formatNumber } from '@polkadot/util';
import { useTranslation } from './translate';
@ -36,7 +36,7 @@ function SummarySession ({ className, withEra = true, withSession = true }: Prop
{sessionInfo && (
<>
{withSession && (
sessionInfo.sessionLength.gtn(1)
sessionInfo.sessionLength.gt(BN_ONE)
? (
<CardSummary
className={className}
@ -56,7 +56,7 @@ function SummarySession ({ className, withEra = true, withSession = true }: Prop
)
)}
{forcing && !forcing.isForceNone && withEra && (
sessionInfo.sessionLength.gtn(1)
sessionInfo.sessionLength.gt(BN_ONE)
? (
<CardSummary
className={className}

View File

@ -11,7 +11,7 @@ import React, { useMemo } from 'react';
import { Badge } from '@polkadot/react-components';
import { useApi, useCall, useCallMulti, useParaApi } from '@polkadot/react-hooks';
import { BlockToTime } from '@polkadot/react-query';
import { formatNumber } from '@polkadot/util';
import { BN_ONE, formatNumber } from '@polkadot/util';
import { getChainLink, sliceHex } from '../util';
@ -81,7 +81,7 @@ function Parachain ({ bestNumber, className = '', id, isScheduled, lastBacked, l
const blockDelay = useMemo(
() => bestNumber && (
lastRelayNumber
? bestNumber.sub(lastRelayNumber).subn(1)
? bestNumber.sub(lastRelayNumber).isub(BN_ONE)
: paraInfo.watermark
? bestNumber.sub(paraInfo.watermark)
: undefined

View File

@ -8,7 +8,7 @@ import React, { useCallback, useState } from 'react';
import { Button, Input, InputAddress, InputBalance, InputFile, InputNumber, InputWasm, MarkWarning, Modal, TxButton } from '@polkadot/react-components';
import { useApi } from '@polkadot/react-hooks';
import { BN_TEN, compactAddLength } from '@polkadot/util';
import { BN_TEN, BN_THOUSAND, compactAddLength } from '@polkadot/util';
import { useTranslation } from '../translate';
@ -50,7 +50,7 @@ function Propose ({ className, onClose }: Props): React.ReactElement<Props> {
const [accountId, setAccountId] = useState<string | null>(null);
const [name, setName] = useState('');
const [paraId, setParaId] = useState(() => new BN(Date.now() % 131072));
const [balance, setBalance] = useState(() => new BN(1000).mul(BN_TEN.pow(new BN(api.registry.chainDecimals[0]))));
const [balance, setBalance] = useState(() => BN_THOUSAND.mul(BN_TEN.pow(new BN(api.registry.chainDecimals[0]))));
const [validators, setValidators] = useState<string[]>(['']);
const [{ isWasmValid, wasm }, setWasm] = useState<CodeState>({ isWasmValid: false, wasm: null });
const [genesisState, setGenesisState] = useState<Uint8Array | null>(null);

View File

@ -13,7 +13,7 @@ import styled from 'styled-components';
import { Button, Columar, InputAddress, Progress, Spinner, Tabs, Toggle, TxButton } from '@polkadot/react-components';
import { useApi, useCall } from '@polkadot/react-hooks';
import { BlockToTime, FormatBalance } from '@polkadot/react-query';
import { BN_ONE, BN_ZERO, bnMax, formatBalance, formatNumber } from '@polkadot/util';
import { BN_MILLION, BN_ONE, BN_ZERO, bnMax, formatBalance, formatNumber } from '@polkadot/util';
import { useTranslation } from './translate';
@ -27,8 +27,6 @@ interface Turnout {
voted: BN;
}
const DIV = new BN(1_000_000);
function PollApp ({ basePath, className }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
@ -53,7 +51,7 @@ function PollApp ({ basePath, className }: Props): React.ReactElement<Props> {
if (totalIssuance && totals) {
const max = bnMax(BN_ONE, ...totals);
setProgress(totals.map((total) => total.mul(DIV).div(max)));
setProgress(totals.map((total) => total.mul(BN_MILLION).div(max)));
api.query.poll.voteOf
.entries<ITuple<[Approvals, Balance]>>()

View File

@ -5,6 +5,7 @@ import BN from 'bn.js';
import React, { useEffect, useState } from 'react';
import { MarkWarning } from '@polkadot/react-components';
import { BN_TEN } from '@polkadot/util';
import { useTranslation } from '../../translate';
@ -23,7 +24,7 @@ function InputValidationUnstakeThreshold ({ onError, unstakeThreshold }: Props):
if (unstakeThreshold.ltn(0)) {
newError = t<string>('The Threshold must be a positive number');
} else if (unstakeThreshold.gtn(10)) {
} else if (unstakeThreshold.gt(BN_TEN)) {
newError = t<string>('The Threshold must lower than 11');
}

View File

@ -8,7 +8,7 @@ import BN from 'bn.js';
import { useMemo } from 'react';
import { useApi, useCall } from '@polkadot/react-hooks';
import { isFunction } from '@polkadot/util';
import { BN_BILLION, BN_ZERO, isFunction } from '@polkadot/util';
export default function useStakerPayouts (): BN {
const { api } = useApi();
@ -17,8 +17,8 @@ export default function useStakerPayouts (): BN {
return useMemo(
() => (migrateEraOpt && migrateEraOpt.isSome && migrateEraOpt.unwrap()) || (
isFunction(api.tx.staking.payoutStakers)
? new BN(0)
: new BN(1_000_000_000)
? BN_ZERO
: BN_BILLION
),
[api, migrateEraOpt]
);

View File

@ -4,7 +4,7 @@
import BN from 'bn.js';
import React from 'react';
import { formatNumber } from '@polkadot/util';
import { BN_ONE, formatNumber } from '@polkadot/util';
function isSingle (entry: BN | [BN, BN]): entry is BN {
return !Array.isArray(entry);
@ -24,13 +24,13 @@ export function createErasString (eras: BN[]): React.ReactNode {
const last = result[result.length - 1];
if (isSingle(last)) {
if (last.addn(1).eq(era)) {
if (last.add(BN_ONE).eq(era)) {
result[result.length - 1] = [last, era];
} else {
result.push(era);
}
} else {
if (last[1].addn(1).eq(era)) {
if (last[1].add(BN_ONE).eq(era)) {
last[1] = era;
} else {
result.push(era);

View File

@ -9,11 +9,11 @@ import React, { useMemo, useRef } from 'react';
import { Chart, Spinner } from '@polkadot/react-components';
import { useApi, useCall } from '@polkadot/react-hooks';
import { BN_BILLION } from '@polkadot/util';
import { useTranslation } from '../translate';
const MULT = new BN(100 * 100);
const BILLION = new BN(1_000_000_000);
const COLORS_POINTS = [undefined, '#acacac'];
function extractPrefs (prefs: DeriveStakerPrefs[] = []): ChartInfo {
@ -24,7 +24,7 @@ function extractPrefs (prefs: DeriveStakerPrefs[] = []): ChartInfo {
let total = 0;
prefs.forEach(({ era, validatorPrefs }): void => {
const comm = validatorPrefs.commission.unwrap().mul(MULT).div(BILLION).toNumber() / 100;
const comm = validatorPrefs.commission.unwrap().mul(MULT).div(BN_BILLION).toNumber() / 100;
total += comm;
labels.push(era.toHuman());

View File

@ -8,7 +8,7 @@ import type { SessionRewards } from '../types';
import { useEffect, useState } from 'react';
import { useApi, useCall, useIsMountedRef } from '@polkadot/react-hooks';
import { isFunction } from '@polkadot/util';
import { BN_ONE, BN_ZERO, isFunction } from '@polkadot/util';
export default function useBlockCounts (accountId: string, sessionRewards: SessionRewards[]): u32[] {
const { api } = useApi();
@ -20,12 +20,12 @@ export default function useBlockCounts (accountId: string, sessionRewards: Sessi
useEffect((): void => {
if (isFunction(api.query.imOnline?.authoredBlocks) && sessionRewards && sessionRewards.length) {
const filtered = sessionRewards.filter(({ sessionIndex }): boolean => sessionIndex.gtn(0));
const filtered = sessionRewards.filter(({ sessionIndex }): boolean => sessionIndex.gt(BN_ZERO));
if (filtered.length) {
Promise
.all(filtered.map(({ parentHash, sessionIndex }): Promise<u32> =>
api.query.imOnline.authoredBlocks.at(parentHash, sessionIndex.subn(1), accountId)
api.query.imOnline.authoredBlocks.at(parentHash, sessionIndex.sub(BN_ONE), accountId)
))
.then((historic): void => {
mountedRef.current && setHistoric(historic);

View File

@ -3,7 +3,7 @@
import BN from 'bn.js';
import { BN_ZERO, isBn, isFunction } from '@polkadot/util';
import { BN_THOUSAND, BN_ZERO, isBn, isFunction } from '@polkadot/util';
interface ToBN {
toBn: () => BN;
@ -16,5 +16,5 @@ export function balanceToNumber (amount: BN | ToBN = BN_ZERO, divisor: BN): numb
? amount.toBn()
: BN_ZERO;
return value.muln(1000).div(divisor).toNumber() / 1000;
return value.mul(BN_THOUSAND).div(divisor).toNumber() / 1000;
}

View File

@ -10,7 +10,7 @@ import React, { useMemo } from 'react';
import { CardSummary, SummaryBox } from '@polkadot/react-components';
import { useApi, useCall } from '@polkadot/react-hooks';
import { FormatBalance } from '@polkadot/react-query';
import { formatNumber } from '@polkadot/util';
import { BN_ONE, formatNumber } from '@polkadot/util';
import { useTranslation } from '../translate';
@ -26,7 +26,7 @@ function Header ({ slash: { era, nominators, reporters, total, validators } }: P
const [blockProgress, blockEnd] = useMemo(
() => sessionInfo
? [
sessionInfo.activeEra.sub(era).subn(1).mul(sessionInfo.eraLength).add(sessionInfo.eraProgress),
sessionInfo.activeEra.sub(era).isub(BN_ONE).imul(sessionInfo.eraLength).iadd(sessionInfo.eraProgress),
api.consts.staking.slashDeferDuration.mul(sessionInfo.eraLength)
]
: [new BN(0), new BN(0)],

View File

@ -11,6 +11,7 @@ import React, { useMemo } from 'react';
import { CardSummary, SummaryBox } from '@polkadot/react-components';
import { useApi, useCall } from '@polkadot/react-hooks';
import { FormatBalance } from '@polkadot/react-query';
import { BN_ONE, BN_ZERO } from '@polkadot/util';
import { useTranslation } from '../translate';
@ -29,7 +30,7 @@ const transformReward = {
};
const transformEra = {
transform: ({ activeEra }: DeriveSessionIndexes) => activeEra.gtn(0) ? activeEra.subn(1) : undefined
transform: ({ activeEra }: DeriveSessionIndexes) => activeEra.gt(BN_ZERO) ? activeEra.sub(BN_ONE) : undefined
};
function Summary ({ avgStaked, lowStaked, numNominators, numValidators, stakedReturn, totalIssuance, totalStaked }: Props): React.ReactElement<Props> {

View File

@ -11,6 +11,7 @@ import styled from 'styled-components';
import { Button, Icon, Table, Toggle } from '@polkadot/react-components';
import { useApi, useAvailableSlashes, useBlocksPerDays, useSavedFlags } from '@polkadot/react-hooks';
import { BN_HUNDRED } from '@polkadot/util';
import { MAX_NOMINATIONS } from '../constants';
import ElectionBanner from '../ElectionBanner';
@ -95,7 +96,7 @@ function applyFilter (validators: ValidatorInfo[], medianComm: number, allIdenti
? (commissionPer < MAX_COMM_PERCENT)
: (!medianComm || (commissionPer <= medianComm)))
) &&
(!withoutOver || !maxPaid || maxPaid.muln(MAX_CAP_PERCENT).divn(100).gten(nomCount))
(!withoutOver || !maxPaid || maxPaid.muln(MAX_CAP_PERCENT).div(BN_HUNDRED).gten(nomCount))
) {
if (!withGroup) {
return true;

View File

@ -9,7 +9,7 @@ import BN from 'bn.js';
import { useMemo } from 'react';
import { calcInflation, useAccounts, useApi, useCall } from '@polkadot/react-hooks';
import { arrayFlatten, BN_ONE, BN_ZERO } from '@polkadot/util';
import { arrayFlatten, BN_MILLION, BN_ONE, BN_ZERO } from '@polkadot/util';
interface LastEra {
activeEra: BN;
@ -82,7 +82,7 @@ function sortValidators (list: ValidatorInfo[]): ValidatorInfo[] {
function extractSingle (api: ApiPromise, allAccounts: string[], derive: DeriveStakingElected | DeriveStakingWaiting, favorites: string[], { activeEra, eraLength, lastEra, sessionLength }: LastEra, historyDepth?: BN): [ValidatorInfo[], string[]] {
const nominators: Record<string, boolean> = {};
const emptyExposure = api.createType('Exposure');
const earliestEra = historyDepth && lastEra.sub(historyDepth).addn(1);
const earliestEra = historyDepth && lastEra.sub(historyDepth).iadd(BN_ONE);
const list = derive.info.map(({ accountId, exposure = emptyExposure, stakingLedger, validatorPrefs }): ValidatorInfo => {
// some overrides (e.g. Darwinia Crab) does not have the own/total field in Exposure
let [bondOwn, bondTotal] = exposure.total
@ -172,7 +172,7 @@ function extractInfo (api: ApiPromise, allAccounts: string[], electedDerive: Der
// add the explicit stakedReturn
!avgStaked.isZero() && elected.forEach((e): void => {
if (!e.skipRewards) {
e.stakedReturn = inflation.stakedReturn * avgStaked.muln(1_000_000).div(e.bondTotal).toNumber() / 1_000_000;
e.stakedReturn = inflation.stakedReturn * avgStaked.mul(BN_MILLION).div(e.bondTotal).toNumber() / BN_MILLION.toNumber();
e.stakedReturnCmp = e.stakedReturn * (100 - e.commissionPer) / 100;
}
});

View File

@ -6,6 +6,7 @@ import React, { useMemo, useState } from 'react';
import { Button, InputAddress, InputBalance, MarkWarning, Modal, Static, TxButton } from '@polkadot/react-components';
import { useApi, useToggle } from '@polkadot/react-hooks';
import { BN_HUNDRED, BN_MILLION } from '@polkadot/util';
import { useTranslation } from '../translate';
@ -23,7 +24,7 @@ function Propose ({ className }: Props): React.ReactElement<Props> | null {
const hasValue = value?.gtn(0);
const bondPercentage = useMemo(
() => `${api.consts.treasury.proposalBond.muln(100).divn(1_000_000).toNumber().toFixed(2)}%`,
() => `${api.consts.treasury.proposalBond.mul(BN_HUNDRED).div(BN_MILLION).toNumber().toFixed(2)}%`,
[api]
);

View File

@ -9,7 +9,7 @@ import React from 'react';
import styled from 'styled-components';
import { BlockToTime } from '@polkadot/react-query';
import { formatNumber, isUndefined } from '@polkadot/util';
import { BN_HUNDRED, formatNumber, isUndefined } from '@polkadot/util';
import Labelled from './Labelled';
import Progress from './Progress';
@ -43,7 +43,7 @@ function CardSummary ({ children, className = '', help, label, progress }: Props
}`
: (
progress.isPercent
? value.muln(100).div(total).toString()
? value.mul(BN_HUNDRED).div(total).toString()
: formatNumber(value)
)
)

View File

@ -8,6 +8,7 @@ import React, { useRef } from 'react';
import { ApiPromise } from '@polkadot/api';
import { useApi, useBlockTime } from '@polkadot/react-hooks';
import { BN_THOUSAND } from '@polkadot/util';
import Dropdown from './Dropdown';
import { useTranslation } from './translate';
@ -30,7 +31,7 @@ function createOptions (api: ApiPromise, t: TFunction, blockTime: number): { tex
text: t<string>('{{value}}x voting balance, locked for {{lock}}x enactment ({{period}} days)', {
replace: {
lock,
period: (bnLock.mul(api.consts.democracy.enactmentPeriod.muln(blockTime).divn(1000)).toNumber() / SEC_DAY).toFixed(2),
period: (bnLock.mul(api.consts.democracy.enactmentPeriod.muln(blockTime).div(BN_THOUSAND)).toNumber() / SEC_DAY).toFixed(2),
value
}
}),

View File

@ -10,7 +10,7 @@ import React, { useCallback, useEffect, useState } from 'react';
import styled from 'styled-components';
import { useApi } from '@polkadot/react-hooks';
import { BN_TEN, BN_ZERO, formatBalance, isBn } from '@polkadot/util';
import { BN_ONE, BN_TEN, BN_TWO, BN_ZERO, formatBalance, isBn } from '@polkadot/util';
import { BitLengthOption } from './constants';
import Dropdown from './Dropdown';
@ -56,7 +56,7 @@ export class TokenUnit {
}
function getGlobalMaxValue (bitLength?: number): BN {
return new BN(2).pow(new BN(bitLength || DEFAULT_BITLENGTH)).subn(1);
return BN_TWO.pow(new BN(bitLength || DEFAULT_BITLENGTH)).isub(BN_ONE);
}
function getRegex (isDecimal: boolean): RegExp {

View File

@ -9,6 +9,7 @@ import BN from 'bn.js';
import { useEffect, useState } from 'react';
import { useApi, useCall, useIsMountedRef } from '@polkadot/react-hooks';
import { BN_ONE } from '@polkadot/util';
type Unsub = () => void;
@ -30,7 +31,7 @@ export function useAvailableSlashes (): [BN, UnappliedSlash[]][] {
// any <= activeEra (we include activeEra since slashes are immediately reflected)
while (start.lte(indexes.activeEra)) {
range.push(start);
start = start.addn(1);
start = start.iadd(BN_ONE);
}
if (range.length) {

View File

@ -8,13 +8,14 @@ import BN from 'bn.js';
import { useEffect, useState } from 'react';
import { getInflationParams } from '@polkadot/apps-config';
import { BN_MILLION } from '@polkadot/util';
import { useApi } from './useApi';
import { useCall } from './useCall';
export function calcInflation (api: ApiPromise, totalStaked: BN, totalIssuance: BN): Inflation {
const { falloff, idealStake, maxInflation, minInflation } = getInflationParams(api);
const stakedFraction = totalStaked.muln(1_000_000).div(totalIssuance).toNumber() / 1_000_000;
const stakedFraction = totalStaked.mul(BN_MILLION).div(totalIssuance).toNumber() / BN_MILLION.toNumber();
const idealInterest = maxInflation / idealStake;
const inflation = 100 * (minInflation + (
stakedFraction <= idealStake

View File

@ -9,9 +9,8 @@ import { useEffect, useState } from 'react';
import { DeriveBalancesAccount } from '@polkadot/api-derive/types';
import { useApi } from '@polkadot/react-hooks/useApi';
import { useCall } from '@polkadot/react-hooks/useCall';
import { BN_ZERO, stringToU8a } from '@polkadot/util';
import { BN_MILLION, BN_ZERO, stringToU8a } from '@polkadot/util';
const PM_DIV = new BN(1000000);
const TREASURY_ACCOUNT = stringToU8a('modlpy/trsry'.padEnd(32, '\0'));
interface Treasury {
@ -38,7 +37,7 @@ export function useTreasury (): Treasury {
? treasuryBalance.freeBalance
: undefined);
setBurn(treasuryBalance?.freeBalance.gtn(0) && !api.consts.treasury.burn.isZero()
? api.consts.treasury.burn.mul(treasuryBalance?.freeBalance).div(PM_DIV)
? api.consts.treasury.burn.mul(treasuryBalance.freeBalance).div(BN_MILLION)
: BN_ZERO);
}, [api, treasuryBalance, spendPeriod]);