Combine elections.info derive (#1659)

* Combine elections.info derive

* remove tests
This commit is contained in:
Keith Ingram
2019-12-09 22:05:56 +01:00
committed by Jaco Greeff
parent 019cb58dd1
commit 3a70594594
7 changed files with 14 additions and 254 deletions
@@ -1,49 +0,0 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { AccountId, ApprovalFlag, SetIndex } from '@polkadot/types/interfaces';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { Observable, of } from 'rxjs';
import { Vec } from '@polkadot/types';
import { switchMap, map } from 'rxjs/operators';
import { approvalFlagsToBools } from '../util/approvalFlagsToBools';
import { memo } from '../util';
function queryElections (api: ApiInterfaceRx, who: AccountId | string): Observable<boolean[][]> {
return api.query.elections.nextVoterSet<SetIndex>().pipe(
switchMap((nextVoterSet: SetIndex): Observable<Vec<ApprovalFlag>[]> =>
api.query.elections.approvalsOf.multi(
[...Array(nextVoterSet.toNumber() + 1).keys()].map((i): [string, number] =>
[who.toString(), i]
)
) as any as Observable<Vec<ApprovalFlag>[]>
),
map((votes: Vec<ApprovalFlag>[]): boolean[][] =>
votes.map((flags: Vec<ApprovalFlag>): boolean[] =>
approvalFlagsToBools(flags)
)
)
);
}
/**
* @name approvalsOf
* @returns A nested array of boolean approvals for the given account in each voter set index, converted from its ApprovalFlag(s).
* @example
* <BR>
*
* ```javascript
* api.derive.elections.approvalsOf(ALICE, (approvals) => {
* // approvals === [[false], [true, false], ...]
* });
* ```
*/
export function approvalsOf (api: ApiInterfaceRx): (who: AccountId | string) => Observable<boolean[][]> {
return memo((who: AccountId | string): Observable<boolean[][]> =>
api.query.elections
? queryElections(api, who)
: of([])
);
}
@@ -1,40 +0,0 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { AccountId, ApprovalFlag, SetIndex } from '@polkadot/types/interfaces';
import BN from 'bn.js';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { Vec } from '@polkadot/types';
import { approvalFlagsToBools } from '../util/approvalFlagsToBools';
import { memo } from '../util';
function queryElections (api: ApiInterfaceRx, who: AccountId | string, at: SetIndex | BN | number): Observable<boolean[]> {
return api.query.elections.approvalsOf<Vec<ApprovalFlag>>([who.toString(), at]).pipe(
map((flags: Vec<ApprovalFlag>): boolean[] => approvalFlagsToBools(flags))
);
}
/**
* @name approvalsOfAt
* @returns An array of boolean approvals for the account and set index, converted from the returned ApprovalFlag.
* @example
* <BR>
*
* ```javascript
* api.derive.elections.approvalsOfAt(ALICE, new BN(0), (approvals) => {
* // approvals === [false, true, ...]
* });
* ```
*/
export function approvalsOfAt (api: ApiInterfaceRx): (who: AccountId, at: SetIndex) => Observable<boolean[]> {
return memo((who: AccountId | string, at: SetIndex | BN | number): Observable<boolean[]> =>
api.query.elections
? queryElections(api, who, at)
: of([])
);
}
@@ -2,8 +2,4 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export * from './approvalsOf';
export * from './approvalsOfAt';
export * from './info';
export * from './voters';
export * from './voterPositions';
+14 -49
View File
@@ -2,7 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { AccountId, Balance, BlockNumber, SetIndex, VoteIndex } from '@polkadot/types/interfaces';
import { AccountId, Balance, BlockNumber } from '@polkadot/types/interfaces';
import { ITuple } from '@polkadot/types/types';
import { Observable, combineLatest } from 'rxjs';
@@ -13,40 +13,7 @@ import { createType, Vec, u32 } from '@polkadot/types';
import { DerivedElectionsInfo } from '../types';
import { memo } from '../util';
type ResultElectionsInner = [u32, u32, Vec<ITuple<[AccountId, BlockNumber]>>, SetIndex, BlockNumber, VoteIndex, SetIndex];
type ResultElections = [Vec<AccountId>, ResultElectionsInner];
function deriveElections (api: ApiInterfaceRx, [candidates, [candidateCount, desiredSeats, members, nextVoterSet, termDuration, voteCount, voterCount]]: ResultElections): DerivedElectionsInfo {
return {
candidates,
candidateCount,
desiredSeats,
nextVoterSet,
members: members.map(([accountId]): [AccountId, Balance] => [accountId, createType(api.registry, 'Balance')]),
runnersUp: [],
termDuration,
voteCount,
voterCount
};
}
function queryElections (api: ApiInterfaceRx): Observable<DerivedElectionsInfo> {
// NOTE We have an issue where candidates can return `null` for an empty array
return combineLatest([
api.query.elections.candidates<Vec<AccountId>>(),
api.queryMulti<ResultElectionsInner>([
api.query.elections.candidateCount,
api.query.elections.desiredSeats,
api.query.elections.members,
api.query.elections.nextVoterSet,
api.query.elections.termDuration,
api.query.elections.voteCount,
api.query.elections.voterCount
])
]).pipe(map((result): DerivedElectionsInfo => deriveElections(api, result)));
}
function derivePhragmen (api: ApiInterfaceRx, candidates: AccountId[], members: [AccountId, Balance][], runnersUp: [AccountId, Balance][], candidacyBond: Balance, desiredSeats: u32, termDuration: BlockNumber, votingBond: Balance): DerivedElectionsInfo {
function deriveElections (api: ApiInterfaceRx, candidates: AccountId[], members: [AccountId, Balance][], runnersUp: [AccountId, Balance][], candidacyBond: Balance, desiredSeats: u32, termDuration: BlockNumber, votingBond: Balance): DerivedElectionsInfo {
return {
candidates,
candidateCount: createType(api.registry, 'u32', candidates.length),
@@ -59,23 +26,25 @@ function derivePhragmen (api: ApiInterfaceRx, candidates: AccountId[], members:
};
}
function queryPhragmen (api: ApiInterfaceRx): Observable<DerivedElectionsInfo> {
function queryElections (api: ApiInterfaceRx): Observable<DerivedElectionsInfo> {
// NOTE We have an issue where candidates can return `null` for an empty array, hence
// we are not using multi queries here, so empty array is empty (instead of space-filled)
const section = api.query.electionPhragmen ? 'electionPhragmen' : 'elections';
return combineLatest([
api.query.electionsPhragmen.candidates<Vec<AccountId>>(),
api.query.electionsPhragmen.members<Vec<ITuple<[AccountId, Balance]>>>(),
api.query.electionsPhragmen.runnersUp<Vec<ITuple<[AccountId, Balance]>>>()
api.query[section].candidates<Vec<AccountId>>(),
api.query[section].members<Vec<ITuple<[AccountId, Balance]>>>(),
api.query[section].runnersUp<Vec<ITuple<[AccountId, Balance]>>>()
]).pipe(
map(([candidates, members, runnersUp]): DerivedElectionsInfo => derivePhragmen(
map(([candidates, members, runnersUp]): DerivedElectionsInfo => deriveElections(
api,
candidates,
members,
runnersUp,
api.consts.electionsPhragmen.candidacyBond as Balance,
api.consts.electionsPhragmen.desiredMembers as u32,
api.consts.electionsPhragmen.termDuration as BlockNumber,
api.consts.electionsPhragmen.votingBond as Balance
api.consts[section].candidacyBond as Balance,
api.consts[section].desiredMembers as u32,
api.consts[section].termDuration as BlockNumber,
api.consts[section].votingBond as Balance
))
);
}
@@ -94,9 +63,5 @@ function queryPhragmen (api: ApiInterfaceRx): Observable<DerivedElectionsInfo> {
* ```
*/
export function info (api: ApiInterfaceRx): () => Observable<DerivedElectionsInfo> {
return memo((): Observable<DerivedElectionsInfo> =>
api.query.electionsPhragmen
? queryPhragmen(api)
: queryElections(api)
);
return memo((): Observable<DerivedElectionsInfo> => queryElections(api));
}
@@ -1,62 +0,0 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { AccountId, SetIndex } from '@polkadot/types/interfaces';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { Vec, Option, createType, u32 } from '@polkadot/types';
import { DerivedVoterPositions } from '../types';
import BN from 'bn.js';
import { of, Observable } from 'rxjs';
import { switchMap, map } from 'rxjs/operators';
import { memo } from '../util';
function queryElections (api: ApiInterfaceRx): Observable<DerivedVoterPositions> {
return api.query.elections.nextVoterSet<SetIndex>().pipe(
switchMap((nextVoterSet: SetIndex): Observable<Vec<Option<AccountId>>[]> =>
api.query.elections.voters.multi<Vec<Option<AccountId>>>([...Array(+nextVoterSet + 1).keys()].map((_, i): [number] => [i]))
),
map((voters: Vec<Option<AccountId>>[]): DerivedVoterPositions => {
return voters.reduce((result: DerivedVoterPositions, vec, setIndex): DerivedVoterPositions => {
vec.forEach((e, index): void => {
// re-create the index based on position 0 is [0][0] and likewise
// 64 (0..63 in first) is [1][0] (the first index value in set 2)
const accountId: AccountId | null = e.unwrapOr(null);
if (accountId) {
result[accountId.toString()] = {
globalIndex: (api.consts.elections.voterSetSize as u32).muln(setIndex).addn(index),
index: new BN(index),
setIndex: createType(api.registry, 'SetIndex', setIndex)
};
}
});
return result;
}, {});
})
);
}
/**
* @name voterPositions
* @returns An mapping of all current voter accounts to their voter set and global index.
* @example
* <BR>
*
* ```javascript
* api.derive.elections.voterPositions((voters) => {
* const { index, setIndex, globalIndex } = voters[ALICE];
* console.log(`ALICE is a voter at index ${index} in voter set ${setIndex}, with global index ${globalIndex}.`);
* });
* ```
*/
export function voterPositions (api: ApiInterfaceRx): () => Observable<DerivedVoterPositions> {
return memo((): Observable<DerivedVoterPositions> =>
api.query.elections
? queryElections(api)
: of({})
);
}
@@ -1,46 +0,0 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiInterfaceRx } from '@polkadot/api/types';
import { AccountId } from '@polkadot/types/interfaces';
import { DerivedVoterPositions } from '../types';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { createType, Vec } from '@polkadot/types';
import { memo } from '../util';
function queryElections (api: ApiInterfaceRx): Observable<AccountId[]> {
return api.derive.elections.voterPositions().pipe(
map((voterPositions: DerivedVoterPositions): Vec<AccountId> =>
createType(
api.registry,
'Vec<AccountId>',
Object.entries(voterPositions)
.sort((a, b): number => a[1].globalIndex.cmp(b[1].globalIndex))
.map(([accountId]): AccountId => createType(api.registry, 'AccountId', accountId))
)
)
);
}
/**
* @name voters
* @returns An array of all current voters from all sets.
* @example
* <BR>
*
* ```javascript
* api.derive.elections.voters((voters) => {
* console.log(`There are ${voters.length} current voters.`);
* });
* ```
*/
export function voters (api: ApiInterfaceRx): () => Observable<AccountId[]> {
return memo((): Observable<AccountId[]> =>
api.query.elections
? queryElections(api)
: of([])
);
}
-4
View File
@@ -55,11 +55,7 @@ describe('derive', (): void => {
testFunction(api)('democracy', 'referendumVotesFor', []);
testFunction(api)('democracy', 'votes', []);
testFunction(api)('elections', 'approvalsOf', []);
// FIXME This one has an additional check which mock doesnt (yet) cater for
// testFunction(api)('elections', 'approvalsOfAt', []);
testFunction(api)('elections', 'info', []);
testFunction(api)('elections', 'voters', []);
testFunction(api)('session', 'eraLength', []);
testFunction(api)('session', 'eraProgress', []);