ghost-portal/packages/react-hooks/src/useInflation.ts
Jaco Greeff fd0ceaff0d
Use BN_{BILLION, MILLION} constants (#4577)
* Use BN_{BILLIN, MILLION} constants

* BN_ONE

* Update packages/page-treasury/src/Overview/ProposalCreate.tsx

* Update packages/page-staking/src/Payouts/useStakerPayouts.ts

* Additional

* Update packages/page-democracy/src/Overview/Summary.tsx

* Additional

* Additional

* Re-apply

* Cleanups

* Apply suggestions from code review
2021-02-03 10:59:37 +01:00

45 lines
1.5 KiB
TypeScript

// Copyright 2017-2021 @polkadot/react-hooks authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ApiPromise } from '@polkadot/api';
import type { Inflation } from './types';
import BN from 'bn.js';
import { useEffect, useState } from 'react';
import { getInflationParams } from '@polkadot/apps-config';
import { BN_MILLION } from '@polkadot/util';
import { useApi } from './useApi';
import { useCall } from './useCall';
export function calcInflation (api: ApiPromise, totalStaked: BN, totalIssuance: BN): Inflation {
const { falloff, idealStake, maxInflation, minInflation } = getInflationParams(api);
const stakedFraction = totalStaked.mul(BN_MILLION).div(totalIssuance).toNumber() / BN_MILLION.toNumber();
const idealInterest = maxInflation / idealStake;
const inflation = 100 * (minInflation + (
stakedFraction <= idealStake
? (stakedFraction * (idealInterest - (minInflation / idealStake)))
: (((idealInterest * idealStake) - minInflation) * Math.pow(2, (idealStake - stakedFraction) / falloff))
));
return {
inflation,
stakedReturn: inflation / stakedFraction
};
}
export function useInflation (totalStaked?: BN): Inflation {
const { api } = useApi();
const totalIssuance = useCall<BN>(api.query.balances.totalIssuance);
const [state, setState] = useState<Inflation>({ inflation: 0, stakedReturn: 0 });
useEffect((): void => {
totalIssuance && totalStaked && setState(
calcInflation(api, totalStaked, totalIssuance)
);
}, [api, totalIssuance, totalStaked]);
return state;
}