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()); } } const lastApproval: number = bools.lastIndexOf(true); return lastApproval >= 0 ? bools.slice(0, lastApproval + 1) : []; } 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() ); }