Skip to content

Commit

Permalink
Use CurrenciesApi in BalanceClient
Browse files Browse the repository at this point in the history
  • Loading branch information
jvonasek committed Nov 5, 2024
1 parent 9f2dce3 commit 0c3290f
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 21 deletions.
5 changes: 5 additions & 0 deletions .changeset/fresh-chairs-carry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@galacticcouncil/sdk': minor
---

Use CurrenciesApi in BalanceClient, support for ERC20 tokens
5 changes: 0 additions & 5 deletions .changeset/lazy-days-applaud.md

This file was deleted.

46 changes: 30 additions & 16 deletions packages/sdk/src/client/BalanceClient.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { ApiPromise } from '@polkadot/api';
import { u32, Vec } from '@polkadot/types';
import { ITuple } from '@polkadot/types-codec/types';
import { OrmlTokensAccountData } from '@polkadot/types/lookup';
import { UnsubscribePromise } from '@polkadot/api-base/types';
import { SYSTEM_ASSET_ID } from '../consts';
import { BigNumber } from '../utils/bignumber';
Expand All @@ -10,26 +13,37 @@ export class BalanceClient extends PolkadotApiClient {
super(api);
}

async getBalance(accountId: string, tokenKey: string): Promise<BigNumber> {
return tokenKey === SYSTEM_ASSET_ID
? await this.getSystemBalance(accountId)
: await this.getTokenBalance(accountId, tokenKey);
async getTokenBalanceData(accountId: string, tokenKey: string) {
const params = this.api.createType('(AssetId, AccountId)', [
tokenKey,
accountId,
]);
const result = await this.api.rpc.state.call(
'CurrenciesApi_account',
params.toHex()
);
return this.api.createType<OrmlTokensAccountData>(
'OrmlTokensAccountData',
result
);
}

async getSystemBalance(accountId: string): Promise<BigNumber> {
const { data } = await this.api.query.system.account(accountId);
return this.calculateFreeBalance(data);
}
async getAccountBalanceData(accountId: string) {
const params = this.api.createType('AccountId', accountId);
const result = await this.api.rpc.state.call(
'CurrenciesApi_accounts',
params.toHex()
);

async getTokenBalance(
accountId: string,
tokenKey: string
): Promise<BigNumber> {
const { free, reserved, frozen } = await this.api.query.tokens.accounts(
accountId,
tokenKey
return this.api.createType<Vec<ITuple<[u32, OrmlTokensAccountData]>>>(
'Vec<(AssetId, OrmlTokensAccountData)>',
result
);
return this.calculateFreeBalance({ free, feeFrozen: reserved, frozen });
}

async getBalance(accountId: string, tokenKey: string): Promise<BigNumber> {
const data = this.getTokenBalanceData(accountId, tokenKey);
return this.calculateFreeBalance(data);
}

async subscribeBalance(
Expand Down

0 comments on commit 0c3290f

Please sign in to comment.