// Copyright 2017-2022 @polkadot/app-staking authors & contributors // SPDX-License-Identifier: Apache-2.0 import type { DeriveEraRewards, DeriveOwnSlashes, DeriveStakerPoints } from '@polkadot/api-derive/types'; import type { ChartInfo, LineDataEntry, Props } from './types'; import React, { useMemo } from 'react'; import { Chart, Spinner } from '@polkadot/react-components'; import { useApi, useCall } from '@polkadot/react-hooks'; import { BN, formatBalance } from '@polkadot/util'; import { useTranslation } from '../translate'; import { balanceToNumber } from './util'; const COLORS_REWARD = ['#8c2200', '#008c22', '#acacac']; function extractRewards (erasRewards: DeriveEraRewards[] = [], ownSlashes: DeriveOwnSlashes[] = [], allPoints: DeriveStakerPoints[] = [], divisor: BN): ChartInfo { const labels: string[] = []; const slashSet: LineDataEntry = []; const rewardSet: LineDataEntry = []; const avgSet: LineDataEntry = []; const [total, avgCount] = erasRewards.reduce(([total, avgCount], { era, eraReward }) => { const points = allPoints.find((points) => points.era.eq(era)); const reward = points?.eraPoints.gtn(0) ? balanceToNumber(points.points.mul(eraReward).div(points.eraPoints), divisor) : 0; if (reward > 0) { total += reward; avgCount++; } return [total, avgCount]; }, [0, 0]); erasRewards.forEach(({ era, eraReward }): void => { const points = allPoints.find((points) => points.era.eq(era)); const slashed = ownSlashes.find((slash) => slash.era.eq(era)); const reward = points?.eraPoints.gtn(0) ? balanceToNumber(points.points.mul(eraReward).div(points.eraPoints), divisor) : 0; const slash = slashed ? balanceToNumber(slashed.total, divisor) : 0; const avg = avgCount > 0 ? Math.ceil(total * 100 / avgCount) / 100 : 0; labels.push(era.toHuman()); rewardSet.push(reward); avgSet.push(avg); slashSet.push(slash); }); return { chart: [slashSet, rewardSet, avgSet], labels }; } function ChartRewards ({ validatorId }: Props): React.ReactElement { const { t } = useTranslation(); const { api } = useApi(); const params = useMemo(() => [validatorId, false], [validatorId]); const ownSlashes = useCall(api.derive.staking.ownSlashes, params); const erasRewards = useCall(api.derive.staking.erasRewards); const stakerPoints = useCall(api.derive.staking.stakerPoints, params); const { currency, divisor } = useMemo(() => ({ currency: formatBalance.getDefaults().unit, divisor: new BN('1'.padEnd(formatBalance.getDefaults().decimals + 1, '0')) }), []); const { chart, labels } = useMemo( () => extractRewards(erasRewards, ownSlashes, stakerPoints, divisor), [divisor, erasRewards, ownSlashes, stakerPoints] ); const legends = useMemo(() => [ t('{{currency}} slashed', { replace: { currency } }), t('{{currency}} rewards', { replace: { currency } }), t('{{currency}} average', { replace: { currency } }) ], [currency, t]); return (

{t('rewards & slashes')}

{labels.length ? ( ) : }
); } export default React.memo(ChartRewards);