From 512879b3a82b53d1c6f9faffa1e0a5f7b02e1120 Mon Sep 17 00:00:00 2001 From: Greg Hill Date: Tue, 4 Jan 2022 16:26:23 +0000 Subject: [PATCH] add custom derive for interbtc native balances (#6779) Signed-off-by: Gregory Hill --- packages/apps-config/src/api/spec/interbtc.ts | 65 +++++++++++++++++-- 1 file changed, 60 insertions(+), 5 deletions(-) diff --git a/packages/apps-config/src/api/spec/interbtc.ts b/packages/apps-config/src/api/spec/interbtc.ts index 4b66ede90d..126b5ca678 100644 --- a/packages/apps-config/src/api/spec/interbtc.ts +++ b/packages/apps-config/src/api/spec/interbtc.ts @@ -1,12 +1,67 @@ // Copyright 2017-2022 @polkadot/apps-config authors & contributors // SPDX-License-Identifier: Apache-2.0 +/* eslint-disable @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment */ + +import type { Observable } from 'rxjs'; +import type { ApiInterfaceRx } from '@polkadot/api/types'; import type { OverrideBundleDefinition } from '@polkadot/types/types'; -import definitions from '@interlay/interbtc-types'; +import interbtc from '@interlay/interbtc-types'; +import { combineLatest, map } from 'rxjs'; -// This is a temp work-around to add the interfaces key to the actual types -// With the next release of the API this should be able tp be added to the base -const extended = definitions as OverrideBundleDefinition; +import { DeriveBalancesAll } from '@polkadot/api-derive/types'; +import { memo } from '@polkadot/api-derive/util'; +import { TypeRegistry, U128 } from '@polkadot/types'; +import { BN, formatBalance } from '@polkadot/util'; -export default extended; +function balanceOf (number: number | string): U128 { + return new U128(new TypeRegistry(), number); +} + +function defaultAccountBalance (): DeriveBalancesAll { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return { + accountNonce: new BN(1), + additional: [], + availableBalance: balanceOf(0), + freeBalance: balanceOf(0), + lockedBalance: balanceOf(0), + lockedBreakdown: [], + reservedBalance: balanceOf(0) + } as any; +} + +export function getBalance ( + instanceId: string, + api: ApiInterfaceRx +): () => Observable { + const nativeToken = api.registry.chainTokens[0] || formatBalance.getDefaults().unit; + + return memo( + instanceId, + (account: string): Observable => + combineLatest([api.query.tokens.accounts(account, { Token: nativeToken })]).pipe( + map(([data]: [any]): DeriveBalancesAll => { + return { + ...defaultAccountBalance(), + freeBalance: data.free, + lockedBalance: data.frozen, + reservedBalance: data.reserved + }; + }) + ) + ); +} + +const definitions: OverrideBundleDefinition = { + derives: { + balances: { + all: getBalance + } + }, + + ...interbtc +} as any; + +export default definitions;