From ece5999bea7895cac1ebde115805176a57e8bf25 Mon Sep 17 00:00:00 2001 From: Jaco Date: Sat, 22 May 2021 10:34:33 +0300 Subject: [PATCH] Inflation adjustment (based on auctions) (#5326) * Inflation adjustment (based on auctions) * Adjust * Adjust * Apply adjustment after inflation * Update packages/react-hooks/src/useInflation.ts --- .../apps-config/src/api/params/inflation.ts | 14 ++-- packages/page-staking/src/types.ts | 1 + packages/page-staking/src/useSortedTargets.ts | 65 ++++++++++++------- packages/react-hooks/src/index.ts | 2 +- packages/react-hooks/src/useInflation.ts | 18 +++-- 5 files changed, 65 insertions(+), 35 deletions(-) diff --git a/packages/apps-config/src/api/params/inflation.ts b/packages/apps-config/src/api/params/inflation.ts index 2872fe04e4..7704a02f9f 100644 --- a/packages/apps-config/src/api/params/inflation.ts +++ b/packages/apps-config/src/api/params/inflation.ts @@ -6,22 +6,26 @@ import type { ApiPromise } from '@polkadot/api'; import { KUSAMA_GENESIS, POLKADOT_GENESIS } from '../constants'; interface InflationParams { + auctionAdjust: number; + auctionMax: number; falloff: number; - idealStake: number; maxInflation: number; minInflation: number; + stakeTarget: number; } const DEFAULT_PARAMS: InflationParams = { + auctionAdjust: 0, + auctionMax: 0, falloff: 0.05, - idealStake: 0.5, maxInflation: 0.1, - minInflation: 0.025 + minInflation: 0.025, + stakeTarget: 0.5 }; const KNOWN_PARAMS: Record = { - [KUSAMA_GENESIS]: { ...DEFAULT_PARAMS, idealStake: 0.75 }, - [POLKADOT_GENESIS]: { ...DEFAULT_PARAMS, idealStake: 0.75 } + [KUSAMA_GENESIS]: { ...DEFAULT_PARAMS, auctionAdjust: (0.3 / 60), auctionMax: 60, stakeTarget: 0.75 }, + [POLKADOT_GENESIS]: { ...DEFAULT_PARAMS, stakeTarget: 0.75 } }; export function getInflationParams (api: ApiPromise): InflationParams { diff --git a/packages/page-staking/src/types.ts b/packages/page-staking/src/types.ts index d8ce0f65ca..4b290b24e1 100644 --- a/packages/page-staking/src/types.ts +++ b/packages/page-staking/src/types.ts @@ -66,6 +66,7 @@ export interface ValidatorInfo extends ValidatorInfoRank { stakedReturn: number; stakedReturnCmp: number; validatorPrefs?: ValidatorPrefs | ValidatorPrefsTo196; + withReturns?: boolean; } export type TargetSortBy = keyof ValidatorInfoRank; diff --git a/packages/page-staking/src/useSortedTargets.ts b/packages/page-staking/src/useSortedTargets.ts index f759f547ce..6172fc1208 100644 --- a/packages/page-staking/src/useSortedTargets.ts +++ b/packages/page-staking/src/useSortedTargets.ts @@ -3,12 +3,13 @@ import type { ApiPromise } from '@polkadot/api'; import type { DeriveSessionInfo, DeriveStakingElected, DeriveStakingWaiting } from '@polkadot/api-derive/types'; +import type { Inflation } from '@polkadot/react-hooks/types'; import type { SortedTargets, TargetSortBy, ValidatorInfo } from './types'; import BN from 'bn.js'; import { useMemo } from 'react'; -import { calcInflation, useAccounts, useApi, useCall } from '@polkadot/react-hooks'; +import { useAccounts, useApi, useCall, useInflation } from '@polkadot/react-hooks'; import { arrayFlatten, BN_HUNDRED, BN_MAX_INTEGER, BN_ONE, BN_ZERO } from '@polkadot/util'; interface LastEra { @@ -18,7 +19,7 @@ interface LastEra { sessionLength: BN; } -const EMPTY_PARTIAL = {}; +const EMPTY_PARTIAL: Partial = {}; const DEFAULT_FLAGS_ELECTED = { withController: true, withExposure: true, withPrefs: true }; const DEFAULT_FLAGS_WAITING = { withController: true, withPrefs: true }; @@ -79,7 +80,7 @@ function sortValidators (list: ValidatorInfo[]): ValidatorInfo[] { ); } -function extractSingle (api: ApiPromise, allAccounts: string[], derive: DeriveStakingElected | DeriveStakingWaiting, favorites: string[], { activeEra, eraLength, lastEra, sessionLength }: LastEra, historyDepth?: BN): [ValidatorInfo[], Record] { +function extractSingle (api: ApiPromise, allAccounts: string[], derive: DeriveStakingElected | DeriveStakingWaiting, favorites: string[], { activeEra, eraLength, lastEra, sessionLength }: LastEra, historyDepth?: BN, withReturns?: boolean): [ValidatorInfo[], Record] { const nominators: Record = {}; const emptyExposure = api.createType('Exposure'); const earliestEra = historyDepth && lastEra.sub(historyDepth).iadd(BN_ONE); @@ -152,15 +153,37 @@ function extractSingle (api: ApiPromise, allAccounts: string[], derive: DeriveSt skipRewards, stakedReturn: 0, stakedReturnCmp: 0, - validatorPrefs + validatorPrefs, + withReturns }; }); return [list, nominators]; } -function extractInfo (api: ApiPromise, allAccounts: string[], electedDerive: DeriveStakingElected, waitingDerive: DeriveStakingWaiting, favorites: string[], totalIssuance: BN, lastEraInfo: LastEra, historyDepth?: BN): Partial { - const [elected, nominators] = extractSingle(api, allAccounts, electedDerive, favorites, lastEraInfo, historyDepth); +function addReturns (inflation: Inflation, baseInfo: Partial): Partial { + const avgStaked = baseInfo.avgStaked; + const validators = baseInfo.validators; + + if (!validators) { + return baseInfo; + } + + avgStaked && !avgStaked.isZero() && validators.forEach((v): void => { + if (!v.skipRewards && v.withReturns) { + const adjusted = avgStaked.mul(BN_HUNDRED).imuln(inflation.stakedReturn).div(v.bondTotal); + + // in some cases, we may have overflows... protect against those + v.stakedReturn = (adjusted.gt(BN_MAX_INTEGER) ? BN_MAX_INTEGER : adjusted).toNumber() / BN_HUNDRED.toNumber(); + v.stakedReturnCmp = v.stakedReturn * (100 - v.commissionPer) / 100; + } + }); + + return { ...baseInfo, validators: sortValidators(validators) }; +} + +function extractBaseInfo (api: ApiPromise, allAccounts: string[], electedDerive: DeriveStakingElected, waitingDerive: DeriveStakingWaiting, favorites: string[], totalIssuance: BN, lastEraInfo: LastEra, historyDepth?: BN): Partial { + const [elected, nominators] = extractSingle(api, allAccounts, electedDerive, favorites, lastEraInfo, historyDepth, true); const [waiting] = extractSingle(api, allAccounts, waitingDerive, favorites, lastEraInfo); const activeTotals = elected .filter(({ isActive }) => isActive) @@ -168,18 +191,6 @@ function extractInfo (api: ApiPromise, allAccounts: string[], electedDerive: Der .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(api, totalStaked, totalIssuance); - - // add the explicit stakedReturn - !avgStaked.isZero() && elected.forEach((e): void => { - if (!e.skipRewards) { - const adjusted = avgStaked.mul(BN_HUNDRED).imuln(inflation.stakedReturn).div(e.bondTotal); - - // in some cases, we may have overflows... protect against those - e.stakedReturn = (adjusted.gt(BN_MAX_INTEGER) ? BN_MAX_INTEGER : adjusted).toNumber() / BN_HUNDRED.toNumber(); - e.stakedReturnCmp = e.stakedReturn * (100 - e.commissionPer) / 100; - } - }); // all validators, calc median commission const minNominated = Object.values(nominators).reduce((min: BN, value) => { @@ -187,7 +198,7 @@ function extractInfo (api: ApiPromise, allAccounts: string[], electedDerive: Der ? value : min; }, BN_ZERO); - const validators = sortValidators(arrayFlatten([elected, waiting])); + const validators = arrayFlatten([elected, waiting]); const commValues = validators.map(({ commissionPer }) => commissionPer).sort((a, b) => a - b); const midIndex = Math.floor(commValues.length / 2); const medianComm = commValues.length @@ -209,7 +220,6 @@ function extractInfo (api: ApiPromise, allAccounts: string[], electedDerive: Der return { avgStaked, - inflation, lowStaked: activeTotals[0] || BN_ZERO, medianComm, minNominated, @@ -241,12 +251,21 @@ export default function useSortedTargets (favorites: string[], withLedger: boole const waitingInfo = useCall(api.derive.staking.waitingInfo, [{ ...DEFAULT_FLAGS_WAITING, withLedger }]); const lastEraInfo = useCall(api.derive.session.info, undefined, transformEra); - const partial = useMemo( + const baseInfo = useMemo( () => electedInfo && lastEraInfo && totalIssuance && waitingInfo - ? extractInfo(api, allAccounts, electedInfo, waitingInfo, favorites, totalIssuance, lastEraInfo, historyDepth) + ? extractBaseInfo(api, allAccounts, electedInfo, waitingInfo, favorites, totalIssuance, lastEraInfo, historyDepth) : EMPTY_PARTIAL, [api, allAccounts, electedInfo, favorites, historyDepth, lastEraInfo, totalIssuance, waitingInfo] ); - return { inflation: { inflation: 0, stakedReturn: 0 }, medianComm: 0, minNominated: BN_ZERO, ...partial }; + const inflation = useInflation(baseInfo?.totalStaked); + + const partial = useMemo( + () => inflation + ? addReturns(inflation, baseInfo) + : baseInfo, + [baseInfo, inflation] + ); + + return { inflation, medianComm: 0, minNominated: BN_ZERO, ...partial }; } diff --git a/packages/react-hooks/src/index.ts b/packages/react-hooks/src/index.ts index 7bd92bd516..2d33207fdf 100644 --- a/packages/react-hooks/src/index.ts +++ b/packages/react-hooks/src/index.ts @@ -19,7 +19,7 @@ export { useEventTrigger } from './useEventTrigger'; export { useExtrinsicTrigger } from './useExtrinsicTrigger'; export { useFavorites } from './useFavorites'; export { useIncrement } from './useIncrement'; -export { calcInflation, useInflation } from './useInflation'; +export { useInflation } from './useInflation'; export { useIpfs } from './useIpfs'; export { useIsMountedRef } from './useIsMountedRef'; export { useLedger } from './useLedger'; diff --git a/packages/react-hooks/src/useInflation.ts b/packages/react-hooks/src/useInflation.ts index 14821a7e27..505006a492 100644 --- a/packages/react-hooks/src/useInflation.ts +++ b/packages/react-hooks/src/useInflation.ts @@ -8,18 +8,19 @@ import BN from 'bn.js'; import { useEffect, useState } from 'react'; import { getInflationParams } from '@polkadot/apps-config'; -import { BN_MILLION } from '@polkadot/util'; +import { BN_MILLION, BN_ZERO } from '@polkadot/util'; import { useApi } from './useApi'; import { useCall } from './useCall'; const EMPTY: Inflation = { inflation: 0, stakedReturn: 0 }; -export function calcInflation (api: ApiPromise, totalStaked: BN, totalIssuance: BN): Inflation { - const { falloff, idealStake, maxInflation, minInflation } = getInflationParams(api); +function calcInflation (api: ApiPromise, totalStaked: BN, totalIssuance: BN, numAuctions: BN): Inflation { + const { auctionAdjust, auctionMax, falloff, maxInflation, minInflation, stakeTarget } = getInflationParams(api); const stakedFraction = totalStaked.isZero() || totalIssuance.isZero() ? 0 : totalStaked.mul(BN_MILLION).div(totalIssuance).toNumber() / BN_MILLION.toNumber(); + const idealStake = stakeTarget - (Math.min(auctionMax, numAuctions.toNumber()) * auctionAdjust); const idealInterest = maxInflation / idealStake; const inflation = 100 * (minInflation + ( stakedFraction <= idealStake @@ -38,13 +39,18 @@ export function calcInflation (api: ApiPromise, totalStaked: BN, totalIssuance: export function useInflation (totalStaked?: BN): Inflation { const { api } = useApi(); const totalIssuance = useCall(api.query.balances?.totalIssuance); + const auctionCounter = useCall(api.query.auctions?.auctionCounter); const [state, setState] = useState(EMPTY); useEffect((): void => { - totalIssuance && totalStaked && setState( - calcInflation(api, totalStaked, totalIssuance) + const numAuctions = api.query.auctions + ? auctionCounter + : BN_ZERO; + + numAuctions && totalIssuance && totalStaked && setState( + calcInflation(api, totalStaked, totalIssuance, numAuctions) ); - }, [api, totalIssuance, totalStaked]); + }, [api, auctionCounter, totalIssuance, totalStaked]); return state; }