ghost-portal/packages/react-hooks/src/useVotingStatus.ts
Jaco 42cb6b84d3
Rework collective queries (#5732)
* Rework collective queries

* members derive

* All via derive

* Adjust society useMembers

* Adjust optional consts

* Detect council module locations

* Adjust tech comm with module locations

* Rework loading

* Unused type import
2021-07-02 10:42:13 +02:00

69 lines
2.1 KiB
TypeScript

// Copyright 2017-2021 @polkadot/react-hooks authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type BN from 'bn.js';
import type { BlockNumber, Votes } from '@polkadot/types/interfaces';
import { useMemo } from 'react';
import { ApiPromise } from '@polkadot/api';
import { isFunction } from '@polkadot/util';
import { useApi } from './useApi';
import { useBestNumber } from './useBestNumber';
interface State {
hasFailed: boolean;
hasPassed: boolean;
isCloseable: boolean;
isVoteable: boolean;
remainingBlocks: BN | null;
}
const DEFAULT_STATUS = { hasFailed: false, hasPassed: false, isCloseable: false, isVoteable: false, remainingBlocks: null };
function getStatus (api: ApiPromise, bestNumber: BlockNumber, votes: Votes, numMembers: number, section: 'council' | 'membership' | 'technicalCommittee'): State {
const [instance] = api.registry.getModuleInstances(api.runtimeVersion.specName.toString(), section) || [section];
const modLocation = isFunction(api.tx[instance as 'technicalCommittee']?.close)
? instance
: null;
if (!votes.end || !modLocation) {
return {
hasFailed: false,
hasPassed: false,
isCloseable: false,
isVoteable: true,
remainingBlocks: null
};
}
const isEnd = bestNumber.gte(votes.end);
const hasPassed = votes.threshold.lten(votes.ayes.length);
const hasFailed = votes.threshold.gtn(Math.abs(numMembers - votes.nays.length));
return {
hasFailed,
hasPassed,
isCloseable: api.tx[modLocation].close.meta.args.length === 4 // current-generation
? isEnd || hasPassed || hasFailed
: isEnd,
isVoteable: !isEnd,
remainingBlocks: isEnd
? null
: votes.end.sub(bestNumber)
};
}
export function useVotingStatus (votes: Votes | null | undefined, numMembers: number, section: 'council' | 'membership' | 'technicalCommittee'): State {
const { api } = useApi();
const bestNumber = useBestNumber();
return useMemo(
() => bestNumber && votes
? getStatus(api, bestNumber, votes, numMembers, section)
: DEFAULT_STATUS,
[api, bestNumber, numMembers, section, votes]
);
}