Add blockInterval hook (#7165)

This commit is contained in:
Jaco 2022-03-15 10:30:41 +01:00 committed by GitHub
parent c1506fd803
commit 9e5fa6a353
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 123 additions and 81 deletions

View File

@ -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<Scheduled>[]];
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<Option<ITuple<[LeasePeriodOf, BlockNumber]>>>(api.query.auctions?.auctionInfo);

View File

@ -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<BN>(
(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;

View File

@ -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<string, DeriveStakerReward[]> | 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<BN>(api.derive.session.eraLength);
const historyDepth = useCall<BN>(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);

View File

@ -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<string>('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<Props> | null {
const { api } = useApi();
const { t } = useTranslation();
const [blockTime] = useBlockTime();
const blockTime = useBlockInterval();
const optionsRef = useRef(createOptions(api, t, blockTime));

View File

@ -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';

View File

@ -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);

View File

@ -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<string>('{{days}} days', { replace: { days } })
: t<string>('1 day')
: null,
hours
? (hours > 1)
? t<string>('{{hours}} hrs', { replace: { hours } })
: t<string>('1 hr')
: null,
minutes
? (minutes > 1)
? t<string>('{{minutes}} mins', { replace: { minutes } })
: t<string>('1 min')
: null,
seconds
? (seconds > 1)
? t<string>('{{seconds}} s', { replace: { seconds } })
: t<string>('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<string>('{{days}} days', { replace: { days } }) : t<string>('1 day') : null,
hours ? (hours > 1) ? t<string>('{{hours}} hrs', { replace: { hours } }) : t<string>('1 hr') : null,
minutes ? (minutes > 1) ? t<string>('{{minutes}} mins', { replace: { minutes } }) : t<string>('1 min') : null,
seconds ? (seconds > 1) ? t<string>('{{seconds}} s', { replace: { seconds } }) : t<string>('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]
);
}

View File

@ -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]
);
}