@paraswap/dex-lib 2.42.30 → 2.42.31

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 (83) hide show
  1. package/build/abi/smardex/smardex-factory.json +185 -0
  2. package/build/abi/smardex/smardex-pool.json +578 -0
  3. package/build/abi/smardex/smardex-router.json +648 -0
  4. package/build/abi/trader-joe-v2_1/FactoryABI.json +0 -0
  5. package/build/abi/trader-joe-v2_1/PairABI.json +1493 -0
  6. package/build/abi/trader-joe-v2_1/RouterABI.json +1489 -0
  7. package/build/abi/wombat/pool-v2.json +1289 -0
  8. package/build/abi/wombat/pool-v3.json +2013 -0
  9. package/build/dex/index.js +2 -2
  10. package/build/dex/index.js.map +1 -1
  11. package/build/dex/smardex/subgraph-queries.d.ts +1 -0
  12. package/build/dex/smardex/subgraph-queries.js +17 -0
  13. package/build/dex/smardex/subgraph-queries.js.map +1 -0
  14. package/build/dex/smardex/usd-reserves.d.ts +23 -0
  15. package/build/dex/smardex/usd-reserves.js +86 -0
  16. package/build/dex/smardex/usd-reserves.js.map +1 -0
  17. package/build/dex/trader-joe-v2-1-2/config.d.ts +4 -0
  18. package/build/dex/trader-joe-v2-1-2/config.js +43 -0
  19. package/build/dex/trader-joe-v2-1-2/config.js.map +1 -0
  20. package/build/dex/trader-joe-v2-1-2/constants.d.ts +17 -0
  21. package/build/dex/trader-joe-v2-1-2/constants.js +19 -0
  22. package/build/dex/trader-joe-v2-1-2/constants.js.map +1 -0
  23. package/build/dex/trader-joe-v2-1-2/trader-joe-v2-1-2-pool.d.ts +60 -0
  24. package/build/dex/trader-joe-v2-1-2/trader-joe-v2-1-2-pool.js +199 -0
  25. package/build/dex/trader-joe-v2-1-2/trader-joe-v2-1-2-pool.js.map +1 -0
  26. package/build/dex/trader-joe-v2-1-2/trader-joe-v2-1-2.d.ts +49 -0
  27. package/build/dex/trader-joe-v2-1-2/trader-joe-v2-1-2.js +269 -0
  28. package/build/dex/trader-joe-v2-1-2/trader-joe-v2-1-2.js.map +1 -0
  29. package/build/dex/trader-joe-v2-1-2/types.d.ts +81 -0
  30. package/build/dex/trader-joe-v2-1-2/types.js +9 -0
  31. package/build/dex/trader-joe-v2-1-2/types.js.map +1 -0
  32. package/build/dex/trader-joe-v2_1/config.d.ts +4 -0
  33. package/build/dex/trader-joe-v2_1/config.js +43 -0
  34. package/build/dex/trader-joe-v2_1/config.js.map +1 -0
  35. package/build/dex/trader-joe-v2_1/constants.d.ts +16 -0
  36. package/build/dex/trader-joe-v2_1/constants.js +18 -0
  37. package/build/dex/trader-joe-v2_1/constants.js.map +1 -0
  38. package/build/dex/trader-joe-v2_1/trader-joe-v2.1.d.ts +0 -0
  39. package/build/dex/trader-joe-v2_1/trader-joe-v2.1.js +384 -0
  40. package/build/dex/trader-joe-v2_1/trader-joe-v2.1.js.map +1 -0
  41. package/build/dex/trader-joe-v2_1/types.d.ts +39 -0
  42. package/build/dex/trader-joe-v2_1/types.js +3 -0
  43. package/build/dex/trader-joe-v2_1/types.js.map +1 -0
  44. package/build/dex/wombat/utils.d.ts +1 -0
  45. package/build/dex/wombat/utils.js +14 -1
  46. package/build/dex/wombat/utils.js.map +1 -1
  47. package/build/dex/wombat/wombat-bmw.d.ts +2 -2
  48. package/build/dex/wombat/wombat-bmw.js +8 -25
  49. package/build/dex/wombat/wombat-bmw.js.map +1 -1
  50. package/build/dex/wombat/wombat-pool-poller.d.ts +22 -0
  51. package/build/dex/wombat/wombat-pool-poller.js +164 -0
  52. package/build/dex/wombat/wombat-pool-poller.js.map +1 -0
  53. package/build/dex/wombat/wombat-pool.d.ts +51 -17
  54. package/build/dex/wombat/wombat-pool.js +398 -112
  55. package/build/dex/wombat/wombat-pool.js.map +1 -1
  56. package/build/dex/wombat/wombat.d.ts +1 -1
  57. package/build/dex/wombat/wombat.js +12 -18
  58. package/build/dex/wombat/wombat.js.map +1 -1
  59. package/package.json +1 -1
  60. package/src/abi/wombat/pool-v3.json +2013 -0
  61. package/src/dex/camelot/camelot-pool-discovery.test.ts +149 -0
  62. package/src/dex/index.ts +2 -2
  63. package/src/dex/wombat/utils.ts +20 -0
  64. package/src/dex/wombat/wombat-bmw.ts +8 -31
  65. package/src/dex/wombat/wombat-e2e.test.ts +13 -1
  66. package/src/dex/wombat/wombat-events.test.ts +147 -0
  67. package/src/dex/wombat/wombat-integration.test.ts +70 -111
  68. package/src/dex/wombat/wombat-pool.ts +623 -171
  69. package/src/dex/wombat/wombat.ts +13 -23
  70. package/tests/constants-e2e.ts +11 -1
  71. package/build/abi/algebra/AlgebraPool.abi.json +0 -727
  72. package/build/abi/uniswap-v3/UniswapV3Quoter.abi.json +0 -193
  73. package/build/dex/algebra/algebra-pool.d.ts +0 -46
  74. package/build/dex/algebra/algebra-pool.js +0 -336
  75. package/build/dex/algebra/algebra-pool.js.map +0 -1
  76. package/build/dex/quickswap/camelot-v3.d.ts +0 -6
  77. package/build/dex/quickswap/camelot-v3.js +0 -19
  78. package/build/dex/quickswap/camelot-v3.js.map +0 -1
  79. package/build/dex/quickswap/zyberswap-v3.d.ts +0 -6
  80. package/build/dex/quickswap/zyberswap-v3.js +0 -19
  81. package/build/dex/quickswap/zyberswap-v3.js.map +0 -1
  82. package/build/dex/uniswap-v2/rebase-tokens.json +0 -7
  83. /package/src/abi/wombat/{pool.json → pool-v2.json} +0 -0
