Show nominator return % per target (#4091)

* Show nominator return % per target

* 2 decimals

* Remove commented
This commit is contained in:
Jaco Greeff 2020-11-28 16:32:53 +01:00 committed by GitHub
parent 4f5fd117fa
commit e940117fac
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 101 additions and 100 deletions

View File

@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
import type { DeriveStakingOverview } from '@polkadot/api-derive/types';
import type { Inflation } from '@polkadot/react-hooks/types';
import React, { useContext } from 'react';
import styled from 'styled-components';
@ -14,7 +13,7 @@ import { useTranslation } from '../translate';
interface Props {
className?: string;
inflation: Inflation;
inflation: number;
isVisible: boolean;
next?: string[];
nominators?: string[];
@ -49,12 +48,12 @@ function Summary ({ className = '', inflation, isVisible, next, nominators, stak
{nominators.length}
</CardSummary>
)}
{(inflation.inflation > 0) && (
{(inflation > 0) && (
<CardSummary
className='media--1200'
label={t<string>('inflation')}
>
{inflation.inflation.toFixed(1)}%
{inflation.toFixed(1)}%
</CardSummary>
)}
</section>

View File

@ -1,31 +1,26 @@
// Copyright 2017-2020 @polkadot/app-staking authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Inflation } from '@polkadot/react-hooks/types';
import type { Balance } from '@polkadot/types/interfaces';
import BN from 'bn.js';
import React, { useMemo } from 'react';
import { SummaryBox, CardSummary } from '@polkadot/react-components';
import { useApi, useCall } from '@polkadot/react-hooks';
import { FormatBalance } from '@polkadot/react-query';
import { useTranslation } from '../translate';
interface Props {
avgStaked?: BN;
inflation: Inflation;
lowStaked?: BN;
lastReward?: BN;
numNominators?: number;
numValidators?: number;
stakedReturn: number;
totalIssuance?: BN;
totalStaked?: BN;
}
function Summary ({ avgStaked, inflation, lastReward, lowStaked, numNominators, numValidators, totalStaked }: Props): React.ReactElement<Props> {
function Summary ({ avgStaked, lastReward, lowStaked, numNominators, numValidators, stakedReturn, totalIssuance, totalStaked }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const totalIssuance = useCall<Balance>(api.query.balances?.totalIssuance);
const progressStake = useMemo(
() => totalIssuance && totalStaked && totalStaked.gtn(0)
@ -53,35 +48,37 @@ function Summary ({ avgStaked, inflation, lastReward, lowStaked, numNominators,
<SummaryBox>
<section className='media--800'>
{totalIssuance && (
<CardSummary
label={`${totalStaked?.gtn(0) ? `${t<string>('total staked')} / ` : ''}${t<string>('total issuance')}`}
progress={progressStake}
>
<div>
{totalStaked?.gtn(0) && (
<>
<FormatBalance
value={totalStaked}
withCurrency={false}
withSi
/>
&nbsp;/&nbsp;
</>
)}
<FormatBalance
value={totalIssuance}
withSi
/>
</div>
</CardSummary>
)}
{(inflation.stakedReturn > 0) && (
<CardSummary
className='media--1200'
label={t<string>('returns')}
>
{inflation.stakedReturn.toFixed(1)}%
</CardSummary>
<>
<CardSummary
label={`${totalStaked?.gtn(0) ? `${t<string>('total staked')} / ` : ''}${t<string>('total issuance')}`}
progress={progressStake}
>
<div>
{totalStaked?.gtn(0) && (
<>
<FormatBalance
value={totalStaked}
withCurrency={false}
withSi
/>
&nbsp;/&nbsp;
</>
)}
<FormatBalance
value={totalIssuance}
withSi
/>
</div>
</CardSummary>
{(stakedReturn > 0) && (
<CardSummary
className='media--1200'
label={t<string>('returns')}
>
{stakedReturn.toFixed(1)}%
</CardSummary>
)}
</>
)}
</section>
{avgStaked && lowStaked && (

View File

@ -109,7 +109,7 @@ function Validator ({ allSlashes, canSelect, filterName, info, isNominated, isSe
return null;
}
const { accountId, bondOther, bondOwn, bondTotal, commissionPer, isCommission, isElected, isFavorite, key, numNominators, rankOverall, rewardPayout, validatorPayment } = info;
const { accountId, bondOther, bondOwn, bondTotal, commissionPer, isCommission, isElected, isFavorite, key, numNominators, rankOverall, stakedReturnCmp, validatorPayment } = info;
return (
<tr>
@ -165,7 +165,7 @@ function Validator ({ allSlashes, canSelect, filterName, info, isNominated, isSe
<td className='number together'>{!bondTotal.isZero() && <FormatBalance value={bondTotal} />}</td>
<td className='number together'>{!bondOwn.isZero() && <FormatBalance value={bondOwn} />}</td>
<td className='number together media--1600'>{!bondOther.isZero() && <FormatBalance value={bondOther} />}</td>
<td className='number together'>{!rewardPayout.isZero() && <FormatBalance value={rewardPayout} />}</td>
<td className='number together'>{(stakedReturnCmp > 0) && <>{stakedReturnCmp.toFixed(2)}%</>}</td>
<td>
{(canSelect || isSelected) && (
<Checkbox

View File

@ -2,13 +2,13 @@
// SPDX-License-Identifier: Apache-2.0
import type { DeriveStakingOverview } from '@polkadot/api-derive/types';
import type { Inflation, StakerState } from '@polkadot/react-hooks/types';
import type { StakerState } from '@polkadot/react-hooks/types';
import type { SortedTargets, TargetSortBy, ValidatorInfo } from '../types';
import BN from 'bn.js';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import styled from 'styled-components';
import { Button, Icon, InputBalance, Table, Toggle } from '@polkadot/react-components';
import { Button, Icon, Table, Toggle } from '@polkadot/react-components';
import { useApi, useAvailableSlashes } from '@polkadot/react-hooks';
import ElectionBanner from '../ElectionBanner';
@ -23,7 +23,6 @@ import useOwnNominators from './useOwnNominators';
interface Props {
className?: string;
inflation: Inflation;
isInElection: boolean;
ownStashes?: StakerState[];
stakingOverview?: DeriveStakingOverview;
@ -75,18 +74,18 @@ function extractNominees (ownNominators: StakerState[] = []): string[] {
}
function selectProfitable (maxPaid: BN |undefined, list: ValidatorInfo[], { withGroup, withIdentity, withoutComm, withoutOver }: Flags): string[] {
const parentIds: (string | null)[] = [];
const parentIds: string[] = [];
const result: string[] = [];
for (let i = 0; i < list.length && result.length < MAX_NOMINATIONS; i++) {
const { commissionPer, hasIdentity, isElected, isFavorite, key, numNominators, parentId, rewardPayout } = list[i];
const { commissionPer, hasIdentity, isElected, isFavorite, key, numNominators, parentId, stakedReturnCmp } = list[i];
if (
(!withIdentity || hasIdentity) &&
(isElected || isFavorite) &&
!rewardPayout.isZero() &&
stakedReturnCmp &&
(isFavorite || (
(!withGroup || !parentIds.includes(parentId)) &&
(!withGroup || !parentId || !parentIds.includes(parentId)) &&
(!withoutComm || commissionPer < 20) &&
(!withoutOver || !maxPaid || maxPaid.gtn(numNominators))
))
@ -99,7 +98,7 @@ function selectProfitable (maxPaid: BN |undefined, list: ValidatorInfo[], { with
return result;
}
function Targets ({ className = '', inflation, isInElection, ownStashes, targets: { avgStaked, calcWith, lastReward, lowStaked, nominators, setCalcWith, totalStaked, validators }, toggleFavorite }: Props): React.ReactElement<Props> {
function Targets ({ className = '', isInElection, ownStashes, targets: { avgStaked, inflation: { stakedReturn }, lastReward, lowStaked, nominators, totalIssuance, totalStaked, validators }, toggleFavorite }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const allSlashes = useAvailableSlashes();
@ -160,7 +159,7 @@ function Targets ({ className = '', inflation, isInElection, ownStashes, targets
rankBondTotal: t<string>('total stake'),
rankComm: t<string>('comm.'),
rankNumNominators: t<string>('nominators'),
rankOverall: t<string>('profit/era')
rankOverall: t<string>('return')
});
const header = useMemo(() => [
@ -179,15 +178,6 @@ function Targets ({ className = '', inflation, isInElection, ownStashes, targets
const filter = useMemo(() => (
sorted && (
<div>
<InputBalance
className='balanceInput'
help={t<string>('The amount that will be used on a per-validator basis to calculate profits for that validator.')}
isFull
isZeroable={false}
label={t<string>('amount to use for estimation')}
onChange={setCalcWith}
value={calcWith}
/>
<Filtering
nameFilter={nameFilter}
setNameFilter={setNameFilter}
@ -221,17 +211,18 @@ function Targets ({ className = '', inflation, isInElection, ownStashes, targets
</Filtering>
</div>
)
), [calcWith, setCalcWith, nameFilter, sorted, t, withElected, withGroup, withIdentity, withoutComm, withoutOver]);
), [nameFilter, sorted, t, withElected, withGroup, withIdentity, withoutComm, withoutOver]);
return (
<div className={className}>
<Summary
avgStaked={avgStaked}
inflation={inflation}
lastReward={lastReward}
lowStaked={lowStaked}
numNominators={nominators?.length}
numValidators={validators?.length}
stakedReturn={stakedReturn}
totalIssuance={totalIssuance}
totalStaked={totalStaked}
/>
<Button.Group>

View File

@ -11,7 +11,7 @@ import { useLocation } from 'react-router-dom';
import styled from 'styled-components';
import { HelpOverlay } from '@polkadot/react-components';
import Tabs from '@polkadot/react-components/Tabs';
import { useAccounts, useApi, useAvailableSlashes, useCall, useFavorites, useInflation, useOwnStashInfos, useStashIds } from '@polkadot/react-hooks';
import { useAccounts, useApi, useAvailableSlashes, useCall, useFavorites, useOwnStashInfos, useStashIds } from '@polkadot/react-hooks';
import { isFunction } from '@polkadot/util';
import basicMd from './md/basic.md';
@ -42,7 +42,6 @@ function StakingApp ({ basePath, className = '' }: Props): React.ReactElement<Pr
const ownStashes = useOwnStashInfos();
const slashes = useAvailableSlashes();
const targets = useSortedTargets(favorites);
const inflation = useInflation(targets?.totalStaked);
const stakingOverview = useCall<DeriveStakingOverview>(api.derive.staking.overview);
const isInElection = useCall<boolean>(api.query.staking?.eraElectionStatus, undefined, transformElection);
@ -115,7 +114,7 @@ function StakingApp ({ basePath, className = '' }: Props): React.ReactElement<Pr
/>
</header>
<Summary
inflation={inflation}
inflation={targets.inflation.inflation}
isVisible={pathname === basePath}
next={next}
nominators={targets.nominators}
@ -139,7 +138,6 @@ function StakingApp ({ basePath, className = '' }: Props): React.ReactElement<Pr
</Route>
<Route path={`${basePath}/targets`}>
<Targets
inflation={inflation}
isInElection={isInElection}
ownStashes={ownStashes}
stakingOverview={stakingOverview}

View File

@ -1,7 +1,8 @@
// Copyright 2017-2020 @polkadot/app-staking authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { AccountId, Balance, BlockNumber, Exposure, Hash, SessionIndex, ValidatorPrefs, ValidatorPrefsTo196 } from '@polkadot/types/interfaces';
import type { AccountId, Balance, BlockNumber, Exposure, Hash, SessionIndex, ValidatorPrefs, ValidatorPrefsTo196 } from '@polkadot/types/interfaces';
import type { Inflation } from '@polkadot/react-hooks/types';
import BN from 'bn.js';
@ -55,8 +56,10 @@ export interface ValidatorInfo extends ValidatorInfoRank {
key: string;
numNominators: number;
parentId: string | null;
rewardPayout: BN;
rewardSplit: BN;
skipRewards: boolean;
stakedReturn: number;
stakedReturnCmp: number;
validatorPayment: BN;
validatorPrefs?: ValidatorPrefs | ValidatorPrefsTo196;
}
@ -65,12 +68,12 @@ export type TargetSortBy = keyof ValidatorInfoRank;
export interface SortedTargets {
avgStaked?: BN;
calcWith?: BN;
inflation: Inflation;
lastReward?: BN;
lowStaked?: BN;
nominators?: string[];
setCalcWith: (amount?: BN) => void;
totalStaked?: BN;
totalIssuance?: BN;
validators?: ValidatorInfo[];
validatorIds?: string[];
}

View File

@ -7,18 +7,14 @@ import type { Balance, ValidatorPrefsTo196 } from '@polkadot/types/interfaces';
import type { SortedTargets, TargetSortBy, ValidatorInfo } from './types';
import BN from 'bn.js';
import { useMemo, useState } from 'react';
import { useMemo } from 'react';
import { registry } from '@polkadot/react-api';
import { useAccounts, useApi, useCall, useDebounce } from '@polkadot/react-hooks';
import { BN_ONE, BN_ZERO, formatBalance } from '@polkadot/util';
import { calcInflation, useAccounts, useApi, useCall } from '@polkadot/react-hooks';
import { BN_ONE, BN_ZERO } from '@polkadot/util';
const PERBILL = new BN(1_000_000_000);
const EMPTY_PARTIAL = {};
function baseBalance (): BN {
return new BN('1'.padEnd(formatBalance.getDefaults().decimals + 4, '0'));
}
function mapIndex (mapBy: TargetSortBy): (info: ValidatorInfo, index: number) => ValidatorInfo {
return (info, index): ValidatorInfo => {
info[mapBy] = index + 1;
@ -57,12 +53,12 @@ function sortValidators (list: ValidatorInfo[]): ValidatorInfo[] {
.map(mapIndex('rankBondTotal'))
.sort((a, b) => b.validatorPayment.cmp(a.validatorPayment))
.map(mapIndex('rankPayment'))
.sort((a, b) => a.rewardSplit.cmp(b.rewardSplit))
.sort((a, b) => a.stakedReturnCmp - b.stakedReturnCmp)
.map(mapIndex('rankReward'))
.sort((a, b) => b.numNominators - a.numNominators)
.map(mapIndex('rankNumNominators'))
.sort((a, b): number => {
const cmp = b.rewardPayout.cmp(a.rewardPayout);
const cmp = b.stakedReturnCmp - a.stakedReturnCmp;
return cmp !== 0
? cmp
@ -80,7 +76,7 @@ function sortValidators (list: ValidatorInfo[]): ValidatorInfo[] {
);
}
function extractSingle (allAccounts: string[], amount: BN = baseBalance(), derive: DeriveStakingElected | DeriveStakingWaiting, favorites: string[], perValidatorReward: BN): [ValidatorInfo[], string[]] {
function extractSingle (allAccounts: string[], derive: DeriveStakingElected | DeriveStakingWaiting, favorites: string[], perValidatorReward: BN): [ValidatorInfo[], string[]] {
const nominators: Record<string, boolean> = {};
const emptyExposure = registry.createType('Exposure');
const info = derive.info;
@ -99,9 +95,6 @@ function extractSingle (allAccounts: string[], amount: BN = baseBalance(), deriv
: validatorPrefs.commission.unwrap().mul(perValidatorReward).div(PERBILL);
const key = accountId.toString();
const rewardSplit = perValidatorReward.sub(validatorPayment);
const rewardPayout = amount.isZero() || rewardSplit.isZero()
? BN_ZERO
: amount.mul(rewardSplit).div(amount.add(bondTotal));
const isNominating = (exposure.others || []).reduce((isNominating, indv): boolean => {
const nominator = indv.who.toString();
@ -136,8 +129,10 @@ function extractSingle (allAccounts: string[], amount: BN = baseBalance(), deriv
rankOverall: 0,
rankPayment: 0,
rankReward: 0,
rewardPayout: skipRewards ? BN_ZERO : rewardPayout,
rewardSplit,
skipRewards,
stakedReturn: 0,
stakedReturnCmp: 0,
validatorPayment,
validatorPrefs
};
@ -146,20 +141,38 @@ function extractSingle (allAccounts: string[], amount: BN = baseBalance(), deriv
return [list, Object.keys(nominators)];
}
function extractInfo (allAccounts: string[], amount: BN = baseBalance(), electedDerive: DeriveStakingElected, waitingDerive: DeriveStakingWaiting, favorites: string[], lastReward = BN_ONE): Partial<SortedTargets> {
function extractInfo (genesisHash: string, allAccounts: string[], electedDerive: DeriveStakingElected, waitingDerive: DeriveStakingWaiting, favorites: string[], totalIssuance: BN, lastReward = BN_ONE): Partial<SortedTargets> {
const perValidatorReward = lastReward.divn(electedDerive.info.length);
const [elected, nominators] = extractSingle(allAccounts, amount, electedDerive, favorites, perValidatorReward);
const [waiting] = extractSingle(allAccounts, amount, waitingDerive, favorites, perValidatorReward);
const validators = sortValidators(elected.concat(waiting));
const validatorIds = validators.map(({ accountId }) => accountId.toString());
const [elected, nominators] = extractSingle(allAccounts, electedDerive, favorites, perValidatorReward);
const [waiting] = extractSingle(allAccounts, waitingDerive, favorites, perValidatorReward);
const activeTotals = elected
.filter(({ isActive }) => isActive)
.map(({ bondTotal }) => bondTotal)
.sort((a, b) => a.cmp(b));
const totalStaked = activeTotals.reduce((total: BN, value) => total.iadd(value), new BN(0));
const avgStaked = totalStaked.divn(activeTotals.length);
const inflation = calcInflation(genesisHash, totalStaked, totalIssuance);
return { avgStaked, lowStaked: activeTotals[0] || BN_ZERO, nominators, totalStaked, validatorIds, validators };
// add the explicit stakedReturn
!avgStaked.isZero() && elected.forEach((e): void => {
if (!e.skipRewards) {
e.stakedReturn = inflation.stakedReturn * avgStaked.muln(1_000_000).div(e.bondTotal).toNumber() / 1_000_000;
e.stakedReturnCmp = e.stakedReturn * (100 - e.commissionPer) / 100;
}
});
const validators = sortValidators(elected.concat(waiting));
return {
avgStaked,
inflation,
lowStaked: activeTotals[0] || BN_ZERO,
nominators,
totalIssuance,
totalStaked,
validatorIds: validators.map(({ accountId }) => accountId.toString()),
validators
};
}
const transformEra = {
@ -173,19 +186,18 @@ const transformReward = {
export default function useSortedTargets (favorites: string[]): SortedTargets {
const { api } = useApi();
const { allAccounts } = useAccounts();
const totalIssuance = useCall<BN>(api.query.balances.totalIssuance);
const electedInfo = useCall<DeriveStakingElected>(api.derive.staking.electedInfo);
const waitingInfo = useCall<DeriveStakingWaiting>(api.derive.staking.waitingInfo);
const lastEra = useCall<BN>(api.derive.session.indexes, undefined, transformEra);
const lastReward = useCall<BN>(lastEra && api.query.staking.erasValidatorReward, [lastEra], transformReward);
const [calcWith, setCalcWith] = useState<BN | undefined>(baseBalance());
const calcWithDebounce = useDebounce(calcWith);
const partial = useMemo(
() => electedInfo && waitingInfo
? extractInfo(allAccounts, calcWithDebounce, electedInfo, waitingInfo, favorites, lastReward)
() => electedInfo && totalIssuance && waitingInfo
? extractInfo(api.genesisHash.toHex(), allAccounts, electedInfo, waitingInfo, favorites, totalIssuance, lastReward)
: EMPTY_PARTIAL,
[allAccounts, calcWithDebounce, electedInfo, favorites, lastReward, waitingInfo]
[api, allAccounts, electedInfo, favorites, lastReward, totalIssuance, waitingInfo]
);
return { ...partial, calcWith, lastReward, setCalcWith };
return { inflation: { inflation: 0, stakedReturn: 0 }, ...partial, lastReward };
}

View File

@ -15,7 +15,7 @@ export { useFormField } from './useFormField';
export { useDebounce } from './useDebounce';
export { useFavorites } from './useFavorites';
export { useIncrement } from './useIncrement';
export { useInflation } from './useInflation';
export { calcInflation, useInflation } from './useInflation';
export { useIpfs } from './useIpfs';
export { useIsMountedRef } from './useIsMountedRef';
export { useLoadingDelay } from './useLoadingDelay';

View File

@ -29,7 +29,8 @@ const KNOWN_CONFIG: Record<string, Config> = {
[POLKADOT_GENESIS]: { ...DEFAULT_CONFIG, idealStake: 0.75 }
};
function getInflation ({ falloff, idealStake, maxInflation, minInflation }: Config = DEFAULT_CONFIG, totalStaked: BN, totalIssuance: BN): Inflation {
export function calcInflation (genesisHash: string, totalStaked: BN, totalIssuance: BN): Inflation {
const { falloff, idealStake, maxInflation, minInflation } = KNOWN_CONFIG[genesisHash] || DEFAULT_CONFIG;
const stakedFraction = totalStaked.muln(1_000_000).div(totalIssuance).toNumber() / 1_000_000;
const idealInterest = maxInflation / idealStake;
const inflation = 100 * (minInflation + (
@ -51,7 +52,7 @@ export function useInflation (totalStaked?: BN): Inflation {
useEffect((): void => {
totalIssuance && totalStaked && setState(
getInflation(KNOWN_CONFIG[api.genesisHash.toHex()], totalStaked, totalIssuance)
calcInflation(api.genesisHash.toHex(), totalStaked, totalIssuance)
);
}, [api, totalIssuance, totalStaked]);