diff --git a/packages/page-staking/src/Overview/Summary.tsx b/packages/page-staking/src/Overview/Summary.tsx index 46746a9f2b..a113266bbc 100644 --- a/packages/page-staking/src/Overview/Summary.tsx +++ b/packages/page-staking/src/Overview/Summary.tsx @@ -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} )} - {(inflation.inflation > 0) && ( + {(inflation > 0) && ( ('inflation')} > - {inflation.inflation.toFixed(1)}% + {inflation.toFixed(1)}% )} diff --git a/packages/page-staking/src/Targets/Summary.tsx b/packages/page-staking/src/Targets/Summary.tsx index 1a39d77b6d..80f0f8f265 100644 --- a/packages/page-staking/src/Targets/Summary.tsx +++ b/packages/page-staking/src/Targets/Summary.tsx @@ -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 { +function Summary ({ avgStaked, lastReward, lowStaked, numNominators, numValidators, stakedReturn, totalIssuance, totalStaked }: Props): React.ReactElement { const { t } = useTranslation(); - const { api } = useApi(); - const totalIssuance = useCall(api.query.balances?.totalIssuance); const progressStake = useMemo( () => totalIssuance && totalStaked && totalStaked.gtn(0) @@ -53,35 +48,37 @@ function Summary ({ avgStaked, inflation, lastReward, lowStaked, numNominators,
{totalIssuance && ( - ('total staked')} / ` : ''}${t('total issuance')}`} - progress={progressStake} - > -
- {totalStaked?.gtn(0) && ( - <> - -  /  - - )} - -
-
- )} - {(inflation.stakedReturn > 0) && ( - ('returns')} - > - {inflation.stakedReturn.toFixed(1)}% - + <> + ('total staked')} / ` : ''}${t('total issuance')}`} + progress={progressStake} + > +
+ {totalStaked?.gtn(0) && ( + <> + +  /  + + )} + +
+
+ {(stakedReturn > 0) && ( + ('returns')} + > + {stakedReturn.toFixed(1)}% + + )} + )}
{avgStaked && lowStaked && ( diff --git a/packages/page-staking/src/Targets/Validator.tsx b/packages/page-staking/src/Targets/Validator.tsx index 362faacce7..79d12c0c5e 100644 --- a/packages/page-staking/src/Targets/Validator.tsx +++ b/packages/page-staking/src/Targets/Validator.tsx @@ -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 ( @@ -165,7 +165,7 @@ function Validator ({ allSlashes, canSelect, filterName, info, isNominated, isSe {!bondTotal.isZero() && } {!bondOwn.isZero() && } {!bondOther.isZero() && } - {!rewardPayout.isZero() && } + {(stakedReturnCmp > 0) && <>{stakedReturnCmp.toFixed(2)}%} {(canSelect || isSelected) && ( { +function Targets ({ className = '', isInElection, ownStashes, targets: { avgStaked, inflation: { stakedReturn }, lastReward, lowStaked, nominators, totalIssuance, totalStaked, validators }, toggleFavorite }: Props): React.ReactElement { const { t } = useTranslation(); const { api } = useApi(); const allSlashes = useAvailableSlashes(); @@ -160,7 +159,7 @@ function Targets ({ className = '', inflation, isInElection, ownStashes, targets rankBondTotal: t('total stake'), rankComm: t('comm.'), rankNumNominators: t('nominators'), - rankOverall: t('profit/era') + rankOverall: t('return') }); const header = useMemo(() => [ @@ -179,15 +178,6 @@ function Targets ({ className = '', inflation, isInElection, ownStashes, targets const filter = useMemo(() => ( sorted && (
- ('The amount that will be used on a per-validator basis to calculate profits for that validator.')} - isFull - isZeroable={false} - label={t('amount to use for estimation')} - onChange={setCalcWith} - value={calcWith} - />
) - ), [calcWith, setCalcWith, nameFilter, sorted, t, withElected, withGroup, withIdentity, withoutComm, withoutOver]); + ), [nameFilter, sorted, t, withElected, withGroup, withIdentity, withoutComm, withoutOver]); return (
diff --git a/packages/page-staking/src/index.tsx b/packages/page-staking/src/index.tsx index fa5ae9f884..cdecfe5810 100644 --- a/packages/page-staking/src/index.tsx +++ b/packages/page-staking/src/index.tsx @@ -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(api.derive.staking.overview); const isInElection = useCall(api.query.staking?.eraElectionStatus, undefined, transformElection); @@ -115,7 +114,7 @@ function StakingApp ({ basePath, className = '' }: Props): React.ReactElement void; totalStaked?: BN; + totalIssuance?: BN; validators?: ValidatorInfo[]; validatorIds?: string[]; } diff --git a/packages/page-staking/src/useSortedTargets.ts b/packages/page-staking/src/useSortedTargets.ts index 87da3041b4..624a9b2726 100644 --- a/packages/page-staking/src/useSortedTargets.ts +++ b/packages/page-staking/src/useSortedTargets.ts @@ -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 = {}; 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 { +function extractInfo (genesisHash: string, allAccounts: string[], electedDerive: DeriveStakingElected, waitingDerive: DeriveStakingWaiting, favorites: string[], totalIssuance: BN, lastReward = BN_ONE): Partial { 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(api.query.balances.totalIssuance); const electedInfo = useCall(api.derive.staking.electedInfo); const waitingInfo = useCall(api.derive.staking.waitingInfo); const lastEra = useCall(api.derive.session.indexes, undefined, transformEra); const lastReward = useCall(lastEra && api.query.staking.erasValidatorReward, [lastEra], transformReward); - const [calcWith, setCalcWith] = useState(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 }; } diff --git a/packages/react-hooks/src/index.ts b/packages/react-hooks/src/index.ts index ca708fe2a2..65071bcbfd 100644 --- a/packages/react-hooks/src/index.ts +++ b/packages/react-hooks/src/index.ts @@ -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'; diff --git a/packages/react-hooks/src/useInflation.ts b/packages/react-hooks/src/useInflation.ts index 82c4538331..2a6ad92643 100644 --- a/packages/react-hooks/src/useInflation.ts +++ b/packages/react-hooks/src/useInflation.ts @@ -29,7 +29,8 @@ const KNOWN_CONFIG: Record = { [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]);