@paraswap/dex-lib 3.10.0 → 3.10.2

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 (43) hide show
  1. package/build/abi/fluid-dex/dexFactory.abi.json +506 -0
  2. package/build/abi/fluid-dex/fluid-dex.abi.json +922 -0
  3. package/build/abi/fluid-dex/liquidityUserModule.abi.json +145 -0
  4. package/build/abi/fluid-dex/resolver.abi.json +999 -0
  5. package/build/dex/fluid-dex/config.d.ts +4 -0
  6. package/build/dex/fluid-dex/config.js +20 -0
  7. package/build/dex/fluid-dex/config.js.map +1 -0
  8. package/build/dex/fluid-dex/fluid-dex-factory.d.ts +49 -0
  9. package/build/dex/fluid-dex/fluid-dex-factory.js +104 -0
  10. package/build/dex/fluid-dex/fluid-dex-factory.js.map +1 -0
  11. package/build/dex/fluid-dex/fluid-dex-pool.d.ts +47 -0
  12. package/build/dex/fluid-dex/fluid-dex-pool.js +119 -0
  13. package/build/dex/fluid-dex/fluid-dex-pool.js.map +1 -0
  14. package/build/dex/fluid-dex/fluid-dex.d.ts +127 -0
  15. package/build/dex/fluid-dex/fluid-dex.js +502 -0
  16. package/build/dex/fluid-dex/fluid-dex.js.map +1 -0
  17. package/build/dex/fluid-dex/types.d.ts +52 -0
  18. package/build/dex/fluid-dex/types.js +3 -0
  19. package/build/dex/fluid-dex/types.js.map +1 -0
  20. package/build/dex/fluid-dex/utils.d.ts +2 -0
  21. package/build/dex/fluid-dex/utils.js +18 -0
  22. package/build/dex/fluid-dex/utils.js.map +1 -0
  23. package/build/dex/index.js +2 -0
  24. package/build/dex/index.js.map +1 -1
  25. package/build/dex/paraswap-limit-orders/paraswap-limit-orders.js +1 -1
  26. package/build/dex/paraswap-limit-orders/paraswap-limit-orders.js.map +1 -1
  27. package/package.json +1 -1
  28. package/src/abi/fluid-dex/dexFactory.abi.json +506 -0
  29. package/src/abi/fluid-dex/fluid-dex.abi.json +922 -0
  30. package/src/abi/fluid-dex/liquidityUserModule.abi.json +145 -0
  31. package/src/abi/fluid-dex/resolver.abi.json +999 -0
  32. package/src/dex/fluid-dex/config.ts +20 -0
  33. package/src/dex/fluid-dex/fluid-dex-e2e.test.ts +153 -0
  34. package/src/dex/fluid-dex/fluid-dex-events.test.ts +293 -0
  35. package/src/dex/fluid-dex/fluid-dex-factory.ts +143 -0
  36. package/src/dex/fluid-dex/fluid-dex-integration.test.ts +299 -0
  37. package/src/dex/fluid-dex/fluid-dex-pool.ts +178 -0
  38. package/src/dex/fluid-dex/fluid-dex.ts +790 -0
  39. package/src/dex/fluid-dex/types.ts +62 -0
  40. package/src/dex/fluid-dex/utils.ts +15 -0
  41. package/src/dex/index.ts +2 -0
  42. package/src/dex/paraswap-limit-orders/paraswap-limit-orders.ts +1 -1
  43. package/tests/constants-e2e.ts +2 -2
