Skip to content

Commit

Permalink
call acc balances callback just once
Browse files Browse the repository at this point in the history
  • Loading branch information
nohaapav committed Nov 7, 2024
1 parent ea2c5e6 commit e1182c7
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 11 deletions.
22 changes: 12 additions & 10 deletions packages/sdk/src/client/BalanceClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,16 @@ export class BalanceClient extends PolkadotApiClient {

async subscribeBalances(
address: string,
onChange: (token: string, balance: BigNumber) => void
onChange: (balances: [string, BigNumber][]) => void
): UnsubscribePromise {
const getBalances = () =>
this.getAccountBalanceData(address).then((balances) => {
balances.forEach(([token, data]) => {
onChange(token.toString(), this.calculateFreeBalance(data));
});
const getBalances = async () => {
const result: [string, BigNumber][] = [];
const balances = await this.getAccountBalanceData(address);
balances.forEach(([token, data]) => {
result.push([token.toString(), this.calculateFreeBalance(data)]);
});
onChange(result);
};

await getBalances();
return this.api.rpc.chain.subscribeNewHeads(async () => {
Expand All @@ -68,10 +70,10 @@ export class BalanceClient extends PolkadotApiClient {
token: string,
onChange: (token: string, balance: BigNumber) => void
): UnsubscribePromise {
const getBalance = () =>
this.getTokenBalanceData(address, token).then((data) => {
onChange(token.toString(), this.calculateFreeBalance(data));
});
const getBalance = async () => {
const data = await this.getTokenBalanceData(address, token);
onChange(token.toString(), this.calculateFreeBalance(data));
};

await getBalance();
return this.api.rpc.chain.subscribeNewHeads(async () => {
Expand Down
13 changes: 12 additions & 1 deletion packages/sdk/src/pool/PoolClientV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export abstract class PoolClient extends BalanceClient {
private subscribeTokensPoolBalance(pool: PoolBase): UnsubscribePromise {
return this.subscribeBalances(
pool.address,
this.updateBalanceCallback(pool)
this.updateBalancesCallback(pool)
);
}

Expand All @@ -80,6 +80,17 @@ export abstract class PoolClient extends BalanceClient {
);
}

private updateBalancesCallback(pool: PoolBase) {
return function (balances: [string, BigNumber][]) {
balances.forEach(([token, balance]) => {
const tokenIndex = pool.tokens.findIndex((t) => t.id == token);
if (tokenIndex >= 0) {
pool.tokens[tokenIndex].balance = balance.toString();
}
});
};
}

private updateBalanceCallback(pool: PoolBase) {
return function (token: string, balance: BigNumber) {
const tokenIndex = pool.tokens.findIndex((t) => t.id == token);
Expand Down

0 comments on commit e1182c7

Please sign in to comment.