From fa4df58066e19381687299151b2f055ebdd4d689 Mon Sep 17 00:00:00 2001 From: Ross Bulat Date: Sat, 2 Nov 2024 09:30:51 +0700 Subject: [PATCH] feat(refactor): Update to latest w3ux utils (#2283) --- package.json | 2 +- src/canvas/CreatePool/Summary/index.tsx | 5 +-- src/canvas/JoinPool/Overview/JoinForm.tsx | 13 +++--- src/canvas/JoinPool/Overview/Stats.tsx | 5 ++- src/canvas/JoinPool/Preloader.tsx | 5 ++- src/canvas/NominatorSetup/Summary/index.tsx | 5 +-- src/canvas/PoolMembers/Lists/Default.tsx | 3 +- .../PoolMembers/Prompts/UnbondMember.tsx | 22 ++++------ .../PoolMembers/Prompts/WithdrawMember.tsx | 15 +++---- src/contexts/FastUnstake/index.tsx | 11 ++--- src/contexts/Plugins/index.tsx | 4 +- src/contexts/Setup/index.tsx | 19 ++++---- src/contexts/Staking/index.tsx | 4 +- .../Validators/ValidatorEntries/index.tsx | 4 +- src/controllers/Balances/index.ts | 17 +++---- src/hooks/useAverageRewardRate/index.tsx | 6 +-- src/hooks/useErasToTimeLeft/index.tsx | 3 +- src/hooks/useFillVariables/index.tsx | 11 ++--- src/library/BarChart/BondedChart.tsx | 13 +++--- src/library/EstimatedTxFee/index.tsx | 4 +- src/library/Form/Bond/BondFeedback.tsx | 11 ++--- .../Form/CreatePoolStatusBar/index.tsx | 4 +- src/library/Form/NominateStatusBar/index.tsx | 6 +-- src/library/Form/Unbond/UnbondFeedback.tsx | 11 +++-- src/library/Form/Unbond/UnbondInput.tsx | 6 +-- src/library/Graphs/Utils.ts | 12 ++--- src/library/ListItem/Labels/EraStatus.tsx | 5 ++- .../ListItem/Labels/NominationStatus.tsx | 6 +-- src/library/ListItem/Labels/PoolBonded.tsx | 5 ++- .../ListItem/Labels/PoolMemberBonded.tsx | 13 +++--- src/library/Utils/index.ts | 13 ++++++ src/library/ValidatorList/index.tsx | 3 +- src/modals/Accounts/Account.tsx | 5 ++- src/modals/Bond/index.tsx | 15 ++++--- src/modals/ClaimPayouts/Forms.tsx | 2 +- src/modals/ClaimPayouts/Item.tsx | 4 +- src/modals/ClaimReward/index.tsx | 6 +-- src/modals/ManageFastUnstake/index.tsx | 6 +-- .../Forms/ClaimCommission/index.tsx | 9 ++-- .../ManagePool/Forms/LeavePool/index.tsx | 20 +++++---- src/modals/Unbond/index.tsx | 27 +++++++----- src/modals/UnlockChunks/Chunk.tsx | 4 +- src/modals/UnlockChunks/Forms.tsx | 9 ++-- src/modals/UnlockChunks/Overview.tsx | 11 +++-- src/modals/Unstake/index.tsx | 17 ++++--- src/modals/UpdateReserve/index.tsx | 12 +++-- src/modals/ValidatorMetrics/index.tsx | 7 +-- src/model/Query/NetworkMeta/index.ts | 31 ++++++------- src/model/Query/StakingConstants/index.ts | 22 +++++----- src/model/Subscribe/PoolsConfig/index.ts | 15 ++++--- src/model/Subscribe/StakingMetrics/index.ts | 18 ++++---- src/pages/Nominate/Active/ManageBond.tsx | 16 ++++--- .../Active/Stats/MinimumActiveStake.tsx | 4 +- .../Active/Stats/MinimumNominatorBond.tsx | 4 +- .../Active/Status/UnclaimedPayoutsStatus.tsx | 5 ++- src/pages/Nominate/Active/UnstakePrompts.tsx | 3 +- src/pages/Overview/BalanceChart.tsx | 44 +++++++++---------- .../Overview/NetworkSats/Announcements.tsx | 12 ++--- src/pages/Overview/Payouts.tsx | 5 ++- src/pages/Overview/Stats/SupplyStaked.tsx | 6 +-- src/pages/Payouts/PayoutList/index.tsx | 7 +-- src/pages/Payouts/Stats/LastEraPayout.tsx | 4 +- src/pages/Pools/Home/ManageBond.tsx | 16 ++++--- .../Pools/Home/PoolStats/Announcements.tsx | 7 +-- src/pages/Pools/Home/PoolStats/index.tsx | 5 ++- src/pages/Pools/Home/Stats/MinCreateBond.tsx | 4 +- src/pages/Pools/Home/Stats/MinJoinBond.tsx | 4 +- src/pages/Pools/Home/Status/RewardsStatus.tsx | 4 +- .../Validators/Stats/ActiveValidators.tsx | 3 +- .../Validators/Stats/TotalValidators.tsx | 3 +- src/workers/stakers.ts | 5 +-- yarn.lock | 11 +++-- 72 files changed, 357 insertions(+), 321 deletions(-) create mode 100644 src/library/Utils/index.ts diff --git a/package.json b/package.json index 9d8ac2a01..5d5db63cf 100644 --- a/package.json +++ b/package.json @@ -32,7 +32,7 @@ "@w3ux/react-connect-kit": "^1.8.0", "@w3ux/react-odometer": "^1.1.0", "@w3ux/react-polkicon": "^1.3.0", - "@w3ux/utils": "^0.10.0", + "@w3ux/utils": "1.0.1", "@w3ux/validator-assets": "^0.2.0", "@zondax/ledger-substrate": "^1.0.0", "bignumber.js": "^9.1.2", diff --git a/src/canvas/CreatePool/Summary/index.tsx b/src/canvas/CreatePool/Summary/index.tsx index 02fb76477..d02c4c649 100644 --- a/src/canvas/CreatePool/Summary/index.tsx +++ b/src/canvas/CreatePool/Summary/index.tsx @@ -55,12 +55,11 @@ export const Summary = ({ section }: SetupStepProps) => { ({ address }: { address: string }) => address ); - const bondToSubmit = unitToPlanck(bond, units); - const bondAsString = bondToSubmit.isNaN() ? '0' : bondToSubmit.toString(); + const bondToSubmit = unitToPlanck(bond, units).toString(); const txs = [ api.tx.nominationPools.create( - bondAsString, + bondToSubmit, roles?.root || activeAccount, roles?.nominator || activeAccount, roles?.bouncer || activeAccount diff --git a/src/canvas/JoinPool/Overview/JoinForm.tsx b/src/canvas/JoinPool/Overview/JoinForm.tsx index 586afe89e..e9c2181d4 100644 --- a/src/canvas/JoinPool/Overview/JoinForm.tsx +++ b/src/canvas/JoinPool/Overview/JoinForm.tsx @@ -1,7 +1,7 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { planckToUnit, unitToPlanck } from '@w3ux/utils'; +import { unitToPlanck } from '@w3ux/utils'; import type BigNumber from 'bignumber.js'; import { useActiveAccounts } from 'contexts/ActiveAccounts'; import { useNetwork } from 'contexts/Network'; @@ -24,6 +24,7 @@ import { SubmitTx } from 'library/SubmitTx'; import type { OverviewSectionProps } from '../types'; import { defaultClaimPermission } from 'controllers/ActivePools/defaults'; import { useTranslation } from 'react-i18next'; +import { planckToUnitBn } from 'library/Utils'; export const JoinForm = ({ bondedPool }: OverviewSectionProps) => { const { t } = useTranslation(); @@ -54,7 +55,7 @@ export const JoinForm = ({ bondedPool }: OverviewSectionProps) => { // Bond amount to join pool with. const [bond, setBond] = useState<{ bond: string }>({ - bond: planckToUnit(totalPossibleBond, units).toString(), + bond: planckToUnitBn(totalPossibleBond, units).toString(), }); // Whether the bond amount is valid. @@ -78,9 +79,11 @@ export const JoinForm = ({ bondedPool }: OverviewSectionProps) => { return tx; } - const bondToSubmit = unitToPlanck(!bondValid ? '0' : bond.bond, units); - const bondAsString = bondToSubmit.isNaN() ? '0' : bondToSubmit.toString(); - const txs = [api.tx.nominationPools.join(bondAsString, bondedPool.id)]; + const bondToSubmit = unitToPlanck( + !bondValid ? '0' : bond.bond, + units + ).toString(); + const txs = [api.tx.nominationPools.join(bondToSubmit, bondedPool.id)]; // If claim permission is not the default, add it to tx. if (claimPermission !== defaultClaimPermission) { diff --git a/src/canvas/JoinPool/Overview/Stats.tsx b/src/canvas/JoinPool/Overview/Stats.tsx index 873a6e1d7..f7b9e69e5 100644 --- a/src/canvas/JoinPool/Overview/Stats.tsx +++ b/src/canvas/JoinPool/Overview/Stats.tsx @@ -3,7 +3,7 @@ import { useNetwork } from 'contexts/Network'; import { HeadingWrapper } from '../Wrappers'; -import { planckToUnit, rmCommas } from '@w3ux/utils'; +import { rmCommas } from '@w3ux/utils'; import { useApi } from 'contexts/Api'; import BigNumber from 'bignumber.js'; import { useEffect, useState } from 'react'; @@ -14,6 +14,7 @@ import { MaxEraRewardPointsEras } from 'consts'; import { StyledLoader } from 'library/PoolSync/Loader'; import type { CSSProperties } from 'styled-components'; import { PoolSync } from 'library/PoolSync'; +import { planckToUnitBn } from 'library/Utils'; export const Stats = ({ bondedPool, @@ -86,7 +87,7 @@ export const Stats = ({ {!poolBalance ? `...` - : planckToUnit(poolBalance, units) + : planckToUnitBn(poolBalance, units) .decimalPlaces(3) .toFormat()}{' '} {unit} {t('bonded')} diff --git a/src/canvas/JoinPool/Preloader.tsx b/src/canvas/JoinPool/Preloader.tsx index 50b04070e..a55cd1b20 100644 --- a/src/canvas/JoinPool/Preloader.tsx +++ b/src/canvas/JoinPool/Preloader.tsx @@ -10,11 +10,12 @@ import { CanvasTitleWrapper } from 'canvas/Wrappers'; import { useBondedPools } from 'contexts/Pools/BondedPools'; import BigNumber from 'bignumber.js'; import type { BondedPool } from 'contexts/Pools/BondedPools/types'; -import { capitalizeFirstLetter, planckToUnit, rmCommas } from '@w3ux/utils'; +import { capitalizeFirstLetter, rmCommas } from '@w3ux/utils'; import { useNetwork } from 'contexts/Network'; import { useApi } from 'contexts/Api'; import { PoolSyncBar } from 'library/PoolSync/Bar'; import type { PoolRewardPointsKey } from 'contexts/Pools/PoolPerformance/types'; +import { planckToUnitBn } from 'library/Utils'; export const Preloader = ({ performanceKey, @@ -36,7 +37,7 @@ export const Preloader = ({ bondedPools.forEach((b: BondedPool) => { totalPoolPoints = totalPoolPoints.plus(rmCommas(b.points)); }); - const totalPoolPointsUnit = planckToUnit(totalPoolPoints, units) + const totalPoolPointsUnit = planckToUnitBn(totalPoolPoints, units) .decimalPlaces(0) .toFormat(); diff --git a/src/canvas/NominatorSetup/Summary/index.tsx b/src/canvas/NominatorSetup/Summary/index.tsx index 7bdc08e06..5a1bf88ce 100644 --- a/src/canvas/NominatorSetup/Summary/index.tsx +++ b/src/canvas/NominatorSetup/Summary/index.tsx @@ -57,11 +57,10 @@ export const Summary = ({ section }: SetupStepProps) => { } : payee.destination; - const bondToSubmit = unitToPlanck(bond || '0', units); - const bondAsString = bondToSubmit.isNaN() ? '0' : bondToSubmit.toString(); + const bondToSubmit = unitToPlanck(bond || '0', units).toString(); const txs = [ - api.tx.staking.bond(bondAsString, payeeToSubmit), + api.tx.staking.bond(bondToSubmit, payeeToSubmit), api.tx.staking.nominate(targetsToSubmit), ]; return newBatchCall(txs, activeAccount); diff --git a/src/canvas/PoolMembers/Lists/Default.tsx b/src/canvas/PoolMembers/Lists/Default.tsx index b5716cf2e..32e1937c6 100644 --- a/src/canvas/PoolMembers/Lists/Default.tsx +++ b/src/canvas/PoolMembers/Lists/Default.tsx @@ -1,7 +1,6 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { isNotZero } from '@w3ux/utils'; import { useEffect, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { poolMembersPerPage } from 'library/List/defaults'; @@ -63,7 +62,7 @@ export const MembersListInner = ({ // Configure list when network is ready to fetch. useEffect(() => { - if (isReady && isNotZero(activeEra.index) && fetched === 'unsynced') { + if (isReady && !activeEra.index.isZero() && fetched === 'unsynced') { setupMembersList(); } }, [isReady, fetched, activeEra.index]); diff --git a/src/canvas/PoolMembers/Prompts/UnbondMember.tsx b/src/canvas/PoolMembers/Prompts/UnbondMember.tsx index bd8984747..14e779d40 100644 --- a/src/canvas/PoolMembers/Prompts/UnbondMember.tsx +++ b/src/canvas/PoolMembers/Prompts/UnbondMember.tsx @@ -2,14 +2,7 @@ // SPDX-License-Identifier: GPL-3.0-only import { Polkicon } from '@w3ux/react-polkicon'; -import { - ellipsisFn, - greaterThanZero, - planckToUnit, - remToUnit, - rmCommas, - unitToPlanck, -} from '@w3ux/utils'; +import { ellipsisFn, remToUnit, rmCommas, unitToPlanck } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { getUnixTime } from 'date-fns'; import { useEffect, useState } from 'react'; @@ -30,6 +23,7 @@ import { Title } from 'library/Prompt/Title'; import { ModalPadding } from 'kits/Overlay/structure/ModalPadding'; import { ModalWarnings } from 'kits/Overlay/structure/ModalWarnings'; import { ModalNotes } from 'kits/Overlay/structure/ModalNotes'; +import { planckToUnitBn } from 'library/Utils'; export const UnbondMember = ({ who, @@ -50,7 +44,7 @@ export const UnbondMember = ({ const { bondDuration } = consts; const { points } = member; - const freeToUnbond = planckToUnit(new BigNumber(rmCommas(points)), units); + const freeToUnbond = planckToUnitBn(new BigNumber(rmCommas(points)), units); const bondDurationFormatted = timeleftAsString( t, @@ -68,7 +62,7 @@ export const UnbondMember = ({ const [bondValid, setBondValid] = useState(false); // unbond all validation - const isValid = (() => greaterThanZero(freeToUnbond))(); + const isValid = (() => freeToUnbond.isGreaterThan(0))(); // update bond value on task change useEffect(() => { @@ -83,9 +77,11 @@ export const UnbondMember = ({ return tx; } // remove decimal errors - const bondToSubmit = unitToPlanck(!bondValid ? '0' : bond.bond, units); - const bondAsString = bondToSubmit.isNaN() ? '0' : bondToSubmit.toString(); - tx = api.tx.nominationPools.unbond(who, bondAsString); + const bondToSubmit = unitToPlanck( + !bondValid ? '0' : bond.bond, + units + ).toString(); + tx = api.tx.nominationPools.unbond(who, bondToSubmit); return tx; }; diff --git a/src/canvas/PoolMembers/Prompts/WithdrawMember.tsx b/src/canvas/PoolMembers/Prompts/WithdrawMember.tsx index f1644a3dc..e3298435a 100644 --- a/src/canvas/PoolMembers/Prompts/WithdrawMember.tsx +++ b/src/canvas/PoolMembers/Prompts/WithdrawMember.tsx @@ -2,13 +2,7 @@ // SPDX-License-Identifier: GPL-3.0-only import { Polkicon } from '@w3ux/react-polkicon'; -import { - ellipsisFn, - isNotZero, - planckToUnit, - remToUnit, - rmCommas, -} from '@w3ux/utils'; +import { ellipsisFn, remToUnit, rmCommas } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import type { RefObject } from 'react'; import { useState } from 'react'; @@ -27,6 +21,7 @@ import { useTranslation } from 'react-i18next'; import { ModalPadding } from 'kits/Overlay/structure/ModalPadding'; import { ModalWarnings } from 'kits/Overlay/structure/ModalWarnings'; import { ModalNotes } from 'kits/Overlay/structure/ModalNotes'; +import { planckToUnitBn } from 'library/Utils'; export const WithdrawMember = ({ who, @@ -62,11 +57,11 @@ export const WithdrawMember = ({ } }); - const bonded = planckToUnit(new BigNumber(rmCommas(points)), units); - const totalWithdraw = planckToUnit(new BigNumber(totalWithdrawUnit), units); + const bonded = planckToUnitBn(new BigNumber(rmCommas(points)), units); + const totalWithdraw = planckToUnitBn(new BigNumber(totalWithdrawUnit), units); // valid to submit transaction - const [valid] = useState(isNotZero(totalWithdraw) ?? false); + const [valid] = useState(!totalWithdraw.isZero()); // tx to submit const getTx = () => { diff --git a/src/contexts/FastUnstake/index.tsx b/src/contexts/FastUnstake/index.tsx index 7d62d8ecd..a52d5c29e 100644 --- a/src/contexts/FastUnstake/index.tsx +++ b/src/contexts/FastUnstake/index.tsx @@ -1,12 +1,7 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { - greaterThanZero, - isNotZero, - rmCommas, - setStateWithRef, -} from '@w3ux/utils'; +import { rmCommas, setStateWithRef } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import type { ReactNode } from 'react'; import { createContext, useContext, useEffect, useRef, useState } from 'react'; @@ -111,7 +106,7 @@ export const FastUnstakeProvider = ({ children }: { children: ReactNode }) => { if ( isReady && activeAccount && - isNotZero(activeEra.index) && + !activeEra.index.isZero() && fastUnstakeErasToCheckPerBlock > 0 && isBonding() ) { @@ -238,7 +233,7 @@ export const FastUnstakeProvider = ({ children }: { children: ReactNode }) => { // ensure current era has synced if ( era.isLessThan(0) || - !greaterThanZero(bondDuration) || + !bondDuration.isGreaterThan(0) || !api || !a || checkingRef.current || diff --git a/src/contexts/Plugins/index.tsx b/src/contexts/Plugins/index.tsx index 35676942c..369b4d493 100644 --- a/src/contexts/Plugins/index.tsx +++ b/src/contexts/Plugins/index.tsx @@ -1,7 +1,7 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { isNotZero, setStateWithRef } from '@w3ux/utils'; +import { setStateWithRef } from '@w3ux/utils'; import type { ReactNode } from 'react'; import { createContext, useContext, useRef, useState } from 'react'; import type { Plugin } from 'config/plugins'; @@ -51,7 +51,7 @@ export const PluginsProvider = ({ children }: { children: ReactNode }) => { useEffectIgnoreInitial(() => { if (!plugins.includes('subscan')) { SubscanController.resetData(); - } else if (isReady && isNotZero(activeEra.index)) { + } else if (isReady && !activeEra.index.isZero()) { SubscanController.network = network; if (activeAccount) { SubscanController.handleFetchPayouts(activeAccount); diff --git a/src/contexts/Setup/index.tsx b/src/contexts/Setup/index.tsx index 5d3454507..1038193d7 100644 --- a/src/contexts/Setup/index.tsx +++ b/src/contexts/Setup/index.tsx @@ -1,11 +1,7 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { - greaterThanZero, - localStorageOrDefault, - unitToPlanck, -} from '@w3ux/utils'; +import { localStorageOrDefault, unitToPlanck } from '@w3ux/utils'; import type { ReactNode } from 'react'; import { createContext, useContext, useState } from 'react'; import type { BondFor, MaybeAddress } from 'types'; @@ -27,6 +23,7 @@ import type { PoolSetups, SetupContextInterface, } from './types'; +import BigNumber from 'bignumber.js'; export const SetupContext = createContext(defaultSetupContext); @@ -179,11 +176,13 @@ export const SetupProvider = ({ children }: { children: ReactNode }) => { } const setup = getSetupProgress('nominator', address) as NominatorSetup; const { progress } = setup; - const bond = unitToPlanck(progress?.bond || '0', units); + const bond = new BigNumber( + unitToPlanck(progress?.bond || '0', units).toString() + ); const p = 33; let percentage = 0; - if (greaterThanZero(bond)) { + if (bond.isGreaterThan(0)) { percentage += p; } if (progress.nominations.length) { @@ -202,14 +201,16 @@ export const SetupProvider = ({ children }: { children: ReactNode }) => { } const setup = getSetupProgress('pool', address) as PoolSetup; const { progress } = setup; - const bond = unitToPlanck(progress?.bond || '0', units); + const bond = new BigNumber( + unitToPlanck(progress?.bond || '0', units).toString() + ); const p = 25; let percentage = 0; if (progress.metadata !== '') { percentage += p; } - if (greaterThanZero(bond)) { + if (bond.isGreaterThan(0)) { percentage += p; } if (progress.nominations.length) { diff --git a/src/contexts/Staking/index.tsx b/src/contexts/Staking/index.tsx index 5518dc0ff..bc8ea15db 100644 --- a/src/contexts/Staking/index.tsx +++ b/src/contexts/Staking/index.tsx @@ -1,7 +1,7 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { greaterThanZero, rmCommas, setStateWithRef } from '@w3ux/utils'; +import { rmCommas, setStateWithRef } from '@w3ux/utils'; import type { ReactNode } from 'react'; import { createContext, useContext, useRef, useState } from 'react'; import { useBalances } from 'contexts/Balances'; @@ -205,7 +205,7 @@ export const StakingProvider = ({ children }: { children: ReactNode }) => { // Helper function to determine whether the active account is bonding, or is yet to start. const isBonding = () => hasController() && - greaterThanZero(getLedger({ stash: activeAccount }).active); + getLedger({ stash: activeAccount }).active.isGreaterThan(0); // Helper function to determine whether the active account. const isUnlocking = () => diff --git a/src/contexts/Validators/ValidatorEntries/index.tsx b/src/contexts/Validators/ValidatorEntries/index.tsx index 31252efe2..452b4be00 100644 --- a/src/contexts/Validators/ValidatorEntries/index.tsx +++ b/src/contexts/Validators/ValidatorEntries/index.tsx @@ -1,7 +1,7 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { greaterThanZero, rmCommas, shuffle } from '@w3ux/utils'; +import { rmCommas, shuffle } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import type { ReactNode } from 'react'; import { createContext, useContext, useEffect, useRef, useState } from 'react'; @@ -573,7 +573,7 @@ export const ValidatorsProvider = ({ children }: { children: ReactNode }) => { // Fetch parachain session validators when `earliestStoredSession` ready. useEffectIgnoreInitial(() => { - if (isReady && greaterThanZero(earliestStoredSession)) { + if (isReady && earliestStoredSession.isGreaterThan(0)) { subscribeParachainValidators(); } }, [isReady, earliestStoredSession]); diff --git a/src/controllers/Balances/index.ts b/src/controllers/Balances/index.ts index 0673c84e8..df8086d5f 100644 --- a/src/controllers/Balances/index.ts +++ b/src/controllers/Balances/index.ts @@ -1,7 +1,7 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { rmCommas, stringToBigNumber } from '@w3ux/utils'; +import { rmCommas } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import type { AnyApi, MaybeAddress } from 'types'; import type { @@ -17,6 +17,7 @@ import { SyncController } from 'controllers/Sync'; import { defaultNominations } from './defaults'; import type { VoidFn } from '@polkadot/api/types'; import type { ApiPromise } from '@polkadot/api'; +import { stringToBn } from 'library/Utils'; export class BalancesController { // ------------------------------------------------------ @@ -171,11 +172,11 @@ export class BalancesController { this.ledgers[address] = { stash: stash.toString(), - active: stringToBigNumber(active.toString()), - total: stringToBigNumber(total.toString()), + active: stringToBn(active.toString()), + total: stringToBn(total.toString()), unlocking: unlocking.toHuman().map(({ era, value }: UnlockChunkRaw) => ({ era: Number(rmCommas(era)), - value: stringToBigNumber(value), + value: stringToBn(value), })), }; }; @@ -189,16 +190,16 @@ export class BalancesController { this.balances[address] = { nonce: nonce.toNumber(), balance: { - free: stringToBigNumber(accountData.free.toString()), - reserved: stringToBigNumber(accountData.reserved.toString()), - frozen: stringToBigNumber(accountData.frozen.toString()), + free: stringToBn(accountData.free.toString()), + reserved: stringToBn(accountData.reserved.toString()), + frozen: stringToBn(accountData.frozen.toString()), }, locks: locksResult .toHuman() .map((lock: { id: string; amount: string }) => ({ ...lock, id: lock.id.trim(), - amount: stringToBigNumber(lock.amount), + amount: stringToBn(lock.amount), })), }; }; diff --git a/src/hooks/useAverageRewardRate/index.tsx b/src/hooks/useAverageRewardRate/index.tsx index c83686a35..ca5cc6179 100644 --- a/src/hooks/useAverageRewardRate/index.tsx +++ b/src/hooks/useAverageRewardRate/index.tsx @@ -7,8 +7,8 @@ import { useValidators } from 'contexts/Validators/ValidatorEntries'; import type { AverageRewardRate, UseAverageRewardRate } from './types'; import { defaultAverageRewardRate } from './defaults'; import { useNetwork } from 'contexts/Network'; -import { planckToUnit } from '@w3ux/utils'; import { useApi } from 'contexts/Api'; +import { planckToUnitBn } from 'library/Utils'; export const useAverageRewardRate = (): UseAverageRewardRate => { const { erasPerDay } = useErasPerDay(); @@ -31,8 +31,8 @@ export const useAverageRewardRate = (): UseAverageRewardRate => { } // total supply as percent. - const totalIssuanceUnit = planckToUnit(totalIssuance, units); - const lastTotalStakeUnit = planckToUnit(lastTotalStake, units); + const totalIssuanceUnit = planckToUnitBn(totalIssuance, units); + const lastTotalStakeUnit = planckToUnitBn(lastTotalStake, units); const supplyStaked = lastTotalStakeUnit.isZero() || totalIssuanceUnit.isZero() ? new BigNumber(0) diff --git a/src/hooks/useErasToTimeLeft/index.tsx b/src/hooks/useErasToTimeLeft/index.tsx index 841380d94..8c2f3eb8a 100644 --- a/src/hooks/useErasToTimeLeft/index.tsx +++ b/src/hooks/useErasToTimeLeft/index.tsx @@ -1,7 +1,6 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { greaterThanZero } from '@w3ux/utils'; import type BigNumber from 'bignumber.js'; import { useApi } from 'contexts/Api'; @@ -11,7 +10,7 @@ export const useErasToTimeLeft = () => { // converts a number of eras to timeleft in seconds. const erasToSeconds = (eras: BigNumber) => { - if (!greaterThanZero(eras)) { + if (!eras.isGreaterThan(0)) { return 0; } // store the duration of an era in number of blocks. diff --git a/src/hooks/useFillVariables/index.tsx b/src/hooks/useFillVariables/index.tsx index 454174239..bc955ff9b 100644 --- a/src/hooks/useFillVariables/index.tsx +++ b/src/hooks/useFillVariables/index.tsx @@ -1,11 +1,12 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { capitalizeFirstLetter, planckToUnit } from '@w3ux/utils'; +import { capitalizeFirstLetter } from '@w3ux/utils'; import { useApi } from 'contexts/Api'; import { useNetwork } from 'contexts/Network'; import type { AnyJson } from '@w3ux/types'; import { useErasPerDay } from '../useErasPerDay'; +import { planckToUnitBn } from 'library/Utils'; export const useFillVariables = () => { const { @@ -29,25 +30,25 @@ export const useFillVariables = () => { ['{MAX_NOMINATIONS}', maxNominations.toString()], [ '{MIN_ACTIVE_STAKE}', - planckToUnit(minimumActiveStake, networkData.units) + planckToUnitBn(minimumActiveStake, networkData.units) .decimalPlaces(3) .toFormat(), ], [ '{MIN_POOL_JOIN_BOND}', - planckToUnit(minJoinBond, networkData.units) + planckToUnitBn(minJoinBond, networkData.units) .decimalPlaces(3) .toFormat(), ], [ '{MIN_POOL_CREATE_BOND}', - planckToUnit(minCreateBond, networkData.units) + planckToUnitBn(minCreateBond, networkData.units) .decimalPlaces(3) .toFormat(), ], [ '{EXISTENTIAL_DEPOSIT}', - planckToUnit(existentialDeposit, networkData.units).toFormat(), + planckToUnitBn(existentialDeposit, networkData.units).toFormat(), ], ]; diff --git a/src/library/BarChart/BondedChart.tsx b/src/library/BarChart/BondedChart.tsx index 6026f0b91..f425699ee 100644 --- a/src/library/BarChart/BondedChart.tsx +++ b/src/library/BarChart/BondedChart.tsx @@ -1,7 +1,6 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { greaterThanZero } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { useTranslation } from 'react-i18next'; import { BarSegment } from 'library/BarChart/BarSegment'; @@ -29,14 +28,14 @@ export const BondedChart = ({ // graph percentages const graphTotal = active.plus(totalUnlocking).plus(free); - const graphActive = greaterThanZero(active) + const graphActive = active.isGreaterThan(0) ? BigNumber.max( active.dividedBy(graphTotal.multipliedBy(0.01)), active.isGreaterThan(MinimumLowerBound) ? MinimumNoNZeroPercent : 0 ) : new BigNumber(0); - const graphUnlocking = greaterThanZero(totalUnlocking) + const graphUnlocking = totalUnlocking.isGreaterThan(0) ? BigNumber.max( totalUnlocking.dividedBy(graphTotal.multipliedBy(0.01)), totalUnlocking.isGreaterThan(MinimumLowerBound) @@ -48,7 +47,7 @@ export const BondedChart = ({ const freeToBond = free.decimalPlaces(3); const remaining = new BigNumber(100).minus(graphActive).minus(graphUnlocking); - const graphFree = greaterThanZero(remaining) + const graphFree = remaining.isGreaterThan(0) ? BigNumber.max( remaining, freeToBond.isGreaterThan(MinimumLowerBound) ? MinimumNoNZeroPercent : 0 @@ -63,15 +62,15 @@ export const BondedChart = ({ {totalUnlocking.plus(active).isZero() ? ( - ) : greaterThanZero(active) ? ( + ) : active.isGreaterThan(0) ? ( ) : null} - {greaterThanZero(totalUnlocking) ? ( + {totalUnlocking.isGreaterThan(0) ? ( ) : null} - {greaterThanZero(totalUnlocking.plus(active)) ? ( + {totalUnlocking.plus(active).isGreaterThan(0) ? ( ) : null} diff --git a/src/library/EstimatedTxFee/index.tsx b/src/library/EstimatedTxFee/index.tsx index 254e0d637..8244e992d 100644 --- a/src/library/EstimatedTxFee/index.tsx +++ b/src/library/EstimatedTxFee/index.tsx @@ -1,7 +1,6 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { planckToUnit } from '@w3ux/utils'; import type { Context } from 'react'; import { Component, useEffect } from 'react'; import { useTranslation } from 'react-i18next'; @@ -10,6 +9,7 @@ import type { TxMetaContextInterface } from 'contexts/TxMeta/types'; import { useNetwork } from 'contexts/Network'; import { Wrapper } from './Wrapper'; import type { EstimatedTxFeeProps } from './types'; +import { planckToUnitBn } from 'library/Utils'; export const EstimatedTxFeeInner = ({ format }: EstimatedTxFeeProps) => { const { t } = useTranslation('library'); @@ -18,7 +18,7 @@ export const EstimatedTxFeeInner = ({ format }: EstimatedTxFeeProps) => { useEffect(() => () => resetTxFees(), []); - const txFeesUnit = planckToUnit(txFees, units).toFormat(); + const txFeesUnit = planckToUnitBn(txFees, units).toFormat(); return format === 'table' ? ( <> diff --git a/src/library/Form/Bond/BondFeedback.tsx b/src/library/Form/Bond/BondFeedback.tsx index 0e55663ef..19605e893 100644 --- a/src/library/Form/Bond/BondFeedback.tsx +++ b/src/library/Form/Bond/BondFeedback.tsx @@ -1,7 +1,7 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { planckToUnit, unitToPlanck } from '@w3ux/utils'; +import { unitToPlanck } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { useEffect, useState } from 'react'; import { useTranslation } from 'react-i18next'; @@ -14,6 +14,7 @@ import { Spacer } from '../Wrappers'; import type { BondFeedbackProps } from '../types'; import { BondInput } from './BondInput'; import { useApi } from 'contexts/Api'; +import { planckToUnitBn } from 'library/Utils'; export const BondFeedback = ({ bondFor, @@ -69,7 +70,7 @@ export const BondFeedback = ({ }; // current bond value BigNumber - const bondBn = unitToPlanck(bond.bond, units); + const bondBn = new BigNumber(unitToPlanck(bond.bond, units).toString()); // whether bond is disabled const [bondDisabled, setBondDisabled] = useState(false); @@ -91,7 +92,7 @@ export const BondFeedback = ({ ? minCreateBond : minJoinBond : minNominatorBond; - const minBondUnit = planckToUnit(minBondBn, units); + const minBondUnit = planckToUnitBn(minBondBn, units); // handle error updates const handleErrors = () => { @@ -166,7 +167,7 @@ export const BondFeedback = ({ useEffect(() => { if (!disableTxFeeUpdate) { if (bondBn.isGreaterThan(freeToBond)) { - setBond({ bond: String(planckToUnit(freeToBond, units)) }); + setBond({ bond: String(planckToUnitBn(freeToBond, units)) }); } } }, [txFees]); @@ -189,7 +190,7 @@ export const BondFeedback = ({ syncing={syncing} disabled={bondDisabled} setters={setters} - freeToBond={planckToUnit(freeToBond, units)} + freeToBond={planckToUnitBn(freeToBond, units)} disableTxFeeUpdate={disableTxFeeUpdate} /> diff --git a/src/library/Form/CreatePoolStatusBar/index.tsx b/src/library/Form/CreatePoolStatusBar/index.tsx index f0e54be7a..cee487b59 100644 --- a/src/library/Form/CreatePoolStatusBar/index.tsx +++ b/src/library/Form/CreatePoolStatusBar/index.tsx @@ -3,13 +3,13 @@ import { faFlag } from '@fortawesome/free-regular-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { planckToUnit } from '@w3ux/utils'; import { useTranslation } from 'react-i18next'; import { useNetwork } from 'contexts/Network'; import type { NominateStatusBarProps } from '../types'; import { Wrapper } from './Wrapper'; import { useApi } from 'contexts/Api'; import { useSyncing } from 'hooks/useSyncing'; +import { planckToUnitBn } from 'library/Utils'; export const CreatePoolStatusBar = ({ value }: NominateStatusBarProps) => { const { t } = useTranslation('library'); @@ -17,7 +17,7 @@ export const CreatePoolStatusBar = ({ value }: NominateStatusBarProps) => { const { unit, units } = useNetwork().networkData; const { syncing } = useSyncing(['initialization']); - const minCreateBondUnit = planckToUnit(minCreateBond, units); + const minCreateBondUnit = planckToUnitBn(minCreateBond, units); const sectionClassName = value.isGreaterThanOrEqualTo(minCreateBondUnit) && !syncing ? 'invert' : ''; diff --git a/src/library/Form/NominateStatusBar/index.tsx b/src/library/Form/NominateStatusBar/index.tsx index 75a58271a..307023bfb 100644 --- a/src/library/Form/NominateStatusBar/index.tsx +++ b/src/library/Form/NominateStatusBar/index.tsx @@ -3,7 +3,6 @@ import { faFlag } from '@fortawesome/free-regular-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { planckToUnit } from '@w3ux/utils'; import { useTranslation } from 'react-i18next'; import { useHelp } from 'contexts/Help'; import { useNetwork } from 'contexts/Network'; @@ -12,6 +11,7 @@ import { Wrapper } from './Wrapper'; import { useApi } from 'contexts/Api'; import { useSyncing } from 'hooks/useSyncing'; import { ButtonHelp } from 'kits/Buttons/ButtonHelp'; +import { planckToUnitBn } from 'library/Utils'; export const NominateStatusBar = ({ value }: NominateStatusBarProps) => { const { t } = useTranslation('library'); @@ -23,8 +23,8 @@ export const NominateStatusBar = ({ value }: NominateStatusBarProps) => { const { unit, units } = useNetwork().networkData; const { syncing } = useSyncing(['initialization']); - const minNominatorBondUnit = planckToUnit(minNominatorBond, units); - const minimumActiveStakeUnit = planckToUnit(minimumActiveStake, units); + const minNominatorBondUnit = planckToUnitBn(minNominatorBond, units); + const minimumActiveStakeUnit = planckToUnitBn(minimumActiveStake, units); const gtMinNominatorBond = value.isGreaterThanOrEqualTo(minNominatorBondUnit); const gtMinActiveStake = value.isGreaterThanOrEqualTo(minimumActiveStakeUnit); diff --git a/src/library/Form/Unbond/UnbondFeedback.tsx b/src/library/Form/Unbond/UnbondFeedback.tsx index 4b2717966..d9196912f 100644 --- a/src/library/Form/Unbond/UnbondFeedback.tsx +++ b/src/library/Form/Unbond/UnbondFeedback.tsx @@ -1,7 +1,7 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { isNotZero, planckToUnit, unitToPlanck } from '@w3ux/utils'; +import { unitToPlanck } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { useEffect, useState } from 'react'; import { useTranslation } from 'react-i18next'; @@ -14,6 +14,7 @@ import { Spacer } from '../Wrappers'; import type { UnbondFeedbackProps } from '../types'; import { UnbondInput } from './UnbondInput'; import { useApi } from 'contexts/Api'; +import { planckToUnitBn } from 'library/Utils'; export const UnbondFeedback = ({ bondFor, @@ -59,7 +60,9 @@ export const UnbondFeedback = ({ }; // current bond value BigNumber - const bondBn = unitToPlanck(String(bond.bond), units); + const bondBn = new BigNumber( + unitToPlanck(String(bond.bond), units).toString() + ); // add this component's setBond to setters setters.push(handleSetBond); @@ -71,7 +74,7 @@ export const UnbondFeedback = ({ ? minCreateBond : minJoinBond : minNominatorBond; - const minBondUnit = planckToUnit(minBondBn, units); + const minBondUnit = planckToUnitBn(minBondBn, units); // unbond amount to minimum threshold const unbondToMin = @@ -84,7 +87,7 @@ export const UnbondFeedback = ({ // check if bonded is below the minimum required const nominatorActiveBelowMin = bondFor === 'nominator' && - isNotZero(active) && + !active.isZero() && active.isLessThan(minNominatorBond); const poolToMinBn = isDepositor() ? minCreateBond : minJoinBond; const poolActiveBelowMin = diff --git a/src/library/Form/Unbond/UnbondInput.tsx b/src/library/Form/Unbond/UnbondInput.tsx index c17cd58ba..2761b69f2 100644 --- a/src/library/Form/Unbond/UnbondInput.tsx +++ b/src/library/Form/Unbond/UnbondInput.tsx @@ -1,7 +1,6 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { planckToUnit } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import type { ChangeEvent } from 'react'; import { useEffect, useState } from 'react'; @@ -11,6 +10,7 @@ import { useActiveAccounts } from 'contexts/ActiveAccounts'; import { InputWrapper } from '../Wrappers'; import type { UnbondInputProps } from '../types'; import { ButtonSubmitInvert } from 'kits/Buttons/ButtonSubmitInvert'; +import { planckToUnitBn } from 'library/Utils'; export const UnbondInput = ({ defaultValue, @@ -25,7 +25,7 @@ export const UnbondInput = ({ const { activeAccount } = useActiveAccounts(); // get the actively bonded amount. - const activeUnit = planckToUnit(active, networkData.units); + const activeUnit = planckToUnitBn(active, networkData.units); // the current local bond value. const [localBond, setLocalBond] = useState(value); @@ -58,7 +58,7 @@ export const UnbondInput = ({ }; // unbond to min as unit. - const unbondToMinUnit = planckToUnit(unbondToMin, networkData.units); + const unbondToMinUnit = planckToUnitBn(unbondToMin, networkData.units); // available funds as jsx. const maxBondedJsx = ( diff --git a/src/library/Graphs/Utils.ts b/src/library/Graphs/Utils.ts index 178dd8a05..e0f691b76 100644 --- a/src/library/Graphs/Utils.ts +++ b/src/library/Graphs/Utils.ts @@ -1,7 +1,6 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { greaterThanZero, planckToUnit } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { addDays, @@ -16,6 +15,7 @@ import { MaxPayoutDays } from 'consts'; import type { AnyApi, AnySubscan } from 'types'; import type { PayoutDayCursor } from './types'; import type { AnyJson } from '@w3ux/types'; +import { planckToUnitBn } from 'library/Utils'; // Given payouts, calculate daily income and fill missing days with zero amounts. export const calculateDailyPayouts = ( @@ -67,7 +67,7 @@ export const calculateDailyPayouts = ( // handle surpassed maximum days. if (daysPassed(thisDay, fromDate) >= maxDays) { dailyPayouts.push({ - amount: planckToUnit(curPayout.amount, units), + amount: planckToUnitBn(curPayout.amount, units), event_id: getEventId(curPayout), block_timestamp: getUnixTime(curDay), }); @@ -81,7 +81,7 @@ export const calculateDailyPayouts = ( if (daysDiff > 0) { // add current payout cursor to dailyPayouts. dailyPayouts.push({ - amount: planckToUnit(curPayout.amount, units), + amount: planckToUnitBn(curPayout.amount, units), event_id: getEventId(curPayout), block_timestamp: getUnixTime(curDay), }); @@ -106,7 +106,7 @@ export const calculateDailyPayouts = ( (p === payouts.length && !curPayout.amount.isZero()) ) { dailyPayouts.push({ - amount: planckToUnit(curPayout.amount, units), + amount: planckToUnitBn(curPayout.amount, units), event_id: getEventId(curPayout), block_timestamp: getUnixTime(curDay), }); @@ -368,11 +368,11 @@ export const getLatestReward = ( ) => { // get most recent payout const payoutExists = - payouts.find((p: AnySubscan) => greaterThanZero(new BigNumber(p.amount))) ?? + payouts.find((p: AnySubscan) => new BigNumber(p.amount).isGreaterThan(0)) ?? null; const poolClaimExists = poolClaims.find((p: AnySubscan) => - greaterThanZero(new BigNumber(p.amount)) + new BigNumber(p.amount).isGreaterThan(0) ) ?? null; // calculate which payout was most recent diff --git a/src/library/ListItem/Labels/EraStatus.tsx b/src/library/ListItem/Labels/EraStatus.tsx index c691e9aec..c79a11f08 100644 --- a/src/library/ListItem/Labels/EraStatus.tsx +++ b/src/library/ListItem/Labels/EraStatus.tsx @@ -1,12 +1,13 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { capitalizeFirstLetter, planckToUnit } from '@w3ux/utils'; +import { capitalizeFirstLetter } from '@w3ux/utils'; import { useTranslation } from 'react-i18next'; import { ValidatorStatusWrapper } from 'library/ListItem/Wrappers'; import { useNetwork } from 'contexts/Network'; import type { EraStatusProps } from '../types'; import { useSyncing } from 'hooks/useSyncing'; +import { planckToUnitBn } from 'library/Utils'; export const EraStatus = ({ noMargin, status, totalStake }: EraStatusProps) => { const { t } = useTranslation('library'); @@ -22,7 +23,7 @@ export const EraStatus = ({ noMargin, status, totalStake }: EraStatusProps) => { {syncing ? t('syncing') : validatorStatus !== 'waiting' - ? `${t('listItemActive')} / ${planckToUnit(totalStake, units) + ? `${t('listItemActive')} / ${planckToUnitBn(totalStake, units) .integerValue() .toFormat()} ${unit}` : capitalizeFirstLetter(t(`${validatorStatus}`) ?? '')} diff --git a/src/library/ListItem/Labels/NominationStatus.tsx b/src/library/ListItem/Labels/NominationStatus.tsx index b82cad409..16e8b6eda 100644 --- a/src/library/ListItem/Labels/NominationStatus.tsx +++ b/src/library/ListItem/Labels/NominationStatus.tsx @@ -1,7 +1,6 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { greaterThanZero, planckToUnit } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { useTranslation } from 'react-i18next'; import { useStaking } from 'contexts/Staking'; @@ -9,6 +8,7 @@ import { ValidatorStatusWrapper } from 'library/ListItem/Wrappers'; import { useNetwork } from 'contexts/Network'; import type { NominationStatusProps } from '../types'; import { useSyncing } from 'hooks/useSyncing'; +import { planckToUnitBn } from 'library/Utils'; export const NominationStatus = ({ address, @@ -40,7 +40,7 @@ export const NominationStatus = ({ const staker = stakers?.find((s) => s.address === address); const exists = (staker?.others || []).find(({ who }) => who === nominator); if (exists) { - stakedAmount = planckToUnit(new BigNumber(exists.value), units); + stakedAmount = planckToUnitBn(new BigNumber(exists.value), units); } } @@ -48,7 +48,7 @@ export const NominationStatus = ({
{t(`${status || 'waiting'}`)} - {greaterThanZero(stakedAmount) + {stakedAmount.isGreaterThan(0) ? ` / ${syncing ? '...' : `${stakedAmount.toFormat()} ${unit}`}` : null}
diff --git a/src/library/ListItem/Labels/PoolBonded.tsx b/src/library/ListItem/Labels/PoolBonded.tsx index 2a2892f7c..7cc851a3a 100644 --- a/src/library/ListItem/Labels/PoolBonded.tsx +++ b/src/library/ListItem/Labels/PoolBonded.tsx @@ -1,13 +1,14 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { planckToUnit, rmCommas } from '@w3ux/utils'; +import { rmCommas } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { useNetwork } from 'contexts/Network'; import type { Pool } from 'library/Pool/types'; import { TooltipTrigger } from '../Wrappers'; import { useTranslation } from 'react-i18next'; import { useTooltip } from 'contexts/Tooltip'; +import { planckToUnitBn } from 'library/Utils'; export const PoolBonded = ({ pool }: { pool: Pool }) => { const { t } = useTranslation('library'); @@ -25,7 +26,7 @@ export const PoolBonded = ({ pool }: { pool: Pool }) => { const TokenIcon = token; // Format total bonded pool amount. - const bonded = planckToUnit(new BigNumber(rmCommas(points)), units); + const bonded = planckToUnitBn(new BigNumber(rmCommas(points)), units); return (
diff --git a/src/library/ListItem/Labels/PoolMemberBonded.tsx b/src/library/ListItem/Labels/PoolMemberBonded.tsx index a0e8a8992..b8d41b9f0 100644 --- a/src/library/ListItem/Labels/PoolMemberBonded.tsx +++ b/src/library/ListItem/Labels/PoolMemberBonded.tsx @@ -1,12 +1,13 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { greaterThanZero, planckToUnit, rmCommas } from '@w3ux/utils'; +import { rmCommas } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { useTranslation } from 'react-i18next'; import { ValidatorStatusWrapper } from 'library/ListItem/Wrappers'; import { useNetwork } from 'contexts/Network'; import type { AnyMetaBatch } from 'types'; +import { planckToUnitBn } from 'library/Utils'; export const PoolMemberBonded = ({ meta, @@ -30,8 +31,8 @@ export const PoolMemberBonded = ({ if (poolMember) { const { points, unbondingEras } = poolMember; - bonded = planckToUnit(new BigNumber(rmCommas(points)), units); - status = greaterThanZero(bonded) ? 'active' : 'inactive'; + bonded = planckToUnitBn(new BigNumber(rmCommas(points)), units); + status = bonded.isGreaterThan(0) ? 'active' : 'inactive'; // converting unbonding eras from points to units let totalUnbondingUnit = new BigNumber(0); @@ -39,7 +40,7 @@ export const PoolMemberBonded = ({ const amountBn = new BigNumber(rmCommas(amount as string)); totalUnbondingUnit = totalUnbondingUnit.plus(amountBn); }); - totalUnbonding = planckToUnit(new BigNumber(totalUnbondingUnit), units); + totalUnbonding = planckToUnitBn(new BigNumber(totalUnbondingUnit), units); } return ( @@ -49,7 +50,7 @@ export const PoolMemberBonded = ({
{t('syncing')}...
) : ( - greaterThanZero(bonded) && ( + bonded.isGreaterThan(0) && (
{t('bonded')}: {bonded.decimalPlaces(3).toFormat()} {unit} @@ -58,7 +59,7 @@ export const PoolMemberBonded = ({ ) )} - {poolMember && greaterThanZero(totalUnbonding) && ( + {poolMember && totalUnbonding.isGreaterThan(0) && (
{t('unbonding')} {totalUnbonding.decimalPlaces(3).toFormat()} {unit} diff --git a/src/library/Utils/index.ts b/src/library/Utils/index.ts new file mode 100644 index 000000000..d40ee98f9 --- /dev/null +++ b/src/library/Utils/index.ts @@ -0,0 +1,13 @@ +// Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors +// SPDX-License-Identifier: GPL-3.0-only + +import { planckToUnit, rmCommas } from '@w3ux/utils'; +import BigNumber from 'bignumber.js'; + +// Return `planckToUnit` as a `BigNumber`. +export const planckToUnitBn = (val: BigNumber, units: number): BigNumber => + new BigNumber(planckToUnit(val.toString(), units)); + +// Converts a string to a BigNumber. +export const stringToBn = (value: string): BigNumber => + new BigNumber(rmCommas(value)); diff --git a/src/library/ValidatorList/index.tsx b/src/library/ValidatorList/index.tsx index 205250494..cf61da7e0 100644 --- a/src/library/ValidatorList/index.tsx +++ b/src/library/ValidatorList/index.tsx @@ -3,7 +3,6 @@ import { faBars, faGripVertical } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { isNotZero } from '@w3ux/utils'; import { motion } from 'framer-motion'; import type { FormEvent } from 'react'; import { useEffect, useRef, useState } from 'react'; @@ -276,7 +275,7 @@ export const ValidatorListInner = ({ // Configure validator list when network is ready to fetch. useEffect(() => { - if (isReady && isNotZero(activeEra.index)) { + if (isReady && !activeEra.index.isZero()) { setupValidatorList(); } }, [isReady, activeEra.index, syncing, fetched]); diff --git a/src/modals/Accounts/Account.tsx b/src/modals/Accounts/Account.tsx index 44e2fb569..629c0e36b 100644 --- a/src/modals/Accounts/Account.tsx +++ b/src/modals/Accounts/Account.tsx @@ -3,7 +3,7 @@ import { faGlasses } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { ellipsisFn, planckToUnit } from '@w3ux/utils'; +import { ellipsisFn } from '@w3ux/utils'; import { useTranslation } from 'react-i18next'; import { ExtensionIcons } from '@w3ux/extension-assets/util'; import LedgerSVG from '@w3ux/extension-assets/LedgerSquare.svg?react'; @@ -17,6 +17,7 @@ import { useImportedAccounts } from 'contexts/Connect/ImportedAccounts'; import { AccountWrapper } from './Wrappers'; import type { AccountItemProps } from './types'; import BigNumber from 'bignumber.js'; +import { planckToUnitBn } from 'library/Utils'; export const AccountButton = ({ label, @@ -127,7 +128,7 @@ export const AccountButton = ({
- {`${t('free')}: ${planckToUnit( + {`${t('free')}: ${planckToUnitBn( transferrableBalance || new BigNumber(0), units ) diff --git a/src/modals/Bond/index.tsx b/src/modals/Bond/index.tsx index d32e44579..6dae88fc7 100644 --- a/src/modals/Bond/index.tsx +++ b/src/modals/Bond/index.tsx @@ -1,7 +1,7 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { planckToUnit, unitToPlanck } from '@w3ux/utils'; +import { unitToPlanck } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { useEffect, useState } from 'react'; import { useTranslation } from 'react-i18next'; @@ -21,6 +21,7 @@ import { useNetwork } from 'contexts/Network'; import { useActiveAccounts } from 'contexts/ActiveAccounts'; import { ModalPadding } from 'kits/Overlay/structure/ModalPadding'; import { ModalWarnings } from 'kits/Overlay/structure/ModalWarnings'; +import { planckToUnitBn } from 'library/Utils'; export const Bond = () => { const { t } = useTranslation('modals'); @@ -44,7 +45,7 @@ export const Bond = () => { const isPooling = bondFor === 'pool'; const { nominate, transferrableBalance } = getTransferOptions(activeAccount); - const freeToBond = planckToUnit( + const freeToBond = planckToUnitBn( (bondFor === 'nominator' ? nominate.totalAdditionalBond : transferrableBalance @@ -55,7 +56,7 @@ export const Bond = () => { const largestTxFee = useBondGreatestFee({ bondFor }); // Format unclaimed pool rewards. - const pendingRewardsUnit = planckToUnit(pendingPoolRewards, units); + const pendingRewardsUnit = planckToUnitBn(pendingPoolRewards, units); // local bond value. const [bond, setBond] = useState<{ bond: string }>({ @@ -76,16 +77,18 @@ export const Bond = () => { // bond minus tx fees. const enoughToCoverTxFees: boolean = freeToBond .minus(bond.bond) - .isGreaterThan(planckToUnit(largestTxFee, units)); + .isGreaterThan(planckToUnitBn(largestTxFee, units)); // bond value after max tx fees have been deducated. let bondAfterTxFees: BigNumber; if (enoughToCoverTxFees) { - bondAfterTxFees = unitToPlanck(String(bond.bond), units); + bondAfterTxFees = new BigNumber(unitToPlanck(bond.bond, units).toString()); } else { bondAfterTxFees = BigNumber.max( - unitToPlanck(String(bond.bond), units).minus(largestTxFee), + new BigNumber(unitToPlanck(String(bond.bond), units).toString()).minus( + largestTxFee + ), 0 ); } diff --git a/src/modals/ClaimPayouts/Forms.tsx b/src/modals/ClaimPayouts/Forms.tsx index af8d5386f..cad731157 100644 --- a/src/modals/ClaimPayouts/Forms.tsx +++ b/src/modals/ClaimPayouts/Forms.tsx @@ -146,7 +146,7 @@ export const Forms = forwardRef(
diff --git a/src/modals/ClaimPayouts/Item.tsx b/src/modals/ClaimPayouts/Item.tsx index cada0eb89..58dfc1ab0 100644 --- a/src/modals/ClaimPayouts/Item.tsx +++ b/src/modals/ClaimPayouts/Item.tsx @@ -2,12 +2,12 @@ // SPDX-License-Identifier: GPL-3.0-only import { useTranslation } from 'react-i18next'; -import { planckToUnit } from '@w3ux/utils'; import { useNetwork } from 'contexts/Network'; import { ItemWrapper } from './Wrappers'; import type { ItemProps } from './types'; import { getTotalPayout } from './Utils'; import { ButtonSubmit } from 'kits/Buttons/ButtonSubmit'; +import { planckToUnitBn } from 'library/Utils'; export const Item = ({ era, @@ -36,7 +36,7 @@ export const Item = ({

- {planckToUnit(totalPayout, units).toString()} {unit} + {planckToUnitBn(totalPayout, units).toString()} {unit}

diff --git a/src/modals/ClaimReward/index.tsx b/src/modals/ClaimReward/index.tsx index 4cf5b7bbe..7c8ec608c 100644 --- a/src/modals/ClaimReward/index.tsx +++ b/src/modals/ClaimReward/index.tsx @@ -1,7 +1,6 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { greaterThanZero, planckToUnit } from '@w3ux/utils'; import { useEffect, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useApi } from 'contexts/Api'; @@ -18,6 +17,7 @@ import { useActiveAccounts } from 'contexts/ActiveAccounts'; import { ModalPadding } from 'kits/Overlay/structure/ModalPadding'; import { ModalWarnings } from 'kits/Overlay/structure/ModalWarnings'; import { ActionItem } from 'library/ActionItem'; +import { planckToUnit } from '@w3ux/utils'; export const ClaimReward = () => { const { t } = useTranslation('modals'); @@ -79,7 +79,7 @@ export const ClaimReward = () => { submitExtrinsic.proxySupported ); - if (!greaterThanZero(pendingPoolRewards)) { + if (!pendingPoolRewards.isGreaterThan(0)) { warnings.push(`${t('noRewards')}`); } @@ -101,7 +101,7 @@ export const ClaimReward = () => { ) : null} diff --git a/src/modals/ManageFastUnstake/index.tsx b/src/modals/ManageFastUnstake/index.tsx index 1d2895c85..75d981702 100644 --- a/src/modals/ManageFastUnstake/index.tsx +++ b/src/modals/ManageFastUnstake/index.tsx @@ -1,7 +1,6 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { planckToUnit } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { useEffect, useState } from 'react'; import { useTranslation } from 'react-i18next'; @@ -23,6 +22,7 @@ import { ModalPadding } from 'kits/Overlay/structure/ModalPadding'; import { ModalWarnings } from 'kits/Overlay/structure/ModalWarnings'; import { ActionItem } from 'library/ActionItem'; import { ModalNotes } from 'kits/Overlay/structure/ModalNotes'; +import { planckToUnitBn } from 'library/Utils'; export const ManageFastUnstake = () => { const { t } = useTranslation('modals'); @@ -113,7 +113,7 @@ export const ManageFastUnstake = () => { if (!isFastUnstaking) { if (!enoughForDeposit) { warnings.push( - `${t('noEnough')} ${planckToUnit( + `${t('noEnough')} ${planckToUnitBn( fastUnstakeDeposit, units ).toString()} ${unit}` @@ -175,7 +175,7 @@ export const ManageFastUnstake = () => {

{t('registerFastUnstake')}{' '} - {planckToUnit(fastUnstakeDeposit, units).toString()} {unit}.{' '} + {planckToUnitBn(fastUnstakeDeposit, units).toString()} {unit}.{' '} {t('fastUnstakeOnceRegistered')}

diff --git a/src/modals/ManagePool/Forms/ClaimCommission/index.tsx b/src/modals/ManagePool/Forms/ClaimCommission/index.tsx index 22c4703d6..c590ebaaf 100644 --- a/src/modals/ManagePool/Forms/ClaimCommission/index.tsx +++ b/src/modals/ManagePool/Forms/ClaimCommission/index.tsx @@ -2,7 +2,7 @@ // SPDX-License-Identifier: GPL-3.0-only import { faChevronLeft } from '@fortawesome/free-solid-svg-icons'; -import { greaterThanZero, planckToUnit, rmCommas } from '@w3ux/utils'; +import { rmCommas } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import type { Dispatch, SetStateAction } from 'react'; import { useEffect, useState } from 'react'; @@ -21,6 +21,7 @@ import { ModalPadding } from 'kits/Overlay/structure/ModalPadding'; import { ModalWarnings } from 'kits/Overlay/structure/ModalWarnings'; import { ActionItem } from 'library/ActionItem'; import { ModalNotes } from 'kits/Overlay/structure/ModalNotes'; +import { planckToUnitBn } from 'library/Utils'; export const ClaimCommission = ({ setSection, @@ -46,7 +47,7 @@ export const ClaimCommission = ({ const [valid, setValid] = useState(false); useEffect(() => { - setValid(isOwner() && greaterThanZero(pendingCommission)); + setValid(isOwner() && pendingCommission.isGreaterThan(0)); }, [activePool, pendingCommission]); // tx to submit @@ -83,10 +84,10 @@ export const ClaimCommission = ({ ) : null}

{t('sentToCommissionPayee')}

diff --git a/src/modals/ManagePool/Forms/LeavePool/index.tsx b/src/modals/ManagePool/Forms/LeavePool/index.tsx index ac4319569..c94c94447 100644 --- a/src/modals/ManagePool/Forms/LeavePool/index.tsx +++ b/src/modals/ManagePool/Forms/LeavePool/index.tsx @@ -2,7 +2,7 @@ // SPDX-License-Identifier: GPL-3.0-only import { faChevronLeft } from '@fortawesome/free-solid-svg-icons'; -import { greaterThanZero, planckToUnit, unitToPlanck } from '@w3ux/utils'; +import { unitToPlanck } from '@w3ux/utils'; import { getUnixTime } from 'date-fns'; import type { Dispatch, SetStateAction } from 'react'; import { useEffect, useState } from 'react'; @@ -24,6 +24,7 @@ import { ButtonSubmitInvert } from 'kits/Buttons/ButtonSubmitInvert'; import { ModalPadding } from 'kits/Overlay/structure/ModalPadding'; import { ModalWarnings } from 'kits/Overlay/structure/ModalWarnings'; import { ActionItem } from 'library/ActionItem'; +import { planckToUnitBn } from 'library/Utils'; export const LeavePool = ({ setSection, @@ -53,10 +54,10 @@ export const LeavePool = ({ true ); - const pendingRewardsUnit = planckToUnit(pendingPoolRewards, units); + const pendingRewardsUnit = planckToUnitBn(pendingPoolRewards, units); // convert BigNumber values to number - const freeToUnbond = planckToUnit(activeBn, units); + const freeToUnbond = planckToUnitBn(activeBn, units); // local bond value const [bond, setBond] = useState<{ bond: string }>({ @@ -67,7 +68,7 @@ export const LeavePool = ({ const [bondValid, setBondValid] = useState(false); // unbond all validation - const isValid = (() => greaterThanZero(freeToUnbond))(); + const isValid = (() => freeToUnbond.isGreaterThan(0))(); // update bond value on task change useEffect(() => { @@ -85,9 +86,12 @@ export const LeavePool = ({ return tx; } - const bondToSubmit = unitToPlanck(!bondValid ? '0' : bond.bond, units); - const bondAsString = bondToSubmit.isNaN() ? '0' : bondToSubmit.toString(); - tx = api.tx.nominationPools.unbond(activeAccount, bondAsString); + const bondToSubmit = unitToPlanck( + !bondValid ? '0' : bond.bond, + units + ).toString(); + + tx = api.tx.nominationPools.unbond(activeAccount, bondToSubmit); return tx; }; @@ -106,7 +110,7 @@ export const LeavePool = ({ submitExtrinsic.proxySupported ); - if (greaterThanZero(pendingRewardsUnit)) { + if (pendingRewardsUnit.isGreaterThan(0)) { warnings.push( `${t('unbondingWithdraw')} ${pendingRewardsUnit.toString()} ${unit}.` ); diff --git a/src/modals/Unbond/index.tsx b/src/modals/Unbond/index.tsx index 0590f191d..ccd85df53 100644 --- a/src/modals/Unbond/index.tsx +++ b/src/modals/Unbond/index.tsx @@ -1,7 +1,7 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { isNotZero, planckToUnit, unitToPlanck } from '@w3ux/utils'; +import { unitToPlanck } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { getUnixTime } from 'date-fns'; import { useEffect, useState } from 'react'; @@ -26,6 +26,7 @@ import { useActiveAccounts } from 'contexts/ActiveAccounts'; import { ModalPadding } from 'kits/Overlay/structure/ModalPadding'; import { ModalWarnings } from 'kits/Overlay/structure/ModalWarnings'; import { ModalNotes } from 'kits/Overlay/structure/ModalNotes'; +import { planckToUnitBn } from 'library/Utils'; export const Unbond = () => { const { t } = useTranslation('modals'); @@ -63,7 +64,7 @@ export const Unbond = () => { true ); - const pendingRewardsUnit = planckToUnit(pendingPoolRewards, units); + const pendingRewardsUnit = planckToUnitBn(pendingPoolRewards, units); const isStaking = bondFor === 'nominator'; const isPooling = bondFor === 'pool'; @@ -74,10 +75,10 @@ export const Unbond = () => { : allTransferOptions.nominate; // convert BigNumber values to number - const freeToUnbond = planckToUnit(activeBn, units); - const minJoinBond = planckToUnit(minJoinBondBn, units); - const minCreateBond = planckToUnit(minCreateBondBn, units); - const minNominatorBond = planckToUnit(minNominatorBondBn, units); + const freeToUnbond = planckToUnitBn(activeBn, units); + const minJoinBond = planckToUnitBn(minJoinBondBn, units); + const minCreateBond = planckToUnitBn(minCreateBondBn, units); + const minNominatorBond = planckToUnitBn(minNominatorBondBn, units); // local bond value const [bond, setBond] = useState<{ bond: string }>({ @@ -109,14 +110,16 @@ export const Unbond = () => { return tx; } - const bondToSubmit = unitToPlanck(!bondValid ? '0' : bond.bond, units); - const bondAsString = bondToSubmit.isNaN() ? '0' : bondToSubmit.toString(); + const bondToSubmit = unitToPlanck( + !bondValid ? '0' : bond.bond, + units + ).toString(); // determine tx if (isPooling) { - tx = api.tx.nominationPools.unbond(activeAccount, bondAsString); + tx = api.tx.nominationPools.unbond(activeAccount, bondToSubmit); } else if (isStaking) { - tx = api.tx.staking.unbond(bondAsString); + tx = api.tx.staking.unbond(bondToSubmit); } return tx; }; @@ -134,7 +137,7 @@ export const Unbond = () => { const nominatorActiveBelowMin = bondFor === 'nominator' && - isNotZero(activeBn) && + !activeBn.isZero() && activeBn.isLessThan(minNominatorBondBn); const poolToMinBn = isDepositor() ? minCreateBondBn : minJoinBondBn; @@ -162,7 +165,7 @@ export const Unbond = () => { if (poolActiveBelowMin) { warnings.push( t('unbondErrorBelowMinimum', { - bond: planckToUnit(poolToMinBn, units), + bond: planckToUnitBn(poolToMinBn, units), unit, }) ); diff --git a/src/modals/UnlockChunks/Chunk.tsx b/src/modals/UnlockChunks/Chunk.tsx index fe0a498a7..10180528e 100644 --- a/src/modals/UnlockChunks/Chunk.tsx +++ b/src/modals/UnlockChunks/Chunk.tsx @@ -1,7 +1,6 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { planckToUnit } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { fromUnixTime } from 'date-fns'; import { useEffect } from 'react'; @@ -16,6 +15,7 @@ import { ChunkWrapper } from './Wrappers'; import type { ChunkProps } from './types'; import { useApi } from 'contexts/Api'; import { ButtonSubmit } from 'kits/Buttons/ButtonSubmit'; +import { planckToUnitBn } from 'library/Utils'; export const Chunk = ({ chunk, bondFor, onRebond }: ChunkProps) => { const { t } = useTranslation('modals'); @@ -48,7 +48,7 @@ export const Chunk = ({ chunk, bondFor, onRebond }: ChunkProps) => {
-

{`${planckToUnit(new BigNumber(value), units)} ${unit}`}

+

{`${planckToUnitBn(new BigNumber(value), units)} ${unit}`}

{left.isLessThanOrEqualTo(0) ? ( t('unlocked') diff --git a/src/modals/UnlockChunks/Forms.tsx b/src/modals/UnlockChunks/Forms.tsx index 4bedecb95..783196201 100644 --- a/src/modals/UnlockChunks/Forms.tsx +++ b/src/modals/UnlockChunks/Forms.tsx @@ -2,7 +2,7 @@ // SPDX-License-Identifier: GPL-3.0-only import { faChevronLeft } from '@fortawesome/free-solid-svg-icons'; -import { planckToUnit, rmCommas } from '@w3ux/utils'; +import { rmCommas } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import type { ForwardedRef } from 'react'; import { forwardRef, useEffect, useState } from 'react'; @@ -27,6 +27,7 @@ import { ButtonSubmitInvert } from 'kits/Buttons/ButtonSubmitInvert'; import { ModalPadding } from 'kits/Overlay/structure/ModalPadding'; import { ModalWarnings } from 'kits/Overlay/structure/ModalWarnings'; import { ActionItem } from 'library/ActionItem'; +import { planckToUnitBn } from 'library/Utils'; export const Forms = forwardRef( ( @@ -101,7 +102,7 @@ export const Forms = forwardRef( // if no more bonded funds from pool, remove from poolMembers list if (bondFor === 'pool') { const points = membership?.points ? rmCommas(membership.points) : 0; - const bonded = planckToUnit(new BigNumber(points), units); + const bonded = planckToUnitBn(new BigNumber(points), units); if (bonded.isZero()) { removePoolMember(activeAccount); } @@ -142,7 +143,7 @@ export const Forms = forwardRef( {task === 'rebond' && ( <>

- {planckToUnit(withdrawAvailable, units) + {planckToUnitBn(withdrawAvailable, units) .decimalPlaces(3) .toFormat()}{' '} {unit} @@ -98,7 +98,10 @@ export const Overview = forwardRef( {t('unbonding')}

- {planckToUnit(totalUnbonding.minus(withdrawAvailable), units) + {planckToUnitBn( + totalUnbonding.minus(withdrawAvailable), + units + ) .decimalPlaces(3) .toFormat()}{' '} {unit} @@ -109,7 +112,7 @@ export const Overview = forwardRef(

{t('total')}

- {planckToUnit(totalUnbonding, units) + {planckToUnitBn(totalUnbonding, units) .decimalPlaces(3) .toFormat()}{' '} {unit} diff --git a/src/modals/Unstake/index.tsx b/src/modals/Unstake/index.tsx index cc1b4616a..3907bda26 100644 --- a/src/modals/Unstake/index.tsx +++ b/src/modals/Unstake/index.tsx @@ -1,7 +1,7 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { greaterThanZero, planckToUnit, unitToPlanck } from '@w3ux/utils'; +import { unitToPlanck } from '@w3ux/utils'; import { getUnixTime } from 'date-fns'; import { useEffect, useState } from 'react'; import { useTranslation } from 'react-i18next'; @@ -25,6 +25,7 @@ import { useBalances } from 'contexts/Balances'; import { ModalPadding } from 'kits/Overlay/structure/ModalPadding'; import { ModalWarnings } from 'kits/Overlay/structure/ModalWarnings'; import { ActionItem } from 'library/ActionItem'; +import { planckToUnitBn } from 'library/Utils'; export const Unstake = () => { const { t } = useTranslation('modals'); @@ -56,7 +57,7 @@ export const Unstake = () => { ); // convert BigNumber values to number - const freeToUnbond = planckToUnit(active, units); + const freeToUnbond = planckToUnitBn(active, units); // local bond value const [bond, setBond] = useState<{ bond: string }>({ @@ -67,7 +68,7 @@ export const Unstake = () => { const [bondValid, setBondValid] = useState(false); // unbond all validation - const isValid = (() => greaterThanZero(freeToUnbond))(); + const isValid = (() => freeToUnbond.isGreaterThan(0))(); // update bond value on task change useEffect(() => { @@ -89,12 +90,14 @@ export const Unstake = () => { String(!bondValid ? '0' : bond.bond), units ); - const bondAsString = bondToSubmit.isNaN() ? '0' : bondToSubmit.toString(); - if (!bondAsString) { + if (bondToSubmit == 0n) { return api.tx.staking.chill(); } - const txs = [api.tx.staking.chill(), api.tx.staking.unbond(bondAsString)]; + const txs = [ + api.tx.staking.chill(), + api.tx.staking.unbond(bondToSubmit.toString()), + ]; return newBatchCall(txs, controller); }; @@ -125,7 +128,7 @@ export const Unstake = () => { ))} ) : null} - {greaterThanZero(freeToUnbond) ? ( + {freeToUnbond.isGreaterThan(0) ? ( { const { t } = useTranslation('modals'); @@ -37,13 +38,16 @@ export const UpdateReserve = () => { useTransferOptions(); const { edReserved } = getTransferOptions(activeAccount); - const minReserve = planckToUnit(edReserved, units); + const minReserve = planckToUnitBn(edReserved, units); const maxReserve = minReserve.plus( ['polkadot', 'westend'].includes(network) ? 3 : 1 ); const [sliderReserve, setSliderReserve] = useState( - planckToUnit(feeReserve, units).plus(minReserve).decimalPlaces(3).toNumber() + planckToUnitBn(feeReserve, units) + .plus(minReserve) + .decimalPlaces(3) + .toNumber() ); const handleChange = (val: BigNumber) => { @@ -52,7 +56,7 @@ export const UpdateReserve = () => { const actualReserve = BigNumber.max(val.minus(minReserve), 0).toNumber(); const actualReservePlanck = unitToPlanck(actualReserve.toString(), units); setSliderReserve(val.decimalPlaces(3).toNumber()); - setFeeReserveBalance(actualReservePlanck); + setFeeReserveBalance(new BigNumber(actualReservePlanck.toString())); }; return ( diff --git a/src/modals/ValidatorMetrics/index.tsx b/src/modals/ValidatorMetrics/index.tsx index 5675f7fd3..d3c7983b8 100644 --- a/src/modals/ValidatorMetrics/index.tsx +++ b/src/modals/ValidatorMetrics/index.tsx @@ -2,7 +2,7 @@ // SPDX-License-Identifier: GPL-3.0-only import { Polkicon } from '@w3ux/react-polkicon'; -import { ellipsisFn, planckToUnit } from '@w3ux/utils'; +import { ellipsisFn } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { useEffect, useState, useRef } from 'react'; import { useTranslation } from 'react-i18next'; @@ -25,6 +25,7 @@ import { usePlugins } from 'contexts/Plugins'; import { useApi } from 'contexts/Api'; import { ButtonHelp } from 'kits/Buttons/ButtonHelp'; import { ModalPadding } from 'kits/Overlay/structure/ModalPadding'; +import { planckToUnitBn } from 'library/Utils'; export const ValidatorMetrics = () => { const { t } = useTranslation('modals'); @@ -80,12 +81,12 @@ export const ValidatorMetrics = () => { const stats = [ { label: t('selfStake'), - value: `${planckToUnit(validatorOwnStake, units).toFormat()} ${unit}`, + value: `${planckToUnitBn(validatorOwnStake, units).toFormat()} ${unit}`, help: 'Self Stake', }, { label: t('nominatorStake'), - value: `${planckToUnit(otherStake, units).toFormat()} ${unit}`, + value: `${planckToUnitBn(otherStake, units).toFormat()} ${unit}`, help: 'Nominator Stake', }, ]; diff --git a/src/model/Query/NetworkMeta/index.ts b/src/model/Query/NetworkMeta/index.ts index a1d5d193d..e818841a1 100644 --- a/src/model/Query/NetworkMeta/index.ts +++ b/src/model/Query/NetworkMeta/index.ts @@ -2,9 +2,10 @@ // SPDX-License-Identifier: GPL-3.0-only import type { ApiPromise } from '@polkadot/api'; -import { rmCommas, stringToBigNumber } from '@w3ux/utils'; +import { rmCommas } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import type { APIActiveEra } from 'contexts/Api/types'; +import { stringToBn } from 'library/Utils'; export class NetworkMeta { // Fetch network constants. @@ -67,28 +68,28 @@ export class NetworkMeta { minimumActiveStake: new BigNumber(networkMeta[4].toString()), }, poolsConfig: { - counterForPoolMembers: stringToBigNumber(networkMeta[5].toString()), - counterForBondedPools: stringToBigNumber(networkMeta[6].toString()), - counterForRewardPools: stringToBigNumber(networkMeta[7].toString()), - lastPoolId: stringToBigNumber(networkMeta[8].toString()), + counterForPoolMembers: stringToBn(networkMeta[5].toString()), + counterForBondedPools: stringToBn(networkMeta[6].toString()), + counterForRewardPools: stringToBn(networkMeta[7].toString()), + lastPoolId: stringToBn(networkMeta[8].toString()), maxPoolMembers, maxPoolMembersPerPool, maxPools, - minCreateBond: stringToBigNumber(networkMeta[12].toString()), - minJoinBond: stringToBigNumber(networkMeta[13].toString()), + minCreateBond: stringToBn(networkMeta[12].toString()), + minJoinBond: stringToBn(networkMeta[13].toString()), globalMaxCommission: Number( String(networkMeta[14]?.toHuman() || '100%').slice(0, -1) ), }, stakingMetrics: { - totalNominators: stringToBigNumber(networkMeta[15].toString()), - totalValidators: stringToBigNumber(networkMeta[16].toString()), - maxValidatorsCount: stringToBigNumber(networkMeta[17].toString()), - validatorCount: stringToBigNumber(networkMeta[18].toString()), - lastReward: stringToBigNumber(networkMeta[19].toString()), - lastTotalStake: stringToBigNumber(networkMeta[20].toString()), - minNominatorBond: stringToBigNumber(networkMeta[21].toString()), - totalStaked: stringToBigNumber(networkMeta[22].toString()), + totalNominators: stringToBn(networkMeta[15].toString()), + totalValidators: stringToBn(networkMeta[16].toString()), + maxValidatorsCount: stringToBn(networkMeta[17].toString()), + validatorCount: stringToBn(networkMeta[18].toString()), + lastReward: stringToBn(networkMeta[19].toString()), + lastTotalStake: stringToBn(networkMeta[20].toString()), + minNominatorBond: stringToBn(networkMeta[21].toString()), + totalStaked: stringToBn(networkMeta[22].toString()), }, }; } diff --git a/src/model/Query/StakingConstants/index.ts b/src/model/Query/StakingConstants/index.ts index 0a419395e..3d908bd35 100644 --- a/src/model/Query/StakingConstants/index.ts +++ b/src/model/Query/StakingConstants/index.ts @@ -2,9 +2,9 @@ // SPDX-License-Identifier: GPL-3.0-only import type { ApiPromise } from '@polkadot/api'; -import { stringToBigNumber } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { NetworkList } from 'config/networks'; +import { stringToBn } from 'library/Utils'; export class StakingConstants { // ------------------------------------------------------ @@ -42,35 +42,35 @@ export class StakingConstants { return { bondDuration: consts[0] - ? stringToBigNumber(consts[0].toString()) + ? stringToBn(consts[0].toString()) : this.FALLBACK.BONDING_DURATION, maxNominations: consts[1] - ? stringToBigNumber(consts[1].toString()) + ? stringToBn(consts[1].toString()) : this.FALLBACK.MAX_NOMINATIONS, sessionsPerEra: consts[2] - ? stringToBigNumber(consts[2].toString()) + ? stringToBn(consts[2].toString()) : this.FALLBACK.SESSIONS_PER_ERA, maxElectingVoters: consts[3] - ? stringToBigNumber(consts[3].toString()) + ? stringToBn(consts[3].toString()) : this.FALLBACK.MAX_ELECTING_VOTERS, expectedBlockTime: consts[4] - ? stringToBigNumber(consts[4].toString()) + ? stringToBn(consts[4].toString()) : this.FALLBACK.EXPECTED_BLOCK_TIME, epochDuration: consts[5] - ? stringToBigNumber(consts[5].toString()) + ? stringToBn(consts[5].toString()) : this.FALLBACK.EPOCH_DURATION, existentialDeposit: consts[6] - ? stringToBigNumber(consts[6].toString()) + ? stringToBn(consts[6].toString()) : new BigNumber(0), historyDepth: consts[7] - ? stringToBigNumber(consts[7].toString()) + ? stringToBn(consts[7].toString()) : new BigNumber(0), fastUnstakeDeposit: consts[8] - ? stringToBigNumber(consts[8].toString()) + ? stringToBn(consts[8].toString()) : new BigNumber(0), poolsPalletId: consts[9] ? consts[9].toU8a() : new Uint8Array(0), maxExposurePageSize: consts[10] - ? stringToBigNumber(consts[10].toString()) + ? stringToBn(consts[10].toString()) : NetworkList[network].maxExposurePageSize, }; } diff --git a/src/model/Subscribe/PoolsConfig/index.ts b/src/model/Subscribe/PoolsConfig/index.ts index 4cf6abd98..1cada3876 100644 --- a/src/model/Subscribe/PoolsConfig/index.ts +++ b/src/model/Subscribe/PoolsConfig/index.ts @@ -2,11 +2,12 @@ // SPDX-License-Identifier: GPL-3.0-only import type { VoidFn } from '@polkadot/api/types'; -import { rmCommas, stringToBigNumber } from '@w3ux/utils'; +import { rmCommas } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { ApiController } from 'controllers/Api'; import type { Unsubscribable } from 'controllers/Subscriptions/types'; import type { NetworkName } from 'types'; +import { stringToBn } from 'library/Utils'; export class PoolsConfig implements Unsubscribable { // ------------------------------------------------------ @@ -67,15 +68,15 @@ export class PoolsConfig implements Unsubscribable { : null; const poolsConfig = { - counterForPoolMembers: stringToBigNumber(result[0].toString()), - counterForBondedPools: stringToBigNumber(result[1].toString()), - counterForRewardPools: stringToBigNumber(result[2].toString()), - lastPoolId: stringToBigNumber(result[3].toString()), + counterForPoolMembers: stringToBn(result[0].toString()), + counterForBondedPools: stringToBn(result[1].toString()), + counterForRewardPools: stringToBn(result[2].toString()), + lastPoolId: stringToBn(result[3].toString()), maxPoolMembers, maxPoolMembersPerPool, maxPools, - minCreateBond: stringToBigNumber(result[7].toString()), - minJoinBond: stringToBigNumber(result[8].toString()), + minCreateBond: stringToBn(result[7].toString()), + minJoinBond: stringToBn(result[8].toString()), globalMaxCommission: Number( String(result[9]?.toHuman() || '100%').slice(0, -1) ), diff --git a/src/model/Subscribe/StakingMetrics/index.ts b/src/model/Subscribe/StakingMetrics/index.ts index b0d399852..7d43b4927 100644 --- a/src/model/Subscribe/StakingMetrics/index.ts +++ b/src/model/Subscribe/StakingMetrics/index.ts @@ -2,12 +2,12 @@ // SPDX-License-Identifier: GPL-3.0-only import type { VoidFn } from '@polkadot/api/types'; -import { stringToBigNumber } from '@w3ux/utils'; import type BigNumber from 'bignumber.js'; import type { APIActiveEra } from 'contexts/Api/types'; import { ApiController } from 'controllers/Api'; import type { Unsubscribable } from 'controllers/Subscriptions/types'; import type { NetworkName } from 'types'; +import { stringToBn } from 'library/Utils'; export class StakingMetrics implements Unsubscribable { // ------------------------------------------------------ @@ -69,14 +69,14 @@ export class StakingMetrics implements Unsubscribable { ], (result) => { const stakingMetrics = { - totalNominators: stringToBigNumber(result[0].toString()), - totalValidators: stringToBigNumber(result[1].toString()), - maxValidatorsCount: stringToBigNumber(result[2].toString()), - validatorCount: stringToBigNumber(result[3].toString()), - lastReward: stringToBigNumber(result[4].toString()), - lastTotalStake: stringToBigNumber(result[5].toString()), - minNominatorBond: stringToBigNumber(result[6].toString()), - totalStaked: stringToBigNumber(result[7].toString()), + totalNominators: stringToBn(result[0].toString()), + totalValidators: stringToBn(result[1].toString()), + maxValidatorsCount: stringToBn(result[2].toString()), + validatorCount: stringToBn(result[3].toString()), + lastReward: stringToBn(result[4].toString()), + lastTotalStake: stringToBn(result[5].toString()), + minNominatorBond: stringToBn(result[6].toString()), + totalStaked: stringToBn(result[7].toString()), }; document.dispatchEvent( diff --git a/src/pages/Nominate/Active/ManageBond.tsx b/src/pages/Nominate/Active/ManageBond.tsx index 16524bcae..ea4e8549a 100644 --- a/src/pages/Nominate/Active/ManageBond.tsx +++ b/src/pages/Nominate/Active/ManageBond.tsx @@ -3,7 +3,7 @@ import { faLockOpen } from '@fortawesome/free-solid-svg-icons'; import { Odometer } from '@w3ux/react-odometer'; -import { minDecimalPlaces, planckToUnit } from '@w3ux/utils'; +import { minDecimalPlaces } from '@w3ux/utils'; import type BigNumber from 'bignumber.js'; import { useTranslation } from 'react-i18next'; import { useBalances } from 'contexts/Balances'; @@ -21,6 +21,7 @@ import { useSyncing } from 'hooks/useSyncing'; import { ButtonHelp } from 'kits/Buttons/ButtonHelp'; import { ButtonPrimary } from 'kits/Buttons/ButtonPrimary'; import { ButtonRow } from 'kits/Structure/ButtonRow'; +import { planckToUnitBn } from 'library/Utils'; export const ManageBond = () => { const { t } = useTranslation('pages'); @@ -57,7 +58,10 @@ export const ManageBond = () => {

@@ -116,10 +120,10 @@ export const ManageBond = () => { diff --git a/src/pages/Nominate/Active/Stats/MinimumActiveStake.tsx b/src/pages/Nominate/Active/Stats/MinimumActiveStake.tsx index 1baac5a84..19338c395 100644 --- a/src/pages/Nominate/Active/Stats/MinimumActiveStake.tsx +++ b/src/pages/Nominate/Active/Stats/MinimumActiveStake.tsx @@ -1,11 +1,11 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { planckToUnit } from '@w3ux/utils'; import { useTranslation } from 'react-i18next'; import { Number } from 'library/StatBoxList/Number'; import { useNetwork } from 'contexts/Network'; import { useApi } from 'contexts/Api'; +import { planckToUnitBn } from 'library/Utils'; export const MinimumActiveStakeStat = () => { const { t } = useTranslation('pages'); @@ -16,7 +16,7 @@ export const MinimumActiveStakeStat = () => { const params = { label: t('nominate.minimumToEarnRewards'), - value: planckToUnit(minimumActiveStake, units).toNumber(), + value: planckToUnitBn(minimumActiveStake, units).toNumber(), decimals: 3, unit: `${unit}`, helpKey: 'Bonding', diff --git a/src/pages/Nominate/Active/Stats/MinimumNominatorBond.tsx b/src/pages/Nominate/Active/Stats/MinimumNominatorBond.tsx index bb2218f12..e108dfe60 100644 --- a/src/pages/Nominate/Active/Stats/MinimumNominatorBond.tsx +++ b/src/pages/Nominate/Active/Stats/MinimumNominatorBond.tsx @@ -1,11 +1,11 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { planckToUnit } from '@w3ux/utils'; import { useTranslation } from 'react-i18next'; import { Number } from 'library/StatBoxList/Number'; import { useNetwork } from 'contexts/Network'; import { useApi } from 'contexts/Api'; +import { planckToUnitBn } from 'library/Utils'; export const MinimumNominatorBondStat = () => { const { t } = useTranslation('pages'); @@ -14,7 +14,7 @@ export const MinimumNominatorBondStat = () => { const params = { label: t('nominate.minimumToNominate'), - value: planckToUnit(minNominatorBond, units).toNumber(), + value: planckToUnitBn(minNominatorBond, units).toNumber(), decimals: 3, unit: `${unit}`, helpKey: 'Bonding', diff --git a/src/pages/Nominate/Active/Status/UnclaimedPayoutsStatus.tsx b/src/pages/Nominate/Active/Status/UnclaimedPayoutsStatus.tsx index eaca0f596..b8e9297da 100644 --- a/src/pages/Nominate/Active/Status/UnclaimedPayoutsStatus.tsx +++ b/src/pages/Nominate/Active/Status/UnclaimedPayoutsStatus.tsx @@ -6,12 +6,13 @@ import { Stat } from 'library/Stat'; import { usePayouts } from 'contexts/Payouts'; import BigNumber from 'bignumber.js'; import { useApi } from 'contexts/Api'; -import { minDecimalPlaces, planckToUnit } from '@w3ux/utils'; +import { minDecimalPlaces } from '@w3ux/utils'; import { faCircleDown } from '@fortawesome/free-solid-svg-icons'; import { useOverlay } from 'kits/Overlay/Provider'; import { useNetwork } from 'contexts/Network'; import { useActiveAccounts } from 'contexts/ActiveAccounts'; import { useImportedAccounts } from 'contexts/Connect/ImportedAccounts'; +import { planckToUnitBn } from 'library/Utils'; export const UnclaimedPayoutsStatus = ({ dimmed }: { dimmed: boolean }) => { const { t } = useTranslation(); @@ -39,7 +40,7 @@ export const UnclaimedPayoutsStatus = ({ dimmed }: { dimmed: boolean }) => { type="odometer" stat={{ value: minDecimalPlaces( - planckToUnit(totalUnclaimed, units).toFormat(), + planckToUnitBn(totalUnclaimed, units).toFormat(), 2 ), }} diff --git a/src/pages/Nominate/Active/UnstakePrompts.tsx b/src/pages/Nominate/Active/UnstakePrompts.tsx index 076c04654..2c94760b0 100644 --- a/src/pages/Nominate/Active/UnstakePrompts.tsx +++ b/src/pages/Nominate/Active/UnstakePrompts.tsx @@ -3,7 +3,6 @@ import { faBolt, faLockOpen } from '@fortawesome/free-solid-svg-icons'; import { PageRow } from 'kits/Structure/PageRow'; -import { isNotZero } from '@w3ux/utils'; import { useTranslation } from 'react-i18next'; import { useTheme } from 'contexts/Themes'; import { useTransferOptions } from 'contexts/TransferOptions'; @@ -35,7 +34,7 @@ export const UnstakePrompts = () => { isUnstaking && active.isZero() && totalUnlocking.isZero() && - isNotZero(totalUnlocked); + !totalUnlocked.isZero(); return ( (isUnstaking || isFastUnstaking) && diff --git a/src/pages/Overview/BalanceChart.tsx b/src/pages/Overview/BalanceChart.tsx index 341607e1c..cbf0c25e2 100644 --- a/src/pages/Overview/BalanceChart.tsx +++ b/src/pages/Overview/BalanceChart.tsx @@ -3,7 +3,7 @@ import { faCheck, faCheckDouble } from '@fortawesome/free-solid-svg-icons'; import { Odometer } from '@w3ux/react-odometer'; -import { greaterThanZero, minDecimalPlaces, planckToUnit } from '@w3ux/utils'; +import { minDecimalPlaces } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { useTranslation } from 'react-i18next'; import { useBalances } from 'contexts/Balances'; @@ -20,6 +20,7 @@ import { useActiveAccounts } from 'contexts/ActiveAccounts'; import { useImportedAccounts } from 'contexts/Connect/ImportedAccounts'; import { useSyncing } from 'hooks/useSyncing'; import { ButtonTertiary } from 'kits/Buttons/ButtonTertiary'; +import { planckToUnitBn } from 'library/Utils'; export const BalanceChart = () => { const { t } = useTranslation('pages'); @@ -49,7 +50,7 @@ export const BalanceChart = () => { // User's total balance. const { free, frozen } = balance; - const totalBalance = planckToUnit( + const totalBalance = planckToUnitBn( free.plus(poolBondOpions.active).plus(unlockingPools), units ); @@ -59,7 +60,7 @@ export const BalanceChart = () => { ); // Total funds nominating. - const nominating = planckToUnit( + const nominating = planckToUnitBn( allTransferOptions.nominate.active .plus(allTransferOptions.nominate.totalUnlocking) .plus(allTransferOptions.nominate.totalUnlocked), @@ -67,7 +68,7 @@ export const BalanceChart = () => { ); // Total funds in pool. - const inPool = planckToUnit( + const inPool = planckToUnitBn( allTransferOptions.pool.active .plus(allTransferOptions.pool.totalUnlocking) .plus(allTransferOptions.pool.totalUnlocked), @@ -82,7 +83,7 @@ export const BalanceChart = () => { : new BigNumber(0); // Total funds available, including existential deposit, minus staking. - const graphAvailable = planckToUnit( + const graphAvailable = planckToUnitBn( BigNumber.max(free.minus(lockStakingAmount), 0), units ); @@ -90,15 +91,15 @@ export const BalanceChart = () => { // Graph percentages. const graphTotal = nominating.plus(inPool).plus(graphAvailable); - const graphNominating = greaterThanZero(nominating) + const graphNominating = nominating.isGreaterThan(0) ? nominating.dividedBy(graphTotal.multipliedBy(0.01)) : new BigNumber(0); - const graphInPool = greaterThanZero(inPool) + const graphInPool = inPool.isGreaterThan(0) ? inPool.dividedBy(graphTotal.multipliedBy(0.01)) : new BigNumber(0); - const graphNotStaking = greaterThanZero(graphTotal) + const graphNotStaking = graphTotal.isGreaterThan(0) ? BigNumber.max( new BigNumber(100).minus(graphNominating).minus(graphInPool), 0 @@ -107,20 +108,20 @@ export const BalanceChart = () => { // Available balance data. const fundsLockedPlank = BigNumber.max(frozen.minus(lockStakingAmount), 0); - const fundsLocked = planckToUnit(fundsLockedPlank, units); - let fundsReserved = planckToUnit(edReserved.plus(feeReserve), units); + const fundsLocked = planckToUnitBn(fundsLockedPlank, units); + let fundsReserved = planckToUnitBn(edReserved.plus(feeReserve), units); - const fundsFree = planckToUnit( + const fundsFree = planckToUnitBn( BigNumber.max(allTransferOptions.freeBalance.minus(fundsLockedPlank), 0), units ); // Available balance percentages. - const graphLocked = greaterThanZero(fundsLocked) + const graphLocked = fundsLocked.isGreaterThan(0) ? fundsLocked.dividedBy(graphAvailable.multipliedBy(0.01)) : new BigNumber(0); - const graphFree = greaterThanZero(fundsFree) + const graphFree = fundsFree.isGreaterThan(0) ? fundsFree.dividedBy(graphAvailable.multipliedBy(0.01)) : new BigNumber(0); @@ -135,12 +136,11 @@ export const BalanceChart = () => { currency: 'USD', }); - const isNominating = greaterThanZero(nominating); - const isInPool = greaterThanZero( - poolBondOpions.active - .plus(poolBondOpions.totalUnlocked) - .plus(poolBondOpions.totalUnlocking) - ); + const isNominating = nominating.isGreaterThan(0); + const isInPool = poolBondOpions.active + .plus(poolBondOpions.totalUnlocked) + .plus(poolBondOpions.totalUnlocking) + .isGreaterThan(0); return ( <> @@ -165,7 +165,7 @@ export const BalanceChart = () => { {isNominating ? ( ) : null} - {greaterThanZero(inPool) ? ( + {inPool.isGreaterThan(0) ? ( ) : null} @@ -197,7 +197,7 @@ export const BalanceChart = () => { flex: 1, minWidth: '8.5rem', flexBasis: `${ - greaterThanZero(graphFree) && greaterThanZero(graphLocked) + graphFree.isGreaterThan(0) && graphLocked.isGreaterThan(0) ? `${graphFree.toFixed(2)}%` : 'auto' }`, @@ -215,7 +215,7 @@ export const BalanceChart = () => { />

- {greaterThanZero(fundsLocked) ? ( + {fundsLocked.isGreaterThan(0) ? (
{ const { t } = useTranslation('pages'); @@ -35,7 +31,7 @@ export const Announcements = () => { bondedPools.forEach((b: BondedPool) => { totalPoolPoints = totalPoolPoints.plus(rmCommas(b.points)); }); - const totalPoolPointsUnit = planckToUnit(totalPoolPoints, units); + const totalPoolPointsUnit = planckToUnitBn(totalPoolPoints, units); const container = { hidden: { opacity: 0 }, @@ -65,7 +61,7 @@ export const Announcements = () => { announcements.push({ class: 'neutral', title: t('overview.networkCurrentlyStaked', { - total: planckToUnit(totalStaked, units).integerValue().toFormat(), + total: planckToUnitBn(totalStaked, units).integerValue().toFormat(), unit, network: capitalizeFirstLetter(network), }), diff --git a/src/pages/Overview/Payouts.tsx b/src/pages/Overview/Payouts.tsx index 7c157b1df..d9c444c43 100644 --- a/src/pages/Overview/Payouts.tsx +++ b/src/pages/Overview/Payouts.tsx @@ -17,9 +17,10 @@ import { Odometer } from '@w3ux/react-odometer'; import { locales, DefaultLocale } from 'locale'; import BigNumber from 'bignumber.js'; import { formatDistance, fromUnixTime, getUnixTime } from 'date-fns'; -import { minDecimalPlaces, planckToUnit } from '@w3ux/utils'; +import { minDecimalPlaces } from '@w3ux/utils'; import { useNetwork } from 'contexts/Network'; import { useSyncing } from 'hooks/useSyncing'; +import { planckToUnitBn } from 'library/Utils'; export const Payouts = () => { const { i18n, t } = useTranslation('pages'); @@ -85,7 +86,7 @@ export const Payouts = () => { value={minDecimalPlaces( lastReward === null ? '0' - : planckToUnit( + : planckToUnitBn( new BigNumber(lastReward.amount), units ).toFormat(), diff --git a/src/pages/Overview/Stats/SupplyStaked.tsx b/src/pages/Overview/Stats/SupplyStaked.tsx index c377b5cb2..abe2f60bb 100644 --- a/src/pages/Overview/Stats/SupplyStaked.tsx +++ b/src/pages/Overview/Stats/SupplyStaked.tsx @@ -1,12 +1,12 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { planckToUnit } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { useTranslation } from 'react-i18next'; import { Pie } from 'library/StatBoxList/Pie'; import { useNetwork } from 'contexts/Network'; import { useApi } from 'contexts/Api'; +import { planckToUnitBn } from 'library/Utils'; export const SupplyStakedStat = () => { const { t } = useTranslation('pages'); @@ -19,8 +19,8 @@ export const SupplyStakedStat = () => { const { totalIssuance } = networkMetrics; // total supply as percent. - const totalIssuanceUnit = planckToUnit(totalIssuance, units); - const lastTotalStakeUnit = planckToUnit(lastTotalStake, units); + const totalIssuanceUnit = planckToUnitBn(totalIssuance, units); + const lastTotalStakeUnit = planckToUnitBn(lastTotalStake, units); const supplyAsPercent = lastTotalStakeUnit.isZero() || totalIssuanceUnit.isZero() ? new BigNumber(0) diff --git a/src/pages/Payouts/PayoutList/index.tsx b/src/pages/Payouts/PayoutList/index.tsx index 9056a7c98..3d373a916 100644 --- a/src/pages/Payouts/PayoutList/index.tsx +++ b/src/pages/Payouts/PayoutList/index.tsx @@ -3,7 +3,7 @@ import { faBars, faGripVertical } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { ellipsisFn, isNotZero, planckToUnit } from '@w3ux/utils'; +import { ellipsisFn } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { formatDistance, fromUnixTime } from 'date-fns'; import { motion } from 'framer-motion'; @@ -26,6 +26,7 @@ import { ItemWrapper } from '../Wrappers'; import type { PayoutListProps } from '../types'; import { PayoutListProvider, usePayoutList } from './context'; import { payoutsPerPage } from 'library/List/defaults'; +import { planckToUnitBn } from 'library/Utils'; export const PayoutListInner = ({ allowMoreCols, @@ -64,7 +65,7 @@ export const PayoutListInner = ({ // configure list when network is ready to fetch useEffect(() => { - if (isReady && isNotZero(activeEra.index) && !fetched) { + if (isReady && !activeEra.index.isZero() && !fetched) { setPayouts(initialPayouts); setFetched(true); } @@ -158,7 +159,7 @@ export const PayoutListInner = ({

<> {p.event_id === 'Slashed' ? '-' : '+'} - {planckToUnit( + {planckToUnitBn( new BigNumber(p.amount), units ).toString()}{' '} diff --git a/src/pages/Payouts/Stats/LastEraPayout.tsx b/src/pages/Payouts/Stats/LastEraPayout.tsx index b6c8429bf..82857caae 100644 --- a/src/pages/Payouts/Stats/LastEraPayout.tsx +++ b/src/pages/Payouts/Stats/LastEraPayout.tsx @@ -1,18 +1,18 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { planckToUnit } from '@w3ux/utils'; import { useTranslation } from 'react-i18next'; import { Number } from 'library/StatBoxList/Number'; import { useNetwork } from 'contexts/Network'; import { useApi } from 'contexts/Api'; +import { planckToUnitBn } from 'library/Utils'; export const LastEraPayoutStat = () => { const { t } = useTranslation('pages'); const { unit, units } = useNetwork().networkData; const { lastReward } = useApi().stakingMetrics; - const lastRewardUnit = planckToUnit(lastReward, units).toNumber(); + const lastRewardUnit = planckToUnitBn(lastReward, units).toNumber(); const params = { label: t('payouts.lastEraPayout'), diff --git a/src/pages/Pools/Home/ManageBond.tsx b/src/pages/Pools/Home/ManageBond.tsx index 8c6869dbd..ce0a71101 100644 --- a/src/pages/Pools/Home/ManageBond.tsx +++ b/src/pages/Pools/Home/ManageBond.tsx @@ -3,7 +3,7 @@ import { faLockOpen } from '@fortawesome/free-solid-svg-icons'; import { Odometer } from '@w3ux/react-odometer'; -import { minDecimalPlaces, planckToUnit } from '@w3ux/utils'; +import { minDecimalPlaces } from '@w3ux/utils'; import { useTranslation } from 'react-i18next'; import { useHelp } from 'contexts/Help'; import { useActivePool } from 'contexts/Pools/ActivePool'; @@ -18,6 +18,7 @@ import { useSyncing } from 'hooks/useSyncing'; import { ButtonHelp } from 'kits/Buttons/ButtonHelp'; import { ButtonPrimary } from 'kits/Buttons/ButtonPrimary'; import { ButtonRow } from 'kits/Structure/ButtonRow'; +import { planckToUnitBn } from 'library/Utils'; export const ManageBond = () => { const { t } = useTranslation('pages'); @@ -54,7 +55,10 @@ export const ManageBond = () => {

@@ -116,10 +120,10 @@ export const ManageBond = () => { diff --git a/src/pages/Pools/Home/PoolStats/Announcements.tsx b/src/pages/Pools/Home/PoolStats/Announcements.tsx index 96c562b14..685506013 100644 --- a/src/pages/Pools/Home/PoolStats/Announcements.tsx +++ b/src/pages/Pools/Home/PoolStats/Announcements.tsx @@ -3,7 +3,7 @@ import { faBullhorn as faBack } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { planckToUnit, rmCommas } from '@w3ux/utils'; +import { rmCommas } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { motion } from 'framer-motion'; import { useTranslation } from 'react-i18next'; @@ -12,6 +12,7 @@ import { useActivePool } from 'contexts/Pools/ActivePool'; import { Announcement as AnnouncementLoader } from 'library/Loader/Announcement'; import { useNetwork } from 'contexts/Network'; import { Item } from 'library/Announcements/Wrappers'; +import { planckToUnitBn } from 'library/Utils'; export const Announcements = () => { const { t } = useTranslation('pages'); @@ -29,10 +30,10 @@ export const Announcements = () => { 0, new BigNumber(rewardAccountBalance || 0).minus(existentialDeposit) ); - const rewardBalance = planckToUnit(rewardPoolBalance, units); + const rewardBalance = planckToUnitBn(rewardPoolBalance, units); // calculate total rewards claimed - const rewardsClaimed = planckToUnit( + const rewardsClaimed = planckToUnitBn( totalRewardsClaimed ? new BigNumber(rmCommas(totalRewardsClaimed)) : new BigNumber(0), diff --git a/src/pages/Pools/Home/PoolStats/index.tsx b/src/pages/Pools/Home/PoolStats/index.tsx index 6afa5876b..3f0bf279f 100644 --- a/src/pages/Pools/Home/PoolStats/index.tsx +++ b/src/pages/Pools/Home/PoolStats/index.tsx @@ -1,7 +1,7 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { planckToUnit, rmCommas } from '@w3ux/utils'; +import { rmCommas } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { useTranslation } from 'react-i18next'; import { useActivePool } from 'contexts/Pools/ActivePool'; @@ -13,6 +13,7 @@ import { Announcements } from './Announcements'; import type { PoolStatLabel } from 'library/Announcements/types'; import { useOverlay } from 'kits/Overlay/Provider'; import { Wrapper } from 'library/Announcements/Wrappers'; +import { planckToUnitBn } from 'library/Utils'; export const PoolStats = () => { const { t } = useTranslation('pages'); @@ -28,7 +29,7 @@ export const PoolStats = () => { const { state, points, memberCounter } = activePool?.bondedPool || {}; const currentCommission = getCurrentCommission(poolId); - const bonded = planckToUnit( + const bonded = planckToUnitBn( new BigNumber(points ? rmCommas(points) : 0), units ) diff --git a/src/pages/Pools/Home/Stats/MinCreateBond.tsx b/src/pages/Pools/Home/Stats/MinCreateBond.tsx index 956fe14ff..dace3c484 100644 --- a/src/pages/Pools/Home/Stats/MinCreateBond.tsx +++ b/src/pages/Pools/Home/Stats/MinCreateBond.tsx @@ -1,11 +1,11 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { planckToUnit } from '@w3ux/utils'; import { useTranslation } from 'react-i18next'; import { Number } from 'library/StatBoxList/Number'; import { useNetwork } from 'contexts/Network'; import { useApi } from 'contexts/Api'; +import { planckToUnitBn } from 'library/Utils'; export const MinCreateBondStat = () => { const { t } = useTranslation('pages'); @@ -16,7 +16,7 @@ export const MinCreateBondStat = () => { const params = { label: t('pools.minimumToCreatePool'), - value: planckToUnit(minCreateBond, units).toNumber(), + value: planckToUnitBn(minCreateBond, units).toNumber(), decimals: 3, unit, helpKey: 'Minimum To Create Pool', diff --git a/src/pages/Pools/Home/Stats/MinJoinBond.tsx b/src/pages/Pools/Home/Stats/MinJoinBond.tsx index afd2a4cea..f06bb377c 100644 --- a/src/pages/Pools/Home/Stats/MinJoinBond.tsx +++ b/src/pages/Pools/Home/Stats/MinJoinBond.tsx @@ -1,11 +1,11 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { planckToUnit } from '@w3ux/utils'; import { useTranslation } from 'react-i18next'; import { Number } from 'library/StatBoxList/Number'; import { useNetwork } from 'contexts/Network'; import { useApi } from 'contexts/Api'; +import { planckToUnitBn } from 'library/Utils'; export const MinJoinBondStat = () => { const { t } = useTranslation('pages'); @@ -16,7 +16,7 @@ export const MinJoinBondStat = () => { const params = { label: t('pools.minimumToJoinPool'), - value: planckToUnit(minJoinBond, units).toNumber(), + value: planckToUnitBn(minJoinBond, units).toNumber(), decimals: 3, unit: ` ${unit}`, helpKey: 'Minimum To Join Pool', diff --git a/src/pages/Pools/Home/Status/RewardsStatus.tsx b/src/pages/Pools/Home/Status/RewardsStatus.tsx index 409423787..1756ad705 100644 --- a/src/pages/Pools/Home/Status/RewardsStatus.tsx +++ b/src/pages/Pools/Home/Status/RewardsStatus.tsx @@ -2,7 +2,6 @@ // SPDX-License-Identifier: GPL-3.0-only import { faCircleDown, faPlus } from '@fortawesome/free-solid-svg-icons'; -import { planckToUnit } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { useTranslation } from 'react-i18next'; import { useApi } from 'contexts/Api'; @@ -13,6 +12,7 @@ import { useNetwork } from 'contexts/Network'; import { useActiveAccounts } from 'contexts/ActiveAccounts'; import { useImportedAccounts } from 'contexts/Connect/ImportedAccounts'; import { useSyncing } from 'hooks/useSyncing'; +import { planckToUnitBn } from 'library/Utils'; export const RewardsStatus = ({ dimmed }: { dimmed: boolean }) => { const { t } = useTranslation('pages'); @@ -30,7 +30,7 @@ export const RewardsStatus = ({ dimmed }: { dimmed: boolean }) => { const minUnclaimedDisplay = new BigNumber(1_000_000); const labelRewards = pendingPoolRewards.isGreaterThan(minUnclaimedDisplay) - ? planckToUnit(pendingPoolRewards, units).toString() + ? planckToUnitBn(pendingPoolRewards, units).toString() : '0'; // Display Reward buttons if unclaimed rewards is a non-zero value. diff --git a/src/pages/Validators/Stats/ActiveValidators.tsx b/src/pages/Validators/Stats/ActiveValidators.tsx index 0ed96afb2..6f382c4a2 100644 --- a/src/pages/Validators/Stats/ActiveValidators.tsx +++ b/src/pages/Validators/Stats/ActiveValidators.tsx @@ -1,7 +1,6 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { greaterThanZero } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { useTranslation } from 'react-i18next'; import { useStaking } from 'contexts/Staking'; @@ -17,7 +16,7 @@ export const ActiveValidatorsStat = () => { // active validators as percent. Avoiding dividing by zero. let activeValidatorsAsPercent = new BigNumber(0); - if (greaterThanZero(validatorCount)) { + if (validatorCount.isGreaterThan(0)) { activeValidatorsAsPercent = new BigNumber(activeValidators).dividedBy( validatorCount.multipliedBy(0.01) ); diff --git a/src/pages/Validators/Stats/TotalValidators.tsx b/src/pages/Validators/Stats/TotalValidators.tsx index bac0d32f9..8219cfddd 100644 --- a/src/pages/Validators/Stats/TotalValidators.tsx +++ b/src/pages/Validators/Stats/TotalValidators.tsx @@ -1,7 +1,6 @@ // Copyright 2024 @polkadot-cloud/polkadot-staking-dashboard authors & contributors // SPDX-License-Identifier: GPL-3.0-only -import { greaterThanZero } from '@w3ux/utils'; import BigNumber from 'bignumber.js'; import { useTranslation } from 'react-i18next'; import { Pie } from 'library/StatBoxList/Pie'; @@ -15,7 +14,7 @@ export const TotalValidatorsStat = () => { // total validators as percent let totalValidatorsAsPercent = 0; - if (greaterThanZero(maxValidatorsCount)) { + if (maxValidatorsCount.isGreaterThan(0)) { totalValidatorsAsPercent = totalValidators .div(maxValidatorsCount.dividedBy(100)) .toNumber(); diff --git a/src/workers/stakers.ts b/src/workers/stakers.ts index 2e3fa31aa..f39127c5b 100644 --- a/src/workers/stakers.ts +++ b/src/workers/stakers.ts @@ -176,10 +176,7 @@ const processExposures = (data: ProcessExposuresArgs) => { if (own !== undefined) { activeAccountOwnStake.push({ address, - value: planckToUnit( - new BigNumber(rmCommas(own.value)), - units - ).toString(), + value: planckToUnit(rmCommas(own.value), units), }); } } diff --git a/yarn.lock b/yarn.lock index cdc9fdaab..9ce55c978 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3775,13 +3775,12 @@ __metadata: languageName: node linkType: hard -"@w3ux/utils@npm:^0.10.0": - version: 0.10.0 - resolution: "@w3ux/utils@npm:0.10.0" +"@w3ux/utils@npm:1.0.1": + version: 1.0.1 + resolution: "@w3ux/utils@npm:1.0.1" dependencies: "@polkadot-api/substrate-bindings": "npm:^0.9.3" - bignumber.js: "npm:^9.1.1" - checksum: 10c0/1ba8e8c725192f82252ee19fcb55b49f069135bd1ab5c3401affc9949378f4987a18ef7f07d4a8e1068037a68d5c1da413afdb9253a2750424f5d6c993d2007e + checksum: 10c0/99ec531fca18b53eaaa1f3979f48049f2cdef77b7a3c2eac0626d6fbd67e287057c1feba2832022b3167ff01792ab590421d7b148cc9d42d72984c53994cf67e languageName: node linkType: hard @@ -8684,7 +8683,7 @@ __metadata: "@w3ux/react-odometer": "npm:^1.1.0" "@w3ux/react-polkicon": "npm:^1.3.0" "@w3ux/types": "npm:^0.2.0" - "@w3ux/utils": "npm:^0.10.0" + "@w3ux/utils": "npm:1.0.1" "@w3ux/validator-assets": "npm:^0.2.0" "@zondax/ledger-substrate": "npm:^1.0.0" bignumber.js: "npm:^9.1.2"