@paraswap/dex-lib 2.14.0 → 2.14.1

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 (64) hide show
  1. package/build/config.js +23 -5
  2. package/build/config.js.map +1 -1
  3. package/build/dex/index.js +2 -2
  4. package/build/dex/index.js.map +1 -1
  5. package/build/dex/simple-exchange.d.ts +1 -0
  6. package/build/dex/simple-exchange.js +2 -0
  7. package/build/dex/simple-exchange.js.map +1 -1
  8. package/build/lib/decoders.d.ts +2 -1
  9. package/build/lib/decoders.js +8 -1
  10. package/build/lib/decoders.js.map +1 -1
  11. package/build/lib/multi-wrapper.d.ts +2 -1
  12. package/build/lib/multi-wrapper.js.map +1 -1
  13. package/build/lib/tokens/balancer-fetcher.js +4 -5
  14. package/build/lib/tokens/balancer-fetcher.js.map +1 -1
  15. package/build/lib/tokens/utils.d.ts +2 -2
  16. package/build/lib/tokens/utils.js +1 -1
  17. package/build/lib/tokens/utils.js.map +1 -1
  18. package/build/types.d.ts +3 -0
  19. package/dex-template/__DexName__-e2e.test.ts.template +1 -0
  20. package/dex-template/__DexName__-events.test.ts.template +1 -0
  21. package/dex-template/__DexName__-integration.test.ts.template +1 -0
  22. package/dex-template/__DexName__-pool.ts.template +8 -5
  23. package/package.json +1 -1
  24. package/scripts/generate-bytecode.ts +2 -0
  25. package/src/abi/woo-fi-v2/IntegrationHelper.abi.json +116 -0
  26. package/src/abi/{woo-fi/Wooracle.abi.json → woo-fi-v2/WooOracleV2.abi.json} +148 -50
  27. package/src/abi/{woo-fi/WooPP.abi.json → woo-fi-v2/WooPPV2.abi.json} +201 -169
  28. package/src/config.ts +27 -5
  29. package/src/dex/balancer-v2/balancer-v2-e2e.test.ts +0 -1
  30. package/src/dex/index.ts +2 -2
  31. package/src/dex/simple-exchange.ts +3 -0
  32. package/src/dex/woo-fi-v2/config.ts +87 -0
  33. package/src/dex/woo-fi-v2/constants.ts +22 -0
  34. package/src/dex/woo-fi-v2/decoders.ts +45 -0
  35. package/src/dex/woo-fi-v2/types.ts +63 -0
  36. package/src/dex/woo-fi-v2/utils.ts +19 -0
  37. package/src/dex/woo-fi-v2/woo-fi-v2-e2e.test.ts +216 -0
  38. package/src/dex/woo-fi-v2/woo-fi-v2-integration.test.ts +495 -0
  39. package/src/dex/woo-fi-v2/woo-fi-v2-math.ts +195 -0
  40. package/src/dex/woo-fi-v2/woo-fi-v2-pool.ts +112 -0
  41. package/src/dex/woo-fi-v2/woo-fi-v2.ts +487 -0
  42. package/src/lib/decoders.ts +12 -1
  43. package/src/lib/log-messages-suppressor.ts +173 -0
  44. package/src/lib/multi-wrapper.ts +2 -1
  45. package/src/lib/stateful-rpc-poller/state-polling-manager.ts +320 -0
  46. package/src/lib/stateful-rpc-poller/stateful-rpc-poller.ts +604 -0
  47. package/src/lib/stateful-rpc-poller/types.ts +66 -0
  48. package/src/lib/stateful-rpc-poller/utils.ts +23 -0
  49. package/src/lib/tokens/balancer-fetcher.ts +5 -6
  50. package/src/lib/tokens/utils.ts +5 -3
  51. package/src/types.ts +4 -0
  52. package/tests/constants-e2e.ts +8 -3
  53. package/tests/tenderly-simulation.ts +1 -1
  54. package/tests/utils-e2e.ts +2 -0
  55. package/tests/utils.ts +2 -0
  56. package/src/abi/woo-fi/WooFeeManager.abi.json +0 -318
  57. package/src/dex/woo-fi/config.ts +0 -141
  58. package/src/dex/woo-fi/constants.ts +0 -21
  59. package/src/dex/woo-fi/types.ts +0 -55
  60. package/src/dex/woo-fi/woo-fi-decimal-math.ts +0 -45
  61. package/src/dex/woo-fi/woo-fi-e2e.test.ts +0 -183
  62. package/src/dex/woo-fi/woo-fi-integration.test.ts +0 -416
  63. package/src/dex/woo-fi/woo-fi-math.ts +0 -527
  64. package/src/dex/woo-fi/woo-fi.ts +0 -693
