Skip to content

Commit

Permalink
wallet ctx init commit
Browse files Browse the repository at this point in the history
  • Loading branch information
nohaapav committed Nov 25, 2024
1 parent 6d21682 commit cf17207
Show file tree
Hide file tree
Showing 5 changed files with 111 additions and 6 deletions.
98 changes: 98 additions & 0 deletions packages/sdk/src/api/WalletCtx.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { ApiPromise } from '@polkadot/api';
import { UnsubscribePromise, VoidFn } from '@polkadot/api-base/types';
import { u32, Vec } from '@polkadot/types';
import { ITuple } from '@polkadot/types-codec/types';
import { OrmlTokensAccountData } from '@polkadot/types/lookup';

import { memoize1 } from '@thi.ng/memoize';

import { AssetClient, BalanceClient } from '../client';
import { Asset } from '../types';
import { BigNumber, ZERO } from '../utils/bignumber';

export class WalletCtx extends BalanceClient {
protected readonly assetClient: AssetClient;

protected ctx: Map<string, BigNumber> = new Map([]);
protected subs: VoidFn[] = [];

private assets: Asset[] = [];

private memBalances = memoize1((account: string) => {
console.log('Wallet mem balances', account, '✅');
return this.getBalances(account);
});

constructor(api: ApiPromise) {
super(api);
this.assetClient = new AssetClient(this.api);
}

async getBalancesMem(account: string): Promise<Map<string, BigNumber>> {
return this.memBalances(account);
}

private async getBalances(account: string): Promise<Map<string, BigNumber>> {
this.unsubscribe();

const balances = await this.getAccountBalanceData(account);
balances.forEach(([token, data]) => {
this.ctx.set(token.toString(), this.calculateFreeBalance(data));
});

this.assets = await this.assetClient.getOnChainAssets(true);
this.subs = await Promise.all([
this.subscribeSystemAccountBalance(account),
this.subscribeTokensAccountBalance(account),
this.subscribeErc20AccountBalance(account),
]);

console.log(`Wallet assets(${this.assets.length})`, '✅');
console.log(`Wallet subs(${this.subs.length})`, '✅');

return this.ctx;
}

unsubscribe() {
this.subs.forEach((unsub) => {
unsub();
});
}

private async getAccountBalanceData(account: string) {
return await this.api.call.currenciesApi.accounts<
Vec<ITuple<[u32, OrmlTokensAccountData]>>
>(account.toString());
}

private subscribeTokensAccountBalance(account: string): UnsubscribePromise {
const updateCtx = this.updateCtxCallback(this.ctx);
return this.subscribeTokenBalance(account, this.assets, (balances) =>
balances.forEach(([token, balance]) => updateCtx(token, balance))
);
}

private subscribeErc20AccountBalance(account: string): UnsubscribePromise {
const updateCtx = this.updateCtxCallback(this.ctx);
return this.subscribeErc20Balance(account, this.assets, (balances) =>
balances.forEach(([token, balance]) => updateCtx(token, balance))
);
}

private subscribeSystemAccountBalance(account: string): UnsubscribePromise {
const updateCtx = this.updateCtxCallback(this.ctx);
return this.subscribeSystemBalance(account, (token, balance) =>
updateCtx(token, balance)
);
}

private updateCtxCallback(ctx: Map<string, BigNumber>) {
return function (token: string, balance: BigNumber) {
if (balance.isGreaterThan(ZERO)) {
ctx.set(token, balance);
} else {
ctx.delete(token);
}
};
}
}
1 change: 1 addition & 0 deletions packages/sdk/src/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { Router } from './Router';
export { TradeRouter } from './TradeRouter';
export { WalletCtx } from './WalletCtx';
2 changes: 1 addition & 1 deletion packages/sdk/src/pool/PoolClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export abstract class PoolClient extends BalanceClient {
this.mem = this.mem + 1;
}

async getMemPools(): Promise<PoolBase[]> {
async getPoolsMem(): Promise<PoolBase[]> {
return this.memPools(this.mem);
}

Expand Down
4 changes: 2 additions & 2 deletions packages/sdk/src/pool/PoolService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,15 +83,15 @@ export class PoolService implements IPoolService {
const pools = await Promise.all(
this.clients
.filter((client) => client.isSupported())
.map((client) => client.getMemPools())
.map((client) => client.getPoolsMem())
);
return pools.flat();
}

const pools = await Promise.all(
this.clients
.filter((client) => includeOnly.some((t) => t === client.getPoolType()))
.map((client) => client.getMemPools())
.map((client) => client.getPoolsMem())
);
return pools.flat();
}
Expand Down
12 changes: 9 additions & 3 deletions packages/sdk/test/script/examples/router/onBlockPoolChange.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { ApiPromise } from '@polkadot/api';
import { ApiUrl, PolkadotExecutor } from '../../executor';
import { PoolService } from '../../../../src/pool';
import { TradeRouter } from '../../../../src/api';
import { TradeRouter, WalletCtx } from '../../../../src/api';
import { HYDRADX_OMNIPOOL_ADDRESS } from '../../../../src/consts';

class GetOnBlockPoolChangeExample extends PolkadotExecutor {
async script(api: ApiPromise): Promise<any> {
const poolService = new PoolService(api);
const router = new TradeRouter(poolService);
const walletCtx = new WalletCtx(api);

const result = await Promise.all([
router.getBestSpotPrice('5', '0'),
Expand All @@ -17,8 +19,9 @@ class GetOnBlockPoolChangeExample extends PolkadotExecutor {
]);
console.log('Call spot 5x simultaneously', result);

api.rpc.chain.subscribeNewHeads(async (_lastHeader) => {
console.log('==================');
api.rpc.chain.subscribeNewHeads(async (lastHeader) => {
const block = lastHeader.number.toString();
console.log('===============', block, '===============');
router.getPools().then((p) => {
p.forEach((o) => {
o.tokens.forEach((t) => {
Expand All @@ -29,6 +32,9 @@ class GetOnBlockPoolChangeExample extends PolkadotExecutor {
});
});
});

const balance = await walletCtx.getBalancesMem(HYDRADX_OMNIPOOL_ADDRESS);
console.log('balance', balance);
});

return [];
Expand Down

0 comments on commit cf17207

Please sign in to comment.