@@ -1,152 +1,261 @@
1
1
  import { Interface } from '@ethersproject/abi';
2
- import { Address } from '@paraswap/core';
3
- import _ from 'lodash';
4
-
5
- import { MultiCallParams, MultiResult } from '../../lib/multi-wrapper';
6
- import { IDexHelper } from '../../dex-helper';
7
- import { StatefulRpcPoller } from '../../lib/stateful-rpc-poller/stateful-rpc-poller';
8
- import { StatePollingManager } from '../../lib/stateful-rpc-poller/state-polling-manager';
9
- import { ObjWithUpdateInfo } from '../../lib/stateful-rpc-poller/types';
10
- import { pollingManagerCbExtractor } from '../../lib/stateful-rpc-poller/utils';
2
+ import { AsyncOrSync, DeepReadonly } from 'ts-essentials';
3
+ import {
4
+ Address,
5
+ Log,
6
+ Logger,
7
+ MultiCallInput,
8
+ MultiCallOutput,
9
+ } from '../../types';
10
+ import { catchParseLogError } from '../../utils';
11
11
  import {
12
- addressArrayDecode,
13
- booleanDecode,
14
- uint256ToBigInt,
15
- uint8ToNumber,
16
- } from '../../lib/decoders';
17
- import PoolABI from '../../abi/wombat/pool.json';
12
+ InitializeStateOptions,
13
+ StatefulEventSubscriber,
14
+ } from '../../stateful-event-subscriber';
15
+ import { IDexHelper } from '../../dex-helper';
16
+ import PoolV2ABI from '../../abi/wombat/pool-v2.json';
17
+ import PoolV3ABI from '../../abi/wombat/pool-v3.json';
18
18
  import AssetABI from '../../abi/wombat/asset.json';
