From 9e5fa6a3532187716c12a564814f812e0fcb1f37 Mon Sep 17 00:00:00 2001 From: Jaco Date: Tue, 15 Mar 2022 10:30:41 +0100 Subject: [PATCH] Add blockInterval hook (#7165) --- packages/page-calendar/src/useScheduled.ts | 22 ++--- packages/page-contracts/src/useWeight.ts | 8 +- packages/page-staking/src/Payouts/index.tsx | 16 ++-- .../src/ConvictionDropdown.tsx | 8 +- packages/react-hooks/src/index.ts | 1 + packages/react-hooks/src/useBlockInterval.ts | 49 ++++++++++ packages/react-hooks/src/useBlockTime.ts | 92 +++++++++---------- packages/react-hooks/src/useBlocksPerDays.ts | 8 +- 8 files changed, 123 insertions(+), 81 deletions(-) create mode 100644 packages/react-hooks/src/useBlockInterval.ts diff --git a/packages/page-calendar/src/useScheduled.ts b/packages/page-calendar/src/useScheduled.ts index ee09fc068f..2be9c360cb 100644 --- a/packages/page-calendar/src/useScheduled.ts +++ b/packages/page-calendar/src/useScheduled.ts @@ -11,7 +11,7 @@ import type { EntryInfo, EntryInfoTyped, EntryType } from './types'; import { useEffect, useState } from 'react'; import { useLeaseRangeMax } from '@polkadot/app-parachains/useLeaseRanges'; -import { createNamedHook, useApi, useBestNumber, useBlockTime, useCall } from '@polkadot/react-hooks'; +import { createNamedHook, useApi, useBestNumber, useBlockInterval, useCall } from '@polkadot/react-hooks'; import { BN_ONE, BN_ZERO } from '@polkadot/util'; interface DateExt { @@ -23,13 +23,13 @@ type SlashEntry = [{ args: [EraIndex] }, UnappliedSlash[]]; type ScheduleEntry = [{ args: [BlockNumber] }, Option[]]; -function newDate (blocks: BN, blockTime: number): DateExt { - const date = new Date(Date.now() + blocks.muln(blockTime).toNumber()); +function newDate (blocks: BN, blockTime: BN): DateExt { + const date = new Date(Date.now() + blocks.mul(blockTime).toNumber()); return { date, dateTime: date.getTime() }; } -function createConstDurations (bestNumber: BlockNumber, blockTime: number, items: [EntryType, BlockNumber?, BN?, BN?][]): [EntryType, EntryInfo[]][] { +function createConstDurations (bestNumber: BlockNumber, blockTime: BN, items: [EntryType, BlockNumber?, BN?, BN?][]): [EntryType, EntryInfo[]][] { return items.map(([type, duration, additional = BN_ZERO, offset = BN_ZERO]): [EntryType, EntryInfo[]] => { if (!duration) { return [type, []]; @@ -47,7 +47,7 @@ function createConstDurations (bestNumber: BlockNumber, blockTime: number, items }); } -function createCouncilMotions (bestNumber: BlockNumber, blockTime: number, motions: DeriveCollectiveProposal[]): [EntryType, EntryInfo[]][] { +function createCouncilMotions (bestNumber: BlockNumber, blockTime: BN, motions: DeriveCollectiveProposal[]): [EntryType, EntryInfo[]][] { return [['councilMotion', motions .map(({ hash, votes }): EntryInfo | null => { if (!votes) { @@ -68,7 +68,7 @@ function createCouncilMotions (bestNumber: BlockNumber, blockTime: number, motio ]]; } -function createDispatches (bestNumber: BlockNumber, blockTime: number, dispatches: DeriveDispatch[]): [EntryType, EntryInfo[]][] { +function createDispatches (bestNumber: BlockNumber, blockTime: BN, dispatches: DeriveDispatch[]): [EntryType, EntryInfo[]][] { return dispatches.map(({ at, index }): [EntryType, EntryInfo[]] => { const blocks = at.sub(bestNumber); @@ -81,7 +81,7 @@ function createDispatches (bestNumber: BlockNumber, blockTime: number, dispatche }); } -function createReferendums (bestNumber: BlockNumber, blockTime: number, referendums: DeriveReferendumExt[]): [EntryType, EntryInfo[]][] { +function createReferendums (bestNumber: BlockNumber, blockTime: BN, referendums: DeriveReferendumExt[]): [EntryType, EntryInfo[]][] { return referendums.reduce((result: [EntryType, EntryInfo[]][], { index, status }): [EntryType, EntryInfo[]][] => { const enactBlocks = status.end.add(status.delay).isub(bestNumber); const voteBlocks = status.end.sub(bestNumber).isub(BN_ONE); @@ -104,7 +104,7 @@ function createReferendums (bestNumber: BlockNumber, blockTime: number, referend }, []); } -function createStakingInfo (bestNumber: BlockNumber, blockTime: number, sessionInfo: DeriveSessionProgress, unapplied: SlashEntry[], slashDeferDuration?: BlockNumber): [EntryType, EntryInfo[]][] { +function createStakingInfo (bestNumber: BlockNumber, blockTime: BN, sessionInfo: DeriveSessionProgress, unapplied: SlashEntry[], slashDeferDuration?: BlockNumber): [EntryType, EntryInfo[]][] { const blocksEra = sessionInfo.eraLength.sub(sessionInfo.eraProgress); const blocksSes = sessionInfo.sessionLength.sub(sessionInfo.sessionProgress); const slashDuration = slashDeferDuration?.mul(sessionInfo.eraLength); @@ -142,7 +142,7 @@ function createStakingInfo (bestNumber: BlockNumber, blockTime: number, sessionI ]; } -function createScheduled (bestNumber: BlockNumber, blockTime: number, scheduled: ScheduleEntry[]): [EntryType, EntryInfo[]][] { +function createScheduled (bestNumber: BlockNumber, blockTime: BN, scheduled: ScheduleEntry[]): [EntryType, EntryInfo[]][] { return [['scheduler', scheduled .filter(([, vecSchedOpt]) => vecSchedOpt.some((schedOpt) => schedOpt.isSome)) .reduce((items: EntryInfo[], [key, vecSchedOpt]): EntryInfo[] => { @@ -171,7 +171,7 @@ function createScheduled (bestNumber: BlockNumber, blockTime: number, scheduled: }, [])]]; } -function createAuctionInfo (bestNumber: BlockNumber, blockTime: number, rangeMax: BN, [leasePeriod, endBlock]: [LeasePeriodOf, BlockNumber]): [EntryType, EntryInfo[]][] { +function createAuctionInfo (bestNumber: BlockNumber, blockTime: BN, rangeMax: BN, [leasePeriod, endBlock]: [LeasePeriodOf, BlockNumber]): [EntryType, EntryInfo[]][] { const blocks = endBlock.sub(bestNumber); return [ @@ -199,7 +199,7 @@ function addFiltered (state: EntryInfoTyped[], types: [EntryType, EntryInfo[]][] // TODO council votes, tips closing function useScheduledImpl (): EntryInfo[] { const { api } = useApi(); - const [blockTime] = useBlockTime(); + const blockTime = useBlockInterval(); const bestNumber = useBestNumber(); const leaseRangeMax = useLeaseRangeMax(); const auctionInfo = useCall>>(api.query.auctions?.auctionInfo); diff --git a/packages/page-contracts/src/useWeight.ts b/packages/page-contracts/src/useWeight.ts index a11e95ea56..66db7febd5 100644 --- a/packages/page-contracts/src/useWeight.ts +++ b/packages/page-contracts/src/useWeight.ts @@ -7,12 +7,12 @@ import type { UseWeight } from './types'; import { useCallback, useMemo, useState } from 'react'; -import { createNamedHook, useApi, useBlockTime } from '@polkadot/react-hooks'; +import { createNamedHook, useApi, useBlockInterval } from '@polkadot/react-hooks'; import { BN_MILLION, BN_TEN, BN_ZERO } from '@polkadot/util'; function useWeightImpl (): UseWeight { const { api } = useApi(); - const [blockTime] = useBlockTime(); + const blockTime = useBlockInterval(); const [megaGas, _setMegaGas] = useState( (api.consts.system.blockWeights ? api.consts.system.blockWeights.maxBlock @@ -39,12 +39,12 @@ function useWeightImpl (): UseWeight { if (megaGas) { weight = megaGas.mul(BN_MILLION); - executionTime = weight.muln(blockTime).div( + executionTime = weight.mul(blockTime).div( api.consts.system.blockWeights ? api.consts.system.blockWeights.maxBlock : api.consts.system.maximumBlockWeight as Weight ).toNumber(); - percentage = (executionTime / blockTime) * 100; + percentage = (executionTime / blockTime.toNumber()) * 100; // execution is 2s of 6s blocks, i.e. 1/3 executionTime = executionTime / 3000; diff --git a/packages/page-staking/src/Payouts/index.tsx b/packages/page-staking/src/Payouts/index.tsx index fd33c9e041..3aed15f4aa 100644 --- a/packages/page-staking/src/Payouts/index.tsx +++ b/packages/page-staking/src/Payouts/index.tsx @@ -9,9 +9,8 @@ import type { PayoutStash, PayoutValidator } from './types'; import React, { useMemo, useRef, useState } from 'react'; import styled from 'styled-components'; -import { ApiPromise } from '@polkadot/api'; import { Button, Table, ToggleGroup } from '@polkadot/react-components'; -import { useApi, useCall, useOwnEraRewards } from '@polkadot/react-hooks'; +import { useApi, useBlockInterval, useCall, useOwnEraRewards } from '@polkadot/react-hooks'; import { FormatBalance } from '@polkadot/react-query'; import { BN, BN_THREE } from '@polkadot/util'; @@ -124,16 +123,12 @@ function getAvailable (allRewards: Record | null | return {}; } -function getOptions (api: ApiPromise, eraLength: BN | undefined, historyDepth: BN | undefined, t: TFunction): EraSelection[] { +function getOptions (blockTime: BN, eraLength: BN | undefined, historyDepth: BN | undefined, t: TFunction): EraSelection[] { if (!eraLength || !historyDepth) { return [{ text: '', value: 0 }]; } - const blocksPerDay = DAY_SECS.div( - api.consts.babe?.expectedBlockTime || - api.consts.timestamp?.minimumPeriod.muln(2) || - new BN(6000) - ); + const blocksPerDay = DAY_SECS.div(blockTime); const maxBlocks = eraLength.mul(historyDepth); const eraSelection: EraSelection[] = []; const days = new BN(2); @@ -169,10 +164,11 @@ function Payouts ({ className = '', isInElection, ownValidators }: Props): React const [eraSelectionIndex, setEraSelectionIndex] = useState(0); const eraLength = useCall(api.derive.session.eraLength); const historyDepth = useCall(api.query.staking.historyDepth); + const blockTime = useBlockInterval(); const eraSelection = useMemo( - () => getOptions(api, eraLength, historyDepth, t), - [api, eraLength, historyDepth, t] + () => getOptions(blockTime, eraLength, historyDepth, t), + [blockTime, eraLength, historyDepth, t] ); const { allRewards, isLoadingRewards } = useOwnEraRewards(eraSelection[eraSelectionIndex].value, myStashesIndex ? undefined : ownValidators); diff --git a/packages/react-components/src/ConvictionDropdown.tsx b/packages/react-components/src/ConvictionDropdown.tsx index 3ae194f907..7c501ed625 100644 --- a/packages/react-components/src/ConvictionDropdown.tsx +++ b/packages/react-components/src/ConvictionDropdown.tsx @@ -6,7 +6,7 @@ import type { TFunction } from 'i18next'; import React, { useRef } from 'react'; import { ApiPromise } from '@polkadot/api'; -import { useApi, useBlockTime } from '@polkadot/react-hooks'; +import { useApi, useBlockInterval } from '@polkadot/react-hooks'; import { BN, BN_THOUSAND } from '@polkadot/util'; import Dropdown from './Dropdown'; @@ -23,7 +23,7 @@ export interface Props { const CONVICTIONS: [number, number, BN][] = [1, 2, 4, 8, 16, 32].map((lock, index) => [index + 1, lock, new BN(lock)]); const SEC_DAY = 60 * 60 * 24; -function createOptions (api: ApiPromise, t: TFunction, blockTime: number): { text: string; value: number }[] { +function createOptions (api: ApiPromise, t: TFunction, blockTime: BN): { text: string; value: number }[] { return [ { text: t('0.1x voting balance, no lockup period'), value: 0 }, ...CONVICTIONS.map(([value, lock, bnLock]): { text: string; value: number } => ({ @@ -34,7 +34,7 @@ function createOptions (api: ApiPromise, t: TFunction, blockTime: number): { tex bnLock.mul( api.consts.democracy.voteLockingPeriod || api.consts.democracy.enactmentPeriod - ).muln(blockTime).div(BN_THOUSAND).toNumber() / SEC_DAY + ).mul(blockTime).div(BN_THOUSAND).toNumber() / SEC_DAY ).toFixed(2), value } @@ -47,7 +47,7 @@ function createOptions (api: ApiPromise, t: TFunction, blockTime: number): { tex function Convictions ({ className = '', help, label, onChange, value }: Props): React.ReactElement | null { const { api } = useApi(); const { t } = useTranslation(); - const [blockTime] = useBlockTime(); + const blockTime = useBlockInterval(); const optionsRef = useRef(createOptions(api, t, blockTime)); diff --git a/packages/react-hooks/src/index.ts b/packages/react-hooks/src/index.ts index 9ac8e784db..ca8f1dfc54 100644 --- a/packages/react-hooks/src/index.ts +++ b/packages/react-hooks/src/index.ts @@ -12,6 +12,7 @@ export { useAvailableSlashes } from './useAvailableSlashes'; export { useBalancesAll } from './useBalancesAll'; export { useBestHash } from './useBestHash'; export { useBestNumber } from './useBestNumber'; +export { useBlockInterval } from './useBlockInterval'; export { useBlockTime } from './useBlockTime'; export { useBlocksPerDays } from './useBlocksPerDays'; export { useCacheKey } from './useCacheKey'; diff --git a/packages/react-hooks/src/useBlockInterval.ts b/packages/react-hooks/src/useBlockInterval.ts new file mode 100644 index 0000000000..3557e79e6c --- /dev/null +++ b/packages/react-hooks/src/useBlockInterval.ts @@ -0,0 +1,49 @@ +// Copyright 2017-2022 @polkadot/react-hooks authors & contributors +// SPDX-License-Identifier: Apache-2.0 + +import type { ApiPromise } from '@polkadot/api'; + +import { useMemo } from 'react'; + +import { BN, BN_THOUSAND, BN_TWO, bnMin } from '@polkadot/util'; + +import { createNamedHook } from './createNamedHook'; +import { useApi } from './useApi'; +import { A_DAY } from './useBlocksPerDays'; + +// Some chains incorrectly use these, i.e. it is set to values such as 0 or even 2 +// Use a low minimum validity threshold to check these against +const THRESHOLD = BN_THOUSAND.div(BN_TWO); +const DEFAULT_TIME = new BN(6_000); + +function calcInterval (api: ApiPromise): BN { + return bnMin(A_DAY, ( + // Babe, e.g. Relay chains (Substrate defaults) + api.consts.babe?.expectedBlockTime || + // POW, eg. Kulupu + api.consts.difficulty?.targetBlockTime || + // Subspace + api.consts.subspace?.expectedBlockTime || ( + // Check against threshold to determine value validity + api.consts.timestamp?.minimumPeriod.gte(THRESHOLD) + // Default minimum period config + ? api.consts.timestamp.minimumPeriod.mul(BN_TWO) + : api.query.parachainSystem + // default guess for a parachain + ? DEFAULT_TIME.mul(BN_TWO) + // default guess for others + : DEFAULT_TIME + ) + )); +} + +function useBlockIntervalImpl (apiOverride?: ApiPromise | null): BN { + const { api } = useApi(); + + return useMemo( + () => calcInterval(apiOverride || api), + [api, apiOverride] + ); +} + +export const useBlockInterval = createNamedHook('useBlockInterval', useBlockIntervalImpl); diff --git a/packages/react-hooks/src/useBlockTime.ts b/packages/react-hooks/src/useBlockTime.ts index 71ffb6f9a9..a440095052 100644 --- a/packages/react-hooks/src/useBlockTime.ts +++ b/packages/react-hooks/src/useBlockTime.ts @@ -1,70 +1,66 @@ -// Copyright 2017-2022 @polkadot/app-democracy authors & contributors +// Copyright 2017-2022 @polkadot/react-hooks authors & contributors // SPDX-License-Identifier: Apache-2.0 +import type { TFunction } from 'i18next'; import type { ApiPromise } from '@polkadot/api'; import type { Time } from '@polkadot/util/types'; import { useMemo } from 'react'; -import { BN, BN_ONE, BN_THOUSAND, BN_TWO, bnToBn, extractTime } from '@polkadot/util'; +import { BN, BN_MAX_INTEGER, BN_ONE, bnMin, bnToBn, extractTime } from '@polkadot/util'; import { createNamedHook } from './createNamedHook'; import { useTranslation } from './translate'; -import { useApi } from './useApi'; +import { useBlockInterval } from './useBlockInterval'; type Result = [number, string, Time]; -const DEFAULT_TIME = new BN(6_000); +function calcResult (blockTime: BN, blocks: BN, t: TFunction): Result { + // in the case of excessively large locks, limit to the max JS integer value + const value = bnMin(BN_MAX_INTEGER, blockTime.mul(blocks)).toNumber(); -// Some chains incorrectly use these, i.e. it is se to values such as 0 or even 2 -// Use a low minimum validity threshold to check these against -const THRESHOLD = BN_THOUSAND.div(BN_TWO); + // time calculations are using the absolute value (< 0 detection only on strings) + const time = extractTime(Math.abs(value)); + const { days, hours, minutes, seconds } = time; + + return [ + blockTime.toNumber(), + `${value < 0 ? '+' : ''}${[ + days + ? (days > 1) + ? t('{{days}} days', { replace: { days } }) + : t('1 day') + : null, + hours + ? (hours > 1) + ? t('{{hours}} hrs', { replace: { hours } }) + : t('1 hr') + : null, + minutes + ? (minutes > 1) + ? t('{{minutes}} mins', { replace: { minutes } }) + : t('1 min') + : null, + seconds + ? (seconds > 1) + ? t('{{seconds}} s', { replace: { seconds } }) + : t('1 s') + : null + ] + .filter((s): s is string => !!s) + .slice(0, 2) + .join(' ')}`, + time + ]; +} function useBlockTimeImpl (blocks: number | BN = BN_ONE, apiOverride?: ApiPromise | null): Result { const { t } = useTranslation(); - const { api } = useApi(); + const blockTime = useBlockInterval(apiOverride); return useMemo( - (): Result => { - const a = apiOverride || api; - const blockTime = ( - // Babe - a.consts.babe?.expectedBlockTime || - // POW, eg. Kulupu - a.consts.difficulty?.targetBlockTime || - // Subspace - a.consts.subspace?.expectedBlockTime || ( - // Check against threshold to determine value validity - a.consts.timestamp?.minimumPeriod.gte(THRESHOLD) - // Default minimum period config - ? a.consts.timestamp.minimumPeriod.mul(BN_TWO) - : a.query.parachainSystem - // default guess for a parachain - ? DEFAULT_TIME.mul(BN_TWO) - // default guess for others - : DEFAULT_TIME - ) - ); - const value = blockTime.mul(bnToBn(blocks)).toNumber(); - const time = extractTime(Math.abs(value)); - const { days, hours, minutes, seconds } = time; - const timeStr = [ - days ? (days > 1) ? t('{{days}} days', { replace: { days } }) : t('1 day') : null, - hours ? (hours > 1) ? t('{{hours}} hrs', { replace: { hours } }) : t('1 hr') : null, - minutes ? (minutes > 1) ? t('{{minutes}} mins', { replace: { minutes } }) : t('1 min') : null, - seconds ? (seconds > 1) ? t('{{seconds}} s', { replace: { seconds } }) : t('1 s') : null - ] - .filter((s): s is string => !!s) - .slice(0, 2) - .join(' '); - - return [ - blockTime.toNumber(), - `${value < 0 ? '+' : ''}${timeStr}`, - time - ]; - }, - [api, apiOverride, blocks, t] + () => calcResult(blockTime, bnToBn(blocks), t), + [blockTime, blocks, t] ); } diff --git a/packages/react-hooks/src/useBlocksPerDays.ts b/packages/react-hooks/src/useBlocksPerDays.ts index 8bacf2df52..16755adcea 100644 --- a/packages/react-hooks/src/useBlocksPerDays.ts +++ b/packages/react-hooks/src/useBlocksPerDays.ts @@ -6,15 +6,15 @@ import { useMemo } from 'react'; import { BN, bnToBn } from '@polkadot/util'; import { createNamedHook } from './createNamedHook'; -import { useBlockTime } from './useBlockTime'; +import { useBlockInterval } from './useBlockInterval'; -const A_DAY = new BN(24 * 60 * 60 * 1000); +export const A_DAY = new BN(24 * 60 * 60 * 1000); function useBlocksPerDaysImpl (days: BN | number = 1): BN { - const [blockTime] = useBlockTime(); + const blockTime = useBlockInterval(); return useMemo( - () => A_DAY.mul(bnToBn(days)).divn(blockTime), + () => A_DAY.mul(bnToBn(days)).div(blockTime), [blockTime, days] ); }