diff --git a/packages/api-derive/src/accounts/accountId.ts b/packages/api-derive/src/accounts/accountId.ts new file mode 100644 index 0000000000..6a655be621 --- /dev/null +++ b/packages/api-derive/src/accounts/accountId.ts @@ -0,0 +1,43 @@ +// Copyright 2017-2020 @polkadot/api-derive authors & contributors +// This software may be modified and distributed under the terms +// of the Apache-2.0 license. See the LICENSE file for details. + +import { AccountId, AccountIndex, Address } from '@polkadot/types/interfaces'; + +import { Observable, of } from 'rxjs'; +import { map } from 'rxjs/operators'; +import { ApiInterfaceRx } from '@polkadot/api/types'; +import { isU8a, assert } from '@polkadot/util'; +import { decodeAddress } from '@polkadot/util-crypto'; + +import { memo } from '../util'; + +function retrieve (api: ApiInterfaceRx, address: Address | AccountId | AccountIndex | string | null | undefined): Observable { + const decoded = isU8a(address) + ? address + : decodeAddress((address || '').toString()); + + if (decoded.length === 32) { + return of(api.registry.createType('AccountId', decoded)); + } + + const accountIndex = api.registry.createType('AccountIndex', decoded); + + return api.derive.accounts.indexToId(accountIndex.toString()).pipe( + map((accountId) => { + assert(accountId, 'Unable to retrieve accountId'); + + return accountId; + }) + ); +} + +/** + * @name accountId + * @param {(Address | AccountId | AccountIndex | string | null)} address - An accounts address in various formats. + * @description An [[AccountId]] + */ +export function accountId (api: ApiInterfaceRx): (address?: Address | AccountId | AccountIndex | string | null) => Observable { + return memo((address?: Address | AccountId | AccountIndex | string | null): Observable => + retrieve(api, address)); +} diff --git a/packages/api-derive/src/accounts/index.ts b/packages/api-derive/src/accounts/index.ts index 363a4e72f2..6af90840f1 100644 --- a/packages/api-derive/src/accounts/index.ts +++ b/packages/api-derive/src/accounts/index.ts @@ -2,6 +2,7 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +export * from './accountId'; export * from './flags'; export * from './idAndIndex'; export * from './idToIndex'; diff --git a/packages/api-derive/src/balances/account.ts b/packages/api-derive/src/balances/account.ts index 4296169d1f..ebd759a135 100644 --- a/packages/api-derive/src/balances/account.ts +++ b/packages/api-derive/src/balances/account.ts @@ -82,8 +82,8 @@ function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable Observable { return memo((address: AccountIndex | AccountId | Address | string): Observable => - api.derive.accounts.info(address).pipe( - switchMap(({ accountId }): Observable<[AccountId, Result]> => + api.derive.accounts.accountId(address).pipe( + switchMap((accountId): Observable<[AccountId, Result]> => (accountId ? combineLatest([ of(accountId),