// Copyright 2017-2022 @polkadot/api-derive authors & contributors // SPDX-License-Identifier: Apache-2.0 import type { Observable } from 'rxjs'; import type { Option, u64 } from '@polkadot/types'; import type { PalletBagsListListBag } from '@polkadot/types/lookup'; import type { BN } from '@polkadot/util'; import type { DeriveApi } from '../types'; import type { Bag } from './types'; import { map, of, switchMap } from 'rxjs'; import { BN_ZERO, bnToBn, objectSpread } from '@polkadot/util'; import { memo } from '../util'; import { getQueryInterface } from './util'; function orderBags (ids: BN[], bags: Option[]): Bag[] { const sorted = ids .map((id, index) => ({ bag: bags[index].unwrapOr(null), id, key: id.toString() })) .sort((a, b) => b.id.cmp(a.id)); const max = sorted.length - 1; return sorted.map((entry, index): Bag => objectSpread(entry, { bagLower: index === max ? BN_ZERO : sorted[index + 1].id, bagUpper: entry.id, index }) ); } export function _getIds (instanceId: string, api: DeriveApi): (ids: (BN | number)[]) => Observable { const query = getQueryInterface(api); return memo(instanceId, (_ids: (BN | number)[]): Observable => { const ids = _ids.map((id) => bnToBn(id)); return ids.length ? query.listBags.multi>(ids).pipe( map((bags) => orderBags(ids, bags)) ) : of([]); }); } export function all (instanceId: string, api: DeriveApi): () => Observable { const query = getQueryInterface(api); return memo(instanceId, (): Observable => query.listBags.keys<[u64]>().pipe( switchMap((keys) => api.derive.bagsList._getIds(keys.map(({ args: [id] }) => id)) ), map((list) => list.filter(({ bag }) => bag) ) ) ); } export function get (instanceId: string, api: DeriveApi): (id: BN | number) => Observable { return memo(instanceId, (id: BN | number): Observable => api.derive.bagsList._getIds([bnToBn(id)]).pipe( map((bags) => bags[0]) ) ); }