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() + ); +}