@paraswap/dex-lib 3.8.23 → 3.8.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/build/abi/infusion/InfusionFactory.json +147 -0
  2. package/build/abi/infusion/InfusionPair.json +658 -0
  3. package/build/abi/infusion/InfusionRouter.json +442 -0
  4. package/build/dex/index.js +4 -0
  5. package/build/dex/index.js.map +1 -1
  6. package/build/dex/infusion/config.d.ts +3 -0
  7. package/build/dex/infusion/config.js +20 -0
  8. package/build/dex/infusion/config.js.map +1 -0
  9. package/build/dex/infusion/infusion-stable-pool.d.ts +4 -0
  10. package/build/dex/infusion/infusion-stable-pool.js +74 -0
  11. package/build/dex/infusion/infusion-stable-pool.js.map +1 -0
  12. package/build/dex/infusion/infusion.d.ts +51 -0
  13. package/build/dex/infusion/infusion.js +457 -0
  14. package/build/dex/infusion/infusion.js.map +1 -0
  15. package/build/dex/infusion/types.d.ts +45 -0
  16. package/build/dex/infusion/types.js +3 -0
  17. package/build/dex/infusion/types.js.map +1 -0
  18. package/build/dex/infusion/utils/isStablePair.d.ts +2 -0
  19. package/build/dex/infusion/utils/isStablePair.js +18 -0
  20. package/build/dex/infusion/utils/isStablePair.js.map +1 -0
  21. package/build/dex/lite-psm/lite-psm.js +2 -5
  22. package/build/dex/lite-psm/lite-psm.js.map +1 -1
  23. package/build/dex/maker-psm/maker-psm.js +2 -6
  24. package/build/dex/maker-psm/maker-psm.js.map +1 -1
  25. package/build/dex/oswap/oswap-pool.js +8 -8
  26. package/build/dex/oswap/oswap-pool.js.map +1 -1
  27. package/build/dex/oswap/oswap.d.ts +5 -5
  28. package/build/dex/oswap/oswap.js +62 -46
  29. package/build/dex/oswap/oswap.js.map +1 -1
  30. package/build/dex/oswap/types.d.ts +4 -4
  31. package/package.json +1 -1
  32. package/src/abi/infusion/InfusionFactory.json +147 -0
  33. package/src/abi/infusion/InfusionPair.json +658 -0
  34. package/src/abi/infusion/InfusionRouter.json +442 -0
  35. package/src/abi/oswap/oswap.abi.json +452 -0
  36. package/src/dex/index.ts +4 -0
  37. package/src/dex/infusion/config.ts +21 -0
  38. package/src/dex/infusion/infusion-e2e.test.ts +110 -0
  39. package/src/dex/infusion/infusion-integration.test.ts +232 -0
  40. package/src/dex/infusion/infusion-stable-pool.ts +91 -0
  41. package/src/dex/infusion/infusion.ts +652 -0
  42. package/src/dex/infusion/types.ts +60 -0
  43. package/src/dex/infusion/utils/isStablePair.ts +18 -0
  44. package/src/dex/lite-psm/lite-psm.ts +2 -5
  45. package/src/dex/maker-psm/maker-psm.ts +2 -6
  46. package/src/dex/oswap/config.ts +32 -0
  47. package/src/dex/oswap/oswap-e2e.test.ts +91 -0
  48. package/src/dex/oswap/oswap-events.test.ts +88 -0
  49. package/src/dex/oswap/oswap-integration.test.ts +291 -0
  50. package/src/dex/oswap/oswap-pool.ts +190 -0
  51. package/src/dex/oswap/oswap.ts +414 -0
  52. package/src/dex/oswap/types.ts +29 -0
  53. package/tests/constants-e2e.ts +1 -1
