Staking display query opt. (#1819)

* Cleanup staking balance rendering

* Nominator details only on onClick

* Fix V1 display

* default for withNominations
This commit is contained in:
Jaco Greeff 2019-10-31 16:16:04 +01:00 committed by GitHub
parent 4104bea1d7
commit c8c0a1d9c3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 143 additions and 92 deletions

View File

@ -53,13 +53,14 @@ interface OnlineState {
const WITH_VALIDATOR_PREFS = { validatorPayment: true };
function Address ({ address, authorsMap, className, currentElected, defaultName, filter, lastAuthors, points, recentlyOnline, stakingInfo, t, withNominations }: Props): React.ReactElement<Props> | null {
function Address ({ address, authorsMap, className, currentElected, defaultName, filter, lastAuthors, points, recentlyOnline, stakingInfo, t, withNominations = true }: Props): React.ReactElement<Props> | null {
const { isSubstrateV2 } = useContext(ApiContext);
const [extraInfo, setExtraInfo] = useState<[React.ReactNode, React.ReactNode][] | undefined>();
const [{ hasOfflineWarnings, onlineStatus }, setOnlineStatus] = useState<OnlineState>({
hasOfflineWarnings: false,
onlineStatus: {}
});
const [isNominationsOpen, setIsNominationsOpen] = useState(false);
const [{ balanceOpts, controllerId, hasNominators, isNominatorMe, isSelected, nominators, sessionId, stashId }, setStakingState] = useState<StakingState>({
balanceOpts: { bonded: true },
hasNominators: false,
@ -90,11 +91,9 @@ function Address ({ address, authorsMap, className, currentElected, defaultName,
const _stashId = stashId && stashId.toString();
setStakingState({
balanceOpts: {
bonded: stakers && !stakers.own.isEmpty
? [stakers.own.unwrap(), stakers.total.unwrap().sub(stakers.own.unwrap())]
: true
},
balanceOpts: stakers && !stakers.own.isEmpty
? { bonded: [stakers.own.unwrap(), stakers.total.unwrap().sub(stakers.own.unwrap())] }
: { bonded: true },
controllerId: controllerId && controllerId.toString(),
hasNominators: nominators.length !== 0,
isNominatorMe: nominators.some(([who]): boolean =>
@ -147,9 +146,15 @@ function Address ({ address, authorsMap, className, currentElected, defaultName,
);
}
const _toggleNominations = (event: React.SyntheticEvent): void => {
event.preventDefault();
event.stopPropagation();
setIsNominationsOpen(!isNominationsOpen);
};
const lastBlockNumber = authorsMap[stashId];
const isAuthor = lastAuthors && lastAuthors.includes(stashId);
// isDisabled={!!points && points.isEmpty}
return (
<AddressCard
@ -193,20 +198,21 @@ function Address ({ address, authorsMap, className, currentElected, defaultName,
)}
</>
}
stakingInfo={stakingInfo}
value={stashId}
withBalance={balanceOpts}
withValidatorPrefs={WITH_VALIDATOR_PREFS}
>
{withNominations && hasNominators && (
<details>
<summary>
<details open={isNominationsOpen}>
<summary onClick={_toggleNominations}>
{t('Nominators ({{count}})', {
replace: {
count: nominators.length
}
})}
</summary>
{nominators.map(([who, bonded]): React.ReactNode =>
{isNominationsOpen && nominators.map(([who, bonded]): React.ReactNode =>
<AddressMini
bonded={bonded}
key={who.toString()}

View File

@ -7,7 +7,8 @@ import { I18nProps } from '@polkadot/react-components/types';
import { EraPoints } from '@polkadot/types/interfaces';
import { ValidatorFilter } from '../types';
import React, { useEffect, useState } from 'react';
import React, { useContext, useEffect, useState } from 'react';
import { ApiContext } from '@polkadot/react-api';
import { Columar, Column, Dropdown, FilterOverlay } from '@polkadot/react-components';
import translate from '../translate';
@ -23,7 +24,7 @@ interface Props extends I18nProps {
recentlyOnline?: DerivedHeartbeats;
}
function renderColumn (addresses: string[], defaultName: string, withNominations: boolean, withPoints: boolean, filter: string, { authorsMap, currentElected, eraPoints, lastAuthors, recentlyOnline }: Props): React.ReactNode {
function renderColumn (addresses: string[], defaultName: string, withPoints: boolean, filter: string, { authorsMap, currentElected, eraPoints, lastAuthors, recentlyOnline }: Props): React.ReactNode {
return addresses.map((address, index): React.ReactNode => (
<Address
address={address}
@ -39,7 +40,6 @@ function renderColumn (addresses: string[], defaultName: string, withNominations
: undefined
}
recentlyOnline={recentlyOnline}
withNominations={withNominations}
/>
));
}
@ -49,6 +49,7 @@ function filterAccounts (list: string[] = [], without: string[]): string[] {
}
function CurrentList (props: Props): React.ReactElement<Props> {
const { isSubstrateV2 } = useContext(ApiContext);
const [filter, setFilter] = useState<ValidatorFilter>('all');
const [{ electedFiltered, nextFiltered }, setFiltered] = useState<{ electedFiltered: string[]; nextFiltered: string[] }>({ electedFiltered: [], nextFiltered: [] });
const { currentElected, currentValidators, next, t } = props;
@ -56,7 +57,7 @@ function CurrentList (props: Props): React.ReactElement<Props> {
useEffect((): void => {
if (currentElected && currentValidators) {
setFiltered({
electedFiltered: filterAccounts(currentElected, currentValidators),
electedFiltered: isSubstrateV2 ? filterAccounts(currentElected, currentValidators) : [],
nextFiltered: filterAccounts(next, currentElected)
});
}
@ -85,7 +86,7 @@ function CurrentList (props: Props): React.ReactElement<Props> {
emptyText={t('No addresses found')}
headerText={t('validators')}
>
{renderColumn(currentValidators, t('validator'), true, true, filter, props)}
{renderColumn(currentValidators, t('validator'), true, filter, props)}
</Column>
<Column
emptyText={t('No addresses found')}
@ -93,8 +94,8 @@ function CurrentList (props: Props): React.ReactElement<Props> {
>
{(electedFiltered.length !== 0 || nextFiltered.length !== 0) && (
<>
{renderColumn(electedFiltered, t('intention'), true, false, filter, props)}
{renderColumn(nextFiltered, t('intention'), false, false, filter, props)}
{renderColumn(electedFiltered, t('intention'), false, filter, props)}
{renderColumn(nextFiltered, t('intention'), false, filter, props)}
</>
)}
</Column>

View File

@ -26,24 +26,25 @@ const NOOP = (): void => {
// ignore
};
const NO_SKIP = (): boolean => false;
// a mapping of actual error messages that has already been shown
const errorred: Record<string, boolean> = {};
export default function withCall<P extends ApiProps> (
endpoint: string,
{
at,
atProp,
callOnResult,
fallbacks,
isMulti = false,
params = [],
paramName,
paramPick,
paramValid = false,
propName,
transform = echoTransform
}: Options = {}): (Inner: React.ComponentType<ApiProps>) => React.ComponentType<any> {
export default function withCall<P extends ApiProps> (endpoint: string, {
at,
atProp,
callOnResult,
fallbacks,
isMulti = false,
params = [],
paramName,
paramPick,
paramValid = false,
propName,
skipIf = NO_SKIP,
transform = echoTransform
}: Options = {}): (Inner: React.ComponentType<ApiProps>) => React.ComponentType<any> {
return (Inner: React.ComponentType<ApiProps>): React.ComponentType<SubtractProps<P, ApiProps>> => {
class WithPromise extends React.Component<P, State> {
public state: State = {
@ -199,7 +200,7 @@ export default function withCall<P extends ApiProps> (
}
private async subscribe ([isValid, newParams]: [boolean, any[]]): Promise<void> {
if (!isValid) {
if (!isValid || skipIf(this.props)) {
return;
}
@ -284,10 +285,13 @@ export default function withCall<P extends ApiProps> (
const _props = {
...this.props,
callUpdated,
callUpdatedAt,
[propName || this.propName]: callResult
callUpdatedAt
};
if (!isUndefined(callResult)) {
(_props as any)[propName || this.propName] = callResult;
}
return (
<Inner {..._props} />
);

View File

@ -24,6 +24,7 @@ export interface Options {
paramPick?: (props: any) => any;
paramValid?: boolean;
propName?: string;
skipIf?: (props: any) => boolean;
transform?: Transform;
}

View File

@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/camelcase */
// Copyright 2017-2019 @polkadot/react-components authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@ -10,7 +9,7 @@ import { BareProps, I18nProps } from './types';
import BN from 'bn.js';
import React from 'react';
import styled from 'styled-components';
import { formatBalance, formatNumber } from '@polkadot/util';
import { formatBalance, formatNumber, isObject } from '@polkadot/util';
import { Icon, Tooltip, TxButton } from '@polkadot/react-components';
import { withCalls, withMulti } from '@polkadot/react-api';
@ -42,10 +41,10 @@ export interface ValidatorPrefsType {
interface Props extends BareProps, I18nProps {
address: string;
balances_all?: DerivedBalances;
balancesAll?: DerivedBalances;
children?: React.ReactNode;
extraInfo?: [string, string][];
staking_info?: DerivedStaking;
stakingInfo?: DerivedStaking;
withBalance?: boolean | BalanceActiveType;
withExtended?: boolean | CryptoActiveType;
withHexSessionId: string | null;
@ -71,8 +70,42 @@ const DEFAULT_PREFS = {
validatorPayment: true
};
// skip balances retrieval of none of this matches
function skipBalancesIf ({ withBalance = true, withExtended = false }: Props): boolean {
if (withBalance === true || withExtended === true) {
return false;
} else if (isObject(withBalance)) {
// these all pull from the all balances
if (withBalance.available || withBalance.locked || withBalance.reserved || withBalance.total) {
return false;
}
} else if (isObject(withExtended)) {
if (withExtended.nonce) {
return false;
}
}
return true;
}
function skipStakingIf ({ stakingInfo, withBalance = true, withRewardDestination = false, withValidatorPrefs = false }: Props): boolean {
if (stakingInfo) {
return true;
} else if (withBalance === true || withValidatorPrefs || withRewardDestination) {
return false;
} else if (isObject(withBalance)) {
if (withBalance.unlocking || withBalance.redeemable) {
return false;
} else if (withBalance.bonded) {
return Array.isArray(withBalance.bonded);
}
}
return true;
}
// calculates the bonded, first being the own, the second being nominated
function calcBonded (staking_info?: DerivedStaking, bonded?: boolean | BN[]): [BN, BN[]] {
function calcBonded (stakingInfo?: DerivedStaking, bonded?: boolean | BN[]): [BN, BN[]] {
let other: BN[] = [];
let own = new BN(0);
@ -82,28 +115,28 @@ function calcBonded (staking_info?: DerivedStaking, bonded?: boolean | BN[]): [B
.filter((value): boolean => value.gtn(0));
own = bonded[0];
} else if (staking_info && staking_info.stakingLedger && staking_info.accountId.eq(staking_info.stashId)) {
own = staking_info.stakingLedger.active.unwrap();
} else if (stakingInfo && stakingInfo.stakingLedger && stakingInfo.accountId.eq(stakingInfo.stashId)) {
own = stakingInfo.stakingLedger.active.unwrap();
}
return [own, other];
}
function renderExtended ({ balances_all, t, address, withExtended }: Props): React.ReactNode {
function renderExtended ({ balancesAll, t, address, withExtended }: Props): React.ReactNode {
const extendedDisplay = withExtended === true
? DEFAULT_EXTENDED
: withExtended || undefined;
if (!extendedDisplay || !balances_all) {
if (!extendedDisplay) {
return null;
}
return (
<div className='column'>
{extendedDisplay.nonce && (
{balancesAll && extendedDisplay.nonce && (
<>
<Label label={t('transactions')} />
<div className='result'>{formatNumber(balances_all.accountNonce)}</div>
<div className='result'>{formatNumber(balancesAll.accountNonce)}</div>
</>
)}
{extendedDisplay.crypto && (
@ -119,12 +152,12 @@ function renderExtended ({ balances_all, t, address, withExtended }: Props): Rea
);
}
function renderUnlocking ({ staking_info, t }: Props): React.ReactNode {
if (!staking_info || !staking_info.unlocking || !staking_info.unlocking.length) {
function renderUnlocking ({ stakingInfo, t }: Props): React.ReactNode {
if (!stakingInfo || !stakingInfo.unlocking || !stakingInfo.unlocking.length) {
return null;
}
const total = staking_info.unlocking.reduce((total, { value }): BN => total.add(value), new BN(0));
const total = stakingInfo.unlocking.reduce((total, { value }): BN => total.add(value), new BN(0));
if (total.eqn(0)) {
return null;
@ -139,7 +172,7 @@ function renderUnlocking ({ staking_info, t }: Props): React.ReactNode {
data-for='unlocking-trigger'
/>
<Tooltip
text={staking_info.unlocking.map(({ remainingBlocks, value }, index): React.ReactNode => (
text={stakingInfo.unlocking.map(({ remainingBlocks, value }, index): React.ReactNode => (
<div key={index}>
{t('{{value}}, {{remaining}} blocks left', {
replace: {
@ -155,31 +188,31 @@ function renderUnlocking ({ staking_info, t }: Props): React.ReactNode {
);
}
function renderValidatorPrefs ({ staking_info, t, withValidatorPrefs = false }: Props): React.ReactNode {
function renderValidatorPrefs ({ stakingInfo, t, withValidatorPrefs = false }: Props): React.ReactNode {
const validatorPrefsDisplay = withValidatorPrefs === true
? DEFAULT_PREFS
: withValidatorPrefs;
if (!validatorPrefsDisplay || !staking_info || !staking_info.validatorPrefs) {
if (!validatorPrefsDisplay || !stakingInfo || !stakingInfo.validatorPrefs) {
return null;
}
return (
<>
<div />
{validatorPrefsDisplay.unstakeThreshold && (staking_info.validatorPrefs as ValidatorPrefs0to145).unstakeThreshold && (
{validatorPrefsDisplay.unstakeThreshold && (stakingInfo.validatorPrefs as ValidatorPrefs0to145).unstakeThreshold && (
<>
<Label label={t('unstake threshold')} />
<div className='result'>
{(staking_info.validatorPrefs as ValidatorPrefs0to145).unstakeThreshold.toString()}
{(stakingInfo.validatorPrefs as ValidatorPrefs0to145).unstakeThreshold.toString()}
</div>
</>
)}
{validatorPrefsDisplay.validatorPayment && staking_info.validatorPrefs.validatorPayment && (
{validatorPrefsDisplay.validatorPayment && stakingInfo.validatorPrefs.validatorPayment && (
<>
<Label label={t('commission')} />
<div className='result'>{
formatBalance(staking_info.validatorPrefs.validatorPayment)
formatBalance(stakingInfo.validatorPrefs.validatorPayment)
}</div>
</>
)}
@ -188,41 +221,41 @@ function renderValidatorPrefs ({ staking_info, t, withValidatorPrefs = false }:
}
function renderBalances (props: Props): React.ReactNode {
const { balances_all, staking_info, t, withBalance = true } = props;
const { balancesAll, stakingInfo, t, withBalance = true } = props;
const balanceDisplay = withBalance === true
? DEFAULT_BALANCES
: withBalance || undefined;
: withBalance || false;
if (!balanceDisplay || !balances_all) {
if (!balanceDisplay) {
return null;
}
const [ownBonded, otherBonded] = calcBonded(staking_info, balanceDisplay.bonded);
const [ownBonded, otherBonded] = calcBonded(stakingInfo, balanceDisplay.bonded);
return (
<>
{balanceDisplay.total && (
{balancesAll && balanceDisplay.total && (
<>
<Label label={t('total')} />
<div className='result'>{formatBalance(balances_all.votingBalance)}</div>
<div className='result'>{formatBalance(balancesAll.votingBalance)}</div>
</>
)}
{balanceDisplay.available && (
{balancesAll && balanceDisplay.available && (
<>
<Label label={t('available')} />
<div className='result'>{formatBalance(balances_all.availableBalance)}</div>
<div className='result'>{formatBalance(balancesAll.availableBalance)}</div>
</>
)}
{balanceDisplay.locked && balances_all.lockedBalance && balances_all.lockedBalance.gtn(0) && (
{balancesAll && balanceDisplay.locked && balancesAll.lockedBalance && balancesAll.lockedBalance.gtn(0) && (
<>
<Label label={t('locked')} />
<div className='result'>{formatBalance(balances_all.lockedBalance)}</div>
<div className='result'>{formatBalance(balancesAll.lockedBalance)}</div>
</>
)}
{balanceDisplay.reserved && balances_all.reservedBalance && balances_all.reservedBalance.gtn(0) && (
{balancesAll && balanceDisplay.reserved && balancesAll.reservedBalance && balancesAll.reservedBalance.gtn(0) && (
<>
<Label label={t('reserved')} />
<div className='result'>{formatBalance(balances_all.reservedBalance)}</div>
<div className='result'>{formatBalance(balancesAll.reservedBalance)}</div>
</>
)}
{balanceDisplay.bonded && (ownBonded.gtn(0) || otherBonded.length !== 0) && (
@ -233,14 +266,14 @@ function renderBalances (props: Props): React.ReactNode {
)}</div>
</>
)}
{balanceDisplay.redeemable && staking_info && staking_info.redeemable && staking_info.redeemable.gtn(0) && (
{balanceDisplay.redeemable && stakingInfo && stakingInfo.redeemable && stakingInfo.redeemable.gtn(0) && (
<>
<Label label={t('redeemable')} />
<div className='result'>
{formatBalance(staking_info.redeemable)}
{staking_info.controllerId && (
{formatBalance(stakingInfo.redeemable)}
{stakingInfo.controllerId && (
<TxButton
accountId={staking_info.controllerId.toString()}
accountId={stakingInfo.controllerId.toString()}
className='iconButton'
icon='lock'
size='small'
@ -254,7 +287,7 @@ function renderBalances (props: Props): React.ReactNode {
</div>
</>
)}
{balanceDisplay.unlocking && staking_info && staking_info.unlocking && (
{balanceDisplay.unlocking && stakingInfo && stakingInfo.unlocking && (
<>
<Label label={t('unbonding')} />
<div className='result'>
@ -267,7 +300,7 @@ function renderBalances (props: Props): React.ReactNode {
}
function AddressInfo (props: Props): React.ReactElement<Props> {
const { className, children, extraInfo, staking_info, t, withHexSessionId, withRewardDestination } = props;
const { className, children, extraInfo, stakingInfo, t, withHexSessionId, withRewardDestination } = props;
return (
<div className={className}>
@ -293,10 +326,10 @@ function AddressInfo (props: Props): React.ReactElement<Props> {
))}
</>
)}
{withRewardDestination && staking_info && staking_info.rewardDestination && (
{withRewardDestination && stakingInfo && stakingInfo.rewardDestination && (
<>
<Label label={t('reward destination')} />
<div className='result'>{staking_info.rewardDestination.toString().toLowerCase()}</div>
<div className='result'>{stakingInfo.rewardDestination.toString().toLowerCase()}</div>
</>
)}
</div>
@ -350,7 +383,15 @@ export default withMulti(
`,
translate,
withCalls<Props>(
['derive.balances.all', { paramName: 'address' }],
['derive.staking.info', { paramName: 'address' }]
['derive.balances.all', {
paramName: 'address',
propName: 'balancesAll',
skipIf: skipBalancesIf
}],
['derive.staking.info', {
paramName: 'address',
propName: 'stakingInfo',
skipIf: skipStakingIf
}]
)
);

View File

@ -33,15 +33,11 @@ interface Props extends BareProps {
withName?: boolean;
}
function AddressMini (props: Props): React.ReactElement<Props> | null {
const { balance, bonded, children, className, iconInfo, isPadded = true, style, value, withAddress = true, withBalance = false, withBonded = false, withLockedVote = false, withName = true } = props;
function AddressMini ({ balance, bonded, children, className, iconInfo, isPadded = true, style, value, withAddress = true, withBalance = false, withBonded = false, withLockedVote = false, withName = true }: Props): React.ReactElement<Props> | null {
if (!value) {
return null;
}
const address = value.toString();
return (
<div
className={classes('ui--AddressMini', isPadded ? 'padded' : '', className)}
@ -51,8 +47,8 @@ function AddressMini (props: Props): React.ReactElement<Props> | null {
{withAddress && (
<div className='ui--AddressMini-address'>
{withName
? <AccountName params={address} />
: toShortAddress(address)
? <AccountName params={value} />
: toShortAddress(value)
}
</div>
)}
@ -61,7 +57,7 @@ function AddressMini (props: Props): React.ReactElement<Props> | null {
<div className='ui--AddressMini-icon'>
<IdentityIcon
size={24}
value={address}
value={value}
/>
{iconInfo && (
<div className='ui--AddressMini-icon-info'>

View File

@ -3,7 +3,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { DeriveAccountInfo } from '@polkadot/api-derive/types';
import { DeriveAccountInfo, DerivedStaking } from '@polkadot/api-derive/types';
import { ApiProps } from '@polkadot/react-api/types';
import { I18nProps } from '@polkadot/react-components/types';
import { AccountId, AccountIndex, Address } from '@polkadot/types/interfaces';
@ -31,6 +31,7 @@ export interface Props extends I18nProps, RowProps {
label?: string;
accounts_info?: DeriveAccountInfo;
noDefaultNameOpacity?: boolean;
stakingInfo?: DerivedStaking;
value: AccountId | AccountIndex | Address | string | null;
withAddressOrName?: boolean;
withBalance?: boolean | BalanceActiveType;
@ -176,7 +177,7 @@ class AddressRow extends Row<ApiProps & Props, State> {
}
private renderBalances (): React.ReactNode {
const { accounts_info = {}, extraInfo, withBalance, withValidatorPrefs } = this.props;
const { accounts_info = {}, extraInfo, stakingInfo, withBalance, withValidatorPrefs } = this.props;
const { accountId } = accounts_info;
if (!(withBalance || withValidatorPrefs) || !accountId) {
@ -188,6 +189,7 @@ class AddressRow extends Row<ApiProps & Props, State> {
<AddressInfo
address={accountId}
extraInfo={extraInfo}
stakingInfo={stakingInfo}
withBalance={withBalance}
withValidatorPrefs={withValidatorPrefs}
/>

View File

@ -4,7 +4,7 @@
import { DeriveAccountInfo } from '@polkadot/api-derive/types';
import { BareProps, CallProps } from '@polkadot/react-api/types';
import { AccountId, AccountIndex } from '@polkadot/types/interfaces';
import { AccountId, AccountIndex, Address } from '@polkadot/types/interfaces';
import React, { useState, useEffect } from 'react';
import { withCalls } from '@polkadot/react-api';
@ -15,13 +15,13 @@ interface Props extends BareProps, CallProps {
defaultName?: string;
info?: DeriveAccountInfo;
label?: React.ReactNode;
params?: string | null;
params?: AccountId | AccountIndex | Address | string | null;
withShort?: boolean;
}
const nameCache: Map<string, string> = new Map();
function defaultOrAddr (defaultName = '', _address?: AccountId | string | null, _accountIndex?: AccountIndex): string {
function defaultOrAddr (defaultName = '', _address?: AccountId | AccountIndex | Address | string | null, _accountIndex?: AccountIndex): string {
const accountId = (_address || '').toString();
const cached = nameCache.get(accountId);
@ -50,7 +50,7 @@ export function AccountName ({ children, className, defaultName, info, label = '
if (nickname) {
const name = nickname.toUpperCase();
nameCache.set(params || '', name);
nameCache.set((params || '').toString(), name);
setName(name);
} else {
setName(defaultOrAddr(defaultName, accountId || params, accountIndex));