@@ -0,0 +1,112 @@
1
+ import _ from 'lodash';
2
+ import { IDexHelper } from '../../dex-helper/idex-helper';
3
+ import {
4
+ DecimalInfo,
5
+ DexParams,
6
+ MulticallResultOutputs,
7
+ PoolState,
8
+ TokenInfo,
9
+ TokenState,
10
+ } from './types';
11
+ import { StatefulRpcPoller } from '../../lib/stateful-rpc-poller/stateful-rpc-poller';
12
+ import { pollingManagerCbExtractor } from '../../lib/stateful-rpc-poller/utils';
13
+ import { StatePollingManager } from '../../lib/stateful-rpc-poller/state-polling-manager';
14
+ import { MultiCallParams } from '../../lib/multi-wrapper';
15
+ import { booleanDecode, uint256ToBigInt } from '../../lib/decoders';
16
+ import { ifaces } from './utils';
17
+ import { Token } from '../../types';
18
+ import { decimalInfoDecoder, stateDecoder, tokenInfoDecoder } from './decoders';
19
+
20
+ export class WooFiV2PollingPool extends StatefulRpcPoller<
21
+ PoolState,
22
+ MulticallResultOutputs
23
+ > {
24
+ constructor(
25
+ dexKey: string,
26
+ poolIdentifier: string,
27
+ dexHelper: IDexHelper,
28
+ protected config: DexParams,
29
+ // It already includes quoteToken
30
+ protected tokens: Token[],
31
+ ) {
32
+ const callbacks = pollingManagerCbExtractor(
33
+ StatePollingManager.getInstance(dexHelper),
34
+ );
35
+
36
+ super(dexKey, poolIdentifier, dexHelper, 0, 0, false, callbacks);
37
+ }
38
+
39
+ protected _getFetchStateMultiCalls(): MultiCallParams<MulticallResultOutputs>[] {
40
+ return (
41
+ [
42
+ {
43
+ target: this.config.wooPPV2Address,
44
+ callData: ifaces.PPV2.encodeFunctionData('paused', []),
45
+ decodeFunction: booleanDecode,
46
+ },
47
+ {
48
+ target: this.config.wooOracleV2Address,
49
+ callData: ifaces.oracleV2.encodeFunctionData('timestamp', []),
50
+ decodeFunction: uint256ToBigInt,
51
+ },
52
+ ] as MultiCallParams<MulticallResultOutputs>[]
53
+ ).concat(
54
+ this.tokens
55
+ .map(t => [
56
+ {
57
+ target: this.config.wooPPV2Address,
58
+ callData: ifaces.PPV2.encodeFunctionData('tokenInfos', [t.address]),
59
+ decodeFunction: tokenInfoDecoder,
60
+ },
61
+ {
62
+ target: this.config.wooPPV2Address,
63
+ callData: ifaces.PPV2.encodeFunctionData('decimalInfo', [
64
+ t.address,
65
+ ]),
66
+ decodeFunction: decimalInfoDecoder,
67
+ },
68
+ {
69
+ target: this.config.wooOracleV2Address,
70
+ callData: ifaces.oracleV2.encodeFunctionData('state', [t.address]),
71
+ decodeFunction: stateDecoder,
72
+ },
73
+ ])
74
+ .flat(),
75
+ );
76
+ }
77
+
78
+ protected _parseStateFromMultiResults(
79
+ multiOutputs: MulticallResultOutputs[],
80
+ ): PoolState {
81
+ const [isPaused, oracleTimestamp, ...remained] = multiOutputs as [
82
+ boolean,
83
+ bigint,
84
+ ...MulticallResultOutputs[],
85
+ ];
86
+
87
+ const tokenInfos: Record<string, TokenInfo> = {};
88
+ const decimals: Record<string, DecimalInfo> = {};
89
+ const tokenStates: Record<string, TokenState> = {};
90
+
91
+ _.chunk(remained, 3).forEach((chunk, i) => {
92
+ const [tokenInfo, decimalInfo, tokenState] = chunk as [
93
+ TokenInfo,
94
+ DecimalInfo,
95
+ TokenState,
96
+ ];
97
+ const token = this.tokens[i];
98
+
99
+ tokenInfos[token.address] = tokenInfo;
100
+ decimals[token.address] = decimalInfo;
101
+ tokenStates[token.address] = tokenState;
102
+ });
103
+
104
+ return {
105
+ tokenInfos,
106
+ tokenStates,
107
+ decimals,
108
+ oracleTimestamp,
109
+ isPaused,
110
+ };
111
+ }
112
+ }
@@ -0,0 +1,487 @@
1
+ import {
2
+ Token,
3
+ Address,
4
+ ExchangePrices,
5
+ PoolPrices,
6
+ AdapterExchangeParam,
7
+ SimpleExchangeParam,
8
+ PoolLiquidity,
9
+ Logger,
10
+ } from '../../types';
11
+ import { SwapSide, Network, NULL_ADDRESS } from '../../constants';
12
+ import * as CALLDATA_GAS_COST from '../../calldata-gas-cost';
13
+ import { getBigIntPow, getDexKeysWithNetwork } from '../../utils';
14
+ import { IDex } from '../../dex/idex';
15
+ import { addressArrayDecode, uint8ToNumber } from '../../lib/decoders';
16
+ import { IDexHelper } from '../../dex-helper/idex-helper';
17
+ import { WooFiV2Data, DexParams } from './types';
18
+ import { SimpleExchange } from '../simple-exchange';
19
+ import { WooFiV2Config, Adapters } from './config';
20
+ import { WooFiV2PollingPool } from './woo-fi-v2-pool';
21
+ import { WooFiV2Math } from './woo-fi-v2-math';
22
+ import { MIN_CONVERSION_RATE, WOO_FI_V2_GAS_COST } from './constants';
23
+ import { assert } from 'ts-essentials';
24
+ import { ethers } from 'ethers';
25
+ import { addressDecode } from '../../lib/decoders';
26
+ import { ifaces } from './utils';
27
+ import { StatePollingManager } from '../../lib/stateful-rpc-poller/state-polling-manager';
28
+
29
+ export class WooFiV2 extends SimpleExchange implements IDex<WooFiV2Data> {
30
+ readonly math: WooFiV2Math;
31
+
32
+ protected pollingManager: StatePollingManager;
33
+
34
+ protected pollingPool?: WooFiV2PollingPool;
35
+
36
+ readonly hasConstantPriceLargeAmounts = false;
37
+ readonly needWrapNative = true;
38
+
39
+ readonly isFeeOnTransferSupported = false;
40
+
41
+ readonly isStatePollingDex = true;
42
+
43
+ readonly quoteTokenAddress: Address;
44
+
45
+ protected _baseTokens?: Token[];
46
+
47
+ // Since exchange anyways takes fee, we provide our fee wallet
48
+ // to take part of that fee and move to DAO
49
+ protected rebateTo?: Address;
50
+
51
+ tokenByAddress?: Record<Address, Token>;
52
+
53
+ vaultUSDBalance: number = 0;
54
+
55
+ public static dexKeysWithNetwork: { key: string; networks: Network[] }[] =
56
+ getDexKeysWithNetwork(WooFiV2Config);
57
+
58
+ logger: Logger;
59
+
60
+ constructor(
61
+ protected network: Network,
62
+ dexKey: string,
63
+ readonly dexHelper: IDexHelper,
64
+ protected adapters = Adapters[network] || {},
65
+ readonly config = WooFiV2Config[dexKey][network],
66
+ ) {
67
+ super(dexHelper, dexKey);
68
+ const loggerName = `${dexKey}-${network}`;
69
+ this.logger = dexHelper.getLogger(loggerName);
70
+
71
+ // Normalise once all config addresses and use across all scenarios
72
+ this.config = this._toLowerForAllConfigAddresses();
73
+
74
+ this.quoteTokenAddress = this.config.quoteToken.address;
75
+
76
+ // Do not do it singleton, because different networks will have different
77
+ // states at the same time
78
+ this.math = new WooFiV2Math(
79
+ dexHelper.getLogger(`${loggerName}_math`),
80
+ this.quoteTokenAddress,
81
+ );
82
+ this.pollingManager = StatePollingManager.getInstance(dexHelper);
83
+ }
84
+
85
+ private _toLowerForAllConfigAddresses() {
86
+ // If new config property will be added, the TS will throw compile error
87
+ const newConfig: DexParams = {
88
+ wooPPV2Address: this.config.wooPPV2Address.toLowerCase(),
89
+ wooOracleV2Address: this.config.wooOracleV2Address.toLowerCase(),
90
+ integrationHelperAddress:
91
+ this.config.integrationHelperAddress.toLowerCase(),
92
+ quoteToken: {
93
+ ...this.config.quoteToken,
94
+ address: this.config.quoteToken.address.toLowerCase(),
95
+ },
96
+ };
97
+ return newConfig;
98
+ }
99
+
100
+ get baseTokens(): Token[] {
101
+ if (!this._baseTokens) {
102
+ throw new Error(
103
+ `Base tokens are not set for ${this.dexKey}-${this.network}. Not properly initialized`,
104
+ );
105
+ }
106
+ return this._baseTokens;
107
+ }
108
+
109
+ async initializePricing(blockNumber: number) {
110
+ await this.initializeTokensAndAddresses();
111
+ this._initializePollingPool();
112
+ }
113
+
114
+ getAdapters(side: SwapSide): { name: string; index: number }[] | null {
115
+ return this.adapters[side] ? this.adapters[side] : null;
116
+ }
117
+
118
+ async getPoolIdentifiers(
119
+ srcToken: Token,
120
+ destToken: Token,
121
+ side: SwapSide,
122
+ blockNumber: number,
123
+ ): Promise<string[]> {
124
+ if (side === SwapSide.BUY) return [];
125
+
126
+ if (this.tokenByAddress === undefined) {
127
+ this.logger.error(`tokenByAddress is undefined in getPoolIdentifiers`);
128
+ return [];
129
+ }
130
+
131
+ const _srcToken = this.dexHelper.config.wrapETH(srcToken);
132
+ const _destToken = this.dexHelper.config.wrapETH(destToken);
133
+
134
+ const _srcAddress = _srcToken.address.toLowerCase();
135
+ const _destAddress = _destToken.address.toLowerCase();
136
+
137
+ if (_srcAddress === _destAddress) return [];
138
+
139
+ if (
140
+ !this.tokenByAddress[_srcAddress] ||
141
+ !this.tokenByAddress[_destAddress]
142
+ ) {
143
+ return [];
144
+ }
145
+
146
+ return [this.getIdentifier()];
147
+ }
148
+
149
+ getIdentifier() {
150
+ return `${this.dexKey}_wooppv2`;
151
+ }
152
+
153
+ async getPricesVolume(
154
+ srcToken: Token,
155
+ destToken: Token,
156
+ amounts: bigint[],
157
+ side: SwapSide,
158
+ blockNumber: number,
159
+ limitPools?: string[],
160
+ ): Promise<null | ExchangePrices<WooFiV2Data>> {
161
+ if (side === SwapSide.BUY) return null;
162
+
163
+ try {
164
+ if (this.tokenByAddress === undefined) {
165
+ this.logger.error(`tokenByAddress is undefined in getPricesVolume`);
166
+ return null;
167
+ }
168
+
169
+ const _srcToken = this.dexHelper.config.wrapETH(srcToken);
170
+ const _destToken = this.dexHelper.config.wrapETH(destToken);
171
+
172
+ const _srcAddress = _srcToken.address.toLowerCase();
173
+ const _destAddress = _destToken.address.toLowerCase();
174
+
175
+ if (_srcAddress === _destAddress) return null;
176
+
177
+ if (
178
+ !this.tokenByAddress[_srcAddress] ||
179
+ !this.tokenByAddress[_destAddress]
180
+ )
181
+ return null;
182
+
183
+ const expectedIdentifier = this.getIdentifier();
184
+
185
+ if (
186
+ limitPools !== undefined &&
187
+ !limitPools.some(p => p === expectedIdentifier)
188
+ )
189
+ return null;
190
+
191
+ const unitVolume = getBigIntPow(_srcToken.decimals);
192
+
193
+ const _amounts = [unitVolume, ...amounts.slice(1)];
194
+
195
+ assert(
196
+ this.pollingPool,
197
+ 'pollingPool is not initialized in getPricesVolume',
198
+ );
199
+
200
+ const state = await this.pollingPool.getState(blockNumber);
201
+
202
+ if (state === null) {
203
+ this.logger.error(`State is null in getPricesVolume`);
204
+ return null;
205
+ }
206
+
207
+ if (state.value.isPaused) {
208
+ this.logger.warn(
209
+ `${this.dexKey} is paused on ${this.network} in getPricesVolume`,
210
+ );
211
+ return null;
212
+ }
213
+
214
+ this.math.state = state.value;
215
+
216
+ const _prices = this.math.query(_srcAddress, _destAddress, _amounts);
217
+
218
+ if (!_prices) return null;
219
+
220
+ const unit = _prices[0];
221
+
222
+ let gasCost = WOO_FI_V2_GAS_COST.baseToBase;
223
+ if (_srcAddress === this.config.quoteToken.address) {
224
+ gasCost = WOO_FI_V2_GAS_COST.sellQuote;
225
+ } else if (_destAddress === this.config.quoteToken.address) {
226
+ gasCost = WOO_FI_V2_GAS_COST.sellBase;
227
+ } else {
228
+ this.logger.error(
229
+ `Can not estimate gas cost in getPricesVolume. Check the logic: ` +
230
+ `${_srcAddress}, ${_destAddress}, ${this.config.quoteToken.address}`,
231
+ );
232
+ }
233
+
234
+ return [
235
+ {
236
+ unit,
237
+ prices: [0n, ..._prices.slice(1)],
238
+ data: {},
239
+ poolIdentifier: expectedIdentifier,
240
+ exchange: this.dexKey,
241
+ gasCost,
242
+ poolAddresses: [this.config.wooPPV2Address],
243
+ },
244
+ ];
245
+ } catch (e) {
246
+ this.logger.error(
247
+ `Error_getPricesVolume ${srcToken.symbol || srcToken.address}, ${
248
+ destToken.symbol || destToken.address
249
+ }, ${side}:`,
250
+ e,
251
+ );
252
+ return null;
253
+ }
254
+ }
255
+
256
+ getCalldataGasCost(poolPrices: PoolPrices<WooFiV2Data>): number | number[] {
257
+ return CALLDATA_GAS_COST.DEX_OVERHEAD + CALLDATA_GAS_COST.ADDRESS;
258
+ }
259
+
260
+ getAdapterParam(
261
+ srcToken: string,
262
+ destToken: string,
263
+ srcAmount: string,
264
+ destAmount: string,
265
+ data: WooFiV2Data,
266
+ side: SwapSide,
267
+ ): AdapterExchangeParam {
268
+ if (side === SwapSide.BUY) throw new Error(`Buy not supported`);
269
+
270
+ let rebateTo = this.rebateTo;
271
+ if (rebateTo === undefined) {
272
+ this.logger.error(`rebateTo is undefined in getAdapterParam`);
273
+ rebateTo = NULL_ADDRESS;
274
+ }
275
+
276
+ const payload = this.abiCoder.encodeParameter('address', rebateTo);
277
+
278
+ return {
279
+ targetExchange: this.config.wooPPV2Address,
280
+ payload,
281
+ networkFee: '0',
282
+ };
283
+ }
284
+
285
+ async getSimpleParam(
286
+ srcToken: string,
287
+ destToken: string,
288
+ srcAmount: string,
289
+ destAmount: string,
290
+ data: WooFiV2Data,
291
+ side: SwapSide,
292
+ ): Promise<SimpleExchangeParam> {
293
+ if (side === SwapSide.BUY) throw new Error(`Buy not supported`);
294
+
295
+ const _srcToken = srcToken.toLowerCase();
296
+ const _destToken = destToken.toLowerCase();
297
+
298
+ let rebateTo = this.rebateTo;
299
+ if (rebateTo === undefined) {
300
+ this.logger.error(`rebateTo is undefined in getAdapterParam`);
301
+ rebateTo = NULL_ADDRESS;
302
+ }
303
+
304
+ const swapData = ifaces.PPV2.encodeFunctionData('swap', [
305
+ _srcToken,
306
+ _destToken,
307
+ srcAmount,
308
+ MIN_CONVERSION_RATE,
309
+ this.augustusAddress,
310
+ rebateTo,
311
+ ]);
312
+
313
+ const transferParams = this.erc20Interface.encodeFunctionData('transfer', [
314
+ this.config.wooPPV2Address,
315
+ srcAmount,
316
+ ]);
317
+
318
+ return {
319
+ callees: [srcToken, this.config.wooPPV2Address],
320
+ calldata: [transferParams, swapData],
321
+ values: ['0', '0'],
322
+ networkFee: '0',
323
+ };
324
+ }
325
+
326
+ async updatePoolState(): Promise<void> {
327
+ if (this._baseTokens === undefined || this.tokenByAddress === undefined) {
328
+ await this.initializeTokensAndAddresses();
329
+ }
330
+ if (this.pollingPool === undefined) {
331
+ this._initializePollingPool();
332
+ }
333
+
334
+ if (this.tokenByAddress === undefined) {
335
+ this.logger.error(`tokenByAddress is undefined in updatePoolState`);
336
+ return;
337
+ }
338
+
339
+ assert(
340
+ this.pollingPool,
341
+ 'pollingPool is not initialized in updatePoolState',
342
+ );
343
+ const state = await this.pollingPool.getState();
344
+
345
+ if (!state) {
346
+ this.logger.error(
347
+ `Failed to updatePoolState. State is null. VaultUSDBalance: ${this.vaultUSDBalance} was not updated`,
348
+ );
349
+ return;
350
+ }
351
+
352
+ const tokenBalancesUSD = await Promise.all(
353
+ Object.values(this.tokenByAddress).map(t =>
354
+ this.dexHelper.getTokenUSDPrice(
355
+ t,
356
+ state.value.tokenInfos[t.address].reserve,
357
+ ),
358
+ ),
359
+ );
360
+ this.vaultUSDBalance = tokenBalancesUSD.reduce(
361
+ (sum: number, curr: number) => sum + curr,
362
+ );
363
+ }
364
+
365
+ async getTopPoolsForToken(
366
+ tokenAddress: Address,
367
+ limit: number,
368
+ ): Promise<PoolLiquidity[]> {
369
+ const wrappedTokenAddress = this.dexHelper.config
370
+ .wrapETH({ address: tokenAddress, decimals: 0 })
371
+ .address.toLowerCase();
372
+
373
+ if (this.tokenByAddress === undefined) {
374
+ this.logger.error(`tokenByAddress is undefined in getTopPoolsForToken`);
375
+ return [];
376
+ }
377
+
378
+ if (!this.tokenByAddress[wrappedTokenAddress]) return [];
379
+
380
+ assert(
381
+ this.pollingPool,
382
+ 'pollingPool is not initialized in getTopPoolsForToken',
383
+ );
384
+ const latestState = await this.pollingPool.getState();
385
+ if (!latestState) return [];
386
+
387
+ if (latestState.value.isPaused) {
388
+ this.logger.warn(`Paused on ${this.network} in getTopPoolsForToken`);
389
+ return [];
390
+ }
391
+
392
+ const connectorTokens = Object.values(this.tokenByAddress).filter(
393
+ t => t.address !== wrappedTokenAddress,
394
+ );
395
+
396
+ return [
397
+ {
398
+ exchange: this.dexKey,
399
+ address: this.config.wooPPV2Address,
400
+ connectorTokens,
401
+ liquidityUSD: this.vaultUSDBalance,
402
+ },
403
+ ];
404
+ }
405
+
406
+ private _initializeTokenByAddress(baseTokens: Token[]) {
407
+ this.tokenByAddress = baseTokens.reduce(
408
+ (acc, cur) => {
409
+ acc[cur.address] = cur;
410
+ return acc;
411
+ },
412
+ { [this.quoteTokenAddress]: this.config.quoteToken },
413
+ );
414
+ }
415
+
416
+ async _fetchBaseTokensAndFeeWallet(): Promise<Address[]> {
417
+ return (
418
+ await this.dexHelper.multiWrapper.aggregate([
419
+ {
420
+ target: this.augustusAddress,
421
+ callData: this.augustusInterface.encodeFunctionData(
422
+ 'getFeeWallet',
423
+ [],
424
+ ),
425
+ decodeFunction: addressDecode,
426
+ },
427
+ {
428
+ target: this.config.integrationHelperAddress,
429
+ callData:
430
+ ifaces.integrationHelper.encodeFunctionData('allBaseTokens'),
431
+ decodeFunction: addressArrayDecode,
432
+ },
433
+ ])
434
+ ).flat();
435
+ }
436
+
437
+ async _fetchDecimals(baseTokenAddresses: Address[]): Promise<number[]> {
438
+ return this.dexHelper.multiWrapper.aggregate(
439
+ baseTokenAddresses.map(address => {
440
+ return {
441
+ target: address,
442
+ callData: this.erc20Interface.encodeFunctionData('decimals'),
443
+ decodeFunction: uint8ToNumber,
444
+ };
445
+ }),
446
+ );
447
+ }
448
+
449
+ async initializeTokensAndAddresses() {
450
+ const [rebateTo, ...baseTokenAddresses] =
451
+ await this._fetchBaseTokensAndFeeWallet();
452
+
453
+ assert(ethers.utils.isAddress(rebateTo), 'Invalid rebateTo address');
454
+
455
+ this.rebateTo = rebateTo;
456
+ const decimals = await this._fetchDecimals(baseTokenAddresses);
457
+
458
+ assert(
459
+ decimals.length === baseTokenAddresses.length,
460
+ 'Decimals length mismatch',
461
+ );
462
+
463
+ this._baseTokens = baseTokenAddresses.reduce<Token[]>((acc, curr, i) => {
464
+ acc.push({
465
+ address: curr,
466
+ decimals: decimals[i],
467
+ });
468
+ return acc;
469
+ }, []);
470
+
471
+ this._initializeTokenByAddress(this.baseTokens);
472
+ }
473
+
474
+ private _initializePollingPool() {
475
+ assert(this.tokenByAddress, 'tokenByAddress is not properly');
476
+
477
+ this.pollingPool = new WooFiV2PollingPool(
478
+ this.dexKey,
479
+ this.getIdentifier(),
480
+ this.dexHelper,
481
+ this.config,
482
+ Object.values(this.tokenByAddress),
483
+ );
484
+
485
+ this.pollingManager.initializeAllPendingPools();
486
+ }
487
+ }
@@ -28,12 +28,15 @@ export const extractSuccessAndValue = (
28
28
  export function generalDecoder<T>(
29
29
  result: MultiResult<BytesLike> | BytesLike,
30
30
  types: string[],
31
- defaultValue: T,
31
+ defaultValue: T | undefined,
32
32
  parser?: (v: Result) => T,
33
33
  ): T {
34
34
  const [isSuccess, toDecode] = extractSuccessAndValue(result);
35
35
 
36
36
  if (!isSuccess || toDecode === '0x') {
37
+ if (defaultValue === undefined) {
38
+ throw new Error(`Failed to decode result: ${result}`);
39
+ }
37
40
  return defaultValue;
38
41
  }
39
42
 
@@ -136,6 +139,14 @@ export const addressDecode = (
136
139
  );
137
140
  };
138
141
 
142
+ export const addressArrayDecode = (
143
+ result: MultiResult<BytesLike> | BytesLike,
144
+ ): string => {
145
+ return generalDecoder(result, ['address[]'], [], v =>
146
+ v[0].map((a: string) => a.toLowerCase()),
147
+ );
148
+ };
149
+
139
150
  export const stringDecode = (
140
151
  result: MultiResult<BytesLike> | BytesLike,
141
152
  ): string => {