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.
This commit is contained in:
Jake Naviasky
2019-07-17 22:15:43 +02:00
committed by Jaco Greeff
parent 58e50f0c16
commit 28cf21dd4f
2 changed files with 49 additions and 0 deletions
@@ -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<ApprovalFlag>): 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<Vector<ApprovalFlag>> {
return (who: AccountId): Observable<Vector<ApprovalFlag>> =>
api.query.elections.nextVoterSet<SetIndex>().pipe(
switchMap((nextVoterSet: SetIndex): Observable<Vector<ApprovalFlag>[]> =>
api.query.elections.approvalsOf.multi(
[...Array(+nextVoterSet + 1)].map((_, i): [AccountId, number] => [who, i])
)
),
map((votes: Vector<ApprovalFlag>[]): Vector<ApprovalFlag> =>
votes.find((v): boolean => v.length > 0) || new Vector(ApprovalFlag, [])),
drr()
);
}
@@ -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<Option<AccountId>[]> {
return (): Observable<Option<AccountId>[]> =>
api.query.elections.nextVoterSet<SetIndex>().pipe(
switchMap((nextVoterSet: SetIndex): Observable<Vector<Option<AccountId>>[]> =>
api.query.elections.voters.multi<Vector<Option<AccountId>>>(
[...Array(+nextVoterSet + 1)].map((_, i): number => i)
)
),
map((voters: Vector<Option<AccountId>>[]): Option<AccountId>[] =>
Array.prototype.concat.apply([], voters)),
drr()
);
}