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
This commit is contained in:
Jaco 2021-07-02 11:42:13 +03:00 committed by GitHub
parent 990556332e
commit 42cb6b84d3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
44 changed files with 265 additions and 157 deletions

View File

@ -11,13 +11,9 @@ export default function create (t: TFunction): Route {
Component,
display: {
needsApi: [
'query.council.prime',
[
'query.phragmenElection.candidates',
'query.electionsPhragmen.candidates',
'query.elections.candidates'
]
]
'query.council.prime'
],
needsApiInstances: true
},
group: 'governance',
icon: 'building',

View File

@ -13,7 +13,8 @@ export default function create (t: TFunction): Route {
needsAccounts: true,
needsApi: [
'query.technicalCommittee.members'
]
],
needsApiInstances: true
},
group: 'governance',
icon: 'microchip',

View File

@ -19,6 +19,7 @@ export interface Route {
isModal?: boolean;
needsAccounts?: boolean;
needsApi?: (string | string[])[];
needsApiInstances?: boolean;
needsSudo?: boolean;
needsTeleport?: boolean;
};

View File

@ -38,7 +38,7 @@ function Content ({ className }: Props): React.ReactElement<Props> {
const { api, isApiConnected, isApiReady } = useApi();
const { queueAction } = useContext(StatusContext);
const { Component, display: { needsApi }, icon, name, text } = useMemo(
const { Component, display: { needsApi, needsApiInstances }, icon, name, text } = useMemo(
(): Route => {
const app = location.pathname.slice(1) || '';
@ -47,11 +47,18 @@ function Content ({ className }: Props): React.ReactElement<Props> {
[location, t]
);
const missingApis = findMissingApis(api, needsApi);
const missingApis = useMemo(
() => needsApi
? isApiReady && isApiConnected
? findMissingApis(api, needsApi, needsApiInstances)
: null
: [],
[api, isApiConnected, isApiReady, needsApi, needsApiInstances]
);
return (
<div className={className}>
{needsApi && (!isApiReady || !isApiConnected)
{!missingApis
? (
<div className='connecting'>
<Spinner label={t<string>('Initializing connection')} />

View File

@ -42,7 +42,7 @@ function createExternals (t: TFunction): ItemRoute[] {
];
}
function checkVisible ({ api, isApiConnected, isApiReady }: ApiProps, allowTeleport: boolean, hasAccounts: boolean, hasSudo: boolean, { isHidden, needsAccounts, needsApi, needsSudo, needsTeleport }: Route['display']): boolean {
function checkVisible ({ api, isApiConnected, isApiReady }: ApiProps, allowTeleport: boolean, hasAccounts: boolean, hasSudo: boolean, { isHidden, needsAccounts, needsApi, needsApiInstances, needsSudo, needsTeleport }: Route['display']): boolean {
if (isHidden) {
return false;
} else if (needsAccounts && !hasAccounts) {
@ -57,7 +57,7 @@ function checkVisible ({ api, isApiConnected, isApiReady }: ApiProps, allowTelep
return false;
}
return findMissingApis(api, needsApi).length === 0;
return findMissingApis(api, needsApi, needsApiInstances).length === 0;
}
function extractGroups (routing: Routes, groupNames: Record<string, string>, apiProps: ApiProps, allowTeleport: boolean, hasAccounts: boolean, hasSudo: boolean): Group[] {

View File

@ -4,26 +4,28 @@
import { ApiPromise } from '@polkadot/api';
import { isFunction } from '@polkadot/util';
function hasEndpoint (api: ApiPromise, endpoint: string): boolean {
const [area, section, method] = endpoint.split('.');
type ApiMapper = Record<string, Record<string, Record<string, unknown>>>;
function hasEndpoint (api: ApiPromise, endpoint: string, needsApiInstances: boolean): boolean {
const [area, _section, method] = endpoint.split('.');
const [section] = (needsApiInstances && api.registry.getModuleInstances(api.runtimeVersion.specName.toString(), _section)) || [_section];
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
return isFunction((api as any)[area][section][method]);
return isFunction((api as unknown as ApiMapper)[area][section][method]);
} catch (error) {
return false;
}
}
export function findMissingApis (api: ApiPromise, needsApi?: (string | string[])[]): (string | string[])[] {
export function findMissingApis (api: ApiPromise, needsApi?: (string | string[])[], needsApiInstances = false): (string | string[])[] {
if (!needsApi) {
return [];
}
return needsApi.filter((endpoint: string | string[]): boolean => {
const hasApi = Array.isArray(endpoint)
? endpoint.reduce((hasApi, endpoint) => hasApi || hasEndpoint(api, endpoint), false)
: hasEndpoint(api, endpoint);
? endpoint.reduce((hasApi, endpoint) => hasApi || hasEndpoint(api, endpoint, needsApiInstances), false)
: hasEndpoint(api, endpoint, needsApiInstances);
return !hasApi;
});

View File

@ -26,7 +26,7 @@ const BOUNTY_METHODS = ['approveBounty', 'closeBounty'];
function BountyInitiateVoting ({ description, index, proposals }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const { api } = useApi();
const { isMember, members } = useMembers();
const { isMember, members } = useMembers('council');
const { approveBounty, closeBounty } = useBounties();
const [isOpen, toggleOpen] = useToggle();
const [accountId, setAccountId] = useState<string | null>(null);

View File

@ -28,7 +28,7 @@ const BOUNTY_METHODS = ['proposeCurator'];
function ProposeCuratorAction ({ description, index, proposals, value }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const { api } = useApi();
const { isMember, members } = useMembers();
const { isMember, members } = useMembers('council');
const { proposeCurator } = useBounties();
const [isOpen, toggleOpen] = useToggle();
const [accountId, setAccountId] = useState<string | null>(null);

View File

@ -23,7 +23,7 @@ interface Props {
function CloseBounty ({ description, index, toggleOpen }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const { api } = useApi();
const { members } = useMembers();
const { members } = useMembers('council');
const { closeBounty } = useBounties();
const [accountId, setAccountId] = useState<string | null>(null);
const [threshold, setThreshold] = useState<BN>();

View File

@ -38,7 +38,7 @@ interface ActionProperties {
function SlashCurator ({ action, curatorId, description, index, toggleOpen }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const { api } = useApi();
const { members } = useMembers();
const { members } = useMembers('council');
const { unassignCurator } = useBounties();
const [accountId, setAccountId] = useState<string | null>(null);
const [threshold, setThreshold] = useState<BN>();

View File

@ -36,7 +36,7 @@ function Index ({ bestNumber, className, description, index, proposals, status }
const [isGiveUpCuratorOpen, toggleGiveUpCurator] = useToggle();
const [selectedAction, setSlashAction] = useState<ValidUnassignCuratorAction>();
const { t } = useTranslation();
const { isMember } = useMembers();
const { isMember } = useMembers('council');
const { curator, updateDue } = useBountyStatus(status);
const blocksUntilUpdate = useMemo(() => updateDue?.sub(bestNumber), [bestNumber, updateDue]);

View File

@ -20,7 +20,7 @@ interface Props {
}
function VotingSummary ({ className, proposal, status }: Props): JSX.Element {
const { members } = useMembers();
const { members } = useMembers('council');
const { t } = useTranslation();
const ayes = useMemo(() => proposal?.votes?.ayes?.length, [proposal]);
const nays = useMemo(() => proposal?.votes?.nays?.length, [proposal]);

View File

@ -14,7 +14,7 @@ export type UserRolesInfo = { roles: UserRole[], isCurator: boolean };
export function useUserRole (curatorId?: AccountId): UserRolesInfo {
const { allAccounts, hasAccounts } = useAccounts();
const { isMember } = useMembers();
const { isMember } = useMembers('council');
const isCurator = useMemo(() => curatorId && allAccounts.includes(curatorId.toString()), [allAccounts, curatorId]);

View File

@ -9,6 +9,7 @@ import { Button, InputAddress, Modal, ProposedAction, TxButton } from '@polkadot
import { useApi, useToggle, useWeight } from '@polkadot/react-hooks';
import { useTranslation } from '../translate';
import { useModuleCouncil } from '../useModuleCouncil';
interface Props {
hasFailed: boolean;
@ -24,9 +25,10 @@ function Close ({ hasFailed, hash, idNumber, members, proposal }: Props): React.
const [isOpen, toggleOpen] = useToggle();
const [accountId, setAccountId] = useState<string | null>(null);
const [proposalWeight, proposalLength] = useWeight(proposal);
const modLocation = useModuleCouncil();
// protect against older versions
if (!api.tx.council.close) {
if (!modLocation) {
return null;
}
@ -59,13 +61,13 @@ function Close ({ hasFailed, hash, idNumber, members, proposal }: Props): React.
accountId={accountId}
onStart={toggleOpen}
params={
api.tx.council.close.meta.args.length === 4
api.tx[modLocation].close.meta.args.length === 4
? hasFailed
? [hash, idNumber, 0, 0]
: [hash, idNumber, proposalWeight, proposalLength]
: [hash, idNumber]
}
tx={api.tx.council.closeOperational || api.tx.council.close}
tx={api.tx[modLocation].closeOperational || api.tx[modLocation].close}
/>
</Modal.Actions>
</Modal>

View File

@ -13,6 +13,7 @@ import { BlockToTime } from '@polkadot/react-query';
import { formatNumber } from '@polkadot/util';
import { useTranslation } from '../translate';
import { useModuleCouncil } from '../useModuleCouncil';
import Close from './Close';
import Voters from './Voters';
import Voting from './Voting';
@ -22,7 +23,7 @@ interface Props {
isMember: boolean;
members: string[];
motion: DeriveCollectiveProposal;
prime: AccountId | null;
prime?: AccountId | null;
}
interface VoterState {
@ -36,6 +37,7 @@ function Motion ({ className = '', isMember, members, motion: { hash, proposal,
const { allAccounts } = useAccounts();
const { hasFailed, isCloseable, isVoteable, remainingBlocks } = useVotingStatus(votes, members.length, 'council');
const [proposalWeight, proposalLength] = useWeight(proposal);
const modLocation = useModuleCouncil();
const [councilId, isMultiMembers] = useMemo(
(): [string | null, boolean] => {
@ -62,7 +64,7 @@ function Motion ({ className = '', isMember, members, motion: { hash, proposal,
[allAccounts, votes]
);
if (!votes) {
if (!votes || !modLocation) {
return null;
}
@ -127,13 +129,13 @@ function Motion ({ className = '', isMember, members, motion: { hash, proposal,
icon='times'
label={t<string>('Close')}
params={
api.tx.council.close?.meta.args.length === 4
api.tx[modLocation].close?.meta.args.length === 4
? hasFailed
? [hash, index, 0, 0]
: [hash, index, proposalWeight, proposalLength]
: [hash, index]
}
tx={api.tx.council.closeOperational || api.tx.council.close}
tx={api.tx[modLocation].closeOperational || api.tx[modLocation].close}
/>
)
)}

View File

@ -11,6 +11,7 @@ import { useApi, useToggle } from '@polkadot/react-hooks';
import { isHex } from '@polkadot/util';
import { useTranslation } from '../translate';
import { useModuleCouncil } from '../useModuleCouncil';
interface Props {
className?: string;
@ -28,13 +29,14 @@ interface ProposalState {
proposalLength: number;
}
function ProposeExternal ({ className = '', isMember, members }: Props): React.ReactElement<Props> {
function ProposeExternal ({ className = '', isMember, members }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const { api } = useApi();
const [isVisible, toggleVisible] = useToggle();
const [accountId, setAcountId] = useState<string | null>(null);
const [{ proposal, proposalLength }, setProposal] = useState<ProposalState>({ proposalLength: 0 });
const [{ hash, isHashValid }, setHash] = useState<HashState>({ hash: '', isHashValid: false });
const modLocation = useModuleCouncil();
const threshold = Math.ceil((members.length || 0) * getProposalThreshold(api));
@ -59,6 +61,10 @@ function ProposeExternal ({ className = '', isMember, members }: Props): React.R
}
}, [api, hash, isHashValid]);
if (!modLocation) {
return null;
}
return (
<>
<Button
@ -88,6 +94,7 @@ function ProposeExternal ({ className = '', isMember, members }: Props): React.R
<Input
autoFocus
help={t<string>('The preimage hash of the proposal')}
isError={!isHashValid}
label={t<string>('preimage hash')}
onChange={_onChangeHash}
value={hash}
@ -102,11 +109,11 @@ function ProposeExternal ({ className = '', isMember, members }: Props): React.R
label={t<string>('Propose')}
onStart={toggleVisible}
params={
api.tx.council.propose.meta.args.length === 3
api.tx[modLocation].propose.meta.args.length === 3
? [threshold, proposal, proposalLength]
: [threshold, proposal]
}
tx={api.tx.council.propose}
tx={api.tx[modLocation].propose}
/>
</Modal.Actions>
</Modal>

View File

@ -12,6 +12,7 @@ import { useApi, useToggle } from '@polkadot/react-hooks';
import { BN_ZERO } from '@polkadot/util';
import { useTranslation } from '../translate';
import { useModuleCouncil } from '../useModuleCouncil';
interface Props {
isMember: boolean;
@ -28,13 +29,14 @@ interface ProposalState {
proposalLength: number;
}
function Propose ({ isMember, members }: Props): React.ReactElement<Props> {
function Propose ({ isMember, members }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const { api, apiDefaultTxSudo } = useApi();
const [isOpen, toggleOpen] = useToggle();
const [accountId, setAcountId] = useState<string | null>(null);
const [{ proposal, proposalLength }, setProposal] = useState<ProposalState>({ proposalLength: 0 });
const [{ isThresholdValid, threshold }, setThreshold] = useState<Threshold>({ isThresholdValid: false });
const modLocation = useModuleCouncil();
useEffect((): void => {
members && setThreshold({
@ -59,6 +61,10 @@ function Propose ({ isMember, members }: Props): React.ReactElement<Props> {
[]
);
if (!modLocation) {
return null;
}
return (
<>
<Button
@ -109,11 +115,11 @@ function Propose ({ isMember, members }: Props): React.ReactElement<Props> {
label={t<string>('Propose')}
onStart={toggleOpen}
params={
api.tx.council.propose.meta.args.length === 3
api.tx[modLocation].propose.meta.args.length === 3
? [threshold, proposal, proposalLength]
: [threshold, proposal]
}
tx={api.tx.council.propose}
tx={api.tx[modLocation].propose}
/>
</Modal.Actions>
</Modal>

View File

@ -10,6 +10,7 @@ import { Button, Dropdown, Input, InputAddress, Modal, TxButton } from '@polkado
import { useApi, useAvailableSlashes, useToggle } from '@polkadot/react-hooks';
import { useTranslation } from '../translate';
import { useModuleCouncil } from '../useModuleCouncil';
interface Props {
className?: string;
@ -27,7 +28,7 @@ interface ProposalState {
proposalLength: number;
}
function Slashing ({ className = '', isMember, members }: Props): React.ReactElement<Props> {
function Slashing ({ className = '', isMember, members }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const { api } = useApi();
const slashes = useAvailableSlashes();
@ -35,6 +36,7 @@ function Slashing ({ className = '', isMember, members }: Props): React.ReactEle
const [accountId, setAcountId] = useState<string | null>(null);
const [{ proposal, proposalLength }, setProposal] = useState<ProposalState>({ proposal: null, proposalLength: 0 });
const [selectedEra, setSelectedEra] = useState(0);
const modLocation = useModuleCouncil();
const threshold = Math.ceil((members.length || 0) * getSlashProposalThreshold(api));
@ -63,6 +65,10 @@ function Slashing ({ className = '', isMember, members }: Props): React.ReactEle
});
}, [api, selectedEra, slashes]);
if (!modLocation) {
return null;
}
return (
<>
<Button
@ -117,11 +123,11 @@ function Slashing ({ className = '', isMember, members }: Props): React.ReactEle
label={t<string>('Revert')}
onStart={toggleVisible}
params={
api.tx.council.propose.meta.args.length === 3
api.tx[modLocation].propose.meta.args.length === 3
? [threshold, proposal, proposalLength]
: [threshold, proposal]
}
tx={api.tx.council.propose}
tx={api.tx[modLocation].propose}
/>
</Modal.Actions>
</Modal>

View File

@ -9,13 +9,14 @@ import { Button, MarkWarning, Modal, ProposedAction, TxButton, VoteAccount } fro
import { useAccounts, useApi, useToggle } from '@polkadot/react-hooks';
import { useTranslation } from '../translate';
import { useModuleCouncil } from '../useModuleCouncil';
interface Props {
hash: Hash;
idNumber: ProposalIndex;
isDisabled: boolean;
members: string[];
prime: AccountId | null;
prime?: AccountId | null;
proposal: Proposal;
}
@ -25,8 +26,9 @@ function Voting ({ hash, idNumber, isDisabled, members, prime, proposal }: Props
const { hasAccounts } = useAccounts();
const [isVotingOpen, toggleVoting] = useToggle();
const [accountId, setAccountId] = useState<string | null>(null);
const modLocation = useModuleCouncil();
if (!hasAccounts) {
if (!hasAccounts || !modLocation) {
return null;
}
@ -64,7 +66,7 @@ function Voting ({ hash, idNumber, isDisabled, members, prime, proposal }: Props
label={t<string>('Vote Nay')}
onStart={toggleVoting}
params={[hash, idNumber, false]}
tx={api.tx.council.vote}
tx={api.tx[modLocation].vote}
/>
<TxButton
accountId={accountId}
@ -73,7 +75,7 @@ function Voting ({ hash, idNumber, isDisabled, members, prime, proposal }: Props
label={t<string>('Vote Aye')}
onStart={toggleVoting}
params={[hash, idNumber, true]}
tx={api.tx.council.vote}
tx={api.tx[modLocation].vote}
/>
</Modal.Actions>
</Modal>

View File

@ -18,12 +18,12 @@ import Slashing from './Slashing';
interface Props {
className?: string;
motions?: DeriveCollectiveProposal[];
prime: AccountId | null;
prime?: AccountId | null;
}
function Proposals ({ className = '', motions, prime }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { isMember, members } = useMembers();
const { isMember, members } = useMembers('council');
const headerRef = useRef([
[t('motions'), 'start', 2],

View File

@ -9,17 +9,18 @@ import { Button, InputAddress, InputBalance, Modal, TxButton } from '@polkadot/r
import { useApi, useModal } from '@polkadot/react-hooks';
import { useTranslation } from '../translate';
import { useModuleElections } from '../useModuleElections';
function SubmitCandidacy ({ electionsInfo }: Props): React.ReactElement<Props> {
function SubmitCandidacy ({ electionsInfo }: Props): React.ReactElement<Props> | null {
const { api } = useApi();
const { t } = useTranslation();
const [accountId, setAcountId] = useState<string | null>(null);
const { isOpen, onClose, onOpen } = useModal();
const modLocation = api.tx.phragmenElection
? 'phragmenElection'
: api.tx.electionsPhragmen
? 'electionsPhragmen'
: 'elections';
const modLocation = useModuleElections();
if (!modLocation) {
return null;
}
return (
<>
@ -38,14 +39,16 @@ function SubmitCandidacy ({ electionsInfo }: Props): React.ReactElement<Props> {
type='account'
/>
</Modal.Columns>
<Modal.Columns hint={t('The bond will be reserved for the duration of your candidacy and membership.')}>
<InputBalance
defaultValue={api.consts[modLocation].candidacyBond}
help={t<string>('The bond that is reserved')}
isDisabled
label={t<string>('candidacy bond')}
/>
</Modal.Columns>
{api.consts[modLocation] && (
<Modal.Columns hint={t('The bond will be reserved for the duration of your candidacy and membership.')}>
<InputBalance
defaultValue={api.consts[modLocation].candidacyBond}
help={t<string>('The bond that is reserved')}
isDisabled
label={t<string>('candidacy bond')}
/>
</Modal.Columns>
)}
</Modal.Content>
<Modal.Actions onCancel={onClose}>
<TxButton
@ -57,7 +60,7 @@ function SubmitCandidacy ({ electionsInfo }: Props): React.ReactElement<Props> {
? [electionsInfo?.candidates.length]
: []
}
tx={(api.tx.phragmenElection || api.tx.electionsPhragmen || api.tx.elections).submitCandidacy}
tx={api.tx[modLocation].submitCandidacy}
/>
</Modal.Actions>
</Modal>

View File

@ -8,7 +8,7 @@ import type { ComponentProps } from './types';
import React from 'react';
import { CardSummary, SummaryBox } from '@polkadot/react-components';
import { formatNumber } from '@polkadot/util';
import { BN_ZERO, formatNumber } from '@polkadot/util';
import { useTranslation } from '../translate';
@ -31,10 +31,10 @@ function Summary ({ bestNumber, className = '', electionsInfo }: Props): React.R
<SummaryBox className={className}>
<section>
<CardSummary label={t<string>('seats')}>
{formatNumber(members.length)}&nbsp;/&nbsp;{formatNumber(desiredSeats)}
{formatNumber(members.length)}{desiredSeats && <>&nbsp;/&nbsp;{formatNumber(desiredSeats)}</>}
</CardSummary>
<CardSummary label={t<string>('runners up')}>
{formatNumber(runnersUp.length)}&nbsp;/&nbsp;{formatNumber(desiredRunnersUp)}
{formatNumber(runnersUp.length)}{desiredRunnersUp && <>&nbsp;/&nbsp;{formatNumber(desiredRunnersUp)}</>}
</CardSummary>
<CardSummary label={t<string>('candidates')}>
{formatNumber(candidateCount)}
@ -47,7 +47,7 @@ function Summary ({ bestNumber, className = '', electionsInfo }: Props): React.R
</CardSummary>
</section>
)}
{bestNumber && termDuration?.gtn(0) && (
{bestNumber && termDuration && termDuration.gt(BN_ZERO) && (
<section>
<CardSummary
label={t<string>('term progress')}

View File

@ -11,6 +11,7 @@ import { useApi, useToggle } from '@polkadot/react-hooks';
import { BN_ZERO } from '@polkadot/util';
import { useTranslation } from '../translate';
import { useModuleElections } from '../useModuleElections';
interface Props {
className?: string;
@ -19,7 +20,7 @@ interface Props {
const MAX_VOTES = 16;
function Vote ({ electionsInfo }: Props): React.ReactElement<Props> {
function Vote ({ electionsInfo }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const { api } = useApi();
const [isVisible, toggleVisible] = useToggle();
@ -28,6 +29,7 @@ function Vote ({ electionsInfo }: Props): React.ReactElement<Props> {
const [defaultVotes, setDefaultVotes] = useState<string[]>([]);
const [votes, setVotes] = useState<string[]>([]);
const [voteValue, setVoteValue] = useState(BN_ZERO);
const modLocation = useModuleElections();
useEffect((): void => {
if (electionsInfo) {
@ -46,8 +48,8 @@ function Vote ({ electionsInfo }: Props): React.ReactElement<Props> {
accountId && api.derive.council.votesOf(accountId).then(({ votes }): void => {
setDefaultVotes(
votes
.map((accountId) => accountId.toString())
.filter((accountId) => available.includes(accountId))
.map((a) => a.toString())
.filter((a) => available.includes(a))
);
});
}, [api, accountId, available]);
@ -56,11 +58,17 @@ function Vote ({ electionsInfo }: Props): React.ReactElement<Props> {
(): BN | undefined => {
const location = api.consts.elections || api.consts.phragmenElection || api.consts.electionsPhragmen;
return location?.votingBondBase && location.votingBondBase.add(location.votingBondFactor.muln(votes.length));
return location &&
location.votingBondBase &&
location.votingBondBase.add(location.votingBondFactor.muln(votes.length));
},
[api, votes]
);
if (!modLocation) {
return null;
}
return (
<>
<Button
@ -124,7 +132,7 @@ function Vote ({ electionsInfo }: Props): React.ReactElement<Props> {
isDisabled={!defaultVotes.length}
label={t<string>('Unvote all')}
onStart={toggleVisible}
tx={(api.tx.phragmenElection || api.tx.electionsPhragmen || api.tx.elections).removeVoter}
tx={api.tx[modLocation].removeVoter}
/>
<TxButton
accountId={accountId}
@ -132,7 +140,7 @@ function Vote ({ electionsInfo }: Props): React.ReactElement<Props> {
label={t<string>('Vote')}
onStart={toggleVisible}
params={[votes, voteValue]}
tx={(api.tx.phragmenElection || api.tx.electionsPhragmen || api.tx.elections).vote}
tx={api.tx[modLocation].vote}
/>
</Modal.Actions>
</Modal>

View File

@ -17,7 +17,7 @@ import Vote from './Vote';
interface Props {
className?: string;
prime: AccountId | null;
prime?: AccountId | null;
}
const transformVotes = {

View File

@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
import type { DeriveCollectiveProposal } from '@polkadot/api-derive/types';
import type { Option } from '@polkadot/types';
import type { AccountId } from '@polkadot/types/interfaces';
import React, { useMemo } from 'react';
@ -25,16 +24,12 @@ interface Props {
className?: string;
}
const transformPrime = {
transform: (result: Option<AccountId>): AccountId | null => result.unwrapOr(null)
};
function CouncilApp ({ basePath, className }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const { pathname } = useLocation();
const numMotions = useCounter();
const prime = useCall<AccountId | null>(api.query.council.prime, undefined, transformPrime) || null;
const prime = useCall<AccountId | null>(api.derive.council.prime);
const motions = useCall<DeriveCollectiveProposal[]>(api.derive.council.proposals);
const items = useMemo(() => [

View File

@ -1,4 +1,4 @@
// Copyright 2017-2021 @polkadot/app-democracy authors & contributors
// Copyright 2017-2021 @polkadot/app-council authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { DeriveCollectiveProposal } from '@polkadot/api-derive/types';

View File

@ -0,0 +1,22 @@
// Copyright 2017-2021 @polkadot/app-council authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { useMemo } from 'react';
import { useApi } from '@polkadot/react-hooks';
import { isFunction } from '@polkadot/util';
export function useModuleCouncil (): string | null {
const { api } = useApi();
return useMemo(
(): string | null => {
const [instance] = api.registry.getModuleInstances(api.runtimeVersion.specName.toString(), 'council') || ['council'];
return isFunction(api.tx[instance as 'council']?.close)
? instance
: null;
},
[api]
);
}

View File

@ -0,0 +1,22 @@
// Copyright 2017-2021 @polkadot/app-council authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { useMemo } from 'react';
import { useApi } from '@polkadot/react-hooks';
export function useModuleElections (): string | null {
const { api } = useApi();
return useMemo(
(): string | null =>
api.tx.phragmenElection
? 'phragmenElection'
: api.tx.electionsPhragmen
? 'electionsPhragmen'
: api.tx.elections
? 'elections'
: null,
[api]
);
}

View File

@ -8,12 +8,13 @@ import { useEffect, useState } from 'react';
import { useAccounts, useApi, useCall } from '@polkadot/react-hooks';
const EMPTY_MEMBERS: OwnMembers = { allMembers: [], isMember: false, ownMembers: [] };
function transform (allAccounts: string[], members: DeriveSocietyMember[]): OwnMembers {
const allMembers = members
.filter((member) => !member.isSuspended)
.filter(({ isSuspended }) => !isSuspended)
.map(({ accountId }) => accountId.toString());
const ownMembers = allMembers
.filter((address) => allAccounts.includes(address));
const ownMembers = allMembers.filter((a) => allAccounts.includes(a));
return { allMembers, isMember: ownMembers.length !== 0, ownMembers };
}
@ -21,8 +22,8 @@ function transform (allAccounts: string[], members: DeriveSocietyMember[]): OwnM
export default function useMembers (): OwnMembers {
const { api } = useApi();
const { allAccounts } = useAccounts();
const [state, setState] = useState<OwnMembers>({ allMembers: [], isMember: false, ownMembers: [] });
const members = useCall<DeriveSocietyMember[]>(api.derive.society?.members);
const [state, setState] = useState<OwnMembers>(EMPTY_MEMBERS);
const members = useCall<DeriveSocietyMember[]>(api.derive.society.members);
useEffect((): void => {
allAccounts && members && setState(

View File

@ -90,7 +90,7 @@ function Slashes ({ ownStashes = [], slashes }: Props): React.ReactElement<Props
const { t } = useTranslation();
const { api } = useApi();
const { allAccounts } = useAccounts();
const { members } = useMembers();
const { members } = useMembers('council');
const [selectedIndex, setSelectedIndex] = useState(0);
const rows = useMemo(

View File

@ -1,7 +1,6 @@
// Copyright 2017-2021 @polkadot/app-tech-comm authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Option } from '@polkadot/types';
import type { AccountId, Hash } from '@polkadot/types/interfaces';
import React, { useMemo } from 'react';
@ -9,7 +8,6 @@ import { Route, Switch } from 'react-router';
import { Tabs } from '@polkadot/react-components';
import { useApi, useCall, useMembers } from '@polkadot/react-hooks';
import { isFunction } from '@polkadot/util';
import Overview from './Overview';
import Proposals from './Proposals';
@ -21,16 +19,16 @@ interface Props {
type: 'membership' | 'technicalCommittee';
}
const transformPrime = {
transform: (result: Option<AccountId>): AccountId | null => result.unwrapOr(null)
};
const HIDDEN_EMPTY: string[] = [];
const HIDDEN_PROPOSALS: string[] = ['proposals'];
function TechCommApp ({ basePath, className, type }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const { isMember, members } = useMembers(type);
const prime = useCall<AccountId | null>(api.query[type].prime, undefined, transformPrime) || null;
const proposals = useCall<Hash[]>(api.query[type].proposals);
const prime = useCall<AccountId | null>(api.derive[type].prime);
const hasProposals = useCall<boolean>(api.derive[type].hasProposals);
const proposalHashes = useCall<Hash[]>(api.derive[type].proposalHashes);
const items = useMemo(() => [
{
@ -40,20 +38,19 @@ function TechCommApp ({ basePath, className, type }: Props): React.ReactElement<
},
{
name: 'proposals',
text: t<string>('Proposals ({{count}})', { replace: { count: (proposals && proposals.length) || 0 } })
text: t<string>('Proposals ({{count}})', { replace: { count: (proposalHashes && proposalHashes.length) || 0 } })
}
], [proposals, t]);
const hidden = useMemo(
() => isFunction(api.query[type].proposals) ? [] : ['proposals'],
[api, type]
);
], [proposalHashes, t]);
return (
<main className={className}>
<Tabs
basePath={basePath}
hidden={hidden}
hidden={
hasProposals
? HIDDEN_EMPTY
: HIDDEN_PROPOSALS
}
items={items}
/>
<Switch>
@ -62,7 +59,7 @@ function TechCommApp ({ basePath, className, type }: Props): React.ReactElement<
isMember={isMember}
members={members}
prime={prime}
proposals={proposals}
proposalHashes={proposalHashes}
type={type}
/>
</Route>
@ -71,7 +68,7 @@ function TechCommApp ({ basePath, className, type }: Props): React.ReactElement<
isMember={isMember}
members={members}
prime={prime}
proposals={proposals}
proposalHashes={proposalHashes}
type={type}
/>
</Route>

View File

@ -8,24 +8,24 @@ import React from 'react';
import { CardSummary, SummaryBox } from '@polkadot/react-components';
import { useApi, useCall } from '@polkadot/react-hooks';
import { formatNumber, isFunction } from '@polkadot/util';
import { formatNumber } from '@polkadot/util';
import { useTranslation } from '../translate';
function Summary ({ className = '', members, proposals, type }: Props): React.ReactElement<Props> {
function Summary ({ className = '', members, proposalHashes, type }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const proposalCount = useCall<u32>(api.query[type].proposalCount);
const proposalCount = useCall<u32>(api.derive[type].proposalCount);
return (
<SummaryBox className={className}>
<CardSummary label={t<string>('members')}>
{formatNumber(members.length)}
</CardSummary>
{isFunction(api.query[type].proposalCount) && (
{proposalCount && (
<section>
<CardSummary label={t<string>('proposals')}>
{formatNumber(proposals?.length)}
{formatNumber(proposalHashes?.length)}
</CardSummary>
<CardSummary label={t<string>('total')}>
{formatNumber(proposalCount)}

View File

@ -8,13 +8,13 @@ import React from 'react';
import Members from './Members';
import Summary from './Summary';
function Overview ({ className = '', isMember, members, prime, proposals, type }: Props): React.ReactElement<Props> {
function Overview ({ className = '', isMember, members, prime, proposalHashes, type }: Props): React.ReactElement<Props> {
return (
<div className={className}>
<Summary
isMember={isMember}
members={members}
proposals={proposals}
proposalHashes={proposalHashes}
type={type}
/>
<Members

View File

@ -9,6 +9,7 @@ import { Button, InputAddress, Modal, ProposedAction, TxButton } from '@polkadot
import { useApi, useToggle, useWeight } from '@polkadot/react-hooks';
import { useTranslation } from '../translate';
import { useModuleCollective } from '../useModuleCollective';
interface Props {
hasFailed: boolean;
@ -25,8 +26,9 @@ function Close ({ hasFailed, hash, idNumber, members, proposal, type }: Props):
const [isOpen, toggleOpen] = useToggle();
const [accountId, setAccountId] = useState<string | null>(null);
const [proposalWeight, proposalLength] = useWeight(proposal);
const modLocation = useModuleCollective(type);
if (!api.tx[type].close) {
if (!modLocation) {
return null;
}
@ -59,13 +61,13 @@ function Close ({ hasFailed, hash, idNumber, members, proposal, type }: Props):
accountId={accountId}
onStart={toggleOpen}
params={
api.tx[type].close.meta.args.length === 4
api.tx[modLocation].close.meta.args.length === 4
? hasFailed
? [hash, idNumber, 0, 0]
: [hash, idNumber, proposalWeight, proposalLength]
: [hash, idNumber]
}
tx={api.tx[type].closeOperational || api.tx[type].close}
tx={api.tx[modLocation].closeOperational || api.tx[modLocation].close}
/>
</Modal.Actions>
</Modal>

View File

@ -1,8 +1,8 @@
// Copyright 2017-2021 @polkadot/app-tech-comm authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Option } from '@polkadot/types';
import type { AccountId, Hash, Proposal as ProposalType, Votes } from '@polkadot/types/interfaces';
import type { DeriveCollectiveProposal } from '@polkadot/api-derive/types';
import type { AccountId, Hash } from '@polkadot/types/interfaces';
import React, { useMemo } from 'react';
@ -13,6 +13,7 @@ import { BlockToTime } from '@polkadot/react-query';
import { formatNumber } from '@polkadot/util';
import { useTranslation } from '../translate';
import { useModuleCollective } from '../useModuleCollective';
import Close from './Close';
import Voting from './Voting';
@ -25,22 +26,14 @@ interface Props {
type: 'membership' | 'technicalCommittee';
}
const transformProposal = {
transform: (optProp: Option<ProposalType>) => optProp.unwrapOr(null)
};
const transformVotes = {
transform: (optVotes: Option<Votes>) => optVotes.unwrapOr(null)
};
function Proposal ({ className = '', imageHash, members, prime, type }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const { api } = useApi();
const { allAccounts } = useAccounts();
const proposal = useCall<ProposalType | null>(api.query[type].proposalOf, [imageHash], transformProposal);
const votes = useCall<Votes | null>(api.query[type].voting, [imageHash], transformVotes);
const { hasFailed, isCloseable, isVoteable, remainingBlocks } = useVotingStatus(votes, members.length, type);
const [proposalWeight, proposalLength] = useWeight(proposal);
const derive = useCall<DeriveCollectiveProposal>(api.derive[type].proposal, [imageHash]);
const { hasFailed, isCloseable, isVoteable, remainingBlocks } = useVotingStatus(derive?.votes, members.length, type);
const [proposalWeight, proposalLength] = useWeight(derive?.proposal);
const modLocation = useModuleCollective(type);
const [councilId, isMultiMembers] = useMemo(
(): [string | null, boolean] => {
@ -51,18 +44,18 @@ function Proposal ({ className = '', imageHash, members, prime, type }: Props):
[allAccounts, members]
);
if (!proposal || !votes) {
if (!modLocation || !derive || !derive.votes) {
return null;
}
const { ayes, end, index, nays, threshold } = votes;
const { ayes, end, index, nays, threshold } = derive.votes;
return (
<tr className={className}>
<td className='number'><h1>{formatNumber(index)}</h1></td>
<ProposalCell
imageHash={imageHash}
proposal={proposal}
proposal={derive.proposal}
/>
<td className='number'>
{formatNumber(ayes.length)}/{formatNumber(threshold)}
@ -111,7 +104,7 @@ function Proposal ({ className = '', imageHash, members, prime, type }: Props):
hash={imageHash}
idNumber={index}
members={members}
proposal={proposal}
proposal={derive.proposal}
type={type}
/>
)
@ -121,13 +114,13 @@ function Proposal ({ className = '', imageHash, members, prime, type }: Props):
icon='times'
label={t<string>('Close')}
params={
api.tx[type].close?.meta.args.length === 4
api.tx[modLocation].close?.meta.args.length === 4
? hasFailed
? [imageHash, index, 0, 0]
: [imageHash, index, proposalWeight, proposalLength]
: [imageHash, index]
}
tx={api.tx[type].closeOperational || api.tx[type].close}
tx={api.tx[modLocation].closeOperational || api.tx[modLocation].close}
/>
)
)}

View File

@ -10,6 +10,7 @@ import { Button, Extrinsic, InputAddress, InputNumber, Modal, TxButton } from '@
import { useApi, useModal } from '@polkadot/react-hooks';
import { useTranslation } from '../translate';
import { useModuleCollective } from '../useModuleCollective';
interface Props {
isMember: boolean;
@ -22,7 +23,7 @@ interface ProposalState {
proposalLength: number;
}
function Propose ({ isMember, members, type }: Props): React.ReactElement<Props> {
function Propose ({ isMember, members, type }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const { api, apiDefaultTxSudo } = useApi();
const { isOpen, onClose, onOpen } = useModal();
@ -32,6 +33,7 @@ function Propose ({ isMember, members, type }: Props): React.ReactElement<Props>
new BN(members.length / 2 + 1),
true
]);
const modLocation = useModuleCollective(type);
const _hasThreshold = useCallback(
(threshold?: BN | null): boolean =>
@ -51,6 +53,10 @@ function Propose ({ isMember, members, type }: Props): React.ReactElement<Props>
[_hasThreshold]
);
if (!modLocation) {
return null;
}
return (
<>
{isOpen && (
@ -88,11 +94,11 @@ function Propose ({ isMember, members, type }: Props): React.ReactElement<Props>
isDisabled={!hasThreshold || !proposal}
onStart={onClose}
params={
api.tx[type].propose.meta.args.length === 3
api.tx[modLocation].propose.meta.args.length === 3
? [threshold, proposal, proposalLength]
: [threshold, proposal]
}
tx={api.tx[type].propose}
tx={api.tx[modLocation].propose}
/>
</Modal.Actions>
</Modal>

View File

@ -10,6 +10,7 @@ import { Button, MarkWarning, Modal, TxButton, VoteAccount } from '@polkadot/rea
import { useAccounts, useApi, useToggle } from '@polkadot/react-hooks';
import { useTranslation } from '../translate';
import { useModuleCollective } from '../useModuleCollective';
interface Props {
hash: Hash | string;
@ -25,8 +26,9 @@ function Voting ({ hash, members, prime, proposalId, type }: Props): React.React
const { hasAccounts } = useAccounts();
const [accountId, setAccountId] = useState<string | null>(null);
const [isVotingOpen, toggleVoting] = useToggle();
const modLocation = useModuleCollective(type);
if (!hasAccounts) {
if (!modLocation || !hasAccounts) {
return null;
}
@ -53,7 +55,7 @@ function Voting ({ hash, members, prime, proposalId, type }: Props): React.React
label={t<string>('Vote Nay')}
onStart={toggleVoting}
params={[hash, proposalId, false]}
tx={api.tx[type].vote}
tx={api.tx[modLocation].vote}
/>
<TxButton
accountId={accountId}
@ -61,7 +63,7 @@ function Voting ({ hash, members, prime, proposalId, type }: Props): React.React
label={t<string>('Vote Aye')}
onStart={toggleVoting}
params={[hash, proposalId, true]}
tx={api.tx[type].vote}
tx={api.tx[modLocation].vote}
/>
</Modal.Actions>
</Modal>

View File

@ -12,7 +12,7 @@ import { useTranslation } from '../translate';
import Proposal from './Proposal';
import Propose from './Propose';
function Proposals ({ className = '', isMember, members, prime, proposals, type }: Props): React.ReactElement<Props> {
function Proposals ({ className = '', isMember, members, prime, proposalHashes, type }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const headerRef = useRef([
@ -34,10 +34,10 @@ function Proposals ({ className = '', isMember, members, prime, proposals, type
/>
</Button.Group>
<Table
empty={proposals && t<string>('No committee proposals')}
empty={proposalHashes && t<string>('No committee proposals')}
header={headerRef.current}
>
{proposals?.map((hash: Hash): React.ReactNode => (
{proposalHashes?.map((hash: Hash): React.ReactNode => (
<Proposal
imageHash={hash}
isMember={isMember}

View File

@ -1,4 +1,4 @@
// Copyright 2017-2021 @polkadot/app-democracy authors & contributors
// Copyright 2017-2021 @polkadot/app-tech-comm authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { AccountId, Hash } from '@polkadot/types/interfaces';
@ -7,7 +7,7 @@ export interface ComponentProps {
className?: string;
isMember: boolean;
prime?: AccountId | null;
proposals?: Hash[];
proposalHashes?: Hash[];
members: string[];
type: 'membership' | 'technicalCommittee';
}

View File

@ -1,4 +1,4 @@
// Copyright 2017-2021 @polkadot/app-democracy authors & contributors
// Copyright 2017-2021 @polkadot/app-tech-comm authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Hash } from '@polkadot/types/interfaces';
@ -11,7 +11,7 @@ const transformCounter = {
export default function useCounter (): number {
const { api, isApiReady } = useApi();
const counter = useCall<number>(isApiReady && api.query.technicalCommittee?.proposals, undefined, transformCounter) || 0;
const counter = useCall<number>(isApiReady && api.derive.technicalCommittee?.proposals, undefined, transformCounter) || 0;
return counter;
}

View File

@ -0,0 +1,22 @@
// Copyright 2017-2021 @polkadot/app-tech-comm authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { useMemo } from 'react';
import { useApi } from '@polkadot/react-hooks';
import { isFunction } from '@polkadot/util';
export function useModuleCollective (type: 'membership' | 'technicalCommittee'): string | null {
const { api } = useApi();
return useMemo(
(): string | null => {
const [instance] = api.registry.getModuleInstances(api.runtimeVersion.specName.toString(), type) || [type];
return isFunction(api.tx[instance as 'technicalCommittee']?.close)
? instance
: null;
},
[api, type]
);
}

View File

@ -30,7 +30,7 @@ interface TabItem {
function TreasuryApp ({ basePath }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const { isMember, members } = useMembers();
const { isMember, members } = useMembers('council');
const tipHashes = useTipHashes();
const items = useMemo(() => [

View File

@ -19,10 +19,10 @@ const transformMembers = {
accounts.map((accountId) => accountId.toString())
};
export function useMembers (collective: 'council' | 'membership' | 'technicalCommittee' = 'council'): Result {
export function useMembers (collective: 'council' | 'membership' | 'technicalCommittee'): Result {
const { api } = useApi();
const { allAccounts, hasAccounts } = useAccounts();
const retrieved = useCall<string[]>(hasAccounts && api.query[collective]?.members, undefined, transformMembers);
const retrieved = useCall<string[]>(hasAccounts && api.derive[collective]?.members, undefined, transformMembers);
return useMemo(
() => ({

View File

@ -23,7 +23,12 @@ interface State {
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 {
if (!votes.end) {
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,
@ -40,11 +45,9 @@ function getStatus (api: ApiPromise, bestNumber: BlockNumber, votes: Votes, numM
return {
hasFailed,
hasPassed,
isCloseable: isFunction(api.tx[section].close)
? api.tx[section].close.meta.args.length === 4 // current-generation
? isEnd || hasPassed || hasFailed
: isEnd
: false,
isCloseable: api.tx[modLocation].close.meta.args.length === 4 // current-generation
? isEnd || hasPassed || hasFailed
: isEnd,
isVoteable: !isEnd,
remainingBlocks: isEnd
? null