@@ -0,0 +1,299 @@
1
+ /* eslint-disable no-console */
2
+ import dotenv from 'dotenv';
3
+ dotenv.config();
4
+
5
+ import { Interface, Result } from '@ethersproject/abi';
6
+ import { DummyDexHelper } from '../../dex-helper/index';
7
+ import { Network, SwapSide } from '../../constants';
8
+ import { BI_POWS } from '../../bigint-constants';
9
+ import { FluidDex } from './fluid-dex';
10
+ import {
11
+ checkPoolPrices,
12
+ checkPoolsLiquidity,
13
+ checkConstantPoolPrices,
14
+ } from '../../../tests/utils';
15
+ import { Tokens } from '../../../tests/constants-e2e';
16
+ import ResolverABI from '../../abi/fluid-dex/resolver.abi.json';
17
+ import { Contract } from 'ethers';
18
+ import { Pool } from './types';
19
+
20
+ /*
21
+ README
22
+ ======
23
+
24
+ This test script adds tests for FluidDex general integration
25
+ with the DEX interface. The test cases below are example tests.
26
+ It is recommended to add tests which cover FluidDex specific
27
+ logic.
28
+
29
+ You can run this individual test script by running:
30
+ `npx jest src/dex/<dex-name>/<dex-name>-integration.test.ts`
31
+
32
+ (This comment should be removed from the final implementation)
33
+ */
34
+
35
+ function getReaderCalldata(
36
+ exchangeAddress: string,
37
+ readerIface: Interface,
38
+ poolAddress: string,
39
+ amounts: bigint[],
40
+ funcName: string,
41
+ pools: { address: string; token0: string; token1: string }[],
42
+ srcToken: string,
43
+ ) {
44
+ const pool = pools.find(
45
+ item => item.address.toLowerCase() === poolAddress.toLowerCase(),
46
+ );
47
+
48
+ return amounts.map(amount => ({
49
+ target: exchangeAddress,
50
+ callData: readerIface.encodeFunctionData(funcName, [
51
+ poolAddress,
52
+ pool!.token0.toLowerCase() === srcToken.toLowerCase() ? true : false,
53
+ amount,
54
+ funcName == 'estimateSwapIn' ? 0 : 2n * amount,
55
+ ]),
56
+ }));
57
+ }
58
+
59
+ function decodeReaderResult(
60
+ results: Result,
61
+ readerIface: Interface,
62
+ funcName: string,
63
+ ) {
64
+ return results.map(result => {
65
+ return BigInt(result);
66
+ });
67
+ }
68
+
69
+ async function checkOnChainPricing(
70
+ fluidDex: FluidDex,
71
+ funcName: string,
72
+ poolAddress: string,
73
+ blockNumber: number,
74
+ prices: bigint[],
75
+ amounts: bigint[],
76
+ dexHelper: DummyDexHelper,
77
+ srcToken: string,
78
+ ) {
79
+ const resolverAddress = '0xE8a07a32489BD9d5a00f01A55749Cf5cB854Fd13';
80
+
81
+ const readerIface = new Interface(ResolverABI);
82
+
83
+ const resolverContract = new Contract(
84
+ resolverAddress,
85
+ ResolverABI,
86
+ dexHelper.provider,
87
+ );
88
+ const rawResult = await resolverContract.callStatic.getAllPools({
89
+ blockTag: blockNumber,
90
+ });
91
+
92
+ const pools: Pool[] = rawResult.map((result: any) => ({
93
+ address: result[0],
94
+ token0: result[1],
95
+ token1: result[2],
96
+ }));
97
+
98
+ const readerCallData = getReaderCalldata(
99
+ resolverAddress,
100
+ readerIface,
101
+ poolAddress,
102
+ amounts.slice(1),
103
+ funcName,
104
+ pools,
105
+ srcToken,
106
+ );
107
+
108
+ const readerResult = (
109
+ await fluidDex.dexHelper.multiContract.methods
110
+ .aggregate(readerCallData)
111
+ .call({}, blockNumber)
112
+ ).returnData;
113
+
114
+ const expectedPrices = [0n].concat(
115
+ decodeReaderResult(readerResult, readerIface, funcName),
116
+ );
117
+
118
+ expect(prices).toEqual(expectedPrices);
119
+ }
120
+
121
+ async function testPricingOnNetwork(
122
+ fluidDex: FluidDex,
123
+ network: Network,
124
+ dexKey: string,
125
+ blockNumber: number,
126
+ srcTokenSymbol: string,
127
+ destTokenSymbol: string,
128
+ side: SwapSide,
129
+ amounts: bigint[],
130
+ funcNameToCheck: string,
131
+ dexHelper: DummyDexHelper,
132
+ ) {
133
+ const networkTokens = Tokens[network];
134
+
135
+ const pools = await fluidDex.getPoolIdentifiers(
136
+ networkTokens[srcTokenSymbol],
137
+ networkTokens[destTokenSymbol],
138
+ side,
139
+ blockNumber,
140
+ );
141
+ console.log(
142
+ `${srcTokenSymbol} <> ${destTokenSymbol} Pool Identifiers: `,
143
+ pools,
144
+ );
145
+
146
+ expect(pools.length).toBeGreaterThan(0);
147
+
148
+ const poolPrices = await fluidDex.getPricesVolume(
149
+ networkTokens[srcTokenSymbol],
150
+ networkTokens[destTokenSymbol],
151
+ amounts,
152
+ side,
153
+ blockNumber,
154
+ pools,
155
+ );
156
+ console.log(
157
+ `${srcTokenSymbol} <> ${destTokenSymbol} Pool Prices: `,
158
+ poolPrices,
159
+ );
160
+ console.log(
161
+ 'logged params : ',
162
+ networkTokens[srcTokenSymbol],
163
+ networkTokens[destTokenSymbol],
164
+ amounts,
165
+ side,
166
+ blockNumber,
167
+ pools,
168
+ );
169
+ expect(poolPrices).not.toBeNull();
170
+
171
+ // Check if onchain pricing equals to calculated ones
172
+ await checkOnChainPricing(
173
+ fluidDex,
174
+ funcNameToCheck,
175
+ poolPrices![0].poolAddresses![0],
176
+ blockNumber,
177
+ poolPrices![0].prices,
178
+ amounts,
179
+ dexHelper,
180
+ networkTokens[srcTokenSymbol].address,
181
+ );
182
+ }
183
+
184
+ describe('FluidDex', function () {
185
+ const dexKey = 'FluidDex';
186
+ let blockNumber: number;
187
+ let fluidDex: FluidDex;
188
+
189
+ describe('Mainnet', () => {
190
+ const network = Network.MAINNET;
191
+ const dexHelper = new DummyDexHelper(network);
192
+
193
+ beforeAll(async () => {
194
+ blockNumber = await dexHelper.provider.getBlockNumber();
195
+ fluidDex = new FluidDex(network, dexKey, dexHelper);
196
+ if (fluidDex.initializePricing) {
197
+ await fluidDex.initializePricing(blockNumber);
198
+ }
199
+ });
200
+
201
+ describe('wstETH -> ETH', () => {
202
+ const tokenASymbol = 'wstETH';
203
+ const tokenBSymbol = 'ETH';
204
+
205
+ const amountsForSell = [
206
+ 0n,
207
+ 1n * BI_POWS[18],
208
+ 2n * BI_POWS[18],
209
+ 3n * BI_POWS[18],
210
+ 4n * BI_POWS[18],
211
+ 5n * BI_POWS[18],
212
+ 6n * BI_POWS[18],
213
+ 7n * BI_POWS[18],
214
+ 8n * BI_POWS[18],
215
+ 9n * BI_POWS[18],
216
+ 10n * BI_POWS[18],
217
+ ];
218
+
219
+ it('wstETH -> ETH, getPoolIdentifiers and getPricesVolume SELL', async function () {
220
+ await testPricingOnNetwork(
221
+ fluidDex,
222
+ network,
223
+ dexKey,
224
+ blockNumber,
225
+ tokenASymbol,
226
+ tokenBSymbol,
227
+ SwapSide.SELL,
228
+ amountsForSell,
229
+ 'estimateSwapIn',
230
+ dexHelper,
231
+ );
232
+ });
233
+
234
+ it('ETH -> wstETH, getPoolIdentifiers and getPricesVolume SELL', async function () {
235
+ await testPricingOnNetwork(
236
+ fluidDex,
237
+ network,
238
+ dexKey,
239
+ blockNumber,
240
+ tokenBSymbol,
241
+ tokenASymbol,
242
+ SwapSide.SELL,
243
+ amountsForSell,
244
+ 'estimateSwapIn',
245
+ dexHelper,
246
+ );
247
+ });
248
+ });
249
+
250
+ describe('USDC -> USDT', () => {
251
+ const tokenASymbol = 'USDC';
252
+ const tokenBSymbol = 'USDT';
253
+
254
+ const amountsForSell = [
255
+ 0n,
256
+ 10n * BI_POWS[6],
257
+ 20n * BI_POWS[6],
258
+ 30n * BI_POWS[6],
259
+ 40n * BI_POWS[6],
260
+ 50n * BI_POWS[6],
261
+ 60n * BI_POWS[6],
262
+ 70n * BI_POWS[6],
263
+ 80n * BI_POWS[6],
264
+ 90n * BI_POWS[6],
265
+ 100n * BI_POWS[6],
266
+ ];
267
+
268
+ it('USDC -> USDT getPoolIdentifiers and getPricesVolume SELL', async function () {
269
+ await testPricingOnNetwork(
270
+ fluidDex,
271
+ network,
272
+ dexKey,
273
+ blockNumber,
274
+ tokenASymbol,
275
+ tokenBSymbol,
276
+ SwapSide.SELL,
277
+ amountsForSell,
278
+ 'estimateSwapIn',
279
+ dexHelper,
280
+ );
281
+ });
282
+
283
+ it('USDT -> USDC getPoolIdentifiers and getPricesVolume SELL', async function () {
284
+ await testPricingOnNetwork(
285
+ fluidDex,
286
+ network,
287
+ dexKey,
288
+ blockNumber,
289
+ tokenBSymbol,
290
+ tokenASymbol,
291
+ SwapSide.SELL,
292
+ amountsForSell,
293
+ 'estimateSwapIn',
294
+ dexHelper,
295
+ );
296
+ });
297
+ });
298
+ });
299
+ });
@@ -0,0 +1,178 @@
1
+ import { Interface } from '@ethersproject/abi';
2
+ import { DeepReadonly } from 'ts-essentials';
3
+ import { Log, Logger } from '../../types';
4
+ import { catchParseLogError } from '../../utils';
5
+ import { StatefulEventSubscriber } from '../../stateful-event-subscriber';
6
+ import { IDexHelper } from '../../dex-helper/idex-helper';
7
+ import ResolverABI from '../../abi/fluid-dex/resolver.abi.json';
8
+ import LiquidityABI from '../../abi/fluid-dex/liquidityUserModule.abi.json';
9
+ import {
10
+ CommonAddresses,
11
+ FluidDexPoolState,
12
+ CollateralReserves,
13
+ DebtReserves,
14
+ } from './types';
15
+ import { Address } from '../../types';
16
+ import { Contract } from 'ethers';
17
+
18
+ export class FluidDexEventPool extends StatefulEventSubscriber<FluidDexPoolState> {
19
+ handlers: {
20
+ [event: string]: (
21
+ event: any,
22
+ state: DeepReadonly<FluidDexPoolState>,
23
+ log: Readonly<Log>,
24
+ ) => Promise<DeepReadonly<FluidDexPoolState> | null>;
25
+ } = {};
26
+
27
+ logDecoder: (log: Log) => any;
28
+
29
+ addressesSubscribed: Address[];
30
+ protected liquidityIface = new Interface(LiquidityABI);
31
+
32
+ constructor(
33
+ readonly parentName: string,
34
+ readonly pool: Address,
35
+ readonly commonAddresses: CommonAddresses,
36
+ protected network: number,
37
+ readonly dexHelper: IDexHelper,
38
+ logger: Logger,
39
+ ) {
40
+ super(parentName, 'FluidDex_' + pool, dexHelper, logger);
41
+
42
+ this.logDecoder = (log: Log) => this.liquidityIface.parseLog(log);
43
+ this.addressesSubscribed = [commonAddresses.liquidityProxy];
44
+
45
+ // Add handlers
46
+ this.handlers['LogOperate'] = this.handleOperate.bind(this);
47
+ }
48
+
49
+ /**
50
+ * Handle a trade rate change on the pool.
51
+ */
52
+ async handleOperate(
53
+ event: any,
54
+ state: DeepReadonly<FluidDexPoolState>,
55
+ log: Readonly<Log>,
56
+ ): Promise<DeepReadonly<FluidDexPoolState> | null> {
57
+ if (!(event.args.user in [this.pool])) {
58
+ return null;
59
+ }
60
+ const resolverContract = new Contract(
61
+ this.commonAddresses.resolver,
62
+ ResolverABI,
63
+ this.dexHelper.provider,
64
+ );
65
+ const rawResult = await resolverContract.callStatic.getPoolReservesAdjusted(
66
+ this.pool,
67
+ {
68
+ blockTag: this.dexHelper.provider,
69
+ },
70
+ );
71
+
72
+ const generatedState = this.convertToFluidDexPoolState(rawResult);
73
+
74
+ this.setState(
75
+ generatedState,
76
+ await this.dexHelper.provider.getBlockNumber(),
77
+ );
78
+
79
+ return generatedState;
80
+ }
81
+
82
+ /**
83
+ * The function is called every time any of the subscribed
84
+ * addresses release log. The function accepts the current
85
+ * state, updates the state according to the log, and returns
86
+ * the updated state.
87
+ * @param state - Current state of event subscriber
88
+ * @param log - Log released by one of the subscribed addresses
89
+ * @returns Updates state of the event subscriber after the log
90
+ */
91
+ async processLog(
92
+ state: DeepReadonly<FluidDexPoolState>,
93
+ log: Readonly<Log>,
94
+ ): Promise<DeepReadonly<FluidDexPoolState> | null> {
95
+ try {
96
+ const event = this.logDecoder(log);
97
+ if (event.name in this.handlers) {
98
+ return await this.handlers[event.name](event, state, log);
99
+ }
100
+ } catch (e) {
101
+ catchParseLogError(e, this.logger);
102
+ }
103
+
104
+ return null;
105
+ }
106
+
107
+ async getStateOrGenerate(
108
+ blockNumber: number,
109
+ readonly: boolean = false,
110
+ ): Promise<FluidDexPoolState> {
111
+ let state = this.getState(blockNumber);
112
+ if (!state) {
113
+ state = await this.generateState(blockNumber);
114
+ if (!readonly) this.setState(state, blockNumber);
115
+ }
116
+ return state;
117
+ }
118
+
119
+ /**
120
+ * The function generates state using on-chain calls. This
121
+ * function is called to regenerate state if the event based
122
+ * system fails to fetch events and the local state is no
123
+ * more correct.
124
+ * @param blockNumber - Blocknumber for which the state should
125
+ * should be generated
126
+ * @returns state of the event subscriber at blocknumber
127
+ */
128
+ async generateState(
129
+ blockNumber: number,
130
+ ): Promise<DeepReadonly<FluidDexPoolState>> {
131
+ const resolverContract = new Contract(
132
+ this.commonAddresses.resolver,
133
+ ResolverABI,
134
+ this.dexHelper.provider,
135
+ );
136
+ const rawResult = await resolverContract.callStatic.getPoolReservesAdjusted(
137
+ this.pool,
138
+ {
139
+ blockTag: blockNumber,
140
+ },
141
+ );
142
+
143
+ const convertedResult = this.convertToFluidDexPoolState(rawResult);
144
+
145
+ return convertedResult;
146
+ }
147
+
148
+ private convertToFluidDexPoolState(input: any[]): FluidDexPoolState {
149
+ // Ignore the first three addresses
150
+ const [, , , feeHex, collateralReservesHex, debtReservesHex] = input;
151
+ // Convert fee from hex to number
152
+ const fee = Number(feeHex.toString());
153
+
154
+ // Convert collateral reserves
155
+ const collateralReserves: CollateralReserves = {
156
+ token0RealReserves: BigInt(collateralReservesHex[0].toString()),
157
+ token1RealReserves: BigInt(collateralReservesHex[1].toString()),
158
+ token0ImaginaryReserves: BigInt(collateralReservesHex[2].toString()),
159
+ token1ImaginaryReserves: BigInt(collateralReservesHex[3].toString()),
160
+ };
161
+
162
+ // Convert debt reserves
163
+ const debtReserves: DebtReserves = {
164
+ token0Debt: BigInt(debtReservesHex[0].toString()),
165
+ token1Debt: BigInt(debtReservesHex[1].toString()),
166
+ token0RealReserves: BigInt(debtReservesHex[2].toString()),
167
+ token1RealReserves: BigInt(debtReservesHex[3].toString()),
168
+ token0ImaginaryReserves: BigInt(debtReservesHex[4].toString()),
169
+ token1ImaginaryReserves: BigInt(debtReservesHex[5].toString()),
170
+ };
171
+
172
+ return {
173
+ collateralReserves,
174
+ debtReserves,
175
+ fee,
176
+ };
177
+ }
178
+ }