diff --git a/packages/api-derive/src/accounts/idToIndex.ts b/packages/api-derive/src/accounts/idToIndex.ts index eeaebe1355..ebdc21fe80 100644 --- a/packages/api-derive/src/accounts/idToIndex.ts +++ b/packages/api-derive/src/accounts/idToIndex.ts @@ -5,14 +5,12 @@ import { AccountId, AccountIndex } from '@polkadot/types/interfaces'; import { AccountIndexes } from '../types'; -import { Observable, of } from 'rxjs'; +import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { ApiInterfaceRx } from '@polkadot/api/types'; import { memo } from '../util'; -const cached = new Map(); - /** * @name idToIndex * @param {( AccountId | string )} accountId - An accounts Id in different formats. @@ -28,19 +26,10 @@ const cached = new Map(); * ``` */ export function idToIndex (api: ApiInterfaceRx): (accountId: AccountId | string) => Observable { - return memo((accountId: AccountId | string): Observable => { - const address = accountId.toString(); - - if (cached.has(address)) { - return of(cached.get(address)); - } - - return api.derive.accounts.indexes().pipe( - map((indexes: AccountIndexes): AccountIndex | undefined => { - Object.entries(indexes).forEach(([address, index]) => cached.set(address, index)); - - return cached.get(address); - }) - ); - }); + return memo((accountId: AccountId | string): Observable => + api.derive.accounts.indexes().pipe( + map((indexes: AccountIndexes): AccountIndex | undefined => + (indexes || {})[accountId.toString()] + ) + )); } diff --git a/packages/api-derive/src/accounts/indexes.ts b/packages/api-derive/src/accounts/indexes.ts index b4b3c578f0..72d9f5f94c 100644 --- a/packages/api-derive/src/accounts/indexes.ts +++ b/packages/api-derive/src/accounts/indexes.ts @@ -16,6 +16,8 @@ import { memo } from '../util'; const enumsetSize = ENUMSET_SIZE.toNumber(); +let indicesCache: AccountIndexes | null = null; + function queryEnumSet (api: ApiInterfaceRx): Observable { return api.query.indices.nextEnumSet().pipe( // use the nextEnumSet (which is a counter of the number of sets) to construct @@ -72,11 +74,20 @@ function queryAccounts (api: ApiInterfaceRx): Observable { */ export function indexes (api: ApiInterfaceRx): () => Observable { return memo((): Observable => - (api.query.indices - ? isFunction(api.query.indices.accounts) - ? queryAccounts(api) - : queryEnumSet(api) - : of({} as AccountIndexes) - ).pipe(startWith({})) + indicesCache + ? of(indicesCache) + : ( + api.query.indices + ? isFunction(api.query.indices.accounts) + ? queryAccounts(api).pipe(startWith({})) + : queryEnumSet(api).pipe(startWith({})) + : of({} as AccountIndexes) + ).pipe( + map((indices): AccountIndexes => { + indicesCache = indices; + + return indices; + }) + ) ); }