@@ -0,0 +1,190 @@
1
+ import { Interface } from '@ethersproject/abi';
2
+ import { DeepReadonly } from 'ts-essentials';
3
+ import { Log, Logger, Token } from '../../types';
4
+ import { catchParseLogError } from '../../utils';
5
+ import { StatefulEventSubscriber } from '../../stateful-event-subscriber';
6
+ import { IDexHelper } from '../../dex-helper/idex-helper';
7
+ import { MultiCallParams } from '../../lib/multi-wrapper';
8
+ import { uint256ToBigInt } from '../../lib/decoders';
9
+ import { OSwapPool, OSwapPoolState } from './types';
10
+ import OSwapABI from '../../abi/oswap/oswap.abi.json';
11
+ import ERC20ABI from '../../abi/ERC20.abi.json';
12
+
13
+ export class OSwapEventPool extends StatefulEventSubscriber<OSwapPoolState> {
14
+ handlers: {
15
+ [event: string]: (
16
+ event: any,
17
+ state: DeepReadonly<OSwapPoolState>,
18
+ log: Readonly<Log>,
19
+ ) => DeepReadonly<OSwapPoolState> | null;
20
+ } = {};
21
+
22
+ logDecoder: (log: Log) => any;
23
+
24
+ addressesSubscribed: string[];
25
+
26
+ constructor(
27
+ readonly parentName: string,
28
+ readonly pool: OSwapPool,
29
+ protected network: number,
30
+ protected dexHelper: IDexHelper,
31
+ logger: Logger,
32
+ protected iOSwap = new Interface(OSwapABI),
33
+ protected iERC20 = new Interface(ERC20ABI),
34
+ ) {
35
+ super(parentName, pool.id, dexHelper, logger);
36
+
37
+ this.logDecoder = (log: Log) => this.parseLog(log);
38
+
39
+ this.addressesSubscribed = [pool.address, pool.token0, pool.token1];
40
+ this.handlers['TraderateChanged'] = this.handleTraderateChanged.bind(this);
41
+ this.handlers['Transfer'] = this.handleTransfer.bind(this);
42
+ }
43
+
44
+ protected parseLog(log: Log) {
45
+ if (log.address.toLowerCase() === this.pool.address) {
46
+ return this.iOSwap.parseLog(log);
47
+ }
48
+ return this.iERC20.parseLog(log);
49
+ }
50
+
51
+ /**
52
+ * The function is called every time any of the subscribed
53
+ * addresses release log. The function accepts the current
54
+ * state, updates the state according to the log, and returns
55
+ * the updated state.
56
+ * @param state - Current state of event subscriber
57
+ * @param log - Log released by one of the subscribed addresses
58
+ * @returns Updates state of the event subscriber after the log
59
+ */
60
+ protected processLog(
61
+ state: DeepReadonly<OSwapPoolState>,
62
+ log: Readonly<Log>,
63
+ ): DeepReadonly<OSwapPoolState> | null {
64
+ try {
65
+ const event = this.logDecoder(log);
66
+ if (event.name in this.handlers) {
67
+ return this.handlers[event.name](event, state, log);
68
+ }
69
+ } catch (e) {
70
+ catchParseLogError(e, this.logger);
71
+ }
72
+
73
+ return null;
74
+ }
75
+
76
+ /**
77
+ * The function generates state using on-chain calls. This
78
+ * function is called to regenerate state if the event based
79
+ * system fails to fetch events and the local state is no
80
+ * more correct.
81
+ * @param blockNumber - Blocknumber for which the state should
82
+ * should be generated
83
+ * @returns state of the event subscriber at blocknumber
84
+ */
85
+ async generateState(
86
+ blockNumber: number,
87
+ ): Promise<DeepReadonly<OSwapPoolState>> {
88
+ const iERC20 = new Interface(ERC20ABI);
89
+ const callData: MultiCallParams<bigint>[] = [
90
+ {
91
+ target: this.pool.token0,
92
+ callData: iERC20.encodeFunctionData('balanceOf', [this.pool.address]),
93
+ decodeFunction: uint256ToBigInt,
94
+ },
95
+ {
96
+ target: this.pool.token1,
97
+ callData: iERC20.encodeFunctionData('balanceOf', [this.pool.address]),
98
+ decodeFunction: uint256ToBigInt,
99
+ },
100
+ {
101
+ target: this.pool.address,
102
+ callData: this.iOSwap.encodeFunctionData('traderate0', []),
103
+ decodeFunction: uint256ToBigInt,
104
+ },
105
+ {
106
+ target: this.pool.address,
107
+ callData: this.iOSwap.encodeFunctionData('traderate1', []),
108
+ decodeFunction: uint256ToBigInt,
109
+ },
110
+ ];
111
+
112
+ const results = await this.dexHelper.multiWrapper.aggregate<bigint>(
113
+ callData,
114
+ blockNumber,
115
+ this.dexHelper.multiWrapper.defaultBatchSize,
116
+ );
117
+
118
+ return {
119
+ balance0: results[0].toString(),
120
+ balance1: results[1].toString(),
121
+ traderate0: results[2].toString(),
122
+ traderate1: results[3].toString(),
123
+ };
124
+ }
125
+
126
+ async getStateOrGenerate(
127
+ blockNumber: number,
128
+ readonly: boolean = true,
129
+ ): Promise<OSwapPoolState> {
130
+ let state = this.getState(blockNumber);
131
+ if (!state) {
132
+ state = await this.generateState(blockNumber);
133
+ if (!readonly) this.setState(state, blockNumber);
134
+ }
135
+ return state;
136
+ }
137
+
138
+ /**
139
+ * Handle a trade rate change on the pool.
140
+ */
141
+ handleTraderateChanged(
142
+ event: any,
143
+ state: DeepReadonly<OSwapPoolState>,
144
+ log: Readonly<Log>,
145
+ ): DeepReadonly<OSwapPoolState> | null {
146
+ return {
147
+ ...state,
148
+ traderate0: event.args.traderate0.toBigInt(),
149
+ traderate1: event.args.traderate1.toBigInt(),
150
+ };
151
+ }
152
+
153
+ /**
154
+ * Process the transfer events for tokens in/out of the pool
155
+ * to keep the state's token balances up to date.
156
+ */
157
+ handleTransfer(
158
+ event: any,
159
+ state: DeepReadonly<OSwapPoolState>,
160
+ log: Readonly<Log>,
161
+ ): DeepReadonly<OSwapPoolState> | null {
162
+ let balance0: bigint = BigInt(state.balance0);
163
+ let balance1: bigint = BigInt(state.balance1);
164
+
165
+ const tokenAddress = log.address.toLowerCase();
166
+ const fromAddress = event.args.from.toLowerCase();
167
+ const toAddress = event.args.to.toLowerCase();
168
+ const amount = event.args.value.toBigInt();
169
+
170
+ if (fromAddress == this.pool.address) {
171
+ if (tokenAddress === this.pool.token0) {
172
+ balance0 -= amount;
173
+ } else if (tokenAddress === this.pool.token1) {
174
+ balance1 -= amount;
175
+ }
176
+ } else if (toAddress == this.pool.address) {
177
+ if (tokenAddress === this.pool.token0) {
178
+ balance0 += amount;
179
+ } else if (tokenAddress === this.pool.token1) {
180
+ balance1 += amount;
181
+ }
182
+ }
183
+
184
+ return {
185
+ ...state,
186
+ balance0: balance0.toString(),
187
+ balance1: balance1.toString(),
188
+ };
189
+ }
190
+ }
@@ -0,0 +1,414 @@
1
+ import { Interface } from '@ethersproject/abi';
2
+ import { AsyncOrSync } from 'ts-essentials';
3
+ import {
4
+ Token,
5
+ Address,
6
+ ExchangePrices,
7
+ PoolPrices,
8
+ AdapterExchangeParam,
9
+ PoolLiquidity,
10
+ Logger,
11
+ NumberAsString,
12
+ DexExchangeParam,
13
+ TransferFeeParams,
14
+ } from '../../types';
15
+ import {
16
+ SwapSide,
17
+ Network,
18
+ DEST_TOKEN_PARASWAP_TRANSFERS,
19
+ SRC_TOKEN_PARASWAP_TRANSFERS,
20
+ } from '../../constants';
21
+ import * as CALLDATA_GAS_COST from '../../calldata-gas-cost';
22
+ import { getDexKeysWithNetwork, getBigIntPow } from '../../utils';
23
+ import { Context, IDex } from '../../dex/idex';
24
+ import { IDexHelper } from '../../dex-helper/idex-helper';
25
+ import { OSwapData, OSwapPool, OSwapPoolState } from './types';
26
+ import {
27
+ SimpleExchange,
28
+ getLocalDeadlineAsFriendlyPlaceholder,
29
+ } from '../simple-exchange';
30
+ import { OSwapConfig, Adapters, OSWAP_GAS_COST } from './config';
31
+ import { OSwapEventPool } from './oswap-pool';
32
+ import OSwapABI from '../../abi/oswap/oswap.abi.json';
33
+ import { extractReturnAmountPosition } from '../../executor/utils';
34
+ import { applyTransferFee } from '../../lib/token-transfer-fee';
35
+
36
+ export class OSwap extends SimpleExchange implements IDex<OSwapData> {
37
+ readonly eventPools: { [id: string]: OSwapEventPool } = {};
38
+
39
+ readonly hasConstantPriceLargeAmounts = false;
40
+
41
+ // This may change in the future, but currently OSwap does not support native ETH.
42
+ readonly needWrapNative = true;
43
+
44
+ readonly isFeeOnTransferSupported = true;
45
+
46
+ public static dexKeysWithNetwork: { key: string; networks: Network[] }[] =
47
+ getDexKeysWithNetwork(OSwapConfig);
48
+
49
+ logger: Logger;
50
+
51
+ readonly iOSwap: Interface;
52
+
53
+ readonly pools: [OSwapPool];
54
+
55
+ constructor(
56
+ readonly network: Network,
57
+ readonly dexKey: string,
58
+ readonly dexHelper: IDexHelper,
59
+ protected adapters = Adapters[network] || {},
60
+ ) {
61
+ super(dexHelper, dexKey);
62
+ this.logger = dexHelper.getLogger(dexKey);
63
+ this.iOSwap = new Interface(OSwapABI);
64
+
65
+ this.pools = OSwapConfig[dexKey][network].pools;
66
+
67
+ // Create an OSwapEventPool per pool, to track each pool's state by subscribing to on-chain events.
68
+ for (const pool of this.pools) {
69
+ this.eventPools[pool.id] = new OSwapEventPool(
70
+ dexKey,
71
+ pool,
72
+ network,
73
+ dexHelper,
74
+ this.logger,
75
+ );
76
+ }
77
+ }
78
+
79
+ // Returns the list of contract adapters (name and index)
80
+ // for a buy/sell. Return null if there are no adapters.
81
+ getAdapters(side: SwapSide): { name: string; index: number }[] | null {
82
+ return null;
83
+ }
84
+
85
+ // Returns the pool matching the specified token pair or null if none found.
86
+ // Note: OSwap V1 does not support more than 1 pool per pair.
87
+ getPoolByTokenPair(srcToken: Token, destToken: Token): OSwapPool | null {
88
+ const srcAddress = srcToken.address.toLowerCase();
89
+ const destAddress = destToken.address.toLowerCase();
90
+
91
+ // A pair must have 2 different tokens.
92
+ if (srcAddress === destAddress) return null;
93
+
94
+ for (const pool of this.pools) {
95
+ if (
96
+ (srcAddress === pool.token0 && destAddress === pool.token1) ||
97
+ (srcAddress === pool.token1 && destAddress === pool.token0)
98
+ ) {
99
+ return pool;
100
+ }
101
+ }
102
+ return null;
103
+ }
104
+
105
+ getPoolById(id: string): OSwapPool | null {
106
+ for (const pool of this.pools) {
107
+ if (pool.id === id) return pool;
108
+ }
109
+ return null;
110
+ }
111
+
112
+ // Returns a list of pool using the token.
113
+ getPoolsByTokenAddress(tokenAddress: Address): OSwapPool[] {
114
+ const address = tokenAddress.toLowerCase();
115
+ let pools: OSwapPool[] = [];
116
+ for (const pool of this.pools) {
117
+ if (address === pool.token0 || address === pool.token1) {
118
+ pools.push(pool);
119
+ }
120
+ }
121
+ return pools;
122
+ }
123
+
124
+ // Returns the list of pool identifiers that can be used
125
+ // for a given swap. poolIdentifiers must be unique
126
+ // across DEXes. It is recommended to use
127
+ // ${dexKey}_${poolAddress} as a poolIdentifier
128
+ async getPoolIdentifiers(
129
+ srcToken: Token,
130
+ destToken: Token,
131
+ side: SwapSide,
132
+ blockNumber: number,
133
+ ): Promise<string[]> {
134
+ const pool = this.getPoolByTokenPair(srcToken, destToken);
135
+ return pool ? [pool.id] : [];
136
+ }
137
+
138
+ // Sell: Given "amount" of "from" token, how much of "to" token will be received by the trader.
139
+ // Buy: Given "amount" of "dest" token, how much of "to" token is required from the trader.
140
+ // Note: OSwap traderate is at precision 36.
141
+ calcPrice(
142
+ pool: OSwapPool,
143
+ state: OSwapPoolState,
144
+ from: Token,
145
+ amount: bigint,
146
+ side: SwapSide,
147
+ checkLiquidity = true,
148
+ ): bigint {
149
+ const rate =
150
+ from.address.toLowerCase() === pool.token0
151
+ ? BigInt(state.traderate0)
152
+ : BigInt(state.traderate1);
153
+
154
+ const price =
155
+ side === SwapSide.SELL
156
+ ? (amount * rate) / getBigIntPow(36)
157
+ : (amount * getBigIntPow(36)) / rate;
158
+
159
+ if (
160
+ checkLiquidity &&
161
+ !this.hasEnoughLiquidity(pool, state, from, amount, price, side)
162
+ ) {
163
+ throw new Error('Not enough liquidity');
164
+ }
165
+
166
+ return price;
167
+ }
168
+
169
+ // Returns true if the pool has enough liquidity for the swap. False otherwise.
170
+ hasEnoughLiquidity(
171
+ pool: OSwapPool,
172
+ state: OSwapPoolState,
173
+ from: Token,
174
+ amount: bigint,
175
+ needed: bigint,
176
+ side: SwapSide,
177
+ ): boolean {
178
+ if (side === SwapSide.SELL) {
179
+ return from.address.toLowerCase() === pool.token0
180
+ ? needed <= BigInt(state.balance1)
181
+ : needed <= BigInt(state.balance0);
182
+ }
183
+ // SwapSide.BUY
184
+ return from.address.toLowerCase() === pool.token0
185
+ ? amount <= BigInt(state.balance1)
186
+ : amount <= BigInt(state.balance0);
187
+ }
188
+
189
+ // Returns pool prices for amounts.
190
+ // If limitPools is defined only pools in limitPools
191
+ // should be used. If limitPools is undefined then
192
+ // any pool can be used.
193
+ async getPricesVolume(
194
+ srcToken: Token,
195
+ destToken: Token,
196
+ amounts: bigint[],
197
+ side: SwapSide,
198
+ blockNumber: number,
199
+ limitPools?: string[],
200
+ transferFees: TransferFeeParams = {
201
+ srcFee: 0,
202
+ destFee: 0,
203
+ srcDexFee: 0,
204
+ destDexFee: 0,
205
+ },
206
+ ): Promise<null | ExchangePrices<OSwapData>> {
207
+ try {
208
+ // Get the pool to use.
209
+ const pool = this.getPoolByTokenPair(srcToken, destToken);
210
+ if (!pool) return null;
211
+
212
+ // Make sure the pool meets the optional limitPools filter.
213
+ if (limitPools && !limitPools.includes(pool.id)) return null;
214
+
215
+ const eventPool = this.eventPools[pool.id];
216
+
217
+ if (!eventPool) {
218
+ this.logger.error(`OSwap pool ${pool.id}: No EventPool found.`);
219
+
220
+ return null;
221
+ }
222
+
223
+ const state = await eventPool.getStateOrGenerate(blockNumber);
224
+
225
+ // Calculate the prices
226
+ const unitAmount = getBigIntPow(18);
227
+ const unitPrice = this.calcPrice(
228
+ pool,
229
+ state,
230
+ srcToken,
231
+ unitAmount,
232
+ side,
233
+ false,
234
+ );
235
+ const prices = amounts.map(amount =>
236
+ this.calcPrice(pool, state, srcToken, amount, side),
237
+ );
238
+
239
+ const [unitPriceWithFee, ...pricesWithFee] = applyTransferFee(
240
+ [unitPrice, ...prices],
241
+ side,
242
+ side === SwapSide.SELL ? transferFees.srcFee : transferFees.destFee,
243
+ side === SwapSide.SELL
244
+ ? SRC_TOKEN_PARASWAP_TRANSFERS
245
+ : DEST_TOKEN_PARASWAP_TRANSFERS,
246
+ );
247
+
248
+ return [
249
+ {
250
+ prices: pricesWithFee,
251
+ unit: unitPriceWithFee,
252
+ data: {
253
+ pool: pool.address,
254
+ path: [srcToken.address, destToken.address],
255
+ },
256
+ exchange: this.dexKey,
257
+ poolIdentifier: pool.id,
258
+ gasCost: OSWAP_GAS_COST,
259
+ poolAddresses: [pool.address],
260
+ },
261
+ ];
262
+ } catch (e) {
263
+ this.logger.error(
264
+ `Error_getPricesVolume ${srcToken.address || srcToken.symbol}, ${
265
+ destToken.address || destToken.symbol
266
+ }, ${side}:`,
267
+ e,
268
+ );
269
+
270
+ return null;
271
+ }
272
+ }
273
+
274
+ // Returns estimated gas cost of calldata for this DEX in multiSwap
275
+ getCalldataGasCost(poolPrices: PoolPrices<OSwapData>): number | number[] {
276
+ return (
277
+ CALLDATA_GAS_COST.DEX_OVERHEAD +
278
+ // ParentStruct header
279
+ CALLDATA_GAS_COST.OFFSET_SMALL +
280
+ // ParentStruct -> path[] header
281
+ CALLDATA_GAS_COST.OFFSET_SMALL +
282
+ // ParentStruct -> path length
283
+ CALLDATA_GAS_COST.LENGTH_SMALL +
284
+ // ParentStruct -> path[0]
285
+ CALLDATA_GAS_COST.ADDRESS +
286
+ // ParentStruct -> path[1]
287
+ CALLDATA_GAS_COST.ADDRESS +
288
+ // ParentStruct -> receiver header
289
+ CALLDATA_GAS_COST.OFFSET_SMALL +
290
+ // ParentStruct -> receiver
291
+ CALLDATA_GAS_COST.ADDRESS
292
+ );
293
+ }
294
+
295
+ // Encode params required by the exchange adapter
296
+ // Used for multiSwap, buy & megaSwap
297
+ getAdapterParam(
298
+ srcToken: string,
299
+ destToken: string,
300
+ srcAmount: string,
301
+ destAmount: string,
302
+ data: OSwapData,
303
+ side: SwapSide,
304
+ ): AdapterExchangeParam {
305
+ return {
306
+ targetExchange: data.pool,
307
+ payload: '',
308
+ networkFee: '0',
309
+ };
310
+ }
311
+
312
+ // Encode call data used by simpleSwap like routers
313
+ // Used for simpleSwap & simpleBuy
314
+ getDexParam(
315
+ srcToken: Address,
316
+ destToken: Address,
317
+ srcAmount: NumberAsString,
318
+ destAmount: NumberAsString,
319
+ recipient: Address,
320
+ data: OSwapData,
321
+ side: SwapSide,
322
+ _: Context,
323
+ executorAddress: Address,
324
+ ): DexExchangeParam {
325
+ let method: string;
326
+ let args: any;
327
+ let returnAmountPos: number | undefined = undefined;
328
+
329
+ const deadline = getLocalDeadlineAsFriendlyPlaceholder();
330
+ if (side === SwapSide.SELL) {
331
+ method = 'swapExactTokensForTokens';
332
+ returnAmountPos = extractReturnAmountPosition(
333
+ this.iOSwap,
334
+ method,
335
+ 'amounts',
336
+ 1,
337
+ );
338
+ args = [srcAmount, destAmount, data.path, recipient, deadline];
339
+ } else {
340
+ method = 'swapTokensForExactTokens';
341
+ args = [destAmount, srcAmount, data.path, recipient, deadline];
342
+ }
343
+
344
+ const swapData = this.iOSwap.encodeFunctionData(method, args);
345
+
346
+ return {
347
+ needWrapNative: this.needWrapNative,
348
+ dexFuncHasRecipient: true,
349
+ exchangeData: swapData,
350
+ targetExchange: data.pool,
351
+ returnAmountPos,
352
+ };
353
+ }
354
+
355
+ // This is called once before getTopPoolsForToken is
356
+ // called for multiple tokens. This can be helpful to
357
+ // update common state required for calculating
358
+ // getTopPoolsForToken. It is optional for a DEX
359
+ // to implement this
360
+ async updatePoolState(): Promise<void> {
361
+ return Promise.resolve();
362
+ }
363
+
364
+ // Returns a list of top pools based on liquidity. Max
365
+ // limit number pools should be returned.
366
+ async getTopPoolsForToken(
367
+ tokenAddress: Address,
368
+ limit: number,
369
+ ): Promise<PoolLiquidity[]> {
370
+ // Get the list of pools using the token.
371
+ const pools = this.getPoolsByTokenAddress(tokenAddress);
372
+ if (!pools.length) return [];
373
+
374
+ const results = await Promise.all<PoolLiquidity>(
375
+ pools.map(async pool => {
376
+ // Get the pool's balance and its USD value.
377
+ const eventPool = this.eventPools[pool.id];
378
+ const blockNumber =
379
+ await this.dexHelper.web3Provider.eth.getBlockNumber();
380
+ const state = await eventPool.getStateOrGenerate(blockNumber);
381
+
382
+ const usd0 = await this.dexHelper.getTokenUSDPrice(
383
+ { address: pool.token0, decimals: 18 },
384
+ BigInt(state.balance0),
385
+ );
386
+ const usd1 = await this.dexHelper.getTokenUSDPrice(
387
+ { address: pool.token1, decimals: 18 },
388
+ BigInt(state.balance1),
389
+ );
390
+
391
+ // Get the other token in the pair.
392
+ const pairedToken =
393
+ pool.token0 === tokenAddress.toLowerCase()
394
+ ? { address: pool.token1, decimals: 18 }
395
+ : { address: pool.token0, decimals: 18 };
396
+
397
+ return {
398
+ exchange: this.dexKey,
399
+ address: pool.address,
400
+ connectorTokens: [pairedToken],
401
+ liquidityUSD: usd0 + usd1,
402
+ };
403
+ }),
404
+ );
405
+ return results
406
+ .filter(r => r)
407
+ .sort((a, b) => a.liquidityUSD - b.liquidityUSD)
408
+ .slice(0, limit);
409
+ }
410
+
411
+ // This is optional function in case if your implementation has acquired any resources
412
+ // you need to release for graceful shutdown. For example, it may be any interval timer
413
+ releaseResources(): AsyncOrSync<void> {}
414
+ }
@@ -0,0 +1,29 @@
1
+ import { Address } from '../../types';
2
+
3
+ // OSwapPoolState is the state of the event subscriber. It is the minimum
4
+ // set of parameters required to compute pool prices.
5
+ export type OSwapPoolState = {
6
+ traderate0: string;
7
+ traderate1: string;
8
+ balance0: string;
9
+ balance1: string;
10
+ };
11
+
12
+ // OSwapPoolState is the state of the event subscriber. It is the minimum
13
+ // set of parameters required to compute pool prices.
14
+ export type OSwapData = {
15
+ pool: Address;
16
+ path: Address[];
17
+ };
18
+
19
+ // Each pool has a contract address and token pairs.
20
+ export type OSwapPool = {
21
+ id: string;
22
+ address: Address;
23
+ token0: Address;
24
+ token1: Address;
25
+ };
26
+
27
+ export type DexParams = {
28
+ pools: [OSwapPool];
29
+ };
@@ -1807,7 +1807,7 @@ export const Holders: {
1807
1807
  PRIME: '0xe3879b7359695f802d6FD56Bb76fD82C362Dafd6',
1808
1808
  ETH: '0xd34ea7278e6bd48defe656bbe263aef11101469c',
1809
1809
  MAV: '0xf977814e90da44bfa03b6295a0616a897441acec',
1810
- USDC: '0xaac391f166f33cdaefaa4afa6616a3bea66b694d',
1810
+ USDC: '0x21bD501F86A0B5cE0907651Df3368DA905B300A9',
1811
1811
  USDbC: '0x4bb6b2efe7036020ba6f02a05602546c9f25bf28',
1812
1812
  DAI: '0x20f03e26968b179025f65c1f4afadfd3959c8d03',
1813
1813
  BAL: '0x854b004700885a61107b458f11ecc169a019b764',