Combine active & waiting staking views (#7354)

* Combine active & waiting staking views

* Sort by stashes

* Filter by own

* useRef for options
This commit is contained in:
Jaco 2022-04-12 07:05:53 +02:00 committed by GitHub
parent a560430fad
commit 1e4f97c1d5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 126 additions and 49 deletions

View File

@ -5,7 +5,7 @@ import type { DeriveHeartbeats, DeriveStakingOverview } from '@polkadot/api-deri
import type { Authors } from '@polkadot/react-query/BlockAuthors';
import type { AccountId } from '@polkadot/types/interfaces';
import type { BN } from '@polkadot/util';
import type { SortedTargets, ValidatorInfo } from '../types';
import type { NominatedByMap, SortedTargets, ValidatorInfo } from '../types';
import React, { useContext, useMemo, useRef, useState } from 'react';
@ -16,14 +16,18 @@ 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 {
className?: string;
favorites: string[];
hasQueries: boolean;
isIntentions?: boolean;
isIntentionsTrigger?: boolean;
isOwn: boolean;
minCommission?: BN;
nominatedBy?: NominatedByMap;
ownStashIds?: string[];
paraValidators?: Record<string, boolean>;
setNominators?: (nominators: string[]) => void;
stakingOverview?: DeriveStakingOverview;
@ -40,45 +44,54 @@ interface Filtered {
const EmptyAuthorsContext: React.Context<Authors> = React.createContext<Authors>({ byAuthor: {}, eraPoints: {}, lastBlockAuthors: [], lastHeaders: [] });
function filterAccounts (accounts: string[] = [], elected: string[], favorites: string[], without: string[]): AccountExtend[] {
function filterAccounts (isOwn: boolean, accounts: string[] = [], ownStashIds: string[] = [], elected: string[], favorites: string[], without: string[]): AccountExtend[] {
return accounts
.filter((accountId) => !without.includes(accountId))
.filter((accountId) =>
!without.includes(accountId) && (
!isOwn ||
ownStashIds.includes(accountId)
)
)
.map((accountId): AccountExtend => [
accountId,
elected.includes(accountId),
favorites.includes(accountId)
])
.sort(([,, isFavA]: AccountExtend, [,, isFavB]: AccountExtend) =>
isFavA === isFavB
? 0
: (isFavA ? -1 : 1)
);
.sort(([accA,, isFavA]: AccountExtend, [accB,, isFavB]: AccountExtend): number => {
const isStashA = ownStashIds.includes(accA);
const isStashB = ownStashIds.includes(accB);
return isFavA === isFavB
? isStashA === isStashB
? 0
: (isStashA ? -1 : 1)
: (isFavA ? -1 : 1);
});
}
function accountsToString (accounts: AccountId[]): string[] {
return accounts.map((a) => a.toString());
}
function getFiltered (stakingOverview: DeriveStakingOverview, favorites: string[], next?: string[]): Filtered {
function getFiltered (isOwn: boolean, stakingOverview: DeriveStakingOverview, favorites: string[], next?: string[], ownStashIds?: string[]): Filtered {
const allElected = accountsToString(stakingOverview.nextElected);
const validatorIds = accountsToString(stakingOverview.validators);
return {
validators: filterAccounts(validatorIds, allElected, favorites, []),
waiting: filterAccounts(allElected, allElected, favorites, validatorIds).concat(
filterAccounts(next, [], favorites, allElected)
validators: filterAccounts(isOwn, validatorIds, ownStashIds, allElected, favorites, []),
waiting: filterAccounts(isOwn, allElected, ownStashIds, allElected, favorites, validatorIds).concat(
filterAccounts(isOwn, next, ownStashIds, [], favorites, allElected)
)
};
}
const DEFAULT_PARAS = {};
function CurrentList ({ favorites, hasQueries, isIntentions, minCommission, paraValidators = DEFAULT_PARAS, stakingOverview, targets, toggleFavorite }: Props): React.ReactElement<Props> | null {
function CurrentList ({ className, favorites, hasQueries, isIntentions, isOwn, minCommission, nominatedBy, ownStashIds, paraValidators = DEFAULT_PARAS, 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 nominatedBy = useNominations(isIntentions);
const [nameFilter, setNameFilter] = useState<string>('');
const [toggles, setToggle] = useSavedFlags('staking:overview', { withIdentity: false });
@ -86,8 +99,8 @@ function CurrentList ({ favorites, hasQueries, isIntentions, minCommission, para
const isLoading = useLoadingDelay();
const { validators, waiting } = useMemo(
() => stakingOverview ? getFiltered(stakingOverview, favorites, targets.waitingIds) : {},
[favorites, stakingOverview, targets]
() => stakingOverview ? getFiltered(isOwn, stakingOverview, favorites, targets.waitingIds, ownStashIds) : {},
[favorites, isOwn, ownStashIds, stakingOverview, targets]
);
const infoMap = useMemo(
@ -122,6 +135,7 @@ function CurrentList ({ favorites, hasQueries, isIntentions, minCommission, para
return (
<Table
className={className}
empty={
!isLoading && (
isIntentions

View File

@ -2,43 +2,107 @@
// SPDX-License-Identifier: Apache-2.0
import type { DeriveStakingOverview } from '@polkadot/api-derive/types';
import type { StakerState } from '@polkadot/react-hooks/types';
import type { BN } from '@polkadot/util';
import type { SortedTargets } from '../types';
import type { NominatedByMap, SortedTargets } from '../types';
import React, { useEffect } from 'react';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Button, ToggleGroup } from '@polkadot/react-components';
import { useTranslation } from '../translate';
import CurrentList from './CurrentList';
interface Props {
className?: string;
favorites: string[];
hasQueries: boolean;
isIntentions?: boolean;
minCommission?: BN;
nominatedBy?: NominatedByMap;
ownStashes?: StakerState[];
paraValidators?: Record<string, boolean>;
stakingOverview?: DeriveStakingOverview;
targets: SortedTargets;
toggleFavorite: (address: string) => void;
toggleLedger?: () => void;
toggleNominatedBy: () => void;
}
function Overview ({ className = '', favorites, hasQueries, isIntentions, minCommission, paraValidators, stakingOverview, targets, toggleFavorite, toggleLedger }: Props): React.ReactElement<Props> {
function Overview ({ className = '', favorites, hasQueries, minCommission, nominatedBy, ownStashes, paraValidators, stakingOverview, targets, toggleFavorite, toggleLedger, toggleNominatedBy }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const [intentIndex, _setIntentIndex] = useState(0);
const [typeIndex, setTypeIndex] = useState(1);
const setIntentIndex = useCallback(
(index: number): void => {
index && toggleNominatedBy();
_setIntentIndex(index);
},
[toggleNominatedBy]
);
const filterOptions = useRef([
{ text: t('Own validators'), value: 'mine' },
{ text: t('All validators'), value: 'all' }
]);
const intentOptions = useRef([
{ text: t('Active'), value: 'active' },
{ text: t('Waiting'), value: 'waiting' }
]);
const ownStashIds = useMemo(
() => ownStashes && ownStashes.map(({ stashId }) => stashId),
[ownStashes]
);
useEffect((): void => {
toggleLedger && toggleLedger();
}, [toggleLedger]);
const isOwn = typeIndex === 0;
return (
<div className={`staking--Overview ${className}`}>
<Button.Group>
<ToggleGroup
onChange={setTypeIndex}
options={filterOptions.current}
value={typeIndex}
/>
<ToggleGroup
onChange={setIntentIndex}
options={intentOptions.current}
value={intentIndex}
/>
</Button.Group>
<CurrentList
className={intentIndex === 0 ? '' : 'staking--hidden'}
favorites={favorites}
hasQueries={hasQueries}
isIntentions={isIntentions}
isOwn={isOwn}
minCommission={minCommission}
ownStashIds={ownStashIds}
paraValidators={paraValidators}
stakingOverview={stakingOverview}
targets={targets}
toggleFavorite={toggleFavorite}
/>
{intentIndex === 1 && (
<CurrentList
className={intentIndex === 1 ? '' : 'staking--hidden'}
favorites={favorites}
hasQueries={hasQueries}
isIntentions
isOwn={isOwn}
nominatedBy={nominatedBy}
ownStashIds={ownStashIds}
paraValidators={paraValidators}
stakingOverview={stakingOverview}
targets={targets}
toggleFavorite={toggleFavorite}
/>
)}
</div>
);
}

View File

@ -5,7 +5,7 @@ import type { DeriveHasIdentity, DeriveStakingOverview } from '@polkadot/api-der
import type { StakerState } from '@polkadot/react-hooks/types';
import type { u32 } from '@polkadot/types-codec';
import type { BN } from '@polkadot/util';
import type { NominatedBy, SortedTargets, TargetSortBy, ValidatorInfo } from '../types';
import type { NominatedByMap, SortedTargets, TargetSortBy, ValidatorInfo } from '../types';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import styled from 'styled-components';
@ -20,7 +20,6 @@ import Filtering from '../Filtering';
import Legend from '../Legend';
import { useTranslation } from '../translate';
import useIdentities from '../useIdentities';
import useNominations from '../useNominations';
import Nominate from './Nominate';
import Summary from './Summary';
import useOwnNominators from './useOwnNominators';
@ -29,11 +28,13 @@ import Validator from './Validator';
interface Props {
className?: string;
isInElection: boolean;
nominatedBy?: NominatedByMap;
ownStashes?: StakerState[];
stakingOverview?: DeriveStakingOverview;
targets: SortedTargets;
toggleFavorite: (address: string) => void;
toggleLedger: () => void;
toggleNominatedBy: () => void;
}
interface SavedFlags {
@ -75,7 +76,7 @@ function overlapsDisplay (displays: (string[])[], test: string[]): boolean {
);
}
function applyFilter (validators: ValidatorInfo[], medianComm: number, allIdentity: Record<string, DeriveHasIdentity>, { daysPayout, isBabe, maxPaid, withElected, withGroup, withIdentity, withPayout, withoutComm, withoutOver }: Flags, nominatedBy?: Record<string, NominatedBy[]>): ValidatorInfo[] {
function applyFilter (validators: ValidatorInfo[], medianComm: number, allIdentity: Record<string, DeriveHasIdentity>, { daysPayout, isBabe, maxPaid, withElected, withGroup, withIdentity, withPayout, withoutComm, withoutOver }: Flags, nominatedBy?: NominatedByMap): ValidatorInfo[] {
const displays: (string[])[] = [];
const parentIds: string[] = [];
@ -191,13 +192,12 @@ const DEFAULT_NAME = { isQueryFiltered: false, nameFilter: '' };
const DEFAULT_SORT: SortState = { sortBy: 'rankOverall', sortFromMax: true };
function Targets ({ className = '', isInElection, ownStashes, targets: { avgStaked, inflation: { stakedReturn }, lowStaked, medianComm, minNominated, minNominatorBond, nominators, totalIssuance, totalStaked, validatorIds, validators }, toggleFavorite, toggleLedger }: Props): React.ReactElement<Props> {
function Targets ({ className = '', isInElection, nominatedBy, ownStashes, targets: { avgStaked, inflation: { stakedReturn }, lowStaked, medianComm, minNominated, minNominatorBond, nominators, totalIssuance, totalStaked, validatorIds, validators }, toggleFavorite, toggleLedger, toggleNominatedBy }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const allSlashes = useAvailableSlashes();
const daysPayout = useBlocksPerDays(MAX_DAYS);
const ownNominators = useOwnNominators(ownStashes);
const nominatedBy = useNominations(true);
const allIdentity = useIdentities(validatorIds);
const [selected, setSelected] = useState<string[]>([]);
const [{ isQueryFiltered, nameFilter }, setNameFilter] = useState(DEFAULT_NAME);
@ -240,7 +240,8 @@ function Targets ({ className = '', isInElection, ownStashes, targets: { avgStak
useEffect((): void => {
toggleLedger();
}, [toggleLedger]);
toggleNominatedBy();
}, [toggleLedger, toggleNominatedBy]);
const maxNominations = useMemo(
() => api.consts.staking.maxNominations

View File

@ -28,6 +28,7 @@ import Query from './Query';
import Slashes from './Slashes';
import Targets from './Targets';
import { useTranslation } from './translate';
import useNominations from './useNominations';
import useSortedTargets from './useSortedTargets';
const HIDDEN_ACC = ['actions', 'payout'];
@ -52,6 +53,8 @@ function StakingApp ({ basePath, className = '' }: Props): React.ReactElement<Pr
const { pathname } = useLocation();
const [withLedger, setWithLedger] = useState(false);
const [favorites, toggleFavorite] = useFavorites(STORE_FAVS_BASE);
const [loadNominations, setLoadNominations] = useState(false);
const nominatedBy = useNominations(loadNominations);
const stakingOverview = useCall<DeriveStakingOverview>(api.derive.staking.overview);
const [isInElection, minCommission, paraValidators] = useCallMulti<[boolean, BN | undefined, Record<string, boolean>]>([
api.query.staking.eraElectionStatus,
@ -83,6 +86,11 @@ function StakingApp ({ basePath, className = '' }: Props): React.ReactElement<Pr
[]
);
const toggleNominatedBy = useCallback(
() => setLoadNominations(true),
[]
);
const items = useMemo(() => [
{
isRoot: true,
@ -110,10 +118,6 @@ function StakingApp ({ basePath, className = '' }: Props): React.ReactElement<Pr
name: 'bags',
text: t<string>('Bags')
},
{
name: 'waiting',
text: t<string>('Waiting')
},
{
count: slashes.reduce((count, [, unapplied]) => count + unapplied.length, 0),
name: 'slashes',
@ -168,22 +172,13 @@ function StakingApp ({ basePath, className = '' }: Props): React.ReactElement<Pr
<Route path={`${basePath}/targets`}>
<Targets
isInElection={isInElection}
nominatedBy={nominatedBy}
ownStashes={ownStashes}
stakingOverview={stakingOverview}
targets={targets}
toggleFavorite={toggleFavorite}
toggleLedger={toggleLedger}
/>
</Route>
<Route path={`${basePath}/waiting`}>
<Overview
favorites={favorites}
hasQueries={hasQueries}
isIntentions
stakingOverview={stakingOverview}
targets={targets}
toggleFavorite={toggleFavorite}
toggleLedger={toggleLedger}
toggleNominatedBy={toggleNominatedBy}
/>
</Route>
</Switch>
@ -202,10 +197,13 @@ function StakingApp ({ basePath, className = '' }: Props): React.ReactElement<Pr
favorites={favorites}
hasQueries={hasQueries}
minCommission={minCommission}
nominatedBy={nominatedBy}
ownStashes={ownStashes}
paraValidators={paraValidators}
stakingOverview={stakingOverview}
targets={targets}
toggleFavorite={toggleFavorite}
toggleNominatedBy={toggleNominatedBy}
/>
</main>
);

View File

@ -17,6 +17,8 @@ export interface NominatedBy {
submittedIn: EraIndex;
}
export type NominatedByMap = Record<string, NominatedBy[]>;
export interface Slash {
accountId: AccountId;
amount: Balance;

View File

@ -3,16 +3,14 @@
import type { Option, StorageKey } from '@polkadot/types';
import type { Nominations } from '@polkadot/types/interfaces';
import type { NominatedBy } from './types';
import type { NominatedByMap } from './types';
import { useMemo } from 'react';
import { createNamedHook, 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]) => {
function extractNominators (nominations: [StorageKey, Option<Nominations>][]): NominatedByMap {
return nominations.reduce((mapped: NominatedByMap, [key, optNoms]) => {
if (optNoms.isSome && key.args.length) {
const nominatorId = key.args[0].toString();
const { submittedIn, targets } = optNoms.unwrap();
@ -33,7 +31,7 @@ function extractNominators (nominations: [StorageKey, Option<Nominations>][]): R
}, {});
}
function useNominationsImpl (isActive = true): Result | undefined {
function useNominationsImpl (isActive = true): NominatedByMap | undefined {
const { api } = useApi();
const nominators = useCall<[StorageKey, Option<Nominations>][]>(isActive && api.query.staking.nominators.entries);