Add elected stake (#1874)

This commit is contained in:
Jaco Greeff 2019-11-12 20:38:15 +01:00 committed by GitHub
parent 117903cdf1
commit 84f6c00829
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 108 additions and 31 deletions

View File

@ -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<Props> {
const [labels, setLabels] = useState<string[]>([]);
const [{ avgSet, idxSet }, setValues] = useState<{ avgSet: number[]; idxSet: BN[] }>({ avgSet: [], idxSet: [] });
function Validator ({ blockCounts, className, currentIndex, startNumber, t, validatorId }: Props): React.ReactElement<Props> {
const { api } = useContext(ApiContext);
const [blocksLabels, setBlocksLabels] = useState<string[]>([]);
const [blocksChart, setBlocksChart] = useState<LineData | undefined>();
const [stakeLabels, setStakeLabels] = useState<string[]>([]);
const [stakeChart, setStateChart] = useState<LineData | undefined>();
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<Hash> =>
api.rpc.chain.getBlockHash(at as any)
))
.then((hashes): Promise<Exposure[]> =>
Promise.all(hashes.map((hash): Promise<Exposure> =>
api.query.staking.stakers.at(hash, validatorId) as Promise<Exposure>
))
)
.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 (
<div className={className}>
<h1>{t('blocks per session')}</h1>
<Chart.Line
labels={labels}
legends={[t('blocks'), t('average')]}
values={[idxSet, avgSet]} />
</div>
<Columar className={className}>
<Column
emptyText={t('Loading data')}
headerText={t('blocks per session')}
>
{blocksChart && (
<Chart.Line
colors={[undefined, '#acacac']}
labels={blocksLabels}
legends={[t('blocks'), t('average')]}
values={blocksChart}
/>
)}
</Column>
<Column
emptyText={t('Loading data')}
headerText={t('elected stake')}
>
{stakeChart && (
<Chart.Line
labels={stakeLabels}
legends={[t('total'), t('own'), t('other')]}
values={stakeChart}
/>
)}
</Column>
</Columar>
);
}

View File

@ -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<{}> {
// />
// </Input>
function Query ({ className, stakingOverview, match: { params: { value } }, t }: Props): React.ReactElement<Props> {
function Query ({ bestNumber, className, stakingOverview, match: { params: { value } }, t }: Props): React.ReactElement<Props> {
const [startNumber, setStartNumber] = useState<BlockNumber | undefined>();
const [validatorId, setValidatorId] = useState<string | null>(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}
/>
</InputAddressSimple>
{value && stakingOverview && (
{value && startNumber && stakingOverview && (
<Validator
currentIndex={stakingOverview.currentIndex}
startNumber={startNumber}
validatorId={value}
/>
)}

View File

@ -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<Props> {
function App ({ allAccounts, allStashesAndControllers: [allStashes, allControllers] = EMPTY_ALL, basePath, bestNumber, className, recentlyOnline, stakingOverview, t }: Props): React.ReactElement<Props> {
const { api } = useContext(ApiContext);
const routeMatch = useRouteMatch({ path: basePath, strict: true });
const _renderComponent = (Component: React.ComponentType<ComponentProps>, 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<Props>(
['derive.chain.bestNumber', { propName: 'bestNumber' }],
['derive.imOnline.receivedHeartbeats', { propName: 'recentlyOnline' }],
['derive.staking.controllers', {
propName: 'allStashesAndControllers',

View File

@ -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<string, string[]>;
@ -11,6 +12,7 @@ export interface ComponentProps {
allAccounts?: SubjectInfo;
allControllers: string[];
allStashes: string[];
bestNumber?: BlockNumber;
className?: string;
recentlyOnline?: DerivedHeartbeats;
stakingOverview?: DerivedStakingOverview;

View File

@ -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<Props> | null {
export default function LineChart ({ className, colors, labels, legends, style, values }: Props): React.ReactElement<Props> | null {
const [{ chartData, chartOptions, jsonValues }, setState] = useState<State>({});
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]);