Rework with useNominations (incl. loading indicators) (#4128)

This commit is contained in:
Jaco Greeff 2020-12-01 13:13:47 +01:00 committed by GitHub
parent 3e8ab064e2
commit 78b3680f3c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 184 additions and 111 deletions

View File

@ -1,16 +1,17 @@
// Copyright 2017-2020 @polkadot/app-staking authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { EraIndex, SlashingSpans } from '@polkadot/types/interfaces';
import type { SlashingSpans } from '@polkadot/types/interfaces';
import type { NominatedBy as NominatedByType } from '../../types';
import React, { useMemo } from 'react';
import { AddressMini, Expander, Spinner } from '@polkadot/react-components';
import { AddressMini, Expander } from '@polkadot/react-components';
import { formatNumber } from '@polkadot/util';
import { useTranslation } from '../../translate';
interface Props {
nominators?: [string, EraIndex, number][];
nominators?: NominatedByType[];
slashingSpans?: SlashingSpans | null;
}
@ -33,18 +34,18 @@ function extractFunction (all: string[]): null | [number, () => React.ReactNode[
: null;
}
function extractChilled (nominators: [string, EraIndex, number][] = [], slashingSpans?: SlashingSpans | null): Chilled {
function extractChilled (nominators: NominatedByType[] = [], slashingSpans?: SlashingSpans | null): Chilled {
const chilled = slashingSpans
? nominators
.filter(([, submittedIn]) => !slashingSpans.lastNonzeroSlash.isZero() && slashingSpans.lastNonzeroSlash.gte(submittedIn))
.map(([who]) => who)
.filter(({ submittedIn }) => !slashingSpans.lastNonzeroSlash.isZero() && slashingSpans.lastNonzeroSlash.gte(submittedIn))
.map(({ nominatorId }) => nominatorId)
: [];
return {
active: extractFunction(
nominators
.filter(([who]) => !chilled.includes(who))
.map(([who]) => who)
.filter(({ nominatorId }) => !chilled.includes(nominatorId))
.map(({ nominatorId }) => nominatorId)
),
chilled: extractFunction(chilled)
};
@ -60,25 +61,18 @@ function NominatedBy ({ nominators, slashingSpans }: Props): React.ReactElement<
return (
<td className='expand all'>
{nominators
? (
<>
{active && (
<Expander
renderChildren={active[1]}
summary={t<string>('Nominations ({{count}})', { replace: { count: formatNumber(active[0]) } })}
/>
)}
{chilled && (
<Expander
renderChildren={chilled[1]}
summary={t<string>('Renomination required ({{count}})', { replace: { count: formatNumber(chilled[0]) } })}
/>
)}
</>
)
: <Spinner variant='mini' />
}
{active && (
<Expander
renderChildren={active[1]}
summary={t<string>('Nominations ({{count}})', { replace: { count: formatNumber(active[0]) } })}
/>
)}
{chilled && (
<Expander
renderChildren={chilled[1]}
summary={t<string>('Renomination required ({{count}})', { replace: { count: formatNumber(chilled[0]) } })}
/>
)}
</td>
);
}

View File

@ -1,7 +1,7 @@
// Copyright 2017-2020 @polkadot/app-staking authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Balance } from '@polkadot/types/interfaces';
import type { NominatorValue } from './types';
import BN from 'bn.js';
import React, { useMemo } from 'react';
@ -12,18 +12,18 @@ import { BN_ZERO } from '@polkadot/util';
interface Props {
stakeOther?: BN;
nominators: [string, Balance][];
nominators: NominatorValue[];
}
function extractFunction (all: [string, Balance][]): null | [number, () => React.ReactNode[]] {
function extractFunction (all: NominatorValue[]): null | [number, () => React.ReactNode[]] {
return all.length
? [
all.length,
() => all.map(([who, bonded]): React.ReactNode =>
() => all.map(({ nominatorId, value }): React.ReactNode =>
<AddressMini
bonded={bonded}
key={who}
value={who}
bonded={value}
key={nominatorId}
value={nominatorId}
withBonded
/>
)
@ -31,8 +31,8 @@ function extractFunction (all: [string, Balance][]): null | [number, () => React
: null;
}
function extractTotals (maxPaid: BN | undefined, nominators: [string, Balance][], stakeOther?: BN): [null | [number, () => React.ReactNode[]], BN, null | [number, () => React.ReactNode[]], BN] {
const sorted = nominators.sort((a, b) => b[1].cmp(a[1]));
function extractTotals (maxPaid: BN | undefined, nominators: NominatorValue[], stakeOther?: BN): [null | [number, () => React.ReactNode[]], BN, null | [number, () => React.ReactNode[]], BN] {
const sorted = nominators.sort((a, b) => b.value.cmp(a.value));
if (!maxPaid || maxPaid.gtn(sorted.length)) {
return [extractFunction(sorted), stakeOther || BN_ZERO, null, BN_ZERO];
@ -40,9 +40,9 @@ function extractTotals (maxPaid: BN | undefined, nominators: [string, Balance][]
const max = maxPaid.toNumber();
const rewarded = sorted.slice(0, max);
const rewardedTotal = rewarded.reduce((total, [, value]) => total.iadd(value), new BN(0));
const rewardedTotal = rewarded.reduce((total, { value }) => total.iadd(value), new BN(0));
const unrewarded = sorted.slice(max);
const unrewardedTotal = unrewarded.reduce((total, [, value]) => total.iadd(value), new BN(0));
const unrewardedTotal = unrewarded.reduce((total, { value }) => total.iadd(value), new BN(0));
return [extractFunction(rewarded), rewardedTotal, extractFunction(unrewarded), unrewardedTotal];
}
@ -66,7 +66,8 @@ function StakeOther ({ nominators, stakeOther }: Props): React.ReactElement<Prop
labelPost={` (${rewarded[0]})`}
value={rewardedTotal}
/>
}/>
}
/>
{unrewarded && (
<Expander
className='stakeOver'

View File

@ -11,7 +11,7 @@ import MaxBadge from '../../MaxBadge';
interface Props {
isElected: boolean;
isMain?: boolean;
nominators?: ([string, BN] | [string, BN, number])[];
nominators?: { nominatorId: string }[];
onlineCount?: false | BN;
onlineMessage?: boolean;
}
@ -21,7 +21,7 @@ function Status ({ isElected, isMain, nominators = [], onlineCount, onlineMessag
const blockCount = onlineCount && onlineCount.toNumber();
const isNominating = useMemo(
() => nominators.some(([nominatorId]) => allAccounts.includes(nominatorId)),
() => nominators.some(({ nominatorId }) => allAccounts.includes(nominatorId)),
[allAccounts, nominators]
);

View File

@ -3,8 +3,9 @@
import type { DeriveAccountInfo } from '@polkadot/api-derive/types';
import type { Option } from '@polkadot/types';
import type { Balance, EraIndex, SlashingSpans, ValidatorPrefs } from '@polkadot/types/interfaces';
import type { ValidatorInfo } from '../../types';
import type { SlashingSpans, ValidatorPrefs } from '@polkadot/types/interfaces';
import type { NominatedBy as NominatedByType, ValidatorInfo } from '../../types';
import type { NominatorValue } from './types';
import BN from 'bn.js';
import React, { useCallback, useMemo } from 'react';
@ -28,7 +29,7 @@ interface Props {
isFavorite: boolean;
isMain?: boolean;
lastBlock?: string;
nominatedBy?: [string, EraIndex, number][];
nominatedBy?: NominatedByType[];
onlineCount?: false | BN;
onlineMessage?: boolean;
points?: string;
@ -39,20 +40,20 @@ interface Props {
interface StakingState {
commission?: string;
nominators: [string, Balance][];
nominators: NominatorValue[];
stakeTotal?: BN;
stakeOther?: BN;
stakeOwn?: BN;
}
function expandInfo ({ exposure, validatorPrefs }: ValidatorInfo): StakingState {
let nominators: [string, Balance][] = [];
let nominators: NominatorValue[] = [];
let stakeTotal: BN | undefined;
let stakeOther: BN | undefined;
let stakeOwn: BN | undefined;
if (exposure) {
nominators = exposure.others.map(({ value, who }): [string, Balance] => [who.toString(), value.unwrap()]);
nominators = exposure.others.map(({ value, who }) => ({ nominatorId: who.toString(), value: value.unwrap() }));
stakeTotal = exposure.total.unwrap();
stakeOwn = exposure.own.unwrap();
stakeOther = stakeTotal.sub(stakeOwn);
@ -86,7 +87,9 @@ function Address ({ address, className = '', filterName, hasQueries, isElected,
const { accountInfo, slashingSpans } = useAddressCalls(api, address, isMain);
const { commission, nominators, stakeOther, stakeOwn } = useMemo(
() => validatorInfo ? expandInfo(validatorInfo) : { nominators: [] },
() => validatorInfo
? expandInfo(validatorInfo)
: { nominators: [] },
[validatorInfo]
);
@ -117,7 +120,7 @@ function Address ({ address, className = '', filterName, hasQueries, isElected,
<Status
isElected={isElected}
isMain={isMain}
nominators={nominatedBy || nominators}
nominators={isMain ? nominators : nominatedBy}
onlineCount={onlineCount}
onlineMessage={onlineMessage}
/>

View File

@ -0,0 +1,9 @@
// Copyright 2017-2020 @polkadot/app-staking authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Balance } from '@polkadot/types/interfaces';
export interface NominatorValue {
nominatorId: string;
value: Balance;
}

View File

@ -2,8 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import type { DeriveHeartbeats, DeriveStakingOverview } from '@polkadot/api-derive/types';
import type { Option, StorageKey } from '@polkadot/types';
import type { AccountId, EraIndex, Nominations } from '@polkadot/types/interfaces';
import type { AccountId } from '@polkadot/types/interfaces';
import type { Authors } from '@polkadot/react-query/BlockAuthors';
import type { SortedTargets, ValidatorInfo } from '../types';
@ -15,6 +14,7 @@ import { BlockAuthorsContext } from '@polkadot/react-query';
import Filtering from '../Filtering';
import Legend from '../Legend';
import { useTranslation } from '../translate';
import useNominations from '../useNominations';
import Address from './Address';
interface Props {
@ -71,34 +71,12 @@ function getFiltered (stakingOverview: DeriveStakingOverview, favorites: string[
};
}
function extractNominators (nominations: [StorageKey, Option<Nominations>][]): Record<string, [string, EraIndex, number][]> {
return nominations.reduce((mapped: Record<string, [string, EraIndex, number][]>, [key, optNoms]) => {
if (optNoms.isSome && key.args.length) {
const nominatorId = key.args[0].toString();
const { submittedIn, targets } = optNoms.unwrap();
targets.forEach((_validatorId, index): void => {
const validatorId = _validatorId.toString();
const info: [string, EraIndex, number] = [nominatorId, submittedIn, index + 1];
if (!mapped[validatorId]) {
mapped[validatorId] = [info];
} else {
mapped[validatorId].push(info);
}
});
}
return mapped;
}, {});
}
function CurrentList ({ favorites, hasQueries, isIntentions, next, stakingOverview, targets, toggleFavorite }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const { api } = useApi();
const { byAuthor, eraPoints } = useContext(isIntentions ? EmptyAuthorsContext : BlockAuthorsContext);
const recentlyOnline = useCall<DeriveHeartbeats>(!isIntentions && api.derive.imOnline?.receivedHeartbeats);
const nominators = useCall<[StorageKey, Option<Nominations>][]>(isIntentions && api.query.staking.nominators.entries);
const nominatedBy = useNominations(isIntentions);
const [nameFilter, setNameFilter] = useState<string>('');
const [withIdentity, setWithIdentity] = useState(false);
@ -111,7 +89,7 @@ function CurrentList ({ favorites, hasQueries, isIntentions, next, stakingOvervi
);
const infoMap = useMemo(
() => (targets?.validators || []).reduce((result: Record<string, ValidatorInfo>, info): Record<string, ValidatorInfo> => {
() => targets.validators?.reduce((result: Record<string, ValidatorInfo>, info): Record<string, ValidatorInfo> => {
result[info.accountId.toString()] = info;
return result;
@ -119,11 +97,6 @@ function CurrentList ({ favorites, hasQueries, isIntentions, next, stakingOvervi
[targets]
);
const nominatedBy = useMemo(
() => nominators ? extractNominators(nominators) : null,
[nominators]
);
const headerWaitingRef = useRef([
[t('intentions'), 'start', 2],
[t('nominators'), 'expand'],
@ -160,7 +133,7 @@ function CurrentList ({ favorites, hasQueries, isIntentions, next, stakingOvervi
onlineMessage={recentlyOnline?.[address]?.hasMessage}
points={eraPoints[address]}
toggleFavorite={toggleFavorite}
validatorInfo={infoMap[address]}
validatorInfo={infoMap?.[address]}
withIdentity={withIdentity}
/>
)),
@ -170,7 +143,14 @@ function CurrentList ({ favorites, hasQueries, isIntentions, next, stakingOvervi
return isIntentions
? (
<Table
empty={!isLoading && waiting && t<string>('No waiting validators found')}
empty={!isLoading && waiting && nominatedBy && t<string>('No waiting validators found')}
emptySpinner={
<>
{!waiting && <div>{t<string>('Retrieving validators')}</div>}
{!infoMap && <div>{t<string>('Retrieving validator info')}</div>}
{!nominatedBy && <div>{t<string>('Retrieving nominators')}</div>}
</>
}
filter={
<Filtering
nameFilter={nameFilter}
@ -182,12 +162,19 @@ function CurrentList ({ favorites, hasQueries, isIntentions, next, stakingOvervi
header={headerWaitingRef.current}
legend={<Legend />}
>
{isLoading ? undefined : _renderRows(elected, false).concat(_renderRows(waiting, false))}
{(isLoading || !nominatedBy) ? undefined : _renderRows(elected, false).concat(_renderRows(waiting, false))}
</Table>
)
: (
<Table
empty={!isLoading && validators && t<string>('No active validators found')}
empty={!isLoading && recentlyOnline && validators && infoMap && t<string>('No active validators found')}
emptySpinner={
<>
{!validators && <div>{t<string>('Retrieving validators')}</div>}
{!infoMap && <div>{t<string>('Retrieving validator info')}</div>}
{!recentlyOnline && <div>{t<string>('Retrieving online status')}</div>}
</>
}
filter={
<Filtering
nameFilter={nameFilter}
@ -199,7 +186,7 @@ function CurrentList ({ favorites, hasQueries, isIntentions, next, stakingOvervi
header={headerActiveRef.current}
legend={<Legend />}
>
{isLoading ? undefined : _renderRows(validators, true)}
{(isLoading || !recentlyOnline || !infoMap) ? undefined : _renderRows(validators, true)}
</Table>
);
}

View File

@ -3,7 +3,7 @@
import type { DeriveAccountInfo } from '@polkadot/api-derive/types';
import type { UnappliedSlash } from '@polkadot/types/interfaces';
import type { ValidatorInfo } from '../types';
import type { NominatedBy, ValidatorInfo } from '../types';
import BN from 'bn.js';
import React, { useCallback, useMemo } from 'react';
@ -24,11 +24,16 @@ interface Props {
info: ValidatorInfo;
isNominated: boolean;
isSelected: boolean;
nominatedBy?: NominatedBy[];
toggleFavorite: (accountId: string) => void;
toggleSelected: (accountId: string) => void;
}
function Validator ({ allSlashes, canSelect, filterName, info, isNominated, isSelected, toggleFavorite, toggleSelected }: Props): React.ReactElement<Props> | null {
function queryAddress (address: string): void {
window.location.hash = `/staking/query/${address}`;
}
function Validator ({ allSlashes, canSelect, filterName, info, isNominated, isSelected, nominatedBy = [], toggleFavorite, toggleSelected }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const { api } = useApi();
const accountInfo = useCall<DeriveAccountInfo>(api.derive.accounts.info, [info.accountId]);
@ -49,9 +54,7 @@ function Validator ({ allSlashes, canSelect, filterName, info, isNominated, isSe
);
const _onQueryStats = useCallback(
(): void => {
window.location.hash = `/staking/query/${info.key}`;
},
() => queryAddress(info.key),
[info.key]
);
@ -92,7 +95,7 @@ function Validator ({ allSlashes, canSelect, filterName, info, isNominated, isSe
)
: <Badge color='transparent' />
}
<MaxBadge numNominators={numNominators} />
<MaxBadge numNominators={numNominators || nominatedBy.length} />
{slashes.length !== 0 && (
<Badge
color='red'
@ -120,7 +123,8 @@ function Validator ({ allSlashes, canSelect, filterName, info, isNominated, isSe
: formatNumber(lastPayout)
)}
</td>
<td className='number media--1200'>{numNominators || ''}</td>
<td className='number media--1200 no-pad-right'>{numNominators || ''}</td>
<td className='number media--1200 no-pad-left'>{nominatedBy.length || ''}</td>
<td className='number media--1100'>
{
isCommission

View File

@ -3,7 +3,7 @@
import type { DeriveStakingOverview, DeriveHasIdentity } from '@polkadot/api-derive/types';
import type { StakerState } from '@polkadot/react-hooks/types';
import type { SortedTargets, TargetSortBy, ValidatorInfo } from '../types';
import type { NominatedBy, SortedTargets, TargetSortBy, ValidatorInfo } from '../types';
import BN from 'bn.js';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
@ -16,6 +16,7 @@ import Filtering from '../Filtering';
import Legend from '../Legend';
import { MAX_NOMINATIONS } from '../constants';
import { useTranslation } from '../translate';
import useNominations from '../useNominations';
import Nominate from './Nominate';
import Summary from './Summary';
import Validator from './Validator';
@ -49,16 +50,14 @@ interface SortState {
const CLASSES: Record<string, string> = {
rankBondOther: 'media--1600',
rankBondOwn: 'media--900',
rankComm: 'media--1100',
rankNumNominators: 'media--1200'
rankBondOwn: 'media--900'
};
const MAX_CAP_PERCENT = 75;
const MAX_COMM_PERCENT = 20; // %
const MAX_CAP_PERCENT = 100; // 75 if only using numNominators
const MAX_COMM_PERCENT = 20;
const MAX_DAYS = 7;
const SORT_KEYS = ['rankNumNominators', 'rankComm', 'rankBondTotal', 'rankBondOwn', 'rankBondOther', 'rankOverall'];
const SORT_KEYS = ['rankBondTotal', 'rankBondOwn', 'rankBondOther', 'rankOverall'];
function filterValidators (validators: ValidatorInfo[], allIdentity: Record<string, DeriveHasIdentity>, { daysPayout, isBabe, maxPaid, withElected, withGroup, withIdentity, withPayout, withoutComm, withoutOver }: Flags): ValidatorInfo[] {
function applyFilter (validators: ValidatorInfo[], allIdentity: Record<string, DeriveHasIdentity>, { daysPayout, isBabe, maxPaid, withElected, withGroup, withIdentity, withPayout, withoutComm, withoutOver }: Flags, nominatedBy?: Record<string, NominatedBy[]>): ValidatorInfo[] {
const parentIds: string[] = [];
return validators.filter(({ accountId, commissionPer, isElected, isFavorite, lastPayout, numNominators }): boolean => {
@ -68,13 +67,14 @@ function filterValidators (validators: ValidatorInfo[], allIdentity: Record<stri
const stashId = accountId.toString();
const thisIdentity = allIdentity[stashId];
const nomCount = nominatedBy?.[stashId]?.length || numNominators || 0;
if (
(!withElected || isElected) &&
(!withIdentity || !!thisIdentity?.hasIdentity) &&
(!withPayout || !isBabe || (!!lastPayout && daysPayout.gte(lastPayout))) &&
(!withoutComm || (commissionPer < MAX_COMM_PERCENT)) &&
(!withoutOver || !maxPaid || maxPaid.muln(MAX_CAP_PERCENT).divn(100).gtn(numNominators))
(!withoutOver || !maxPaid || maxPaid.muln(MAX_CAP_PERCENT).divn(100).gten(nomCount))
) {
if (!withGroup || !thisIdentity || !thisIdentity.parentId) {
if (!parentIds.includes(stashId)) {
@ -145,6 +145,7 @@ function Targets ({ className = '', isInElection, ownStashes, targets: { avgStak
const allSlashes = useAvailableSlashes();
const daysPayout = useBlocksPerDays(MAX_DAYS);
const ownNominators = useOwnNominators(ownStashes);
const nominatedBy = useNominations(true);
const [selected, setSelected] = useState<string[]>([]);
const [{ isQueryFiltered, nameFilter }, setNameFilter] = useState({ isQueryFiltered: false, nameFilter: '' });
const [withElected, setWithElected] = useState(false);
@ -161,8 +162,6 @@ function Targets ({ className = '', isInElection, ownStashes, targets: { avgStak
rankBondOther: t<string>('other stake'),
rankBondOwn: t<string>('own stake'),
rankBondTotal: t<string>('total stake'),
rankComm: t<string>('comm.'),
rankNumNominators: t<string>('nominators'),
rankOverall: t<string>('return')
});
@ -183,8 +182,8 @@ function Targets ({ className = '', isInElection, ownStashes, targets: { avgStak
);
const filtered = useMemo(
() => allIdentity && validators && filterValidators(validators, allIdentity, flags),
[allIdentity, flags, validators]
() => allIdentity && validators && nominatedBy && applyFilter(validators, allIdentity, flags, nominatedBy),
[allIdentity, flags, nominatedBy, validators]
);
// We are using an effect here to get this async. Sorting will have a double-render, however it allows
@ -235,6 +234,8 @@ function Targets ({ className = '', isInElection, ownStashes, targets: { avgStak
const header = useMemo(() => [
[t('validators'), 'start', 3],
[t('payout'), 'media--1500'],
[t('nominators'), 'media--1200', 2],
[t('comm.'), 'media--1100'],
...(SORT_KEYS as (keyof typeof labelsRef.current)[]).map((header) => [
<>{labelsRef.current[header]}<Icon icon={sortBy === header ? (sortFromMax ? 'chevron-down' : 'chevron-up') : 'minus'} /></>,
`${sorted ? `isClickable ${sortBy === header ? 'highlight--border' : ''} number` : 'number'} ${CLASSES[header] || ''}`,
@ -267,7 +268,11 @@ function Targets ({ className = '', isInElection, ownStashes, targets: { avgStak
/>
<Toggle
className='staking--buttonToggle'
label={t<string>('no {{maxCap}}%+ capacity', { replace: { maxCap: MAX_CAP_PERCENT } })}
label={
MAX_CAP_PERCENT < 100
? t<string>('no {{maxCap}}%+ capacity', { replace: { maxCap: MAX_CAP_PERCENT } })
: t<string>('no at capacity')
}
onChange={setWithoutOver}
value={withoutOver}
/>
@ -322,6 +327,12 @@ function Targets ({ className = '', isInElection, ownStashes, targets: { avgStak
<ElectionBanner isInElection={isInElection} />
<Table
empty={sorted && t<string>('No active validators to check')}
emptySpinner={
<>
{!(validators && allIdentity) && <div>{t('Retrieving validators')}</div>}
{!nominatedBy && <div>{t('Retrieving nominators')}</div>}
</>
}
filter={filter}
header={header}
legend={<Legend />}
@ -335,6 +346,7 @@ function Targets ({ className = '', isInElection, ownStashes, targets: { avgStak
isNominated={myNominees.includes(info.key)}
isSelected={selected.includes(info.key)}
key={info.key}
nominatedBy={nominatedBy?.[info.key]}
toggleFavorite={toggleFavorite}
toggleSelected={_toggleSelected}
/>

View File

@ -1,7 +1,7 @@
// Copyright 2017-2020 @polkadot/app-staking authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { AccountId, Balance, BlockNumber, Exposure, Hash, SessionIndex, ValidatorPrefs, ValidatorPrefsTo196 } from '@polkadot/types/interfaces';
import type { AccountId, Balance, BlockNumber, EraIndex, Exposure, Hash, SessionIndex, ValidatorPrefs, ValidatorPrefsTo196 } from '@polkadot/types/interfaces';
import type { Inflation } from '@polkadot/react-hooks/types';
import BN from 'bn.js';
@ -12,6 +12,12 @@ export type AccountFilter = 'all' | 'controller' | 'session' | 'stash' | 'unbond
export type ValidatorFilter = 'all' | 'hasNominators' | 'noNominators' | 'hasWarnings' | 'noWarnings' | 'iNominated' | 'nextSet';
export interface NominatedBy {
index: number;
nominatorId: string;
submittedIn: EraIndex;
}
export interface Slash {
accountId: AccountId;
amount: Balance;

View File

@ -0,0 +1,43 @@
// Copyright 2017-2020 @polkadot/app-staking authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Option, StorageKey } from '@polkadot/types';
import type { Nominations } from '@polkadot/types/interfaces';
import type { NominatedBy } from './types';
import { useMemo } from 'react';
import { useApi, useCall } from '@polkadot/react-hooks';
type Result = Record<string, NominatedBy[]>;
function extractNominators (nominations: [StorageKey, Option<Nominations>][]): Result {
return nominations.reduce((mapped: Result, [key, optNoms]) => {
if (optNoms.isSome && key.args.length) {
const nominatorId = key.args[0].toString();
const { submittedIn, targets } = optNoms.unwrap();
targets.forEach((_validatorId, index): void => {
const validatorId = _validatorId.toString();
const info = { index: index + 1, nominatorId, submittedIn };
if (!mapped[validatorId]) {
mapped[validatorId] = [info];
} else {
mapped[validatorId].push(info);
}
});
}
return mapped;
}, {});
}
export default function useNominations (isActive = true): Result | undefined {
const { api } = useApi();
const nominators = useCall<[StorageKey, Option<Nominations>][]>(isActive && api.query.staking.nominators.entries);
return useMemo(
() => nominators && extractNominators(nominators),
[nominators]
);
}

View File

@ -51,8 +51,9 @@ function sortValidators (list: ValidatorInfo[]): ValidatorInfo[] {
return false;
})
.filter((a) => a.bondTotal.gtn(0))
.sort((a, b) => b.commissionPer - a.commissionPer)
.map(mapIndex('rankComm'))
// ignored, not used atm
// .sort((a, b) => b.commissionPer - a.commissionPer)
// .map(mapIndex('rankComm'))
.sort((a, b) => b.bondOther.cmp(a.bondOther))
.map(mapIndex('rankBondOther'))
.sort((a, b) => b.bondOwn.cmp(a.bondOwn))
@ -63,8 +64,9 @@ function sortValidators (list: ValidatorInfo[]): ValidatorInfo[] {
.map(mapIndex('rankPayment'))
.sort((a, b) => a.stakedReturnCmp - b.stakedReturnCmp)
.map(mapIndex('rankReward'))
.sort((a, b) => b.numNominators - a.numNominators)
.map(mapIndex('rankNumNominators'))
// ignored, not used atm
// .sort((a, b) => b.numNominators - a.numNominators)
// .map(mapIndex('rankNumNominators'))
.sort((a, b): number => {
const cmp = b.stakedReturnCmp - a.stakedReturnCmp;

View File

@ -59,5 +59,9 @@ export default React.memo(styled(Spinner)`
color: inherit !important;
margin: 0.25rem auto 1.5rem auto;
opacity: 0.6;
div+div {
margin-top: 0.25rem;
}
}
`);

View File

@ -107,6 +107,14 @@ export default React.memo(styled(Body)(({ theme }: ThemeProps) => `
width: 0;
}
&.no-pad-left {
padding-left: 0.125rem;
}
&.no-pad-right {
padding-right: 0.125rem;
}
&.number {
text-align: right;
}