19
- import { uint120ToBigInt } from './utils';
20
- import { AssetState, MulticallResultOutputs, PoolState } from './types';
21
-
22
- export class WombatPool extends StatefulRpcPoller<
23
- PoolState,
24
- MulticallResultOutputs
25
- > {
26
- static readonly poolInterface = new Interface(PoolABI);
19
+ import { convertUint256ToInt256, toWad, WAD, wdiv, wmul } from './utils';
20
+ import { BlockHeader } from 'web3-eth';
21
+ import { AssetState, PoolState } from './types';
22
+
23
+ const CLEAR_RPC_CALL_COUNT_INTERVAL = 1000 * 60 * 5; // 5 minutes
24
+
25
+ export class WombatPool extends StatefulEventSubscriber<PoolState> {
26
+ static readonly poolV2Interface = new Interface(PoolV2ABI);
27
+ static readonly poolV3Interface = new Interface(PoolV3ABI);
27
28
  static readonly assetInterface = new Interface(AssetABI);
28
29
 
30
+ private rpcCallCount = 0;
31
+
32
+ private handlers: {
33
+ [event: string]: (
34
+ event: any,
35
+ state: DeepReadonly<PoolState>,
36
+ log: Readonly<Log>,
37
+ ) => AsyncOrSync<DeepReadonly<PoolState> | null>;
38
+ } = {};
39
+ private poolInterface: Interface = WombatPool.poolV2Interface;
40
+ private eventRefetched: string[];
41
+
42
+ blankState: PoolState = {
43
+ asset: {},
44
+ underlyingAddresses: [],
45
+ params: {
46
+ paused: false,
47
+ ampFactor: 0n,
48
+ haircutRate: 0n,
49
+ startCovRatio: 0n,
50
+ endCovRatio: 0n,
51
+ },
52
+ };
53
+
29
54
  constructor(
30
55
  dexKey: string,
31
- poolIdentifier: string,
32
- dexHelper: IDexHelper,
56
+ name: string,
57
+ protected network: number,
58
+ protected dexHelper: IDexHelper,
59
+ logger: Logger,
33
60
  protected poolAddress: Address,
34
- protected asset2TokenMap: Map<Address, Address>,
35
61
  ) {
36
- const callbacks = pollingManagerCbExtractor(
37
- StatePollingManager.getInstance(dexHelper),
62
+ super(dexKey, `${network}_${name}`, dexHelper, logger);
63
+
64
+ this.addressesSubscribed = [this.poolAddress];
65
+
66
+ // users-actions handlers
67
+ this.handlers['Swap'] = this.handleSwap.bind(this);
68
+ this.handlers['SwapV2'] = this.handleSwapV2.bind(this);
69
+
70
+ // admin-actions handlers
71
+ this.handlers['SetAmpFactor'] = this.handleSetAmpFactor.bind(this);
72
+ this.handlers['SetHaircutRate'] = this.handleSetHaircutRate.bind(this);
73
+ this.handlers['AssetAdded'] = this.handleAssetAdded.bind(this);
74
+ this.handlers['AssetRemoved'] = this.handleAssetRemoved.bind(this);
75
+ this.handlers['FillPool'] = this.handleFillPool.bind(this);
76
+ this.handlers['Paused'] = this.handlePaused.bind(this);
77
+ this.handlers['Unpaused'] = this.handleUnpaused.bind(this);
78
+ this.handlers['PausedAsset'] = this.handlePausedAsset.bind(this);
79
+ this.handlers['UnpausedAsset'] = this.handleUnpausedAsset.bind(this);
80
+
81
+ this.eventRefetched = ['Deposit', 'Withdraw'];
82
+
83
+ setInterval(() => {
84
+ this.rpcCallCount = 0;
85
+ }, CLEAR_RPC_CALL_COUNT_INTERVAL);
86
+ }
87
+
88
+ async initialize(
89
+ blockNumber: number,
90
+ options?: InitializeStateOptions<PoolState>,
91
+ ) {
92
+ const poolContract = new this.dexHelper.web3Provider.eth.Contract(
93
+ PoolV3ABI as any,
94
+ this.poolAddress,
38
95
  );
96
+ try {
97
+ await poolContract.methods.withdrawalHaircutRate().call({}, blockNumber);
98
+ this.poolInterface = WombatPool.poolV3Interface;
99
+ } catch (e) {
100
+ this.logger.info(
101
+ `no public variable withdrawalHaircutRate in pool ${this.poolAddress}, this is v2 pool`,
102
+ );
103
+ }
104
+ await super.initialize(blockNumber, options);
105
+ }
106
+
107
+ protected async processBlockLogs(
108
+ state: DeepReadonly<PoolState>,
109
+ logs: Readonly<Log>[],
110
+ blockHeader: Readonly<BlockHeader>,
111
+ ): Promise<DeepReadonly<PoolState> | null> {
112
+ let nextState: DeepReadonly<PoolState> | null = null;
113
+ for (const log of logs) {
114
+ try {
115
+ const event = this.poolInterface.parseLog(log);
116
+ if (this.eventRefetched.includes(event.name)) {
117
+ // if the state is refetched, no need to deal with the left logs in the block
118
+ return await this.generateState(log.blockNumber);
119
+ }
120
+ } catch (e) {
121
+ catchParseLogError(e, this.logger);
122
+ }
123
+
124
+ const retState: DeepReadonly<PoolState> | null = await this.processLog(
125
+ nextState || state,
126
+ log,
127
+ blockHeader,
128
+ );
39
129
 
40
- super(dexKey, poolIdentifier, dexHelper, 0, 0, false, callbacks);
130
+ if (retState) {
131
+ nextState = retState;
132
+ }
133
+ }
134
+ return nextState;
41
135
  }
42
136
 
43
- protected _getFetchStateMultiCalls(): MultiCallParams<MulticallResultOutputs>[] {
44
- const params: MultiCallParams<MulticallResultOutputs>[] = [];
137
+ /**
138
+ * The function is called every time any of the subscribed
139
+ * addresses release log. The function accepts the current
140
+ * state, updates the state according to the log, and returns
141
+ * the updated state.
142
+ * @param state - Current state of event subscriber
143
+ * @param log - Log released by one of the subscribed addresses
144
+ * @param blockHeader
145
+ * @returns Updates state of the event subscriber after the log
146
+ */
147
+ protected async processLog(
148
+ state: DeepReadonly<PoolState>,
149
+ log: Readonly<Log>,
150
+ blockHeader: Readonly<BlockHeader>,
151
+ ): Promise<DeepReadonly<PoolState> | null> {
152
+ try {
153
+ const event = this.poolInterface.parseLog(log);
154
+ if (event.name in this.handlers) {
155
+ return await this.handlers[event.name](event, state, log);
156
+ }
157
+ } catch (e) {
158
+ catchParseLogError(e, this.logger);
159
+ }
160
+
161
+ return null;
162
+ }
45
163
 
46
- params.push({
164
+ /**
165
+ * The function generates state using on-chain calls. This
166
+ * function is called to regenerate state if the event based
167
+ * system fails to fetch events and the local state is no
168
+ * more correct.
169
+ * @param blockNumber - Blocknumber for which the state should
170
+ * should be generated
171
+ * @returns state of the event subscriber at blocknumber
172
+ */
173
+ async generateState(blockNumber: number): Promise<DeepReadonly<PoolState>> {
174
+ this.rpcCallCount++;
175
+
176
+ if (this.rpcCallCount > 1) {
177
+ this.logger.warn(
178
+ `WombatPool generateState excessive RPC call. Name: ${
179
+ this.name
180
+ }. Called ${this.rpcCallCount} times during ${
181
+ CLEAR_RPC_CALL_COUNT_INTERVAL / 1000
182
+ }s interval`,
183
+ );
184
+ }
185
+ let multiCallInputs: MultiCallInput[] = [];
186
+
187
+ // 1.A generate pool params requests
188
+ // paused
189
+ multiCallInputs.push({
47
190
  target: this.poolAddress,
48
- callData: WombatPool.poolInterface.encodeFunctionData('paused'),
49
- decodeFunction: booleanDecode,
191
+ callData: this.poolInterface.encodeFunctionData('paused'),
50
192
  });
51
- params.push({
193
+ // ampFactor
194
+ multiCallInputs.push({
52
195
  target: this.poolAddress,
53
- callData: WombatPool.poolInterface.encodeFunctionData('ampFactor'),
54
- decodeFunction: uint256ToBigInt,
196
+ callData: this.poolInterface.encodeFunctionData('ampFactor'),
55
197
  });
56
- params.push({
198
+ // haircutRate
199
+ multiCallInputs.push({
57
200
  target: this.poolAddress,
58
- callData: WombatPool.poolInterface.encodeFunctionData('haircutRate'),
59
- decodeFunction: uint256ToBigInt,
201
+ callData: this.poolInterface.encodeFunctionData('haircutRate'),
60
202
  });
61
- params.push({
203
+ // startCovRatio
204
+ multiCallInputs.push({
62
205
  target: this.poolAddress,
63
- callData: WombatPool.poolInterface.encodeFunctionData('startCovRatio'),
64
- decodeFunction: uint256ToBigInt,
206
+ callData: this.poolInterface.encodeFunctionData('startCovRatio'),
65
207
  });
66
- params.push({
208
+ // endCovRatio
209
+ multiCallInputs.push({
67
210
  target: this.poolAddress,
68
- callData: WombatPool.poolInterface.encodeFunctionData('endCovRatio'),
69
- decodeFunction: uint256ToBigInt,
211
+ callData: this.poolInterface.encodeFunctionData('endCovRatio'),
70
212
  });
71
- params.push({
213
+ // tokens
214
+ multiCallInputs.push({
72
215
  target: this.poolAddress,
73
- callData: WombatPool.poolInterface.encodeFunctionData('getTokens'),
74
- decodeFunction: addressArrayDecode,
75
- });
76
-
77
- this.asset2TokenMap.forEach((token, asset) => {
78
- params.push({
79
- target: this.poolAddress,
80
- callData: WombatPool.poolInterface.encodeFunctionData('isPaused', [
81
- token,
82
- ]),
83
- decodeFunction: booleanDecode,
84
- });
85
- params.push({
86
- target: asset,
87
- callData: WombatPool.assetInterface.encodeFunctionData('cash'),
88
- decodeFunction: uint120ToBigInt,
89
- });
90
- params.push({
91
- target: asset,
92
- callData: WombatPool.assetInterface.encodeFunctionData('liability'),
93
- decodeFunction: uint120ToBigInt,
94
- });
95
- params.push({
96
- target: asset,
97
- callData: WombatPool.assetInterface.encodeFunctionData(
98
- 'underlyingTokenDecimals',
99
- ),
100
- decodeFunction: uint8ToNumber,
101
- });
102
- params.push({
103
- target: asset,
104
- callData:
105
- WombatPool.assetInterface.encodeFunctionData('getRelativePrice'),
106
- decodeFunction: uint256ToBigInt,
107
- });
216
+ callData: this.poolInterface.encodeFunctionData('getTokens'),
108
217
  });
109
218
 
110
- return params;
111
- }
219
+ // 1.B. invoke multicall
220
+ let returnData: MultiCallOutput[] = [];
221
+ if (multiCallInputs.length) {
222
+ returnData = (
223
+ await this.dexHelper.multiContract.methods
224
+ .aggregate(multiCallInputs)
225
+ .call({}, blockNumber)
226
+ ).returnData;
227
+ }
112
228
 
113
- protected _parseStateFromMultiResults(
114
- multiOutputs: MulticallResultOutputs[],
115
- ): PoolState {
116
- const [
117
- paused,
118
- ampFactor,
119
- haircutRate,
120
- startCovRatio,
121
- endCovRatio,
122
- tokens,
123
- ...remained
124
- ] = multiOutputs as [
125
- boolean,
126
- bigint,
127
- bigint,
128
- bigint,
129
- bigint,
130
- Address[],
131
- ...MulticallResultOutputs[],
132
- ];
229
+ let i = 0;
230
+ // 1.C. decode pool params
231
+ const paused = Boolean(
232
+ this.poolInterface.decodeFunctionResult('paused', returnData[i++])[0],
233
+ );
234
+ const ampFactor = BigInt(
235
+ this.poolInterface.decodeFunctionResult('ampFactor', returnData[i++])[0],
236
+ );
237
+ const haircutRate = BigInt(
238
+ this.poolInterface.decodeFunctionResult(
239
+ 'haircutRate',
240
+ returnData[i++],
241
+ )[0],
242
+ );
243
+ const startCovRatio = BigInt(
244
+ this.poolInterface.decodeFunctionResult(
245
+ 'startCovRatio',
246
+ returnData[i++],
247
+ )[0],
248
+ );
249
+ const endCovRatio = BigInt(
250
+ this.poolInterface.decodeFunctionResult(
251
+ 'endCovRatio',
252
+ returnData[i++],
253
+ )[0],
254
+ );
133
255
 
134
- const assetTokenArray = Array.from(this.asset2TokenMap.entries());
135
- const token2AssetStates = new Map<Address, AssetState>();
136
- _.chunk(remained, 5).forEach((chunk, i) => {
137
- const [paused, cash, liability, underlyingTokenDecimals, relativePrice] =
138
- chunk as [boolean, bigint, bigint, number, bigint | undefined];
139
-
140
- const [asset, token] = assetTokenArray[i];
141
- token2AssetStates.set(token, {
142
- address: asset,
143
- paused,
144
- cash,
145
- liability,
146
- underlyingTokenDecimals,
147
- relativePrice,
148
- });
149
- });
256
+ const tokens = this.poolInterface
257
+ .decodeFunctionResult('getTokens', returnData[i++])[0]
258
+ .map((tokenAddress: Address) => tokenAddress.toLowerCase());
150
259
 
151
260
  const poolState: PoolState = {
152
261
  params: {
@@ -160,77 +269,420 @@ export class WombatPool extends StatefulRpcPoller<
160
269
  asset: {},
161
270
  };
162
271
 
272
+ // 2.A. generate requests for getting asset addresses
273
+ multiCallInputs = tokens.map((tokenAddress: Address) => ({
274
+ target: this.poolAddress,
275
+ callData: this.poolInterface.encodeFunctionData('addressOfAsset', [
276
+ tokenAddress,
277
+ ]),
278
+ }));
279
+
280
+ // 2.B. invoke multicall
281
+ returnData = (
282
+ await this.dexHelper.multiContract.methods
283
+ .aggregate(multiCallInputs)
284
+ .call({}, blockNumber)
285
+ ).returnData;
286
+
287
+ // 2.C. decode asset addresses
288
+ const assets: Address[] = returnData.map(data => {
289
+ return this.poolInterface.decodeFunctionResult('addressOfAsset', data)[0];
290
+ });
291
+
292
+ // 3. get asset states
293
+ const assetState = await this.getAssetState(
294
+ this.poolAddress,
295
+ assets.map(asset => asset.toLowerCase()),
296
+ tokens,
297
+ blockNumber,
298
+ );
163
299
  const isMainPool =
164
- Array.from(token2AssetStates.values()).filter(
165
- assetState => assetState.relativePrice === undefined,
166
- ).length > 0;
167
- for (const token of poolState.underlyingAddresses) {
168
- if (!token2AssetStates.has(token)) {
169
- // this happens when asset has been added to pool but is not added to BMW yet
170
- continue;
171
- }
172
- poolState.asset[token] = token2AssetStates.get(token)!;
300
+ assetState.filter(asset => asset.relativePrice === undefined).length > 0;
301
+ for (let j = 0; j < tokens.length; j++) {
173
302
  if (isMainPool) {
174
- poolState.asset[token].relativePrice = undefined;
303
+ assetState[j].relativePrice = undefined;
175
304
  }
305
+ poolState.asset[tokens[j]] = assetState[j];
176
306
  }
177
307
 
178
308
  return poolState;
179
309
  }
180
310
 
181
- public async fetchLatestStateFromRpc(): Promise<ObjWithUpdateInfo<PoolState> | null> {
182
- const multiCalls = this.getFetchStateWithBlockInfoMultiCalls();
183
- try {
184
- const lastUpdatedAtMs = Date.now();
185
- const aggregatedResults = (await this.dexHelper.multiWrapper.tryAggregate<
186
- number | MulticallResultOutputs
187
- >(
188
- false,
189
- multiCalls as MultiCallParams<MulticallResultOutputs | number>[],
190
- undefined,
191
- undefined,
192
- // multiCalls includes calls asset.isPaused, asset.getRelativePrice
193
- // some of the contracts don't have these methods, so prevent logging errors
194
- false,
195
- )) as [MultiResult<number>, ...MultiResult<MulticallResultOutputs>[]];
196
-
197
- return this.parseStateFromMultiResultsWithBlockInfo(
198
- aggregatedResults,
199
- lastUpdatedAtMs,
311
+ handleSwap(
312
+ event: any,
313
+ state: DeepReadonly<PoolState>,
314
+ log: Readonly<Log>,
315
+ ): AsyncOrSync<DeepReadonly<PoolState> | null> {
316
+ const fromTokenAddress = event.args.fromToken.toString().toLowerCase();
317
+ const fromAmount = BigInt(event.args.fromAmount.toString());
318
+ const toTokenAddress = event.args.toToken.toString().toLowerCase();
319
+ const toAmount = BigInt(event.args.toAmount.toString());
320
+
321
+ if (
322
+ !state.underlyingAddresses.includes(fromTokenAddress) ||
323
+ !state.underlyingAddresses.includes(toTokenAddress)
324
+ ) {
325
+ return null;
326
+ }
327
+
328
+ let idealToAmount;
329
+ const fromAmountInt256 = convertUint256ToInt256(fromAmount);
330
+ if (fromAmountInt256 > 0) {
331
+ idealToAmount = wdiv(toAmount, WAD - state.params.haircutRate);
332
+ } else {
333
+ this.logger.warn(
334
+ `pool ${this.poolAddress} swap from a negative amount ${fromAmountInt256} at block ${log.blockNumber} should not happen`,
200
335
  );
201
- } catch (e) {
202
- this._logMessageWithSuppression('ERROR_FETCHING_STATE_FROM_RPC', e);
336
+ const haircut = wmul(-fromAmount, state.params.haircutRate);
337
+ idealToAmount = toAmount + haircut;
203
338
  }
204
339
 
205
- return null;
340
+ const fromAmountInWad = toWad(
341
+ fromAmount,
342
+ BigInt(state.asset[fromTokenAddress].underlyingTokenDecimals),
343
+ );
344
+ const toAmountInWad = toWad(
345
+ idealToAmount,
346
+ BigInt(state.asset[toTokenAddress].underlyingTokenDecimals),
347
+ );
348
+
349
+ return {
350
+ ...state,
351
+ asset: {
352
+ ...state.asset,
353
+ [fromTokenAddress]: {
354
+ ...state.asset[fromTokenAddress],
355
+ cash: state.asset[fromTokenAddress].cash + fromAmountInWad,
356
+ },
357
+ [toTokenAddress]: {
358
+ ...state.asset[toTokenAddress],
359
+ cash: state.asset[toTokenAddress].cash - toAmountInWad,
360
+ },
361
+ },
362
+ };
206
363
  }
207
364
 
208
- public parseStateFromMultiResultsWithBlockInfo(
209
- multiOutputs: [
210
- MultiResult<number>,
211
- ...MultiResult<MulticallResultOutputs>[],
212
- ],
213
- lastUpdatedAtMs: number,
214
- ): ObjWithUpdateInfo<PoolState> {
215
- const [blockNumber, ...outputsForAbstract] = multiOutputs.map((m, i) => {
216
- return m.returnData;
217
- }) as [number, ...MulticallResultOutputs[]];
365
+ handleSwapV2(
366
+ event: any,
367
+ state: DeepReadonly<PoolState>,
368
+ _log: Readonly<Log>,
369
+ ): AsyncOrSync<DeepReadonly<PoolState> | null> {
370
+ const fromTokenAddress = event.args.fromToken.toString().toLowerCase();
371
+ const fromAmount = BigInt(event.args.fromAmount.toString());
372
+ const toTokenAddress = event.args.toToken.toString().toLowerCase();
373
+ const toAmount = BigInt(event.args.toAmount.toString());
374
+ const toTokenFee = BigInt(event.args.toTokenFee.toString());
375
+
376
+ if (
377
+ !state.underlyingAddresses.includes(fromTokenAddress) ||
378
+ !state.underlyingAddresses.includes(toTokenAddress)
379
+ ) {
380
+ return null;
381
+ }
382
+
383
+ const fromAmountInWad = toWad(
384
+ fromAmount,
385
+ BigInt(state.asset[fromTokenAddress].underlyingTokenDecimals),
386
+ );
387
+ const toAmountInWad = toWad(
388
+ toAmount + toTokenFee,
389
+ BigInt(state.asset[toTokenAddress].underlyingTokenDecimals),
390
+ );
218
391
 
219
392
  return {
220
- value: this._parseStateFromMultiResults(outputsForAbstract),
221
- blockNumber,
222
- lastUpdatedAtMs,
393
+ ...state,
394
+ asset: {
395
+ ...state.asset,
396
+ [fromTokenAddress]: {
397
+ ...state.asset[fromTokenAddress],
398
+ cash: state.asset[fromTokenAddress].cash + fromAmountInWad,
399
+ },
400
+ [toTokenAddress]: {
401
+ ...state.asset[toTokenAddress],
402
+ cash: state.asset[toTokenAddress].cash - toAmountInWad,
403
+ },
404
+ },
405
+ };
406
+ }
407
+
408
+ handleSetAmpFactor(
409
+ event: any,
410
+ state: DeepReadonly<PoolState>,
411
+ _log: Readonly<Log>,
412
+ ): AsyncOrSync<DeepReadonly<PoolState> | null> {
413
+ const ampFactor = BigInt(event.args.value.toString());
414
+
415
+ return {
416
+ ...state,
417
+ params: {
418
+ ...state.params,
419
+ ampFactor,
420
+ },
421
+ };
422
+ }
423
+
424
+ handleSetHaircutRate(
425
+ event: any,
426
+ state: DeepReadonly<PoolState>,
427
+ _log: Readonly<Log>,
428
+ ): AsyncOrSync<DeepReadonly<PoolState> | null> {
429
+ const haircutRate = BigInt(event.args.value.toString());
430
+
431
+ return {
432
+ ...state,
433
+ params: {
434
+ ...state.params,
435
+ haircutRate,
436
+ },
437
+ };
438
+ }
439
+
440
+ async handleAssetAdded(
441
+ event: any,
442
+ state: DeepReadonly<PoolState>,
443
+ log: Readonly<Log>,
444
+ ): Promise<DeepReadonly<PoolState> | null> {
445
+ const token: Address = event.args.token.toString().toLowerCase();
446
+ const asset: Address = event.args.asset.toString().toLowerCase();
447
+ if (state.underlyingAddresses.includes(token)) {
448
+ return null;
449
+ }
450
+
451
+ const assetState = await this.getAssetState(
452
+ this.poolAddress,
453
+ [asset],
454
+ [token],
455
+ log.blockNumber,
456
+ );
457
+ const poolState = {
458
+ ...state,
459
+ underlyingAddresses: [...state.underlyingAddresses, token],
460
+ asset: {
461
+ ...state.asset,
462
+ [token]: assetState[0],
463
+ },
464
+ };
465
+
466
+ const isMainPool =
467
+ Object.values(poolState.asset).filter(
468
+ asset => asset.relativePrice === undefined,
469
+ ).length > 0;
470
+ if (isMainPool) {
471
+ for (const underlyingAddress of poolState.underlyingAddresses) {
472
+ poolState.asset[underlyingAddress] = {
473
+ ...poolState.asset[underlyingAddress],
474
+ relativePrice: undefined,
475
+ };
476
+ }
477
+ }
478
+ return poolState;
479
+ }
480
+
481
+ async handleAssetRemoved(
482
+ event: any,
483
+ state: DeepReadonly<PoolState>,
484
+ _log: Readonly<Log>,
485
+ ): Promise<DeepReadonly<PoolState> | null> {
486
+ const token = event.args.token.toString().toLowerCase();
487
+ if (!state.underlyingAddresses.includes(token)) {
488
+ return null;
489
+ }
490
+
491
+ return {
492
+ ...state,
493
+ underlyingAddresses: state.underlyingAddresses.filter(
494
+ underlyingAddress => underlyingAddress !== token,
495
+ ),
496
+ asset: {
497
+ ...state.asset,
498
+ [token]: undefined,
499
+ },
500
+ };
501
+ }
502
+
503
+ async handleFillPool(
504
+ event: any,
505
+ state: DeepReadonly<PoolState>,
506
+ _log: Readonly<Log>,
507
+ ): Promise<DeepReadonly<PoolState> | null> {
508
+ const token = event.args.token.toString().toLowerCase();
509
+ const amount = BigInt(event.args.amount.toString());
510
+ if (!state.underlyingAddresses.includes(token)) {
511
+ return null;
512
+ }
513
+
514
+ return {
515
+ ...state,
516
+ asset: {
517
+ ...state.asset,
518
+ [token]: {
519
+ ...state.asset[token],
520
+ cash: state.asset[token].cash + amount,
521
+ },
522
+ },
523
+ };
524
+ }
525
+
526
+ async handlePaused(
527
+ event: any,
528
+ state: DeepReadonly<PoolState>,
529
+ _log: Readonly<Log>,
530
+ ): Promise<DeepReadonly<PoolState> | null> {
531
+ return {
532
+ ...state,
533
+ params: {
534
+ ...state.params,
535
+ paused: true,
536
+ },
537
+ };
538
+ }
539
+
540
+ async handleUnpaused(
541
+ event: any,
542
+ state: DeepReadonly<PoolState>,
543
+ _log: Readonly<Log>,
544
+ ): Promise<DeepReadonly<PoolState> | null> {
545
+ return {
546
+ ...state,
547
+ params: {
548
+ ...state.params,
549
+ paused: false,
550
+ },
223
551
  };
224
552
  }
225
553
 
226
- public addAssets(asset2TokenMap: Map<Address, Address>) {
227
- for (const [asset, token] of asset2TokenMap) {
228
- if (this.asset2TokenMap.has(asset)) {
229
- continue;
554
+ async handlePausedAsset(
555
+ event: any,
556
+ state: DeepReadonly<PoolState>,
557
+ _log: Readonly<Log>,
558
+ ): Promise<DeepReadonly<PoolState> | null> {
559
+ const token = event.args.token.toString();
560
+ if (!state.underlyingAddresses.includes(token)) {
561
+ return null;
562
+ }
563
+
564
+ return {
565
+ ...state,
566
+ asset: {
567
+ ...state.asset,
568
+ [token]: {
569
+ ...state.asset[token],
570
+ paused: true,
571
+ },
572
+ },
573
+ };
574
+ }
575
+
576
+ async handleUnpausedAsset(
577
+ event: any,
578
+ state: DeepReadonly<PoolState>,
579
+ _log: Readonly<Log>,
580
+ ): Promise<DeepReadonly<PoolState> | null> {
581
+ const token = event.args.token.toString();
582
+ if (!state.underlyingAddresses.includes(token)) {
583
+ return null;
584
+ }
585
+
586
+ return {
587
+ ...state,
588
+ asset: {
589
+ ...state.asset,
590
+ [token]: {
591
+ ...state.asset[token],
592
+ paused: true,
593
+ },
594
+ },
595
+ };
596
+ }
597
+
598
+ private async getAssetState(
599
+ pool: Address,
600
+ assets: Address[],
601
+ tokens: Address[],
602
+ blockNumber: number,
603
+ ): Promise<AssetState[]> {
604
+ const assetStates: AssetState[] = [];
605
+ const multiCallInputs: MultiCallInput[] = [];
606
+
607
+ const methods = [
608
+ 'cash',
609
+ 'liability',
610
+ 'underlyingTokenDecimals',
611
+ 'getRelativePrice',
612
+ ];
613
+
614
+ for (let i = 0; i < assets.length; i++) {
615
+ const asset = assets[i];
616
+ const token = tokens[i];
617
+
618
+ multiCallInputs.push({
619
+ target: pool,
620
+ callData: this.poolInterface.encodeFunctionData('isPaused', [token]),
621
+ });
622
+
623
+ for (const method of methods) {
624
+ multiCallInputs.push({
625
+ target: asset,
626
+ callData: WombatPool.assetInterface.encodeFunctionData(method),
627
+ });
628
+ }
629
+ }
630
+
631
+ const returnData = await this.dexHelper.multiContract.methods
632
+ .tryAggregate(false, multiCallInputs)
633
+ .call({}, blockNumber);
634
+
635
+ for (
636
+ let i = 0;
637
+ i < assets.length * (methods.length + 1);
638
+ i += methods.length + 1
639
+ ) {
640
+ const paused = returnData[i].success
641
+ ? Boolean(
642
+ this.poolInterface.decodeFunctionResult(
643
+ 'isPaused',
644
+ returnData[i].returnData,
645
+ )[0],
646
+ )
647
+ : false;
648
+ const cash = BigInt(
649
+ WombatPool.assetInterface.decodeFunctionResult(
650
+ methods[0],
651
+ returnData[i + 1].returnData,
652
+ )[0],
653
+ );
654
+ const liability = BigInt(
655
+ WombatPool.assetInterface.decodeFunctionResult(
656
+ methods[1],
657
+ returnData[i + 2].returnData,
658
+ )[0],
659
+ );
660
+ const underlyingTokenDecimals =
661
+ WombatPool.assetInterface.decodeFunctionResult(
662
+ methods[2],
663
+ returnData[i + 3].returnData,
664
+ )[0];
665
+
666
+ let relativePrice: bigint | undefined;
667
+ if (returnData[i + 4].success) {
668
+ relativePrice = BigInt(
669
+ WombatPool.assetInterface.decodeFunctionResult(
670
+ methods[3],
671
+ returnData[i + 4].returnData,
672
+ )[0],
673
+ );
230
674
  }
231
675
 
232
- this.asset2TokenMap.set(asset, token);
233
- this._cachedMultiCallData = undefined;
676
+ assetStates.push({
677
+ address: assets[i / (methods.length + 1)],
678
+ paused,
679
+ cash,
680
+ liability,
681
+ underlyingTokenDecimals,
682
+ relativePrice,
683
+ });
234
684
  }
685
+
686
+ return assetStates;
235
687
  }
236
688
  }