From 28cf21dd4f921f4b0591523730b301a4f0d0be93 Mon Sep 17 00:00:00 2001 From: Jake Naviasky Date: Wed, 17 Jul 2019 16:15:43 -0400 Subject: [PATCH] Adding derives for election sets and approval flags. (#1141) * Adding derives for election sets and approval flags. * Bugfixes to derived election functions. * Attempting linter fix. * Fixing typing error. * Another eslint fix. * Adding explicit types to api calls. --- .../api-derive/src/elections/approvalsOf.ts | 30 +++++++++++++++++++ packages/api-derive/src/elections/voters.ts | 19 ++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 packages/api-derive/src/elections/approvalsOf.ts create mode 100644 packages/api-derive/src/elections/voters.ts diff --git a/packages/api-derive/src/elections/approvalsOf.ts b/packages/api-derive/src/elections/approvalsOf.ts new file mode 100644 index 0000000000..dc884057be --- /dev/null +++ b/packages/api-derive/src/elections/approvalsOf.ts @@ -0,0 +1,30 @@ +import BN from 'bn.js'; +import { Observable } from 'rxjs'; +import { switchMap, map } from 'rxjs/operators'; +import { ApiInterfaceRx } from '@polkadot/api/types'; +import { AccountId, Vector, SetIndex, ApprovalFlag } from '@polkadot/types'; +import { drr } from '../util/drr'; + +export function approvalFlagToBool (flags: Vector): boolean[] { + const bools: boolean[] = []; + for (const flag of flags) { + for (const bit of Array(flag.bitLength()).map((_, i): number => i)) { + bools.push(!flag.toBn().uand((new BN(1)).shln(bit)).isZero()); + } + } + return bools; +} + +export function approvalsOf (api: ApiInterfaceRx): (who: AccountId) => Observable> { + return (who: AccountId): Observable> => + api.query.elections.nextVoterSet().pipe( + switchMap((nextVoterSet: SetIndex): Observable[]> => + api.query.elections.approvalsOf.multi( + [...Array(+nextVoterSet + 1)].map((_, i): [AccountId, number] => [who, i]) + ) + ), + map((votes: Vector[]): Vector => + votes.find((v): boolean => v.length > 0) || new Vector(ApprovalFlag, [])), + drr() + ); +} diff --git a/packages/api-derive/src/elections/voters.ts b/packages/api-derive/src/elections/voters.ts new file mode 100644 index 0000000000..9f5d3b7ae6 --- /dev/null +++ b/packages/api-derive/src/elections/voters.ts @@ -0,0 +1,19 @@ +import { Observable } from 'rxjs'; +import { switchMap, map } from 'rxjs/operators'; +import { ApiInterfaceRx } from '@polkadot/api/types'; +import { AccountId, Vector, Option, SetIndex } from '@polkadot/types'; +import { drr } from '../util/drr'; + +export function voters (api: ApiInterfaceRx): () => Observable[]> { + return (): Observable[]> => + api.query.elections.nextVoterSet().pipe( + switchMap((nextVoterSet: SetIndex): Observable>[]> => + api.query.elections.voters.multi>>( + [...Array(+nextVoterSet + 1)].map((_, i): number => i) + ) + ), + map((voters: Vector>[]): Option[] => + Array.prototype.concat.apply([], voters)), + drr() + ); +}