Add slashing indicator (#3302)

* Add slashing indicator

* Display slashing on targets page

* Show chilled from before slash

* Sizing
This commit is contained in:
Jaco Greeff 2020-07-31 14:09:28 +02:00 committed by GitHub
parent 34ae69a4e0
commit 43470277e7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 164 additions and 29 deletions

View File

@ -6,11 +6,10 @@ import { SubmittableExtrinsic } from '@polkadot/api/types';
import React, { useEffect, useState } from 'react';
import { Button, Dropdown, Input, InputAddress, Modal, TxButton } from '@polkadot/react-components';
import { useApi, useToggle } from '@polkadot/react-hooks';
import { useApi, useAvailableSlashes, useToggle } from '@polkadot/react-hooks';
import { useTranslation } from '../translate';
import { getSlashThreshold } from './thresholds';
import useAvailableSlashes from './useAvailableSlashes';
interface Props {
className?: string;

View File

@ -2,6 +2,8 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Slash } from '../types';
import React from 'react';
import { AddressMini, Expander } from '@polkadot/react-components';
@ -11,11 +13,12 @@ import useInactives from '../useInactives';
interface Props {
nominating?: string[];
stashId: string;
slashes: Slash[];
}
function ListNominees ({ nominating, stashId }: Props): React.ReactElement<Props> {
function ListNominees ({ nominating, slashes, stashId }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { nomsActive, nomsInactive, nomsWaiting } = useInactives(stashId, nominating);
const { nomsActive, nomsChilled, nomsInactive, nomsWaiting } = useInactives(stashId, slashes, nominating);
return (
<>
@ -30,6 +33,17 @@ function ListNominees ({ nominating, stashId }: Props): React.ReactElement<Props
))}
</Expander>
)}
{nomsChilled && nomsChilled.length !== 0 && (
<Expander summary={t<string>('Chilled nominations ({{count}})', { replace: { count: nomsChilled.length } })}>
{nomsChilled.map((nomineeId, index): React.ReactNode => (
<AddressMini
key={index}
value={nomineeId}
withBalance={false}
/>
))}
</Expander>
)}
{nomsInactive && nomsInactive.length !== 0 && (
<Expander summary={t<string>('Inactive nominations ({{count}})', { replace: { count: nomsInactive.length } })}>
{nomsInactive.map((nomineeId, index): React.ReactNode => (

View File

@ -6,12 +6,14 @@ import { NominateInfo } from '../partials/types';
import { SortedTargets } from '../../types';
import React, { useState } from 'react';
import styled from 'styled-components';
import { Modal, TxButton } from '@polkadot/react-components';
import { useTranslation } from '../../translate';
import NominatePartial from '../partials/Nominate';
interface Props {
className?: string;
controllerId: string;
next?: string[];
nominating?: string[];
@ -21,17 +23,19 @@ interface Props {
validators?: string[];
}
function Nominate ({ controllerId, next, nominating, onClose, stashId, targets, validators }: Props): React.ReactElement<Props> | null {
function Nominate ({ className = '', controllerId, next, nominating, onClose, stashId, targets, validators }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const [{ nominateTx }, setTx] = useState<NominateInfo>({});
return (
<Modal
className={className}
header={t<string>('Nominate Validators')}
size='large'
>
<Modal.Content>
<NominatePartial
className='nominatePartial'
controllerId={controllerId}
next={next}
nominating={nominating}
@ -56,4 +60,11 @@ function Nominate ({ controllerId, next, nominating, onClose, stashId, targets,
);
}
export default React.memo(Nominate);
export default React.memo(styled(Nominate)`
.nominatePartial {
.ui--Static .ui--AddressMini .ui--AddressMini-info {
max-width: 10.5rem;
min-width: 10.5rem;
}
}
`);

View File

@ -3,15 +3,18 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { DeriveBalancesAll, DeriveStakingAccount } from '@polkadot/api-derive/types';
import { EraIndex, SlashingSpans } from '@polkadot/types/interfaces';
import { SlashingSpans, UnappliedSlash } from '@polkadot/types/interfaces';
import { StakerState } from '@polkadot/react-hooks/types';
import { SortedTargets } from '../../types';
import { Slash } from '../types';
import BN from 'bn.js';
import React, { useCallback, useContext, useEffect, useState } from 'react';
import styled from 'styled-components';
import { AddressInfo, AddressMini, AddressSmall, Button, Menu, Popup, StakingBonded, StakingRedeemable, StakingUnbonding, StatusContext, TxButton } from '@polkadot/react-components';
import { AddressInfo, AddressMini, AddressSmall, Badge, Button, Menu, Popup, StakingBonded, StakingRedeemable, StakingUnbonding, StatusContext, TxButton } from '@polkadot/react-components';
import { useApi, useCall, useToggle } from '@polkadot/react-hooks';
import { Option } from '@polkadot/types';
import { formatNumber } from '@polkadot/util';
import { useTranslation } from '../../translate';
import BondExtra from './BondExtra';
@ -25,7 +28,7 @@ import Unbond from './Unbond';
import Validate from './Validate';
interface Props {
activeEra?: EraIndex;
allSlashes?: [BN, UnappliedSlash[]][];
className?: string;
isDisabled?: boolean;
info: StakerState;
@ -35,7 +38,7 @@ interface Props {
validators?: string[];
}
function Account ({ className = '', info: { controllerId, destination, destinationId, hexSessionIdNext, hexSessionIdQueue, isLoading, isOwnController, isOwnStash, isStashNominating, isStashValidating, nominating, sessionIds, stakingLedger, stashId }, isDisabled, next, targets, validators }: Props): React.ReactElement<Props> {
function Account ({ allSlashes, className = '', info: { controllerId, destination, destinationId, hexSessionIdNext, hexSessionIdQueue, isLoading, isOwnController, isOwnStash, isStashNominating, isStashValidating, nominating, sessionIds, stakingLedger, stashId }, isDisabled, next, targets, validators }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const { queueExtrinsic } = useContext(StatusContext);
@ -57,6 +60,7 @@ function Account ({ className = '', info: { controllerId, destination, destinati
const [isUnbondOpen, toggleUnbond] = useToggle();
const [isValidateOpen, toggleValidate] = useToggle();
const [hasBonded, setHasBonded] = useState(false);
const [slashes, setSlashes] = useState<Slash[]>([]);
useEffect((): void => {
stakingAccount?.stakingLedger && setHasBonded(
@ -64,6 +68,26 @@ function Account ({ className = '', info: { controllerId, destination, destinati
);
}, [stakingAccount]);
useEffect((): void => {
allSlashes && setSlashes(
allSlashes
.map(([era, all]) => {
const slashes = all
.filter(({ others, validator }) => validator.eq(stashId) || others.some(([nominatorId]) => nominatorId.eq(stashId)))
.map(({ others, own, payout, reporters, validator }) => ({
isValidator: validator.eq(stashId), others, own, payout, reporters, validator
}));
return {
era,
isValidator: slashes.some(({ isValidator }) => isValidator),
slashes
};
})
.filter(({ slashes }) => slashes.length)
);
}, [allSlashes, stashId]);
const withdrawFunds = useCallback(
() => {
queueExtrinsic({
@ -80,6 +104,19 @@ function Account ({ className = '', info: { controllerId, destination, destinati
return (
<tr className={className}>
<td className='badge together'>
{!isStashNominating && slashes.length !== 0 && (
<Badge
color='red'
hover={t<string>('Slashed in era {{eras}}', {
replace: {
eras: slashes.map(({ era }) => formatNumber(era)).join(', ')
}
})}
icon='skull-crossbones'
/>
)}
</td>
<td className='address'>
<AddressSmall value={stashId} />
{isBondExtraOpen && (
@ -167,6 +204,7 @@ function Account ({ className = '', info: { controllerId, destination, destinati
{isStashNominating && (
<ListNominees
nominating={nominating}
slashes={slashes}
stashId={stashId}
/>
)}

View File

@ -2,16 +2,14 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ActiveEraInfo, EraIndex } from '@polkadot/types/interfaces';
import { StakerState } from '@polkadot/react-hooks/types';
import { SortedTargets } from '../types';
import BN from 'bn.js';
import React, { useEffect, useMemo, useState } from 'react';
import { Button, Table } from '@polkadot/react-components';
import { useCall, useApi } from '@polkadot/react-hooks';
import { useAvailableSlashes } from '@polkadot/react-hooks';
import { FormatBalance } from '@polkadot/react-query';
import { Option } from '@polkadot/types';
import { BN_ZERO } from '@polkadot/util';
import ElectionBanner from '../ElectionBanner';
@ -52,10 +50,7 @@ function extractState (ownStashes: StakerState[]): State {
function Actions ({ className = '', isInElection, next, ownStashes, targets, validators }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const activeEra = useCall<EraIndex | undefined>(api.query.staking?.activeEra, [], {
transform: (activeEra: Option<ActiveEraInfo>) => activeEra.unwrapOr({ index: undefined }).index
});
const allSlashes = useAvailableSlashes();
const [{ bondedTotal, foundStashes }, setState] = useState<State>({});
useEffect((): void => {
@ -63,7 +58,7 @@ function Actions ({ className = '', isInElection, next, ownStashes, targets, val
}, [ownStashes]);
const header = useMemo(() => [
[t('stashes'), 'start'],
[t('stashes'), 'start', 2],
[t('controller'), 'address'],
[t('rewards'), 'number ui--media-1200'],
[t('bonded'), 'number'],
@ -72,7 +67,7 @@ function Actions ({ className = '', isInElection, next, ownStashes, targets, val
const footer = useMemo(() => (
<tr>
<td colSpan={3} />
<td colSpan={4} />
<td className='number'>
{bondedTotal && <FormatBalance value={bondedTotal} />}
</td>
@ -100,7 +95,7 @@ function Actions ({ className = '', isInElection, next, ownStashes, targets, val
>
{foundStashes?.map((info): React.ReactNode => (
<Account
activeEra={activeEra}
allSlashes={allSlashes}
info={info}
isDisabled={isInElection}
key={info.stashId}

View File

@ -96,7 +96,12 @@ function Nominate ({ className = '', controllerId, next, nominating, onChange, s
const { t } = useTranslation();
const { api } = useApi();
const [favorites] = useFavorites(STORE_FAVS_BASE);
const [{ isAutoSelect, selected }, setSelected] = useState<Selected>(initialPick(targets));
const [{ isAutoSelect, selected }, setSelected] = useState<Selected>(
// nominating?.length
// ? { isAutoSelect: false, selected: nominating }
// : initialPick(targets)
initialPick(targets)
);
const [available] = useState<string[]>((): string[] => {
const shortlist = [
// ensure that the favorite is included in the list of stashes

View File

@ -2,7 +2,26 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { AccountId, Balance, UnappliedSlashOther } from '@polkadot/types/interfaces';
import BN from 'bn.js';
export interface AmountValidateState {
error: string | null;
warning: string | null;
}
interface Unapplied {
isValidator: boolean;
others: UnappliedSlashOther[];
own: Balance;
payout: Balance;
reporters: AccountId[];
validator: AccountId;
}
export interface Slash {
era: BN;
isValidator: boolean;
slashes: Unapplied[];
}

View File

@ -4,6 +4,7 @@
import { DeriveSessionIndexes } from '@polkadot/api-derive/types';
import { EraIndex, Exposure, Nominations } from '@polkadot/types/interfaces';
import { Slash } from './types';
import { useEffect, useState } from 'react';
import { useApi, useCall, useIsMountedRef } from '@polkadot/react-hooks';
@ -11,11 +12,25 @@ import { Option } from '@polkadot/types';
interface Inactives {
nomsActive?: string[];
nomsChilled?: string[];
nomsInactive?: string[];
nomsWaiting?: string[];
}
function extractState (stashId: string, nominees: string[], activeEra: EraIndex, submittedIn: EraIndex, exposures: Exposure[]): Inactives {
function extractState (stashId: string, slashes: Slash[], nominees: string[], activeEra: EraIndex, submittedIn: EraIndex, exposures: Exposure[]): Inactives {
// chilled
const nomsChilled = nominees.filter((nominee) =>
slashes.some(({ era, slashes }) =>
submittedIn.lt(era) && (
slashes
.filter(({ validator }) => validator.eq(nominee))
.some(({ others }) =>
others.some(([accountId]) => accountId.eq(stashId))
)
)
)
);
// first a blanket find of nominations not in the active set
let nomsInactive = exposures
.map((exposure, index) =>
@ -32,22 +47,24 @@ function extractState (stashId: string, nominees: string[], activeEra: EraIndex,
? nominees[index]
: null
)
.filter((waitingId): waitingId is string => !!waitingId);
.filter((waitingId): waitingId is string => !!waitingId)
.filter((nominee) => !nomsChilled.includes(nominee));
// filter based on all inactives
const nomsActive = nominees.filter((nominee) => !nomsInactive.includes(nominee));
const nomsActive = nominees.filter((nominee) => !nomsInactive.includes(nominee) && !nomsChilled.includes(nominee));
// inactive also contains waiting, remove those
nomsInactive = nomsInactive.filter((inactiveId) => !nomsWaiting.includes(inactiveId));
nomsInactive = nomsInactive.filter((nominee) => !nomsWaiting.includes(nominee) && !nomsChilled.includes(nominee));
return {
nomsActive,
nomsChilled,
nomsInactive,
nomsWaiting
};
}
export default function useInactives (stashId: string, nominees?: string[]): Inactives {
export default function useInactives (stashId: string, slashes: Slash[], nominees?: string[]): Inactives {
const { api } = useApi();
const mountedRef = useIsMountedRef();
const [state, setState] = useState<Inactives>({});
@ -66,7 +83,7 @@ export default function useInactives (stashId: string, nominees?: string[]): Ina
),
([optNominators, ...exposures]: [Option<Nominations>, ...Exposure[]]): void => {
mountedRef.current && setState(
extractState(stashId, nominees, indexes.activeEra, optNominators.unwrapOrDefault().submittedIn, exposures)
extractState(stashId, slashes, nominees, indexes.activeEra, optNominators.unwrapOrDefault().submittedIn, exposures)
);
}
)
@ -78,7 +95,7 @@ export default function useInactives (stashId: string, nominees?: string[]): Ina
return (): void => {
unsub && unsub();
};
}, [api, indexes, mountedRef, nominees, stashId]);
}, [api, indexes, mountedRef, nominees, slashes, stashId]);
return state;
}

View File

@ -3,8 +3,10 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { DeriveAccountInfo } from '@polkadot/api-derive/types';
import { UnappliedSlash } from '@polkadot/types/interfaces';
import { ValidatorInfo } from '../types';
import BN from 'bn.js';
import React, { useCallback, useEffect, useState } from 'react';
import { ApiPromise } from '@polkadot/api';
import { AddressSmall, Badge, Checkbox, Icon } from '@polkadot/react-components';
@ -15,9 +17,11 @@ import keyring from '@polkadot/ui-keyring';
import MaxBadge from '../MaxBadge';
import Favorite from '../Overview/Address/Favorite';
import { useTranslation } from '../translate';
import { checkVisibility } from '../util';
interface Props {
allSlashes?: [BN, UnappliedSlash[]][];
canSelect: boolean;
filterName: string;
info: ValidatorInfo;
@ -29,6 +33,11 @@ interface Props {
withIdentity: boolean;
}
interface Slash {
era: BN;
slashes: UnappliedSlash[];
}
function checkIdentity (api: ApiPromise, accountInfo: DeriveAccountInfo): boolean {
let hasIdentity = false;
@ -49,10 +58,12 @@ function checkIdentity (api: ApiPromise, accountInfo: DeriveAccountInfo): boolea
return hasIdentity;
}
function Validator ({ canSelect, filterName, info, isNominated, isSelected, toggleFavorite, toggleSelected, withElected, withIdentity }: Props): React.ReactElement<Props> | null {
function Validator ({ allSlashes, canSelect, filterName, info, isNominated, isSelected, toggleFavorite, toggleSelected, withElected, withIdentity }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const { api } = useApi();
const accountInfo = useCall<DeriveAccountInfo>(api.derive.accounts.info, [info.accountId]);
const [isVisible, setVisibility] = useState(true);
const [slashes, setSlashes] = useState<Slash[]>([]);
useEffect((): void => {
if (accountInfo) {
@ -61,6 +72,17 @@ function Validator ({ canSelect, filterName, info, isNominated, isSelected, togg
}
}, [accountInfo, api, filterName, info, withIdentity]);
useEffect((): void => {
allSlashes && setSlashes(
allSlashes
.map(([era, slashes]) => ({
era,
slashes: slashes.filter(({ validator }) => validator.eq(info.accountId))
}))
.filter(({ slashes }) => slashes.length)
);
}, [allSlashes, info]);
const _onQueryStats = useCallback(
(): void => {
window.location.hash = `/staking/query/${info.key}`;
@ -106,6 +128,17 @@ function Validator ({ canSelect, filterName, info, isNominated, isSelected, togg
: <Badge color='transparent' />
}
<MaxBadge numNominators={numNominators} />
{slashes.length !== 0 && (
<Badge
color='red'
hover={t<string>('Slashed in era {{eras}}', {
replace: {
eras: slashes.map(({ era }) => formatNumber(era)).join(', ')
}
})}
icon='skull-crossbones'
/>
)}
</td>
<td className='number'>{formatNumber(rankOverall)}</td>
<td className='address all'>

View File

@ -9,6 +9,7 @@ import { SortedTargets, TargetSortBy, ValidatorInfo } from '../types';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import styled from 'styled-components';
import { Button, Icon, InputBalance, Table, Toggle } from '@polkadot/react-components';
import { useAvailableSlashes } from '@polkadot/react-hooks';
import ElectionBanner from '../ElectionBanner';
import Filtering from '../Filtering';
@ -50,6 +51,7 @@ function sort (sortBy: TargetSortBy, sortFromMax: boolean, validators: Validator
function Targets ({ className = '', isInElection, ownStashes, targets: { calcWith, lastReward, nominators, setCalcWith, totalStaked, validators }, toggleFavorite }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const allSlashes = useAvailableSlashes();
const ownNominators = useOwnNominators(ownStashes);
const [selected, setSelected] = useState<string[]>([]);
const [sorted, setSorted] = useState<number[] | undefined>();
@ -197,6 +199,7 @@ function Targets ({ className = '', isInElection, ownStashes, targets: { calcWit
>
{validators && sorted && (validators.length === sorted.length) && sorted.map((index): React.ReactNode =>
<Validator
allSlashes={allSlashes}
canSelect={selected.length < MAX_NOMINATIONS}
filterName={nameFilter}
info={validators[index]}

View File

@ -7,6 +7,7 @@ export { default as useAccountInfo } from './useAccountInfo';
export { default as useAccounts } from './useAccounts';
export { default as useAddresses } from './useAddresses';
export { default as useApi } from './useApi';
export { default as useAvailableSlashes } from './useAvailableSlashes';
export { default as useBlockTime } from './useBlockTime';
export { default as useCacheKey } from './useCacheKey';
export { default as useCall } from './useCall';