// Copyright 2017-2021 @polkadot/api-derive authors & contributors // SPDX-License-Identifier: Apache-2.0 import type { ApiInterfaceRx } from '@polkadot/api/types'; import type { AccountId, AccountIndex } from '@polkadot/types/interfaces'; import type { Observable } from '@polkadot/x-rxjs'; import type { AccountIndexes } from '../types'; import { map } from '@polkadot/x-rxjs/operators'; import { memo } from '../util'; /** * @name idToIndex * @param {( AccountId | string )} accountId - An accounts Id in different formats. * @returns Returns the corresponding AccountIndex. * @example *
* * ```javascript * const ALICE = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; * api.derive.accounts.idToIndex(ALICE, (accountIndex) => { * console.log(`The AccountIndex of ${ALICE} is ${accountIndex}`); * }); * ``` */ export function idToIndex (instanceId: string, api: ApiInterfaceRx): (accountId: AccountId | string) => Observable { return memo(instanceId, (accountId: AccountId | string): Observable => api.derive.accounts.indexes().pipe( map((indexes: AccountIndexes): AccountIndex | undefined => (indexes || {})[accountId.toString()] ) )); }