Adjust createNamedHook (#6449)
* Adjust createNamedHook * All (most) in react-hooks now named * Add useValidators hook * linting?
This commit is contained in:
parent
06437f92a1
commit
68a423748b
@ -6,7 +6,7 @@ import type { Balance, ParaId } from '@polkadot/types/interfaces';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { useAccounts, useApi, useCall, useNamedHook } from '@polkadot/react-hooks';
|
||||
import { createNamedHook, useAccounts, useApi, useCall } from '@polkadot/react-hooks';
|
||||
import { encodeAddress } from '@polkadot/util-crypto';
|
||||
|
||||
interface Result extends DeriveContributions {
|
||||
@ -58,6 +58,4 @@ function useContributionsImpl (paraId: ParaId): Result {
|
||||
return state;
|
||||
}
|
||||
|
||||
export default function useContributions (paraId: ParaId): Result {
|
||||
return useNamedHook('useContributions', useContributionsImpl, paraId);
|
||||
}
|
||||
export default createNamedHook('useContributions', useContributionsImpl);
|
||||
|
||||
@ -4,18 +4,20 @@
|
||||
import type BN from 'bn.js';
|
||||
import type { ApiPromise } from '@polkadot/api';
|
||||
import type { SignedBlockExtended } from '@polkadot/api-derive/types';
|
||||
import type { AccountId, CandidateReceipt, CoreAssignment, Event, GroupIndex, ParaId, ParaValidatorIndex } from '@polkadot/types/interfaces';
|
||||
import type { Event, ParaId } from '@polkadot/types/interfaces';
|
||||
import type { PolkadotPrimitivesV1CandidateReceipt } from '@polkadot/types/lookup';
|
||||
import type { IEvent } from '@polkadot/types/types';
|
||||
import type { LeasePeriod, QueuedAction, ScheduledProposals } from '../types';
|
||||
import type { EventMapInfo, ValidatorInfo } from './types';
|
||||
import type { EventMapInfo } from './types';
|
||||
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
|
||||
import { Table } from '@polkadot/react-components';
|
||||
import { useApi, useBestNumber, useCall, useCallMulti, useIsParasLinked } from '@polkadot/react-hooks';
|
||||
import { useApi, useBestNumber, useCall, useIsParasLinked } from '@polkadot/react-hooks';
|
||||
|
||||
import { useTranslation } from '../translate';
|
||||
import Parachain from './Parachain';
|
||||
import useValidators from './useValidators';
|
||||
|
||||
interface Props {
|
||||
actionsQueue: QueuedAction[];
|
||||
@ -32,16 +34,10 @@ interface LastEvents {
|
||||
lastTimeout: EventMap;
|
||||
}
|
||||
|
||||
type MultiResult = [AccountId[] | null, CoreAssignment[] | null, ParaValidatorIndex[][] | null, ParaValidatorIndex[] | null];
|
||||
|
||||
const EMPTY_EVENTS: LastEvents = { lastBacked: {}, lastIncluded: {}, lastTimeout: {} };
|
||||
|
||||
const optionsMulti = {
|
||||
defaultValue: [null, null, null, null] as MultiResult
|
||||
};
|
||||
|
||||
function includeEntry (map: EventMap, event: Event, blockHash: string, blockNumber: BN): void {
|
||||
const { descriptor } = (event as unknown as IEvent<[CandidateReceipt]>).data[0];
|
||||
const { descriptor } = (event as unknown as IEvent<[PolkadotPrimitivesV1CandidateReceipt]>).data[0];
|
||||
|
||||
if (descriptor) {
|
||||
map[descriptor.paraId.toString()] = {
|
||||
@ -60,33 +56,6 @@ function extractScheduledIds (scheduled: ScheduledProposals[] = []): Record<stri
|
||||
}), all), {});
|
||||
}
|
||||
|
||||
function mapValidators (startWith: Record<string, [GroupIndex, ValidatorInfo[]]>, ids: ParaId[] | undefined, validators: AccountId[] | null, validatorGroups: ParaValidatorIndex[][] | null, activeIndices: ParaValidatorIndex[] | null, assignments: CoreAssignment[] | null): Record<string, [GroupIndex, ValidatorInfo[]]> {
|
||||
return assignments && activeIndices && validators && validatorGroups && ids
|
||||
? ids.reduce((all: Record<string, [GroupIndex, ValidatorInfo[]]>, id) => {
|
||||
const assignment = assignments.find(({ paraId }) => paraId.eq(id));
|
||||
|
||||
if (!assignment) {
|
||||
return all;
|
||||
}
|
||||
|
||||
return {
|
||||
...all,
|
||||
[id.toString()]: [
|
||||
assignment.groupIdx,
|
||||
validatorGroups[assignment.groupIdx.toNumber()]
|
||||
.map((indexActive) => [indexActive, activeIndices[indexActive.toNumber()]])
|
||||
.filter(([, a]) => a)
|
||||
.map(([indexActive, indexValidator]) => ({
|
||||
indexActive,
|
||||
indexValidator,
|
||||
validatorId: validators[indexValidator.toNumber()]
|
||||
}))
|
||||
]
|
||||
};
|
||||
}, { ...startWith })
|
||||
: startWith;
|
||||
}
|
||||
|
||||
function extractEvents (api: ApiPromise, lastBlock: SignedBlockExtended, prev: LastEvents): LastEvents {
|
||||
const backed: EventMap = {};
|
||||
const included: EventMap = {};
|
||||
@ -128,18 +97,16 @@ function extractEvents (api: ApiPromise, lastBlock: SignedBlockExtended, prev: L
|
||||
: prev;
|
||||
}
|
||||
|
||||
function extractActions (actionsQueue: QueuedAction[], knownIds?: [ParaId, string][]): Record<string, QueuedAction | undefined> {
|
||||
return actionsQueue && knownIds
|
||||
? knownIds.reduce((all: Record<string, QueuedAction | undefined>, [id, key]) => ({
|
||||
...all,
|
||||
[key]: actionsQueue.find(({ paraIds }) => paraIds.some((p) => p.eq(id)))
|
||||
}), {})
|
||||
: {};
|
||||
function extractActions (actionsQueue: QueuedAction[], knownIds: [ParaId, string][] = []): Record<string, QueuedAction | undefined> {
|
||||
return knownIds.reduce((all: Record<string, QueuedAction | undefined>, [id, key]) => ({
|
||||
...all,
|
||||
[key]: actionsQueue.find(({ paraIds }) => paraIds.some((p) => p.eq(id)))
|
||||
}), {});
|
||||
}
|
||||
|
||||
function extractIds (hasLinksMap: Record<string, boolean>, ids?: ParaId[]): [ParaId, string][] | undefined {
|
||||
function extractIds (hasLinksMap: Record<string, boolean>, ids: ParaId[]): [ParaId, string][] | undefined {
|
||||
return ids
|
||||
?.map((id): [ParaId, string] => [id, id.toString()])
|
||||
.map((id): [ParaId, string] => [id, id.toString()])
|
||||
.sort(([aId, aIds], [bId, bIds]): number => {
|
||||
const aKnown = hasLinksMap[aIds] || false;
|
||||
const bKnown = hasLinksMap[bIds] || false;
|
||||
@ -158,14 +125,8 @@ function Parachains ({ actionsQueue, ids, leasePeriod, scheduled }: Props): Reac
|
||||
const bestNumber = useBestNumber();
|
||||
const lastBlock = useCall<SignedBlockExtended>(api.derive.chain.subscribeNewBlocks);
|
||||
const [{ lastBacked, lastIncluded, lastTimeout }, setLastEvents] = useState<LastEvents>(EMPTY_EVENTS);
|
||||
const [validators, assignments, validatorGroups, validatorIndices] = useCallMulti<MultiResult>([
|
||||
api.query.session.validators,
|
||||
(api.query.parasScheduler || api.query.paraScheduler || api.query.scheduler)?.scheduled,
|
||||
(api.query.parasScheduler || api.query.paraScheduler || api.query.scheduler)?.validatorGroups,
|
||||
(api.query.parasShared || api.query.paraShared || api.query.shared)?.activeValidatorIndices
|
||||
], optionsMulti);
|
||||
const hasLinksMap = useIsParasLinked(ids);
|
||||
const [validatorMap, setValidatorMap] = useState<Record<string, [GroupIndex, ValidatorInfo[]]>>({});
|
||||
const [validators, validatorMap] = useValidators(ids);
|
||||
|
||||
const headerRef = useRef([
|
||||
[t('parachains'), 'start', 2],
|
||||
@ -187,7 +148,7 @@ function Parachains ({ actionsQueue, ids, leasePeriod, scheduled }: Props): Reac
|
||||
);
|
||||
|
||||
const knownIds = useMemo(
|
||||
() => extractIds(hasLinksMap, ids),
|
||||
() => ids && extractIds(hasLinksMap, ids),
|
||||
[ids, hasLinksMap]
|
||||
);
|
||||
|
||||
@ -202,12 +163,6 @@ function Parachains ({ actionsQueue, ids, leasePeriod, scheduled }: Props): Reac
|
||||
);
|
||||
}, [api, lastBlock]);
|
||||
|
||||
useEffect((): void => {
|
||||
setValidatorMap((prev) =>
|
||||
mapValidators(prev, ids, validators, validatorGroups, validatorIndices, assignments)
|
||||
);
|
||||
}, [assignments, ids, validators, validatorGroups, validatorIndices]);
|
||||
|
||||
return (
|
||||
<Table
|
||||
empty={knownIds && t<string>('There are no registered parachains')}
|
||||
|
||||
68
packages/page-parachains/src/Overview/useValidators.ts
Normal file
68
packages/page-parachains/src/Overview/useValidators.ts
Normal file
@ -0,0 +1,68 @@
|
||||
// Copyright 2017-2021 @polkadot/app-parachains authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AccountId, CoreAssignment, GroupIndex, ParaId, ParaValidatorIndex } from '@polkadot/types/interfaces';
|
||||
import type { ValidatorInfo } from './types';
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
|
||||
import { createNamedHook, useApi, useCallMulti } from '@polkadot/react-hooks';
|
||||
|
||||
type MultiResult = [AccountId[] | null, CoreAssignment[] | null, ParaValidatorIndex[][] | null, ParaValidatorIndex[] | null];
|
||||
|
||||
type Result = [AccountId[] | null, Record<string, [GroupIndex, ValidatorInfo[]]>];
|
||||
|
||||
const optionsMulti = {
|
||||
defaultValue: [null, null, null, null] as MultiResult
|
||||
};
|
||||
|
||||
function mapValidators (startWith: Record<string, [GroupIndex, ValidatorInfo[]]>, ids: ParaId[], validators: AccountId[], groups: ParaValidatorIndex[][], indices: ParaValidatorIndex[], scheduled: CoreAssignment[]): Record<string, [GroupIndex, ValidatorInfo[]]> {
|
||||
return ids.reduce((all: Record<string, [GroupIndex, ValidatorInfo[]]>, id) => {
|
||||
// paraId should never be undefined, since it comes from the state, yet here we are...
|
||||
// See https://github.com/polkadot-js/apps/issues/6435
|
||||
const assignment = scheduled.find(({ paraId }) => paraId && paraId.eq(id));
|
||||
|
||||
if (!assignment) {
|
||||
return all;
|
||||
}
|
||||
|
||||
return {
|
||||
...all,
|
||||
[id.toString()]: [
|
||||
assignment.groupIdx,
|
||||
groups[assignment.groupIdx.toNumber()]
|
||||
.map((index) => [index, indices[index.toNumber()]])
|
||||
.filter(([, a]) => a)
|
||||
.map(([indexActive, indexValidator]) => ({
|
||||
indexActive,
|
||||
indexValidator,
|
||||
validatorId: validators[indexValidator.toNumber()]
|
||||
}))
|
||||
]
|
||||
};
|
||||
}, { ...startWith });
|
||||
}
|
||||
|
||||
function useValidatorsImpl (ids?: ParaId[]): Result {
|
||||
const { api } = useApi();
|
||||
const [validators, scheduled, groups, indices] = useCallMulti<MultiResult>([
|
||||
api.query.session.validators,
|
||||
(api.query.parasScheduler || api.query.paraScheduler || api.query.scheduler)?.scheduled,
|
||||
(api.query.parasScheduler || api.query.paraScheduler || api.query.scheduler)?.validatorGroups,
|
||||
(api.query.parasShared || api.query.paraShared || api.query.shared)?.activeValidatorIndices
|
||||
], optionsMulti);
|
||||
const [state, setState] = useState<Record<string, [GroupIndex, ValidatorInfo[]]>>({});
|
||||
|
||||
useEffect((): void => {
|
||||
groups && ids && indices && scheduled && validators && setState((prev) =>
|
||||
mapValidators(prev, ids, validators, groups, indices, scheduled)
|
||||
);
|
||||
}, [groups, ids, indices, scheduled, validators]);
|
||||
|
||||
return useMemo(
|
||||
(): Result => [validators, state],
|
||||
[state, validators]
|
||||
);
|
||||
}
|
||||
|
||||
export default createNamedHook('useValidators', useValidatorsImpl);
|
||||
@ -7,7 +7,7 @@ import type { ProposalExt, ScheduledProposals } from '../types';
|
||||
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import { useApi, useCall, useNamedHook } from '@polkadot/react-hooks';
|
||||
import { createNamedHook, useApi, useCall } from '@polkadot/react-hooks';
|
||||
|
||||
function useProposalImpl (id: ParaId, approvedIds: ParaId[], scheduled: ScheduledProposals[]): ProposalExt {
|
||||
const { api } = useApi();
|
||||
@ -26,6 +26,4 @@ function useProposalImpl (id: ParaId, approvedIds: ParaId[], scheduled: Schedule
|
||||
);
|
||||
}
|
||||
|
||||
export default function useProposal (id: ParaId, approvedIds: ParaId[], scheduled: ScheduledProposals[]): ProposalExt {
|
||||
return useNamedHook('useProposal', useProposalImpl, id, approvedIds, scheduled);
|
||||
}
|
||||
export default createNamedHook('useProposal', useProposalImpl);
|
||||
|
||||
@ -7,7 +7,7 @@ import type { QueuedAction } from './types';
|
||||
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import { useApi, useCall, useNamedHook } from '@polkadot/react-hooks';
|
||||
import { createNamedHook, useApi, useCall } from '@polkadot/react-hooks';
|
||||
import { BN_EIGHT, BN_FIVE, BN_FOUR, BN_NINE, BN_ONE, BN_SEVEN, BN_SIX, BN_TEN, BN_THREE, BN_TWO } from '@polkadot/util';
|
||||
|
||||
const INC = [BN_ONE, BN_TWO, BN_THREE, BN_FOUR, BN_FIVE, BN_SIX, BN_SEVEN, BN_EIGHT, BN_NINE, BN_TEN];
|
||||
@ -36,6 +36,4 @@ function useActionsQueueImpl (): QueuedAction[] {
|
||||
);
|
||||
}
|
||||
|
||||
export default function useActionsQueue (): QueuedAction[] {
|
||||
return useNamedHook('useActionsQueue', useActionsQueueImpl);
|
||||
}
|
||||
export default createNamedHook('useActionsQueue', useActionsQueueImpl);
|
||||
|
||||
@ -6,7 +6,7 @@ import type { AuctionIndex, BlockNumber, LeasePeriodOf } from '@polkadot/types/i
|
||||
import type { ITuple } from '@polkadot/types/types';
|
||||
import type { AuctionInfo } from './types';
|
||||
|
||||
import { useApi, useCallMulti, useNamedHook } from '@polkadot/react-hooks';
|
||||
import { createNamedHook, useApi, useCallMulti } from '@polkadot/react-hooks';
|
||||
|
||||
const optionsMulti = {
|
||||
transform: ([numAuctions, optInfo]: [AuctionIndex, Option<ITuple<[LeasePeriodOf, BlockNumber]>>]): AuctionInfo => {
|
||||
@ -29,6 +29,4 @@ function useAuctionInfoImpl (): AuctionInfo | undefined {
|
||||
], optionsMulti);
|
||||
}
|
||||
|
||||
export default function useAuctionInfo (): AuctionInfo | undefined {
|
||||
return useNamedHook('useAuctionInfo', useAuctionInfoImpl);
|
||||
}
|
||||
export default createNamedHook('useAuctionInfo', useAuctionInfoImpl);
|
||||
|
||||
@ -10,7 +10,7 @@ import type { Campaign, Campaigns } from './types';
|
||||
import BN from 'bn.js';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { useApi, useBestNumber, useCall, useEventTrigger, useIsMountedRef, useMapKeys, useNamedHook } from '@polkadot/react-hooks';
|
||||
import { createNamedHook, useApi, useBestNumber, useCall, useEventTrigger, useIsMountedRef, useMapKeys } from '@polkadot/react-hooks';
|
||||
import { BN_ZERO, u8aConcat } from '@polkadot/util';
|
||||
import { encodeAddress } from '@polkadot/util-crypto';
|
||||
|
||||
@ -172,6 +172,4 @@ function useFundsImpl (): Campaigns {
|
||||
return result;
|
||||
}
|
||||
|
||||
export default function useFunds (): Campaigns {
|
||||
return useNamedHook('useFunds', useFundsImpl);
|
||||
}
|
||||
export default createNamedHook('useFunds', useFundsImpl);
|
||||
|
||||
@ -6,7 +6,7 @@ import type { LeasePeriod } from './types';
|
||||
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import { useApi, useBestNumber, useNamedHook } from '@polkadot/react-hooks';
|
||||
import { createNamedHook, useApi, useBestNumber } from '@polkadot/react-hooks';
|
||||
import { BN_ZERO } from '@polkadot/util';
|
||||
|
||||
function useLeasePeriodImpl (): LeasePeriod | undefined {
|
||||
@ -31,6 +31,4 @@ function useLeasePeriodImpl (): LeasePeriod | undefined {
|
||||
}, [api, bestNumber]);
|
||||
}
|
||||
|
||||
export default function useLeasePeriod (): LeasePeriod | undefined {
|
||||
return useNamedHook('useLeasePeriod', useLeasePeriodImpl);
|
||||
}
|
||||
export default createNamedHook('useLeasePeriod', useLeasePeriodImpl);
|
||||
|
||||
@ -6,7 +6,7 @@ import type { u32 } from '@polkadot/types';
|
||||
import BN from 'bn.js';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import { useApi, useNamedHook } from '@polkadot/react-hooks';
|
||||
import { createNamedHook, useApi } from '@polkadot/react-hooks';
|
||||
|
||||
const RANGES_DEFAULT: [number, number][] = [
|
||||
[0, 0], [0, 1], [0, 2], [0, 3],
|
||||
@ -42,9 +42,7 @@ function useLeaseRangesImpl (): [number, number][] {
|
||||
);
|
||||
}
|
||||
|
||||
export function useLeaseRanges (): [number, number][] {
|
||||
return useNamedHook('useLeaseRanges', useLeaseRangesImpl);
|
||||
}
|
||||
export const useLeaseRanges = createNamedHook('useLeaseRanges', useLeaseRangesImpl);
|
||||
|
||||
function useLeaseRangeMaxImpl (): BN {
|
||||
const ranges = useLeaseRanges();
|
||||
@ -55,6 +53,4 @@ function useLeaseRangeMaxImpl (): BN {
|
||||
);
|
||||
}
|
||||
|
||||
export function useLeaseRangeMax (): BN {
|
||||
return useNamedHook('useLeaseRangeMax', useLeaseRangeMaxImpl);
|
||||
}
|
||||
export const useLeaseRangeMax = createNamedHook('useLeaseRangeMax', useLeaseRangeMaxImpl);
|
||||
|
||||
@ -8,7 +8,7 @@ import type { OwnedId, OwnedIdPartial } from './types';
|
||||
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import { useAccounts, useApi, useCall, useEventTrigger, useMapEntries, useNamedHook } from '@polkadot/react-hooks';
|
||||
import { createNamedHook, useAccounts, useApi, useCall, useEventTrigger, useMapEntries } from '@polkadot/react-hooks';
|
||||
|
||||
interface CodeHash {
|
||||
hash: Hash | null;
|
||||
@ -65,13 +65,11 @@ function useOwnedIdsImpl (): OwnedId[] {
|
||||
.filter((id) => allAccounts.some((a) => a === id.manager))
|
||||
.map((data): OwnedId => ({
|
||||
...data,
|
||||
hasCode: hashes.some(({ hash, paraId }) => !!hash && paraId.eq(data.paraId))
|
||||
hasCode: hashes.some((h) => !!h.hash && h.paraId.eq(data.paraId))
|
||||
}))
|
||||
: [],
|
||||
[allAccounts, hashes, unfiltered]
|
||||
);
|
||||
}
|
||||
|
||||
export default function useOwnedIds (): OwnedId[] {
|
||||
return useNamedHook('useOwnedIds', useOwnedIdsImpl);
|
||||
}
|
||||
export default createNamedHook('useOwnedIds', useOwnedIdsImpl);
|
||||
|
||||
@ -7,7 +7,7 @@ import type { Proposals } from './types';
|
||||
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import { useApi, useCallMulti, useEventTrigger, useIsMountedRef, useMapEntries, useMapKeys, useNamedHook } from '@polkadot/react-hooks';
|
||||
import { createNamedHook, useApi, useCallMulti, useEventTrigger, useIsMountedRef, useMapEntries, useMapKeys } from '@polkadot/react-hooks';
|
||||
|
||||
type MultiQuery = [SessionIndex | undefined, ParaId[] | undefined];
|
||||
|
||||
@ -54,6 +54,4 @@ function useProposalsImpl (): Proposals | undefined {
|
||||
);
|
||||
}
|
||||
|
||||
export default function useProposals (): Proposals | undefined {
|
||||
return useNamedHook('useProposals', useProposalsImpl);
|
||||
}
|
||||
export default createNamedHook('useProposals', useProposalsImpl);
|
||||
|
||||
@ -5,7 +5,7 @@ import type { Option, StorageKey } from '@polkadot/types';
|
||||
import type { ParaId } from '@polkadot/types/interfaces';
|
||||
import type { PolkadotRuntimeParachainsParasParaLifecycle } from '@polkadot/types/lookup';
|
||||
|
||||
import { useApi, useEventTrigger, useMapEntries, useNamedHook } from '@polkadot/react-hooks';
|
||||
import { createNamedHook, useApi, useEventTrigger, useMapEntries } from '@polkadot/react-hooks';
|
||||
|
||||
function extractIds (entries: [StorageKey<[ParaId]>, Option<PolkadotRuntimeParachainsParasParaLifecycle>][]): ParaId[] {
|
||||
return entries
|
||||
@ -38,6 +38,4 @@ function useUpomingIdsImpl (): ParaId[] | undefined {
|
||||
});
|
||||
}
|
||||
|
||||
export default function useUpomingIds (): ParaId[] | undefined {
|
||||
return useNamedHook('useUpomingIds', useUpomingIdsImpl);
|
||||
}
|
||||
export default createNamedHook('useUpomingIds', useUpomingIdsImpl);
|
||||
|
||||
@ -8,7 +8,7 @@ import type { AuctionInfo, WinnerData, Winning } from './types';
|
||||
import BN from 'bn.js';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
|
||||
import { useApi, useBestNumber, useCall, useEventTrigger, useIsMountedRef, useNamedHook } from '@polkadot/react-hooks';
|
||||
import { createNamedHook, useApi, useBestNumber, useCall, useEventTrigger, useIsMountedRef } from '@polkadot/react-hooks';
|
||||
import { BN_ONE, BN_ZERO, u8aEq } from '@polkadot/util';
|
||||
|
||||
import { CROWD_PREFIX } from './constants';
|
||||
@ -169,6 +169,4 @@ function useWinningDataImpl (auctionInfo?: AuctionInfo): Winning[] | undefined {
|
||||
return result;
|
||||
}
|
||||
|
||||
export default function useWinningData (auctionInfo?: AuctionInfo): Winning[] | undefined {
|
||||
return useNamedHook('useWinningData', useWinningDataImpl, auctionInfo);
|
||||
}
|
||||
export default createNamedHook('useWinningData', useWinningDataImpl);
|
||||
|
||||
@ -34,7 +34,7 @@ export { useLoadingDelay } from './useLoadingDelay';
|
||||
export { useMapEntries } from './useMapEntries';
|
||||
export { useMapKeys } from './useMapKeys';
|
||||
export { useModal } from './useModal';
|
||||
export { useNamedHook } from './useNamedHook';
|
||||
export { createNamedHook } from './useNamedHook';
|
||||
export { useNonEmptyString } from './useNonEmptyString';
|
||||
export { useNonZeroBn } from './useNonZeroBn';
|
||||
export { useOwnEraRewards } from './useOwnEraRewards';
|
||||
|
||||
@ -15,6 +15,7 @@ import { useAccounts } from './useAccounts';
|
||||
import { useAddresses } from './useAddresses';
|
||||
import { useApi } from './useApi';
|
||||
import { useCall } from './useCall';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
import { useToggle } from './useToggle';
|
||||
|
||||
const IS_NONE = {
|
||||
@ -36,7 +37,7 @@ const IS_NONE = {
|
||||
isValidator: false
|
||||
};
|
||||
|
||||
export function useAccountInfo (value: string | null, isContract = false): UseAccountInfo {
|
||||
function useAccountInfoImpl (value: string | null, isContract = false): UseAccountInfo {
|
||||
const { api } = useApi();
|
||||
const { isAccount } = useAccounts();
|
||||
const { isAddress } = useAddresses();
|
||||
@ -269,3 +270,5 @@ export function useAccountInfo (value: string | null, isContract = false): UseAc
|
||||
toggleIsEditingTags
|
||||
};
|
||||
}
|
||||
|
||||
export const useAccountInfo = createNamedHook('useAccountInfo', useAccountInfoImpl);
|
||||
|
||||
@ -8,6 +8,7 @@ import { u8aToHex } from '@polkadot/util';
|
||||
import { decodeAddress } from '@polkadot/util-crypto';
|
||||
|
||||
import { useIsMountedRef } from './useIsMountedRef';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
export interface UseAccounts {
|
||||
allAccounts: string[];
|
||||
@ -19,7 +20,7 @@ export interface UseAccounts {
|
||||
|
||||
const EMPTY: UseAccounts = { allAccounts: [], allAccountsHex: [], areAccountsLoaded: false, hasAccounts: false, isAccount: () => false };
|
||||
|
||||
export function useAccounts (): UseAccounts {
|
||||
function useAccountsImpl (): UseAccounts {
|
||||
const mountedRef = useIsMountedRef();
|
||||
const [state, setState] = useState<UseAccounts>(EMPTY);
|
||||
|
||||
@ -42,3 +43,5 @@ export function useAccounts (): UseAccounts {
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
export const useAccounts = createNamedHook('useAccounts', useAccountsImpl);
|
||||
|
||||
@ -6,6 +6,7 @@ import { useEffect, useState } from 'react';
|
||||
import { keyring } from '@polkadot/ui-keyring';
|
||||
|
||||
import { useIsMountedRef } from './useIsMountedRef';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
interface UseAddresses {
|
||||
allAddresses: string[];
|
||||
@ -13,7 +14,7 @@ interface UseAddresses {
|
||||
isAddress: (address: string) => boolean;
|
||||
}
|
||||
|
||||
export function useAddresses (): UseAddresses {
|
||||
function useAddressesImpl (): UseAddresses {
|
||||
const mountedRef = useIsMountedRef();
|
||||
const [state, setState] = useState<UseAddresses>({ allAddresses: [], hasAddresses: false, isAddress: () => false });
|
||||
|
||||
@ -35,3 +36,5 @@ export function useAddresses (): UseAddresses {
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
export const useAddresses = createNamedHook('useAddresses', useAddressesImpl);
|
||||
|
||||
@ -2,8 +2,9 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { DeriveSessionIndexes } from '@polkadot/api-derive/types';
|
||||
import type { Option, Vec } from '@polkadot/types';
|
||||
import type { EraIndex, UnappliedSlash } from '@polkadot/types/interfaces';
|
||||
import type { Option } from '@polkadot/types';
|
||||
import type { EraIndex } from '@polkadot/types/interfaces';
|
||||
import type { PalletStakingUnappliedSlash } from '@polkadot/types/lookup';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { useEffect, useState } from 'react';
|
||||
@ -13,15 +14,16 @@ import { BN_ONE } from '@polkadot/util';
|
||||
import { useApi } from './useApi';
|
||||
import { useCall } from './useCall';
|
||||
import { useIsMountedRef } from './useIsMountedRef';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
type Unsub = () => void;
|
||||
|
||||
export function useAvailableSlashes (): [BN, UnappliedSlash[]][] {
|
||||
function useAvailableSlashesImpl (): [BN, PalletStakingUnappliedSlash[]][] {
|
||||
const { api } = useApi();
|
||||
const indexes = useCall<DeriveSessionIndexes>(api.derive.session?.indexes);
|
||||
const earliestSlash = useCall<Option<EraIndex>>(api.query.staking?.earliestUnappliedSlash);
|
||||
const mountedRef = useIsMountedRef();
|
||||
const [slashes, setSlashes] = useState<[BN, UnappliedSlash[]][]>([]);
|
||||
const [slashes, setSlashes] = useState<[BN, PalletStakingUnappliedSlash[]][]>([]);
|
||||
|
||||
useEffect((): Unsub => {
|
||||
let unsub: Unsub | undefined;
|
||||
@ -39,10 +41,10 @@ export function useAvailableSlashes (): [BN, UnappliedSlash[]][] {
|
||||
|
||||
if (range.length) {
|
||||
(async (): Promise<void> => {
|
||||
unsub = await api.query.staking.unappliedSlashes.multi<Vec<UnappliedSlash>>(range, (values): void => {
|
||||
unsub = await api.query.staking.unappliedSlashes.multi(range, (values): void => {
|
||||
mountedRef.current && setSlashes(
|
||||
values
|
||||
.map((value, index): [BN, UnappliedSlash[]] => [from.addn(index), value])
|
||||
.map((value, index): [BN, PalletStakingUnappliedSlash[]] => [from.addn(index), value])
|
||||
.filter(([, slashes]) => slashes.length)
|
||||
);
|
||||
});
|
||||
@ -57,3 +59,5 @@ export function useAvailableSlashes (): [BN, UnappliedSlash[]][] {
|
||||
|
||||
return slashes;
|
||||
}
|
||||
|
||||
export const useAvailableSlashes = createNamedHook('useAvailableSlashes', useAvailableSlashesImpl);
|
||||
|
||||
@ -5,6 +5,7 @@ import type { DeriveBalancesAll } from '@polkadot/api-derive/types';
|
||||
|
||||
import { useApi } from './useApi';
|
||||
import { useCall } from './useCall';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
/**
|
||||
* Gets the account full balance information
|
||||
@ -12,8 +13,10 @@ import { useCall } from './useCall';
|
||||
* @param accountAddress The account address of which balance is to be returned
|
||||
* @returns full information about account's balances
|
||||
*/
|
||||
export function useBalancesAll (accountAddress: string): DeriveBalancesAll | undefined {
|
||||
function useBalancesAllImpl (accountAddress: string): DeriveBalancesAll | undefined {
|
||||
const { api } = useApi();
|
||||
|
||||
return useCall<DeriveBalancesAll>(api.derive.balances?.all, [accountAddress]);
|
||||
}
|
||||
|
||||
export const useBalancesAll = createNamedHook('useBalancesAll', useBalancesAllImpl);
|
||||
|
||||
@ -5,13 +5,16 @@ import type { Header } from '@polkadot/types/interfaces';
|
||||
|
||||
import { useApi } from './useApi';
|
||||
import { useCall } from './useCall';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
const optCall = {
|
||||
transform: (header: Header) => header.hash.toHex()
|
||||
};
|
||||
|
||||
export function useBestHash (): string | undefined {
|
||||
function useBestHashImpl (): string | undefined {
|
||||
const { api } = useApi();
|
||||
|
||||
return useCall<string>(api.rpc.chain.subscribeNewHeads, undefined, optCall);
|
||||
}
|
||||
|
||||
export const useBestHash = createNamedHook('useBestHash', useBestHashImpl);
|
||||
|
||||
@ -5,9 +5,12 @@ import type { BlockNumber } from '@polkadot/types/interfaces';
|
||||
|
||||
import { useApi } from './useApi';
|
||||
import { useCall } from './useCall';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
export function useBestNumber (): BlockNumber | undefined {
|
||||
function useBestNumberImpl (): BlockNumber | undefined {
|
||||
const { api } = useApi();
|
||||
|
||||
return useCall<BlockNumber>(api.derive.chain.bestNumber);
|
||||
}
|
||||
|
||||
export const useBestNumber = createNamedHook('useBestNumber', useBestNumberImpl);
|
||||
|
||||
@ -10,6 +10,7 @@ import { BN, BN_ONE, BN_THOUSAND, BN_TWO, bnToBn, extractTime } from '@polkadot/
|
||||
|
||||
import { useTranslation } from './translate';
|
||||
import { useApi } from './useApi';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
type Result = [number, string, Time];
|
||||
|
||||
@ -19,7 +20,7 @@ const DEFAULT_TIME = new BN(6_000);
|
||||
// Use a low minimum validity threshold to check these against
|
||||
const THRESHOLD = BN_THOUSAND.div(BN_TWO);
|
||||
|
||||
export function useBlockTime (blocks: number | BN = BN_ONE, apiOverride?: ApiPromise | null): Result {
|
||||
function useBlockTimeImpl (blocks: number | BN = BN_ONE, apiOverride?: ApiPromise | null): Result {
|
||||
const { t } = useTranslation();
|
||||
const { api } = useApi();
|
||||
|
||||
@ -64,3 +65,5 @@ export function useBlockTime (blocks: number | BN = BN_ONE, apiOverride?: ApiPro
|
||||
[api, apiOverride, blocks, t]
|
||||
);
|
||||
}
|
||||
|
||||
export const useBlockTime = createNamedHook('useBlockTime', useBlockTimeImpl);
|
||||
|
||||
@ -6,10 +6,11 @@ import { useMemo } from 'react';
|
||||
import { BN, bnToBn } from '@polkadot/util';
|
||||
|
||||
import { useBlockTime } from './useBlockTime';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
const A_DAY = new BN(24 * 60 * 60 * 1000);
|
||||
|
||||
export function useBlocksPerDays (days: BN | number = 1): BN {
|
||||
function useBlocksPerDaysImpl (days: BN | number = 1): BN {
|
||||
const [blockTime] = useBlockTime();
|
||||
|
||||
return useMemo(
|
||||
@ -17,3 +18,5 @@ export function useBlocksPerDays (days: BN | number = 1): BN {
|
||||
[blockTime, days]
|
||||
);
|
||||
}
|
||||
|
||||
export const useBlocksPerDays = createNamedHook('useBlocksPerDays', useBlocksPerDaysImpl);
|
||||
|
||||
@ -68,7 +68,7 @@ export function useCallMulti <T> (calls?: QueryableStorageMultiArg<'promise'>[]
|
||||
const { api } = useApi();
|
||||
const mountedRef = useIsMountedRef();
|
||||
const tracker = useRef<Tracker>({ isActive: false, serialized: null, subscriber: null });
|
||||
const [value, setValue] = useState<T>((options || {}).defaultValue || [] as unknown as T);
|
||||
const [value, setValue] = useState<T>(() => (options || {}).defaultValue || [] as unknown as T);
|
||||
|
||||
// initial effect, we need an un-subscription
|
||||
useEffect((): () => void => {
|
||||
|
||||
@ -8,7 +8,9 @@ import { useMemo } from 'react';
|
||||
import { useApi } from '@polkadot/react-hooks';
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
export function useCollectiveInstance (instanceType: CollectiveType, instanceIndex?: number): CollectiveType | null {
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
function useCollectiveInstanceImpl (instanceType: CollectiveType, instanceIndex?: number): CollectiveType | null {
|
||||
const { api } = useApi();
|
||||
|
||||
return useMemo(
|
||||
@ -26,3 +28,5 @@ export function useCollectiveInstance (instanceType: CollectiveType, instanceInd
|
||||
[api, instanceIndex, instanceType]
|
||||
);
|
||||
}
|
||||
|
||||
export const useCollectiveInstance = createNamedHook('useCollectiveInstance', useCollectiveInstanceImpl);
|
||||
|
||||
@ -9,6 +9,7 @@ import { useMemo } from 'react';
|
||||
import { useAccounts } from './useAccounts';
|
||||
import { useApi } from './useApi';
|
||||
import { useCall } from './useCall';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
interface Result {
|
||||
isMember: boolean;
|
||||
@ -20,7 +21,7 @@ const transformMembers = {
|
||||
accounts.map((accountId) => accountId.toString())
|
||||
};
|
||||
|
||||
export function useCollectiveMembers (collective: CollectiveType): Result {
|
||||
function useCollectiveMembersImpl (collective: CollectiveType): Result {
|
||||
const { api } = useApi();
|
||||
const { allAccounts, hasAccounts } = useAccounts();
|
||||
const retrieved = useCall<string[]>(hasAccounts && api.derive[collective]?.members, undefined, transformMembers);
|
||||
@ -33,3 +34,5 @@ export function useCollectiveMembers (collective: CollectiveType): Result {
|
||||
[allAccounts, retrieved]
|
||||
);
|
||||
}
|
||||
|
||||
export const useCollectiveMembers = createNamedHook('useCollectiveMembers', useCollectiveMembersImpl);
|
||||
|
||||
@ -1,12 +1,17 @@
|
||||
// Copyright 2017-2021 @polkadot/react-hooks authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { useAccounts, useApi, useCall } from '@polkadot/react-hooks';
|
||||
import { Voting } from '@polkadot/types/interfaces';
|
||||
import type { PalletDemocracyVoteVoting } from '@polkadot/types/lookup';
|
||||
|
||||
export function useDelegations (): Voting[] | undefined {
|
||||
import { useAccounts, useApi, useCall } from '@polkadot/react-hooks';
|
||||
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
function useDelegationsImpl (): PalletDemocracyVoteVoting[] | undefined {
|
||||
const { api } = useApi();
|
||||
const { allAccounts } = useAccounts();
|
||||
|
||||
return useCall<Voting[]>(api.query.democracy?.votingOf?.multi, [allAccounts]);
|
||||
return useCall<PalletDemocracyVoteVoting[]>(api.query.democracy?.votingOf?.multi, [allAccounts]);
|
||||
}
|
||||
|
||||
export const useDelegations = createNamedHook('useDelegations', useDelegationsImpl);
|
||||
|
||||
@ -10,6 +10,7 @@ import { useEffect, useState } from 'react';
|
||||
import { useApi } from './useApi';
|
||||
import { useCall } from './useCall';
|
||||
import { useIsMountedRef } from './useIsMountedRef';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
type EventCheck = AugmentedEvent<'promise'> | false | undefined | null;
|
||||
|
||||
@ -25,7 +26,7 @@ const EMPTY_RESULT: Result = {
|
||||
|
||||
const IDENTITY_FILTER = () => true;
|
||||
|
||||
export function useEventTrigger (_checks: EventCheck[], filter: (record: EventRecord) => boolean = IDENTITY_FILTER): Result {
|
||||
function useEventTriggerImpl (_checks: EventCheck[], filter: (record: EventRecord) => boolean = IDENTITY_FILTER): Result {
|
||||
const { api } = useApi();
|
||||
const [state, setState] = useState(() => EMPTY_RESULT);
|
||||
const [checks] = useState(() => _checks);
|
||||
@ -51,3 +52,5 @@ export function useEventTrigger (_checks: EventCheck[], filter: (record: EventRe
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
export const useEventTrigger = createNamedHook('useEventTrigger', useEventTriggerImpl);
|
||||
|
||||
@ -9,10 +9,11 @@ import { useEffect, useState } from 'react';
|
||||
import { useApi } from './useApi';
|
||||
import { useCall } from './useCall';
|
||||
import { useIsMountedRef } from './useIsMountedRef';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
type ExtrinsicCheck = SubmittableExtrinsicFunction<'promise'> | false | undefined | null;
|
||||
|
||||
export function useExtrinsicTrigger (checks: ExtrinsicCheck[]): string {
|
||||
function useExtrinsicTriggerImpl (checks: ExtrinsicCheck[]): string {
|
||||
const { api } = useApi();
|
||||
const [trigger, setTrigger] = useState('0');
|
||||
const mountedRef = useIsMountedRef();
|
||||
@ -27,3 +28,5 @@ export function useExtrinsicTrigger (checks: ExtrinsicCheck[]): string {
|
||||
|
||||
return trigger;
|
||||
}
|
||||
|
||||
export const useExtrinsicTrigger = createNamedHook('useExtrinsicTrigger', useExtrinsicTriggerImpl);
|
||||
|
||||
@ -14,7 +14,7 @@ export function useFavorites (storageKeyBase: string): [string[], (address: stri
|
||||
(address: string): void => setFavorites(
|
||||
(favorites: string[]) => setCache(
|
||||
favorites.includes(address)
|
||||
? favorites.filter((accountId): boolean => address !== accountId)
|
||||
? favorites.filter((a) => address !== a)
|
||||
: [...favorites, address]
|
||||
)
|
||||
),
|
||||
|
||||
@ -12,6 +12,7 @@ import { BN_MILLION, BN_ZERO } from '@polkadot/util';
|
||||
|
||||
import { useApi } from './useApi';
|
||||
import { useCall } from './useCall';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
const EMPTY: Inflation = { idealInterest: 0, idealStake: 0, inflation: 0, stakedFraction: 0, stakedReturn: 0 };
|
||||
|
||||
@ -39,7 +40,7 @@ function calcInflation (api: ApiPromise, totalStaked: BN, totalIssuance: BN, num
|
||||
};
|
||||
}
|
||||
|
||||
export function useInflation (totalStaked?: BN): Inflation {
|
||||
function useInflationImpl (totalStaked?: BN): Inflation {
|
||||
const { api } = useApi();
|
||||
const totalIssuance = useCall<BN>(api.query.balances?.totalIssuance);
|
||||
const auctionCounter = useCall<BN>(api.query.auctions?.auctionCounter);
|
||||
@ -57,3 +58,5 @@ export function useInflation (totalStaked?: BN): Inflation {
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
export const useInflation = createNamedHook('useInflation', useInflationImpl);
|
||||
|
||||
@ -1,14 +1,17 @@
|
||||
// Copyright 2017-2021 @polkadot/react-hooks authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { UseJudgements } from './types';
|
||||
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import { getJudgements } from './utils/getJudgements';
|
||||
import { matchRegistrarAccountsWithIndexes } from './utils/matchRegistrarAccountsWithIndexes';
|
||||
import { UseJudgements } from './types';
|
||||
import { useAccountInfo, useRegistrars } from './';
|
||||
import { useAccountInfo } from './useAccountInfo';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
import { useRegistrars } from './useRegistrars';
|
||||
|
||||
export function useJudgements (address: string): UseJudgements {
|
||||
function useJudgementsImpl (address: string): UseJudgements {
|
||||
const { identity } = useAccountInfo(address);
|
||||
const { registrars: allRegistrars } = useRegistrars();
|
||||
|
||||
@ -19,3 +22,5 @@ export function useJudgements (address: string): UseJudgements {
|
||||
[allRegistrars, judgementsWithRegistrarIndexes]
|
||||
);
|
||||
}
|
||||
|
||||
export const useJudgements = createNamedHook('useJudgements', useJudgementsImpl);
|
||||
|
||||
@ -12,6 +12,7 @@ import uiSettings from '@polkadot/ui-settings';
|
||||
import { assert } from '@polkadot/util';
|
||||
|
||||
import { useApi } from './useApi';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
interface StateBase {
|
||||
isLedgerCapable: boolean;
|
||||
@ -60,7 +61,7 @@ function getState (api: ApiPromise): StateBase {
|
||||
};
|
||||
}
|
||||
|
||||
export function useLedger (): State {
|
||||
function useLedgerImpl (): State {
|
||||
const { api, isApiReady } = useApi();
|
||||
|
||||
const getLedger = useCallback(
|
||||
@ -73,3 +74,5 @@ export function useLedger (): State {
|
||||
[api, getLedger, isApiReady]
|
||||
);
|
||||
}
|
||||
|
||||
export const useLedger = createNamedHook('useLedger', useLedgerImpl);
|
||||
|
||||
@ -1,10 +1,13 @@
|
||||
// Copyright 2017-2021 @polkadot/react-hooks authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export function useNamedHook <T, F extends (...args: any[]) => T> (name: string, fn: F, ...args: Parameters<F>): T {
|
||||
try {
|
||||
return fn(...args);
|
||||
} catch (error) {
|
||||
throw new Error(`${name}:: ${(error as Error).message}:: ${(error as Error).stack || '<unknown>'}`);
|
||||
}
|
||||
export function createNamedHook <F extends (...args: any[]) => any> (name: string, fn: F): (...args: Parameters<F>) => ReturnType<F> {
|
||||
return (...args: Parameters<F>): ReturnType<F> => {
|
||||
try {
|
||||
// eslint-disable-next-line
|
||||
return fn(...args);
|
||||
} catch (error) {
|
||||
throw new Error(`${name}:: ${(error as Error).message}:: ${(error as Error).stack || '<unknown>'}`);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@ -13,6 +13,7 @@ import { BN_ZERO } from '@polkadot/util';
|
||||
import { useApi } from './useApi';
|
||||
import { useCall } from './useCall';
|
||||
import { useIsMountedRef } from './useIsMountedRef';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
import { useOwnStashIds } from './useOwnStashes';
|
||||
|
||||
interface State {
|
||||
@ -98,7 +99,7 @@ function getValRewards (api: ApiPromise, validatorEras: ValidatorWithEras[], era
|
||||
};
|
||||
}
|
||||
|
||||
export function useOwnEraRewards (maxEras?: number, ownValidators?: StakerState[]): State {
|
||||
function useOwnEraRewardsImpl (maxEras?: number, ownValidators?: StakerState[]): State {
|
||||
const { api } = useApi();
|
||||
const mountedRef = useIsMountedRef();
|
||||
const stashIds = useOwnStashIds();
|
||||
@ -164,3 +165,5 @@ export function useOwnEraRewards (maxEras?: number, ownValidators?: StakerState[
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
export const useOwnEraRewards = createNamedHook('useOwnEraRewards', useOwnEraRewardsImpl);
|
||||
|
||||
@ -14,6 +14,7 @@ import { u8aConcat, u8aToHex } from '@polkadot/util';
|
||||
import { useAccounts } from './useAccounts';
|
||||
import { useApi } from './useApi';
|
||||
import { useIsMountedRef } from './useIsMountedRef';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
import { useOwnStashes } from './useOwnStashes';
|
||||
|
||||
type ValidatorInfo = ITuple<[ValidatorPrefs, Codec]> | ValidatorPrefs;
|
||||
@ -62,7 +63,7 @@ function getStakerState (stashId: string, allAccounts: string[], [isOwnStash, {
|
||||
};
|
||||
}
|
||||
|
||||
export function useOwnStashInfos (): StakerState[] | undefined {
|
||||
function useOwnStashInfosImpl (): StakerState[] | undefined {
|
||||
const { api } = useApi();
|
||||
const { allAccounts } = useAccounts();
|
||||
const mountedRef = useIsMountedRef();
|
||||
@ -109,3 +110,5 @@ export function useOwnStashInfos (): StakerState[] | undefined {
|
||||
[allAccounts, ownStashes, queried]
|
||||
);
|
||||
}
|
||||
|
||||
export const useOwnStashInfos = createNamedHook('useOwnStashInfos', useOwnStashInfosImpl);
|
||||
|
||||
@ -9,6 +9,7 @@ import { useMemo } from 'react';
|
||||
import { useAccounts } from './useAccounts';
|
||||
import { useApi } from './useApi';
|
||||
import { useCall } from './useCall';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
type IsInKeyring = boolean;
|
||||
|
||||
@ -30,7 +31,7 @@ function getStashes (allAccounts: string[], ownBonded: Option<AccountId>[], ownL
|
||||
return result;
|
||||
}
|
||||
|
||||
export function useOwnStashes (): [string, IsInKeyring][] | undefined {
|
||||
function useOwnStashesImpl (): [string, IsInKeyring][] | undefined {
|
||||
const { allAccounts, hasAccounts } = useAccounts();
|
||||
const { api } = useApi();
|
||||
const ownBonded = useCall<Option<AccountId>[]>(hasAccounts && api.query.staking?.bonded.multi, [allAccounts]);
|
||||
@ -46,7 +47,9 @@ export function useOwnStashes (): [string, IsInKeyring][] | undefined {
|
||||
);
|
||||
}
|
||||
|
||||
export function useOwnStashIds (): string[] | undefined {
|
||||
export const useOwnStashes = createNamedHook('useOwnStashes', useOwnStashesImpl);
|
||||
|
||||
function useOwnStashIdsImpl (): string[] | undefined {
|
||||
const ownStashes = useOwnStashes();
|
||||
|
||||
return useMemo(
|
||||
@ -56,3 +59,5 @@ export function useOwnStashIds (): string[] | undefined {
|
||||
[ownStashes]
|
||||
);
|
||||
}
|
||||
|
||||
export const useOwnStashIds = createNamedHook('useOwnStashIds', useOwnStashIdsImpl);
|
||||
|
||||
@ -3,24 +3,30 @@
|
||||
|
||||
import BN from 'bn.js';
|
||||
|
||||
import { useAccounts } from '@polkadot/react-hooks/useAccounts';
|
||||
import { useApi } from '@polkadot/react-hooks/useApi';
|
||||
import { useCall } from '@polkadot/react-hooks/useCall';
|
||||
import { AccountId, ProxyDefinition, ProxyType } from '@polkadot/types/interfaces';
|
||||
import { AccountId } from '@polkadot/types/interfaces';
|
||||
import { NodeRuntimeProxyType, PalletProxyProxyDefinition } from '@polkadot/types/lookup';
|
||||
|
||||
export function useProxies (): [ProxyDefinition[], BN][] | undefined {
|
||||
import { useAccounts } from './useAccounts';
|
||||
import { useApi } from './useApi';
|
||||
import { useCall } from './useCall';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
function useProxiesImpl (): [PalletProxyProxyDefinition[], BN][] | undefined {
|
||||
const { api } = useApi();
|
||||
const { allAccounts } = useAccounts();
|
||||
|
||||
return useCall<[ProxyDefinition[], BN][]>(api.query.proxy?.proxies.multi, [allAccounts], {
|
||||
transform: (result: [([AccountId, ProxyType] | ProxyDefinition)[], BN][]): [ProxyDefinition[], BN][] =>
|
||||
return useCall<[PalletProxyProxyDefinition[], BN][]>(api.query.proxy?.proxies.multi, [allAccounts], {
|
||||
transform: (result: [([AccountId, NodeRuntimeProxyType] | PalletProxyProxyDefinition)[], BN][]): [PalletProxyProxyDefinition[], BN][] =>
|
||||
api.tx.proxy.addProxy.meta.args.length === 3
|
||||
? result as [ProxyDefinition[], BN][]
|
||||
: (result as [[AccountId, ProxyType][], BN][]).map(([arr, bn]): [ProxyDefinition[], BN] =>
|
||||
[arr.map(([delegate, proxyType]): ProxyDefinition => api.createType('ProxyDefinition', {
|
||||
delegate,
|
||||
proxyType
|
||||
})), bn]
|
||||
? result as [PalletProxyProxyDefinition[], BN][]
|
||||
: (result as [[AccountId, NodeRuntimeProxyType][], BN][]).map(([arr, bn]): [PalletProxyProxyDefinition[], BN] =>
|
||||
[arr.map(([delegate, proxyType]): PalletProxyProxyDefinition =>
|
||||
api.createType('ProxyDefinition', {
|
||||
delegate,
|
||||
proxyType
|
||||
})), bn]
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
export const useProxies = createNamedHook('useProxies', useProxiesImpl);
|
||||
|
||||
@ -10,6 +10,7 @@ import { useMemo } from 'react';
|
||||
import { useAccounts } from './useAccounts';
|
||||
import { useApi } from './useApi';
|
||||
import { useCall } from './useCall';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
interface RegistrarNull {
|
||||
address: string | null;
|
||||
@ -22,7 +23,7 @@ interface State {
|
||||
skipQuery?: boolean;
|
||||
}
|
||||
|
||||
export function useRegistrars (skipQuery?: boolean): State {
|
||||
function useRegistrarsImpl (skipQuery?: boolean): State {
|
||||
const { api } = useApi();
|
||||
const { allAccounts, hasAccounts } = useAccounts();
|
||||
const query = useCall<Option<RegistrarInfo>[]>(!skipQuery && api.query.identity?.registrars);
|
||||
@ -47,3 +48,5 @@ export function useRegistrars (skipQuery?: boolean): State {
|
||||
[allAccounts, hasAccounts, query]
|
||||
);
|
||||
}
|
||||
|
||||
export const useRegistrars = createNamedHook('useRegistrars', useRegistrarsImpl);
|
||||
|
||||
@ -5,9 +5,12 @@ import type { DeriveStakingAccount } from '@polkadot/api-derive/types';
|
||||
|
||||
import { useApi } from './useApi';
|
||||
import { useCall } from './useCall';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
export function useStakingInfo (accountId: string | null): DeriveStakingAccount | undefined {
|
||||
function useStakingInfoImpl (accountId: string | null): DeriveStakingAccount | undefined {
|
||||
const { api } = useApi();
|
||||
|
||||
return useCall<DeriveStakingAccount>(api.derive.staking?.account, [accountId]);
|
||||
}
|
||||
|
||||
export const useStakingInfo = createNamedHook('useStakingInfo', useStakingInfoImpl);
|
||||
|
||||
@ -5,9 +5,12 @@ import { AccountId, BalanceOf } from '@polkadot/types/interfaces';
|
||||
|
||||
import { useApi } from './useApi';
|
||||
import { useCall } from './useCall';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
export function useSubidentities (address: string): AccountId[] | undefined {
|
||||
function useSubidentitiesImpl (address: string): AccountId[] | undefined {
|
||||
const { api } = useApi();
|
||||
|
||||
return useCall<[BalanceOf, AccountId[]]>(api.query.identity?.subsOf, [address])?.[1];
|
||||
}
|
||||
|
||||
export const useSubidentities = createNamedHook('useSubidentities', useSubidentitiesImpl);
|
||||
|
||||
@ -9,12 +9,13 @@ import { useEffect, useState } from 'react';
|
||||
import { useAccounts } from './useAccounts';
|
||||
import { useApi } from './useApi';
|
||||
import { useCall } from './useCall';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
const transformSudo = {
|
||||
transform: (key: AccountId) => key.toString()
|
||||
};
|
||||
|
||||
export function useSudo (): UseSudo {
|
||||
function useSudoImpl (): UseSudo {
|
||||
const { api } = useApi();
|
||||
const { allAccounts, hasAccounts } = useAccounts();
|
||||
const sudoKey = useCall<string>(hasAccounts && api.query.sudo?.key, undefined, transformSudo);
|
||||
@ -26,3 +27,5 @@ export function useSudo (): UseSudo {
|
||||
|
||||
return { allAccounts, hasSudoKey, sudoKey };
|
||||
}
|
||||
|
||||
export const useSudo = createNamedHook('useSudo', useSudoImpl);
|
||||
|
||||
@ -11,6 +11,7 @@ import { isNumber } from '@polkadot/util';
|
||||
|
||||
import { useApi } from './useApi';
|
||||
import { useCall } from './useCall';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
interface Teleport {
|
||||
allowTeleport: boolean;
|
||||
@ -61,7 +62,7 @@ function extractRelayDestinations (relayGenesis: string, filter: (l: ExtLinkOpti
|
||||
);
|
||||
}
|
||||
|
||||
export function useTeleport (): Teleport {
|
||||
function useTeleportImpl (): Teleport {
|
||||
const { api, apiUrl, isApiReady } = useApi();
|
||||
const paraId = useCall<ParaId>(isApiReady && api.query.parachainInfo?.parachainId);
|
||||
const [state, setState] = useState<Teleport>(() => ({ ...DEFAULT_STATE }));
|
||||
@ -115,3 +116,5 @@ export function useTeleport (): Teleport {
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
export const useTeleport = createNamedHook('useTeleport', useTeleportImpl);
|
||||
|
||||
@ -11,6 +11,7 @@ import { BN_MILLION, BN_ZERO, u8aConcat } from '@polkadot/util';
|
||||
|
||||
import { useApi } from './useApi';
|
||||
import { useCall } from './useCall';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
const EMPTY_U8A_32 = new Uint8Array(32);
|
||||
|
||||
@ -21,7 +22,7 @@ interface Result {
|
||||
treasuryAccount: Uint8Array;
|
||||
}
|
||||
|
||||
export function useTreasury (): Result {
|
||||
function useTreasuryImpl (): Result {
|
||||
const { api } = useApi();
|
||||
const [result, setResult] = useState<Result>(() => ({
|
||||
spendPeriod: api.consts.treasury
|
||||
@ -53,3 +54,5 @@ export function useTreasury (): Result {
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export const useTreasury = createNamedHook('useTreasury', useTreasuryImpl);
|
||||
|
||||
@ -11,6 +11,7 @@ import { isFunction } from '@polkadot/util';
|
||||
|
||||
import { useAccounts } from './useAccounts';
|
||||
import { useApi } from './useApi';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
interface Options {
|
||||
batchSize?: number;
|
||||
@ -43,7 +44,7 @@ function createBatches (api: ApiPromise, txs: SubmittableExtrinsic<'promise'>[],
|
||||
);
|
||||
}
|
||||
|
||||
export function useTxBatch (txs?: SubmittableExtrinsic<'promise'>[] | null | false, options?: Options): SubmittableExtrinsic<'promise'>[] | null {
|
||||
function useTxBatchImpl (txs?: SubmittableExtrinsic<'promise'>[] | null | false, options?: Options): SubmittableExtrinsic<'promise'>[] | null {
|
||||
const { api } = useApi();
|
||||
const { allAccounts } = useAccounts();
|
||||
const [batchSize, setBatchSize] = useState(Math.floor(options?.batchSize || 64));
|
||||
@ -76,3 +77,5 @@ export function useTxBatch (txs?: SubmittableExtrinsic<'promise'>[] | null | fal
|
||||
[api, batchSize, options, txs]
|
||||
);
|
||||
}
|
||||
|
||||
export const useTxBatch = createNamedHook('useTxBatch', useTxBatchImpl);
|
||||
|
||||
@ -11,6 +11,7 @@ import { isFunction } from '@polkadot/util';
|
||||
|
||||
import { useApi } from './useApi';
|
||||
import { useBestNumber } from './useBestNumber';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
interface State {
|
||||
hasFailed: boolean;
|
||||
@ -55,7 +56,7 @@ function getStatus (api: ApiPromise, bestNumber: BlockNumber, votes: Votes, numM
|
||||
};
|
||||
}
|
||||
|
||||
export function useVotingStatus (votes: Votes | null | undefined, numMembers: number, section: 'council' | 'membership' | 'technicalCommittee'): State {
|
||||
function useVotingStatusImpl (votes: Votes | null | undefined, numMembers: number, section: 'council' | 'membership' | 'technicalCommittee'): State {
|
||||
const { api } = useApi();
|
||||
const bestNumber = useBestNumber();
|
||||
|
||||
@ -66,3 +67,5 @@ export function useVotingStatus (votes: Votes | null | undefined, numMembers: nu
|
||||
[api, bestNumber, numMembers, section, votes]
|
||||
);
|
||||
}
|
||||
|
||||
export const useVotingStatus = createNamedHook('useVotingStatus', useVotingStatusImpl);
|
||||
|
||||
@ -10,13 +10,14 @@ import { BN_ZERO, isFunction } from '@polkadot/util';
|
||||
|
||||
import { useApi } from './useApi';
|
||||
import { useIsMountedRef } from './useIsMountedRef';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
// a random address that we are using for our queries
|
||||
const ZERO_ACCOUNT = '5CAUdnwecHGxxyr5vABevAfZ34Fi4AaraDRMwfDQXQ52PXqg';
|
||||
const EMPTY_STATE: [BN, number] = [BN_ZERO, 0];
|
||||
|
||||
// for a given call, calculate the weight
|
||||
export function useWeight (call?: Call | null): [BN, number] {
|
||||
function useWeightImpl (call?: Call | null): [BN, number] {
|
||||
const { api } = useApi();
|
||||
const mountedRef = useIsMountedRef();
|
||||
const [state, setState] = useState(EMPTY_STATE);
|
||||
@ -34,3 +35,5 @@ export function useWeight (call?: Call | null): [BN, number] {
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
export const useWeight = createNamedHook('useWeight', useWeightImpl);
|
||||
|
||||
@ -10,8 +10,9 @@ import { useMemo } from 'react';
|
||||
import { BN_BILLION, BN_ZERO, bnToBn, isUndefined } from '@polkadot/util';
|
||||
|
||||
import { useApi } from './useApi';
|
||||
import { createNamedHook } from './useNamedHook';
|
||||
|
||||
export function useWeightFee (weight: BN | number, apiOverride?: ApiPromise | null): BN {
|
||||
function useWeightFeeImpl (weight: BN | number, apiOverride?: ApiPromise | null): BN {
|
||||
const { api } = useApi();
|
||||
|
||||
return useMemo(
|
||||
@ -35,3 +36,5 @@ export function useWeightFee (weight: BN | number, apiOverride?: ApiPromise | nu
|
||||
[api, apiOverride, weight]
|
||||
);
|
||||
}
|
||||
|
||||
export const useWeightFee = createNamedHook('useWeightFee', useWeightFeeImpl);
|
||||
|
||||
Loading…
Reference in New Issue
Block a user