diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c7344ccc3..df42db4d85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # CHANGELOG +## 1.22.0-beta.x + +- Improve derive accountId -> accountIndex lookups (optimize entries queries) + ## 1.21.1 Jun 23, 2020 - Fix subscriptions never unsubscribing after the id swap in 1.18.1 (Thanks to https://github.com/dillu24 for testing iterations) diff --git a/packages/api-derive/src/accounts/idToIndex.ts b/packages/api-derive/src/accounts/idToIndex.ts index ebdc21fe80..eeaebe1355 100644 --- a/packages/api-derive/src/accounts/idToIndex.ts +++ b/packages/api-derive/src/accounts/idToIndex.ts @@ -5,12 +5,14 @@ import { AccountId, AccountIndex } from '@polkadot/types/interfaces'; import { AccountIndexes } from '../types'; -import { Observable } from 'rxjs'; +import { Observable, of } 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. @@ -26,10 +28,19 @@ import { memo } from '../util'; * ``` */ export function idToIndex (api: ApiInterfaceRx): (accountId: AccountId | string) => Observable { - return memo((accountId: AccountId | string): Observable => - api.derive.accounts.indexes().pipe( - map((indexes: AccountIndexes): AccountIndex | undefined => - (indexes || {})[accountId.toString()] - ) - )); + 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); + }) + ); + }); }