From 84f6c008297558b822424a9ef7f9b43af747edd7 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Tue, 12 Nov 2019 20:38:15 +0100 Subject: [PATCH] Add elected stake (#1874) --- packages/app-staking/src/Query/Validator.tsx | 104 +++++++++++++++---- packages/app-staking/src/Query/index.tsx | 15 ++- packages/app-staking/src/index.tsx | 4 +- packages/app-staking/src/types.ts | 2 + packages/react-components/src/Chart/Line.tsx | 14 ++- 5 files changed, 108 insertions(+), 31 deletions(-) diff --git a/packages/app-staking/src/Query/Validator.tsx b/packages/app-staking/src/Query/Validator.tsx index 5f6504775f..005a4b5b80 100644 --- a/packages/app-staking/src/Query/Validator.tsx +++ b/packages/app-staking/src/Query/Validator.tsx @@ -3,13 +3,13 @@ // of the Apache-2.0 license. See the LICENSE file for details. import { I18nProps } from '@polkadot/react-components/types'; -import { SessionIndex } from '@polkadot/types/interfaces'; +import { BlockNumber, Exposure, Hash, SessionIndex } from '@polkadot/types/interfaces'; import BN from 'bn.js'; -import React, { useEffect, useState } from 'react'; -import { Chart } from '@polkadot/react-components'; -import { withCalls } from '@polkadot/react-api'; -import { formatNumber } from '@polkadot/util'; +import React, { useContext, useEffect, useState } from 'react'; +import { Chart, Columar, Column } from '@polkadot/react-components'; +import { ApiContext, withCalls } from '@polkadot/react-api'; +import { formatBalance, formatNumber } from '@polkadot/util'; import translate from '../translate'; @@ -17,10 +17,13 @@ interface Props extends I18nProps { blockCounts?: BN[]; className?: string; currentIndex: SessionIndex; + startNumber: BlockNumber; validatorId: string; } -// assuming 4 hrs sessions, we we grab results for 10 days +type LineData = (BN | number)[][]; + +// assuming 4 hrs sessions, we grab results for 10 days const SESSIONS = 10 * (24 / 4); function getIndexRange (currentIndex: SessionIndex): BN[] { @@ -36,12 +39,55 @@ function getIndexRange (currentIndex: SessionIndex): BN[] { return range.reverse(); } -function Validator ({ blockCounts, className, currentIndex, t }: Props): React.ReactElement { - const [labels, setLabels] = useState([]); - const [{ avgSet, idxSet }, setValues] = useState<{ avgSet: number[]; idxSet: BN[] }>({ avgSet: [], idxSet: [] }); +function Validator ({ blockCounts, className, currentIndex, startNumber, t, validatorId }: Props): React.ReactElement { + const { api } = useContext(ApiContext); + const [blocksLabels, setBlocksLabels] = useState([]); + const [blocksChart, setBlocksChart] = useState(); + const [stakeLabels, setStakeLabels] = useState([]); + const [stakeChart, setStateChart] = useState(); useEffect((): void => { - setLabels( + const numbers: BN[] = []; + const checkLength = (api.consts.babe + ? api.consts.babe.epochDuration as BlockNumber + : new BN(500)).muln(2).divn(3); + const divisor = new BN('1'.padEnd(formatBalance.getDefaults().decimals + 1, '0')); + + api.isReady.then((): void => { + let currentNumber: BN = startNumber; + + // here we end up with more-or-less 6.66 days + while (startNumber.gtn(0) && numbers.length < SESSIONS) { + numbers.unshift(currentNumber); + currentNumber = currentNumber.sub(checkLength); + } + + setStakeLabels(numbers.map((bn): string => formatNumber(bn))); + + Promise + .all(numbers.map((at): Promise => + api.rpc.chain.getBlockHash(at as any) + )) + .then((hashes): Promise => + Promise.all(hashes.map((hash): Promise => + api.query.staking.stakers.at(hash, validatorId) as Promise + )) + ) + .then((exposures): void => { + setStateChart([ + exposures.map(({ total }): BN => + total.unwrap().div(divisor)) + // exposures.map(({ own }): BN => + // own.unwrap().div(divisor)), + // exposures.map(({ others }): BN => + // others.reduce((total, { value }): BN => total.add(value.unwrap()), new BN(0)).div(divisor)) + ]); + }); + }); + }, []); + + useEffect((): void => { + setBlocksLabels( getIndexRange(currentIndex).map((index): string => formatNumber(index)) ); }, [currentIndex]); @@ -60,18 +106,38 @@ function Validator ({ blockCounts, className, currentIndex, t }: Props): React.R return total; }, new BN(0)); - setValues({ avgSet, idxSet }); + setBlocksChart([idxSet, avgSet]); } - }, [blockCounts, labels]); + }, [blockCounts, blocksLabels]); return ( -
-

{t('blocks per session')}

- -
+ + + {blocksChart && ( + + )} + + + {stakeChart && ( + + )} + + ); } diff --git a/packages/app-staking/src/Query/index.tsx b/packages/app-staking/src/Query/index.tsx index f5c5a33f1c..c3ff9f5c8d 100644 --- a/packages/app-staking/src/Query/index.tsx +++ b/packages/app-staking/src/Query/index.tsx @@ -3,9 +3,10 @@ // of the Apache-2.0 license. See the LICENSE file for details. import { I18nProps } from '@polkadot/react-components/types'; +import { BlockNumber } from '@polkadot/types/interfaces'; import { ComponentProps } from '../types'; -import React, { useState } from 'react'; +import React, { useEffect, useState } from 'react'; import { withRouter, RouteComponentProps } from 'react-router-dom'; import { Button, InputAddressSimple } from '@polkadot/react-components'; @@ -46,9 +47,16 @@ interface Props extends I18nProps, ComponentProps, RouteComponentProps<{}> { // /> // -function Query ({ className, stakingOverview, match: { params: { value } }, t }: Props): React.ReactElement { +function Query ({ bestNumber, className, stakingOverview, match: { params: { value } }, t }: Props): React.ReactElement { + const [startNumber, setStartNumber] = useState(); const [validatorId, setValidatorId] = useState(value || null); + useEffect((): void => { + if (bestNumber && !startNumber) { + setStartNumber(bestNumber); + } + }, [bestNumber, startNumber]); + const _onQuery = (): void => { if (validatorId) { window.location.hash = `/staking/query/${validatorId}`; @@ -71,9 +79,10 @@ function Query ({ className, stakingOverview, match: { params: { value } }, t }: onClick={_onQuery} /> - {value && stakingOverview && ( + {value && startNumber && stakingOverview && ( )} diff --git a/packages/app-staking/src/index.tsx b/packages/app-staking/src/index.tsx index 25fb681551..9bb8b16acb 100644 --- a/packages/app-staking/src/index.tsx +++ b/packages/app-staking/src/index.tsx @@ -36,7 +36,7 @@ interface Props extends AppProps, ApiProps, I18nProps { const EMPY_ACCOUNTS: string[] = []; const EMPTY_ALL: [string[], string[]] = [EMPY_ACCOUNTS, EMPY_ACCOUNTS]; -function App ({ allAccounts, allStashesAndControllers: [allStashes, allControllers] = EMPTY_ALL, basePath, className, recentlyOnline, stakingOverview, t }: Props): React.ReactElement { +function App ({ allAccounts, allStashesAndControllers: [allStashes, allControllers] = EMPTY_ALL, basePath, bestNumber, className, recentlyOnline, stakingOverview, t }: Props): React.ReactElement { const { api } = useContext(ApiContext); const routeMatch = useRouteMatch({ path: basePath, strict: true }); const _renderComponent = (Component: React.ComponentType, className?: string): () => React.ReactNode => { @@ -51,6 +51,7 @@ function App ({ allAccounts, allStashesAndControllers: [allStashes, allControlle allAccounts={allAccounts} allControllers={allControllers} allStashes={allStashes} + bestNumber={bestNumber} className={className} recentlyOnline={recentlyOnline} stakingOverview={stakingOverview} @@ -112,6 +113,7 @@ export default withMulti( `, translate, withCalls( + ['derive.chain.bestNumber', { propName: 'bestNumber' }], ['derive.imOnline.receivedHeartbeats', { propName: 'recentlyOnline' }], ['derive.staking.controllers', { propName: 'allStashesAndControllers', diff --git a/packages/app-staking/src/types.ts b/packages/app-staking/src/types.ts index f7cee5ae38..b088c143ab 100644 --- a/packages/app-staking/src/types.ts +++ b/packages/app-staking/src/types.ts @@ -3,6 +3,7 @@ // of the Apache-2.0 license. See the LICENSE file for details. import { DerivedFees, DerivedBalances, DerivedHeartbeats, DerivedStakingOverview } from '@polkadot/api-derive/types'; +import { BlockNumber } from '@polkadot/types/interfaces'; import { SubjectInfo } from '@polkadot/ui-keyring/observable/types'; export type Nominators = Record; @@ -11,6 +12,7 @@ export interface ComponentProps { allAccounts?: SubjectInfo; allControllers: string[]; allStashes: string[]; + bestNumber?: BlockNumber; className?: string; recentlyOnline?: DerivedHeartbeats; stakingOverview?: DerivedStakingOverview; diff --git a/packages/react-components/src/Chart/Line.tsx b/packages/react-components/src/Chart/Line.tsx index 09b5e33872..7d3c40892a 100644 --- a/packages/react-components/src/Chart/Line.tsx +++ b/packages/react-components/src/Chart/Line.tsx @@ -10,7 +10,7 @@ import ChartJs from 'chart.js'; import { Line } from 'react-chartjs-2'; interface Props extends BareProps { - aspectRatio?: number; + colors?: (string | undefined)[]; labels: string[]; legends: string[]; values: (number | BN)[][]; @@ -36,14 +36,14 @@ interface Config { datasets: Dataset[]; } -const COLORS = ['#ff8c00', '#acacac']; +const COLORS = ['#ff8c00', '#008c8c', '#8c008c']; const alphaColor = (hexColor: string): string => ChartJs.helpers.color(hexColor).alpha(0.65).rgbString(); -function calculateOptions (aspectRatio: number, legends: string[], labels: string[], values: (number | BN)[][], jsonValues: string): State { +function calculateOptions (colors: (string | undefined)[] = [], legends: string[], labels: string[], values: (number | BN)[][], jsonValues: string): State { const chartData = values.reduce((config, values, index): Config => { - const color = alphaColor(COLORS[index]); + const color = colors[index] || alphaColor(COLORS[index]); const data = values.map((value): number => BN.isBN(value) ? value.toNumber() : value); config.datasets.push({ @@ -64,8 +64,6 @@ function calculateOptions (aspectRatio: number, legends: string[], labels: strin return { chartData, chartOptions: { - // width/height by default this is "1", i.e. a square box - aspectRatio, // no need for the legend, expect the labels contain everything legend: { display: false @@ -82,14 +80,14 @@ function calculateOptions (aspectRatio: number, legends: string[], labels: strin }; } -export default function LineChart ({ aspectRatio = 10, className, labels, legends, style, values }: Props): React.ReactElement | null { +export default function LineChart ({ className, colors, labels, legends, style, values }: Props): React.ReactElement | null { const [{ chartData, chartOptions, jsonValues }, setState] = useState({}); useEffect((): void => { const newJsonValues = JSON.stringify(values); if (newJsonValues !== jsonValues) { - setState(calculateOptions(aspectRatio, legends, labels, values, newJsonValues)); + setState(calculateOptions(colors, legends, labels, values, newJsonValues)); } }, [labels, legends, values]);