Display nominators in the waiting list (#2557)

* Display nominators in the waiting list

* Highlight mine
This commit is contained in:
Jaco Greeff 2020-04-12 11:01:46 +02:00 committed by GitHub
parent 84d4e9ea98
commit 091934e69e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 127 additions and 31 deletions

View File

@ -14,7 +14,7 @@ interface Props {
className?: string;
controllerId: string;
next?: string[];
nominees?: string[];
nominating?: string[];
onClose: () => void;
stashId: string;
validators: string[];
@ -22,7 +22,7 @@ interface Props {
const MAX_NOMINEES = 16;
function Nominate ({ className, controllerId, next, nominees, onClose, stashId, validators }: Props): React.ReactElement<Props> | null {
function Nominate ({ className, controllerId, next, nominating, onClose, stashId, validators }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const [favorites] = useFavorites(STORE_FAVS_BASE);
const [selection, setSelection] = useState<string[]>([]);
@ -31,7 +31,7 @@ function Nominate ({ className, controllerId, next, nominees, onClose, stashId,
// ensure that the favorite is included in the list of stashes
...favorites.filter((acc) => (validators || []).includes(acc) || (next || []).includes(acc)),
// make sure the nominee is not in our favorites already
...(nominees || []).filter((acc) => !favorites.includes(acc))
...(nominating || []).filter((acc) => !favorites.includes(acc))
];
return shortlist
@ -58,7 +58,7 @@ function Nominate ({ className, controllerId, next, nominees, onClose, stashId,
<InputAddressMulti
available={available}
availableLabel={t('candidate accounts')}
defaultValue={nominees}
defaultValue={nominating}
help={t('Filter available candidates based on name, address or short account index.')}
maxCount={MAX_NOMINEES}
onChange={setSelection}

View File

@ -48,7 +48,7 @@ interface StakeState {
isOwnController: boolean;
isStashNominating: boolean;
isStashValidating: boolean;
nominees?: string[];
nominating?: string[];
sessionIds: string[];
stakingLedger?: StakingLedger;
validatorPrefs?: ValidatorPrefs;
@ -79,7 +79,7 @@ function getStakeState (allAccounts: string[], allStashes: string[] | undefined,
isStashNominating,
isStashValidating,
// we assume that all ids are non-null
nominees: nominators?.map(toIdString) as string[],
nominating: nominators?.map(toIdString) as string[],
sessionIds: (
nextSessionIds.length
? nextSessionIds
@ -97,9 +97,9 @@ function Account ({ allStashes, className, isDisabled, isOwnStash, next, onUpdat
const validateInfo = useCall<ValidatorInfo>(api.query.staking.validators, [stashId]);
const balancesAll = useCall<DeriveBalancesAll>(api.derive.balances.all, [stashId]);
const stakingAccount = useCall<DeriveStakingAccount>(api.derive.staking.account, [stashId]);
const [{ controllerId, destination, destinationId, hexSessionIdNext, hexSessionIdQueue, isLoading, isOwnController, isStashNominating, isStashValidating, nominees, sessionIds, stakingLedger }, setStakeState] = useState<StakeState>({ controllerId: null, destinationId: 0, hexSessionIdNext: null, hexSessionIdQueue: null, isLoading: true, isOwnController: false, isStashNominating: false, isStashValidating: false, sessionIds: [] });
const [{ controllerId, destination, destinationId, hexSessionIdNext, hexSessionIdQueue, isLoading, isOwnController, isStashNominating, isStashValidating, nominating, sessionIds, stakingLedger }, setStakeState] = useState<StakeState>({ controllerId: null, destinationId: 0, hexSessionIdNext: null, hexSessionIdQueue: null, isLoading: true, isOwnController: false, isStashNominating: false, isStashValidating: false, sessionIds: [] });
const [activeNoms, setActiveNoms] = useState<string[]>([]);
const inactiveNoms = useInactives(stashId, nominees);
const inactiveNoms = useInactives(stashId, nominating);
const [isBondExtraOpen, toggleBondExtra] = useToggle();
const [isInjectOpen, toggleInject] = useToggle();
const [isNominateOpen, toggleNominate] = useToggle();
@ -127,10 +127,10 @@ function Account ({ allStashes, className, isDisabled, isOwnStash, next, onUpdat
}, [allAccounts, allStashes, onUpdateType, stakingAccount, stashId, validateInfo]);
useEffect((): void => {
nominees && setActiveNoms(
nominees.filter((id): boolean => !inactiveNoms.includes(id))
nominating && setActiveNoms(
nominating.filter((id): boolean => !inactiveNoms.includes(id))
);
}, [inactiveNoms, nominees]);
}, [inactiveNoms, nominating]);
return (
<tr className={className}>
@ -150,7 +150,7 @@ function Account ({ allStashes, className, isDisabled, isOwnStash, next, onUpdat
controllerId={controllerId}
isOpen={isNominateOpen}
next={next}
nominees={nominees}
nominating={nominating}
onClose={toggleNominate}
stashId={stashId}
validators={validators}

View File

@ -0,0 +1,38 @@
// Copyright 2017-2020 @polkadot/app-staking authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import React from 'react';
import { AddressMini, Expander, Spinner } from '@polkadot/react-components';
import { formatNumber } from '@polkadot/util';
import { useTranslation } from '../../translate';
interface Props {
nominators?: [string, number][];
}
function NominatedBy ({ nominators }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
return (
<td className='start all'>
{nominators
? (nominators.length !== 0 && (
<Expander summary={t('Nominations ({{count}})', { replace: { count: formatNumber(nominators.length) } })}>
{nominators.map(([who, index]): React.ReactNode =>
<AddressMini
key={who}
summary={t('priority {{index}}', { replace: { index } })}
value={who}
/>
)}
</Expander>
))
: <Spinner variant='mini' />
}
</td>
);
}
export default React.memo(NominatedBy);

View File

@ -9,11 +9,12 @@ import BN from 'bn.js';
import React, { useCallback, useEffect, useState } from 'react';
import ApiPromise from '@polkadot/api/promise';
import { AddressSmall, Icon } from '@polkadot/react-components';
import { useApi, useCall } from '@polkadot/react-hooks';
import { useAccounts, useApi, useCall } from '@polkadot/react-hooks';
import { FormatBalance } from '@polkadot/react-query';
import keyring from '@polkadot/ui-keyring';
import Favorite from './Favorite';
import NominatedBy from './NominatedBy';
import Status from './Status';
import StakeOther from './StakeOther';
@ -27,6 +28,7 @@ interface Props {
isFavorite: boolean;
isMain?: boolean;
lastBlock?: string;
nominatedBy?: [string, number][];
onlineCount?: false | number;
onlineMessage?: boolean;
points?: string;
@ -103,12 +105,14 @@ function checkVisibility (api: ApiPromise, address: string, filterName: string,
return isVisible;
}
function Address ({ address, className, filterName, hasQueries, isAuthor, isElected, isFavorite, isMain, lastBlock, onlineCount, onlineMessage, points, setNominators, toggleFavorite }: Props): React.ReactElement<Props> | null {
function Address ({ address, className, filterName, hasQueries, isAuthor, isElected, isFavorite, isMain, lastBlock, nominatedBy, onlineCount, onlineMessage, points, setNominators, toggleFavorite }: Props): React.ReactElement<Props> | null {
const { api } = useApi();
const accountInfo = useCall<DeriveAccountInfo>(api.derive.accounts.info, [address]);
const stakingInfo = useCall<DeriveStakingQuery>(isMain && api.derive.staking.query, [address]);
const { allAccounts } = useAccounts();
const accountInfo = useCall<DeriveAccountInfo>(isMain && api.derive.accounts.info, [address]);
const stakingInfo = useCall<DeriveStakingQuery>(api.derive.staking.query, [address]);
const [{ commission, nominators, stakeOther, stakeOwn }, setStakingState] = useState<StakingState>({ nominators: [] });
const [isVisible, setIsVisible] = useState(true);
const [isNominating, setIsNominating] = useState(false);
useEffect((): void => {
if (stakingInfo) {
@ -125,6 +129,13 @@ function Address ({ address, className, filterName, hasQueries, isAuthor, isElec
);
}, [api, accountInfo, address, filterName]);
useEffect((): void => {
!isMain && setIsNominating(
allAccounts.includes(address) ||
(nominatedBy || []).some(([address]) => allAccounts.includes(address))
);
}, [address, allAccounts, isMain, nominatedBy]);
const _onQueryStats = useCallback(
(): void => {
window.location.hash = `/staking/query/${address}`;
@ -133,7 +144,7 @@ function Address ({ address, className, filterName, hasQueries, isAuthor, isElec
);
return (
<tr className={`${className} ${isAuthor && 'isHighlight'} ${!isVisible && 'staking--hidden'}`}>
<tr className={`${className} ${(isAuthor || isNominating) && 'isHighlight'} ${!isVisible && 'staking--hidden'}`}>
<Favorite
address={address}
isFavorite={isFavorite}
@ -144,15 +155,20 @@ function Address ({ address, className, filterName, hasQueries, isAuthor, isElec
onlineCount={onlineCount}
onlineMessage={onlineMessage}
/>
<td className='address all'>
<td className={`address ${isMain ? 'all' : ''}`}>
<AddressSmall value={address} />
</td>
<StakeOther
nominators={nominators}
stakeOther={stakeOther}
/>
{isMain
? (
<StakeOther
nominators={nominators}
stakeOther={stakeOther}
/>
)
: <NominatedBy nominators={nominatedBy} />
}
<td className='number'>
{stakeOwn && (
{stakeOwn?.gtn(0) && (
<FormatBalance value={stakeOwn} />
)}
</td>

View File

@ -3,13 +3,14 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { DeriveHeartbeats, DeriveStakingOverview } from '@polkadot/api-derive/types';
import { AccountId } from '@polkadot/types/interfaces';
import { AccountId, Nominations } from '@polkadot/types/interfaces';
import { Authors } from '@polkadot/react-query/BlockAuthors';
import React, { useCallback, useContext, useEffect, useState } from 'react';
import { Input, Table } from '@polkadot/react-components';
import { useApi, useCall, useFavorites } from '@polkadot/react-hooks';
import { BlockAuthorsContext } from '@polkadot/react-query';
import { Option, StorageKey } from '@polkadot/types';
import { STORE_FAVS_BASE } from '../constants';
import { useTranslation } from '../translate';
@ -66,14 +67,37 @@ function getFiltered (stakingOverview: DeriveStakingOverview, favorites: string[
};
}
function extractNominators (nominations: [StorageKey, Option<Nominations>][]): Record<string, [string, number][]> {
return nominations.reduce((mapped: Record<string, [string, number][]>, [key, optNoms]) => {
if (optNoms.isSome) {
const nominatorId = key.args[0].toString();
optNoms.unwrap().targets.forEach((_validatorId, index): void => {
const validatorId = _validatorId.toString();
const info: [string, number] = [nominatorId, index + 1];
if (!mapped[validatorId]) {
mapped[validatorId] = [info];
} else {
mapped[validatorId].push(info);
}
});
}
return mapped;
}, {});
}
function CurrentList ({ hasQueries, isIntentions, next, setNominators, stakingOverview }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const { api } = useApi();
const { byAuthor, eraPoints, lastBlockAuthors } = 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 as any, []);
const [favorites, toggleFavorite] = useFavorites(STORE_FAVS_BASE);
const [{ elected, validators, waiting }, setFiltered] = useState<Filtered>({});
const [nameFilter, setNameFilter] = useState<string>('');
const [nominatedBy, setNominatedBy] = useState<Record<string, [string, number][]> | null>();
useEffect((): void => {
stakingOverview && setFiltered(
@ -81,6 +105,12 @@ function CurrentList ({ hasQueries, isIntentions, next, setNominators, stakingOv
);
}, [favorites, next, stakingOverview]);
useEffect((): void => {
nominators && setNominatedBy(
extractNominators(nominators)
);
}, [nominators]);
const _renderRows = useCallback(
(addresses?: AccountExtend[], isMain?: boolean): React.ReactNode[] =>
(addresses || []).map(([address, isElected, isFavorite]): React.ReactNode => (
@ -94,6 +124,7 @@ function CurrentList ({ hasQueries, isIntentions, next, setNominators, stakingOv
isMain={isMain}
key={address}
lastBlock={byAuthor[address]}
nominatedBy={nominatedBy ? (nominatedBy[address] || []) : undefined}
onlineCount={recentlyOnline?.[address]?.blockCount.toNumber()}
onlineMessage={recentlyOnline?.[address]?.hasMessage}
points={eraPoints[address]}
@ -101,7 +132,7 @@ function CurrentList ({ hasQueries, isIntentions, next, setNominators, stakingOv
toggleFavorite={toggleFavorite}
/>
)),
[byAuthor, eraPoints, hasQueries, lastBlockAuthors, nameFilter, recentlyOnline, setNominators, toggleFavorite]
[byAuthor, eraPoints, hasQueries, lastBlockAuthors, nameFilter, nominatedBy, recentlyOnline, setNominators, toggleFavorite]
);
return isIntentions
@ -109,7 +140,10 @@ function CurrentList ({ hasQueries, isIntentions, next, setNominators, stakingOv
<Table
empty={waiting && t('No waiting validators found')}
header={[
[t('intentions'), 'start', 9]
[t('intentions'), 'start', 3],
[t('nominators'), 'start', 2],
[t('commission'), 'number', 1],
[undefined, undefined, 3]
]}
>
{_renderRows(elected, false).concat(..._renderRows(waiting, false))}

View File

@ -27,6 +27,7 @@ interface Props extends BareProps {
label?: React.ReactNode;
labelBalance?: React.ReactNode;
noName?: boolean;
summary?: React.ReactNode;
type?: KeyringItemType;
value?: AccountId | AccountIndex | Address | string | null | Uint8Array;
withAddress?: boolean;
@ -37,16 +38,13 @@ interface Props extends BareProps {
withShrink?: boolean;
}
function AddressMini ({ balance, bonded, children, className, iconInfo, isPadded = true, label, labelBalance, noName, style, value, withAddress = true, withBalance = false, withBonded = false, withLockedVote = false, withName = true, withShrink = false }: Props): React.ReactElement<Props> | null {
function AddressMini ({ balance, bonded, children, className, iconInfo, isPadded = true, label, labelBalance, noName, summary, value, withAddress = true, withBalance = false, withBonded = false, withLockedVote = false, withName = true, withShrink = false }: Props): React.ReactElement<Props> | null {
if (!value) {
return null;
}
return (
<div
className={classes('ui--AddressMini', isPadded ? 'padded' : '', withShrink ? 'withShrink' : '', className)}
style={style}
>
<div className={classes('ui--AddressMini', isPadded ? 'padded' : '', withShrink ? 'withShrink' : '', className)}>
{label && (
<label className='ui--AddressMini-label'>{label}</label>
)}
@ -95,6 +93,9 @@ function AddressMini ({ balance, bonded, children, className, iconInfo, isPadded
{withLockedVote && (
<LockedVote params={value} />
)}
{summary && (
<div className='ui--AddressMini-summary'>{summary}</div>
)}
</div>
</div>
);
@ -174,4 +175,11 @@ export default React.memo(styled(AddressMini)`
position: relative;
vertical-align: middle;
}
.ui--AddressMini-summary {
font-size: 0.75rem;
margin-left: 2.25rem;
margin-top: -0.5rem;
text-align: left;
}
`);