@paraswap/dex-lib 2.42.26 → 2.42.27

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 (66) hide show
  1. package/build/abi/smardex/all/smardex-router.json +648 -0
  2. package/build/abi/smardex/layer-1/smardex-factory.json +242 -0
  3. package/build/abi/smardex/layer-1/smardex-pool.json +506 -0
  4. package/build/abi/smardex/layer-2/smardex-factory.json +185 -0
  5. package/build/abi/smardex/layer-2/smardex-pool.json +578 -0
  6. package/build/config.js +20 -10
  7. package/build/config.js.map +1 -1
  8. package/build/dex/index.js +2 -0
  9. package/build/dex/index.js.map +1 -1
  10. package/build/dex/smardex/config.d.ts +4 -0
  11. package/build/dex/smardex/config.js +64 -0
  12. package/build/dex/smardex/config.js.map +1 -0
  13. package/build/dex/smardex/constants.d.ts +18 -0
  14. package/build/dex/smardex/constants.js +33 -0
  15. package/build/dex/smardex/constants.js.map +1 -0
  16. package/build/dex/smardex/sdk/constants.d.ts +6 -0
  17. package/build/dex/smardex/sdk/constants.js +13 -0
  18. package/build/dex/smardex/sdk/constants.js.map +1 -0
  19. package/build/dex/smardex/sdk/core.d.ts +113 -0
  20. package/build/dex/smardex/sdk/core.js +499 -0
  21. package/build/dex/smardex/sdk/core.js.map +1 -0
  22. package/build/dex/smardex/sdk/errors.d.ts +15 -0
  23. package/build/dex/smardex/sdk/errors.js +22 -0
  24. package/build/dex/smardex/sdk/errors.js.map +1 -0
  25. package/build/dex/smardex/sdk/types.d.ts +62 -0
  26. package/build/dex/smardex/sdk/types.js +3 -0
  27. package/build/dex/smardex/sdk/types.js.map +1 -0
  28. package/build/dex/smardex/sdk/utils.d.ts +44 -0
  29. package/build/dex/smardex/sdk/utils.js +133 -0
  30. package/build/dex/smardex/sdk/utils.js.map +1 -0
  31. package/build/dex/smardex/smardex-event-pool.d.ts +28 -0
  32. package/build/dex/smardex/smardex-event-pool.js +119 -0
  33. package/build/dex/smardex/smardex-event-pool.js.map +1 -0
  34. package/build/dex/smardex/smardex.d.ts +65 -0
  35. package/build/dex/smardex/smardex.js +519 -0
  36. package/build/dex/smardex/smardex.js.map +1 -0
  37. package/build/dex/smardex/types.d.ts +55 -0
  38. package/build/dex/smardex/types.js +3 -0
  39. package/build/dex/smardex/types.js.map +1 -0
  40. package/build/types.d.ts +1 -0
  41. package/package.json +3 -2
  42. package/src/abi/smardex/all/smardex-router.json +648 -0
  43. package/src/abi/smardex/layer-1/smardex-factory.json +242 -0
  44. package/src/abi/smardex/layer-1/smardex-pool.json +506 -0
  45. package/src/abi/smardex/layer-2/smardex-factory.json +185 -0
  46. package/src/abi/smardex/layer-2/smardex-pool.json +578 -0
  47. package/src/config.ts +21 -10
  48. package/src/dex/index.ts +2 -0
  49. package/src/dex/smardex/config.ts +67 -0
  50. package/src/dex/smardex/constants.ts +35 -0
  51. package/src/dex/smardex/sdk/constants.ts +10 -0
  52. package/src/dex/smardex/sdk/core.ts +832 -0
  53. package/src/dex/smardex/sdk/errors.ts +18 -0
  54. package/src/dex/smardex/sdk/types.ts +68 -0
  55. package/src/dex/smardex/sdk/utils.ts +156 -0
  56. package/src/dex/smardex/smardex-e2e.test.ts +275 -0
  57. package/src/dex/smardex/smardex-event-pool.ts +164 -0
  58. package/src/dex/smardex/smardex-events.test.ts +297 -0
  59. package/src/dex/smardex/smardex-integration.test.ts +258 -0
  60. package/src/dex/smardex/smardex.ts +770 -0
  61. package/src/dex/smardex/types.ts +69 -0
  62. package/src/types.ts +1 -0
  63. package/tests/constants-e2e.ts +26 -1
  64. package/.vscode/launch.json +0 -54
  65. package/.vscode/settings.json +0 -2
  66. package/.vscode/tasks.json +0 -15
@@ -0,0 +1,832 @@
1
+ import { FEES_BASE, LATENCY_OFFSET_SECONDS } from './constants';
2
+ import { ratioApproxEq, sqrt } from './utils';
3
+ import SmardexError from './errors';
4
+ import type { CurrencyAmount, Pair } from './types';
5
+
6
+ // compute first trade amountIn using arbitrage feature
7
+ function computeFirstTradeQtyIn(
8
+ amountIn: bigint,
9
+ reserveInFic: bigint,
10
+ reserveOutFic: bigint,
11
+ priceAverageIn: bigint,
12
+ priceAverageOut: bigint,
13
+ feesLP: bigint,
14
+ feesPool: bigint,
15
+ ): bigint {
16
+ // default value
17
+ let firstAmountIn = amountIn;
18
+
19
+ // if trade is in the good direction
20
+ if (reserveOutFic * priceAverageIn > reserveInFic * priceAverageOut) {
21
+ // pre-compute all operands
22
+ const feesTotalReversed = FEES_BASE - feesLP - feesPool;
23
+ const toSub = reserveInFic * (FEES_BASE + feesTotalReversed - feesPool);
24
+ const toDiv = (feesTotalReversed + feesLP) * 2n;
25
+ const inSqrt =
26
+ ((reserveInFic * reserveOutFic * 4n) / priceAverageOut) *
27
+ priceAverageIn *
28
+ feesTotalReversed *
29
+ (FEES_BASE - feesPool) +
30
+ reserveInFic * reserveInFic * feesLP * feesLP;
31
+
32
+ // reverse sqrt check to only compute sqrt if really needed
33
+ if (inSqrt < (amountIn * toDiv + toSub) ** 2n) {
34
+ firstAmountIn = (sqrt(inSqrt) - toSub) / toDiv;
35
+ }
36
+ }
37
+
38
+ return firstAmountIn;
39
+ }
40
+
41
+ // compute first trade amountOut using arbitrage feature
42
+ function computeFirstTradeQtyOut(
43
+ amountOut: bigint,
44
+ reserveInFic: bigint,
45
+ reserveOutFic: bigint,
46
+ priceAverageIn: bigint,
47
+ priceAverageOut: bigint,
48
+ feesLP: bigint,
49
+ feesPool: bigint,
50
+ ): bigint {
51
+ // default value
52
+ let firstAmountOut = amountOut;
53
+
54
+ // if trade is in the good direction
55
+ if (reserveOutFic * priceAverageIn > reserveInFic * priceAverageOut) {
56
+ // pre-compute all operands
57
+ const feesTotalReversed = FEES_BASE - feesLP - feesPool;
58
+ const reserveOutFicPredictedFees =
59
+ (reserveInFic * feesLP * priceAverageOut) / priceAverageIn;
60
+ const toAdd =
61
+ reserveOutFic * feesTotalReversed * 2n + reserveOutFicPredictedFees;
62
+ const toDiv = feesTotalReversed * 2n;
63
+ const inSqrt =
64
+ (reserveOutFic *
65
+ reserveOutFicPredictedFees *
66
+ 4n *
67
+ feesTotalReversed *
68
+ (FEES_BASE - feesPool)) /
69
+ feesLP +
70
+ reserveOutFicPredictedFees ** 2n;
71
+
72
+ // reverse sqrt check to only compute sqrt if really needed
73
+ if (inSqrt > (toAdd - amountOut * toDiv) ** 2n) {
74
+ firstAmountOut = (toAdd - sqrt(inSqrt)) / toDiv;
75
+ }
76
+ }
77
+
78
+ return firstAmountOut;
79
+ }
80
+
81
+ // apply uniswap k const rule. amountIn -> amountOut
82
+ // return [amountOut, newResIn, newResOut, newResInFic, newResOutFic]
83
+ function applyKConstRuleOut(
84
+ amountIn: bigint,
85
+ reserveIn: bigint,
86
+ reserveOut: bigint,
87
+ reserveInFic: bigint,
88
+ reserveOutFic: bigint,
89
+ feesLP: bigint,
90
+ feesPool: bigint,
91
+ ): [bigint, bigint, bigint, bigint, bigint] {
92
+ // k const rule
93
+ const feesTotalReversed = FEES_BASE - feesLP - feesPool;
94
+ const amountInWithFee = amountIn * feesTotalReversed;
95
+ const numerator = amountInWithFee * reserveOutFic;
96
+ const denominator = reserveInFic * FEES_BASE + amountInWithFee;
97
+
98
+ if (denominator === 0n) {
99
+ throw new SmardexError('SMARDEX_K_ERROR');
100
+ }
101
+
102
+ const amountOut = numerator / denominator;
103
+
104
+ // update new reserves and add lp-fees to pools
105
+ const amountInWithFeeLp = (amountIn * feesLP + amountInWithFee) / FEES_BASE;
106
+ const newResIn = reserveIn + amountInWithFeeLp;
107
+ const newResInFic = reserveInFic + amountInWithFeeLp;
108
+ const newResOut = reserveOut - amountOut;
109
+ const newResOutFic = reserveOutFic - amountOut;
110
+
111
+ return [amountOut, newResIn, newResOut, newResInFic, newResOutFic];
112
+ }
113
+
114
+ // apply uniswap k const rule. amountOut -> amountIn
115
+ // returns [amountIn, newResIn, newResOut, newResInFic, newResOutFic]
116
+ function applyKConstRuleIn(
117
+ amountOut: bigint,
118
+ reserveIn: bigint,
119
+ reserveOut: bigint,
120
+ reserveInFic: bigint,
121
+ reserveOutFic: bigint,
122
+ feesLP: bigint,
123
+ feesPool: bigint,
124
+ ): [bigint, bigint, bigint, bigint, bigint] {
125
+ // k const rule
126
+ const feesTotalReversed = FEES_BASE - feesLP - feesPool;
127
+ const numerator = reserveInFic * amountOut * FEES_BASE;
128
+ const denominator = (reserveOutFic - amountOut) * feesTotalReversed;
129
+
130
+ if (denominator === 0n) {
131
+ throw new SmardexError('SMARDEX_K_ERROR');
132
+ }
133
+
134
+ const amountIn = numerator / denominator + 1n;
135
+
136
+ // update new reserves
137
+ const amountInWithFeeLp =
138
+ ((feesTotalReversed + feesLP) * amountIn) / FEES_BASE;
139
+ const newResIn = reserveIn + amountInWithFeeLp;
140
+ const newResInFic = reserveInFic + amountInWithFeeLp;
141
+ const newResOut = reserveOut - amountOut;
142
+ const newResOutFic = reserveOutFic - amountOut;
143
+
144
+ return [amountIn, newResIn, newResOut, newResInFic, newResOutFic];
145
+ }
146
+
147
+ /**
148
+ * Compute fictive reserves based on current reserves state
149
+ *
150
+ * @param {bigint} reserveIn the reserves of input token.
151
+ * @param {bigint} reserveOut the reserves of output token.
152
+ * @param {bigint} reserveInFic the fictive reserves of input token.
153
+ * @param {bigint} reserveOutFic the fictive reserves of output token.
154
+ * @returns {Array} [ficIn, ficOut]
155
+ */
156
+ export function computeReserveFic(
157
+ reserveIn: bigint,
158
+ reserveOut: bigint,
159
+ reserveInFic: bigint,
160
+ reserveOutFic: bigint,
161
+ ): [bigint, bigint] {
162
+ if (reserveOut * reserveInFic < reserveIn * reserveOutFic) {
163
+ const temp =
164
+ (((reserveOut * reserveOut) / reserveOutFic) * reserveInFic) / reserveIn;
165
+ const newResFicIn =
166
+ (temp * reserveInFic) / reserveOutFic +
167
+ (reserveOut * reserveInFic) / reserveOutFic;
168
+ const newResFicOut = reserveOut + temp;
169
+
170
+ return [newResFicIn / 4n, newResFicOut / 4n];
171
+ }
172
+
173
+ const newResFicIn = (reserveInFic * reserveOut) / reserveOutFic + reserveIn;
174
+ const newResFicOut = (reserveIn * reserveOutFic) / reserveInFic + reserveOut;
175
+
176
+ return [newResFicIn / 4n, newResFicOut / 4n];
177
+ }
178
+
179
+ /**
180
+ * Simulate a full trasaction, if you know the "in" token quantity, provide you the "out" and all reserves change
181
+ * Use case: you want to receive exactly amountOut and want to know the exact amountIn to send.
182
+ * @param {bigint} amountIn the desired input amount of the trade.
183
+ * @param {bigint} reserveIn the reserves of input token.
184
+ * @param {bigint} reserveOut the reserves of output token.
185
+ * @param {bigint} reserveInFic the fictive reserves of input token.
186
+ * @param {bigint} reserveOutFic the fictive reserves of output token.
187
+ * @param {bigint} priceAverageIn the price average of input token.
188
+ * @param {bigint} priceAverageOut the price average of output token.
189
+ * @param {bigint} feesLP LP fees
190
+ * @param {bigint} feesPool Pool fees
191
+ * @returns {Array} [amountOut, newResIn, newResOut, newResInFic, newResOutFic]
192
+ */
193
+ export function getAmountOut(
194
+ amountIn: bigint,
195
+ reserveIn: bigint,
196
+ reserveOut: bigint,
197
+ reserveInFic: bigint,
198
+ reserveOutFic: bigint,
199
+ priceAverageIn: bigint,
200
+ priceAverageOut: bigint,
201
+ feesLP: bigint,
202
+ feesPool: bigint,
203
+ ): [bigint, bigint, bigint, bigint, bigint] {
204
+ // if (amountIn <= 0n) {
205
+ // throw new SmardexError('INSUFFICIENT_INPUT_AMOUNT');
206
+ // }
207
+
208
+ if (reserveIn <= 0n || reserveOut <= 0n) {
209
+ throw new SmardexError('INSUFFICIENT_LIQUIDITY');
210
+ }
211
+
212
+ if (reserveInFic <= 0n || reserveOutFic <= 0n) {
213
+ throw new SmardexError('INSUFFICIENT_LIQUIDITY');
214
+ }
215
+
216
+ if (priceAverageIn <= 0n || priceAverageOut <= 0n) {
217
+ throw new SmardexError('INSUFFICIENT_PRICE_AVERAGE');
218
+ }
219
+
220
+ let reserveInFicUpdated = reserveInFic;
221
+ let reserveOutFicUpdated = reserveOutFic;
222
+
223
+ const feesTotalReversed = FEES_BASE - feesLP - feesPool;
224
+ const amountWithFees = (amountIn * feesTotalReversed) / FEES_BASE;
225
+ const firstAmount = computeFirstTradeQtyIn(
226
+ amountWithFees,
227
+ reserveInFic,
228
+ reserveOutFic,
229
+ priceAverageIn,
230
+ priceAverageOut,
231
+ feesLP,
232
+ feesPool,
233
+ );
234
+
235
+ // if there are 2 trades: 1st trade mustn't re-compute ReserveFic, 2nd should
236
+ if (
237
+ firstAmount === amountWithFees &&
238
+ ratioApproxEq(reserveInFic, reserveOutFic, priceAverageIn, priceAverageOut)
239
+ ) {
240
+ [reserveInFicUpdated, reserveOutFicUpdated] = computeReserveFic(
241
+ reserveIn,
242
+ reserveOut,
243
+ reserveInFic,
244
+ reserveOutFic,
245
+ );
246
+ }
247
+
248
+ // avoid K constant division by 0
249
+ if (reserveInFicUpdated <= 0n) {
250
+ return [
251
+ 0n,
252
+ reserveIn,
253
+ reserveOut,
254
+ reserveInFicUpdated,
255
+ reserveOutFicUpdated,
256
+ ];
257
+ }
258
+
259
+ const firstAmountNoFees = (firstAmount * FEES_BASE) / feesTotalReversed;
260
+
261
+ let [amountOut, newResIn, newResOut, newResInFic, newResOutFic] =
262
+ applyKConstRuleOut(
263
+ firstAmountNoFees,
264
+ reserveIn,
265
+ reserveOut,
266
+ reserveInFicUpdated,
267
+ reserveOutFicUpdated,
268
+ feesLP,
269
+ feesPool,
270
+ );
271
+
272
+ // if we need a second trade
273
+ if (firstAmount < amountWithFees && firstAmountNoFees < amountIn) {
274
+ [newResInFic, newResOutFic] = computeReserveFic(
275
+ newResIn,
276
+ newResOut,
277
+ newResInFic,
278
+ newResOutFic,
279
+ );
280
+
281
+ // Avoid K constant division by 0
282
+ if (newResInFic <= 0n) {
283
+ return [
284
+ 0n,
285
+ reserveIn,
286
+ reserveOut,
287
+ reserveInFicUpdated,
288
+ reserveOutFicUpdated,
289
+ ];
290
+ }
291
+
292
+ let secondAmountOutNoFees: bigint;
293
+
294
+ [secondAmountOutNoFees, newResIn, newResOut, newResInFic, newResOutFic] =
295
+ applyKConstRuleOut(
296
+ amountIn - firstAmountNoFees,
297
+ newResIn,
298
+ newResOut,
299
+ newResInFic,
300
+ newResOutFic,
301
+ feesLP,
302
+ feesPool,
303
+ );
304
+
305
+ amountOut += secondAmountOutNoFees;
306
+ }
307
+
308
+ if (
309
+ newResIn <= 0n ||
310
+ newResOut <= 0n ||
311
+ newResInFic <= 0n ||
312
+ newResOutFic <= 0n
313
+ ) {
314
+ throw new SmardexError('INSUFFICIENT_LIQUIDITY');
315
+ }
316
+
317
+ return [amountOut, newResIn, newResOut, newResInFic, newResOutFic];
318
+ }
319
+
320
+ /**
321
+ * Simulate a full transaction, if you know the "out" token quantity, provide you the "in" and all reserves change
322
+ * Use case: you want to receive exactly amountOut and want to know the exact amountIn to send.
323
+ * @param {bigint} amountOut the desired output amount of the trade.
324
+ * @param {bigint} reserveIn the reserves of input token.
325
+ * @param {bigint} reserveOut the reserves of output token.
326
+ * @param {bigint} reserveInFic the fictive reserves of input token.
327
+ * @param {bigint} reserveOutFic the fictive reserves of output token.
328
+ * @param {bigint} priceAverageIn the price average of input token.
329
+ * @param {bigint} priceAverageOut the price average of output token.
330
+ * @param {bigint} feesLP LP fees
331
+ * @param {bigint} feesPool Pool fees
332
+ * @returns {Array} [amountIn, newResIn, newResOut, newResInFic, newResOutFic]
333
+ */
334
+ export function getAmountIn(
335
+ amountOut: bigint,
336
+ reserveIn: bigint,
337
+ reserveOut: bigint,
338
+ reserveInFic: bigint,
339
+ reserveOutFic: bigint,
340
+ priceAverageIn: bigint,
341
+ priceAverageOut: bigint,
342
+ feesLP: bigint,
343
+ feesPool: bigint,
344
+ ): [bigint, bigint, bigint, bigint, bigint] {
345
+ // if (amountOut <= 0n) {
346
+ // throw new SmardexError('INSUFFICIENT_OUTPUT_AMOUNT');
347
+ // }
348
+
349
+ if (reserveIn <= 0n || reserveOut <= 0n) {
350
+ throw new SmardexError('INSUFFICIENT_LIQUIDITY');
351
+ }
352
+
353
+ if (reserveInFic <= 0n || reserveOutFic <= 0n) {
354
+ throw new SmardexError('INSUFFICIENT_LIQUIDITY');
355
+ }
356
+
357
+ if (priceAverageIn <= 0n || priceAverageOut <= 0n) {
358
+ throw new SmardexError('INSUFFICIENT_PRICE_AVERAGE');
359
+ }
360
+
361
+ let reserveInFicUpdated = reserveInFic;
362
+ let reserveOutFicUpdated = reserveOutFic;
363
+
364
+ const firstAmount = computeFirstTradeQtyOut(
365
+ amountOut,
366
+ reserveInFic,
367
+ reserveOutFic,
368
+ priceAverageIn,
369
+ priceAverageOut,
370
+ feesLP,
371
+ feesPool,
372
+ );
373
+
374
+ // if there are 2 trades: 1st trade mustn't re-compute ReserveFic, 2nd should
375
+ if (
376
+ firstAmount === amountOut &&
377
+ ratioApproxEq(reserveInFic, reserveOutFic, priceAverageIn, priceAverageOut)
378
+ ) {
379
+ [reserveInFicUpdated, reserveOutFicUpdated] = computeReserveFic(
380
+ reserveIn,
381
+ reserveOut,
382
+ reserveInFic,
383
+ reserveOutFic,
384
+ );
385
+ }
386
+
387
+ if (
388
+ // Avoid K constant division by 0
389
+ reserveInFic <= 0n ||
390
+ // Avoid finding an amountIn for an exact amountOut that is equal to 0
391
+ amountOut <= 0n
392
+ ) {
393
+ return [
394
+ BigInt('0'),
395
+ reserveIn,
396
+ reserveOut,
397
+ reserveInFicUpdated,
398
+ reserveOutFicUpdated,
399
+ ];
400
+ }
401
+
402
+ let [amountIn, newResIn, newResOut, newResInFic, newResOutFic] =
403
+ applyKConstRuleIn(
404
+ firstAmount,
405
+ reserveIn,
406
+ reserveOut,
407
+ reserveInFicUpdated,
408
+ reserveOutFicUpdated,
409
+ feesLP,
410
+ feesPool,
411
+ );
412
+
413
+ // if we need a second trade
414
+ if (firstAmount < amountOut) {
415
+ // in the second trade ALWAYS recompute fictive reserves
416
+ [newResInFic, newResOutFic] = computeReserveFic(
417
+ newResIn,
418
+ newResOut,
419
+ newResInFic,
420
+ newResOutFic,
421
+ );
422
+
423
+ // Avoid K constant division by 0
424
+ if (newResInFic <= 0n) {
425
+ return [
426
+ BigInt('0'),
427
+ reserveIn,
428
+ reserveOut,
429
+ reserveInFicUpdated,
430
+ reserveOutFicUpdated,
431
+ ];
432
+ }
433
+
434
+ let secondAmountIn: bigint;
435
+
436
+ [secondAmountIn, newResIn, newResOut, newResInFic, newResOutFic] =
437
+ applyKConstRuleIn(
438
+ amountOut - firstAmount,
439
+ newResIn,
440
+ newResOut,
441
+ newResInFic,
442
+ newResOutFic,
443
+ feesLP,
444
+ feesPool,
445
+ );
446
+
447
+ amountIn += secondAmountIn;
448
+ }
449
+
450
+ if (
451
+ newResIn <= 0n ||
452
+ newResOut <= 0n ||
453
+ newResInFic <= 0n ||
454
+ newResOutFic <= 0n
455
+ ) {
456
+ throw new SmardexError('INSUFFICIENT_LIQUIDITY');
457
+ }
458
+
459
+ return [amountIn, newResIn, newResOut, newResInFic, newResOutFic];
460
+ }
461
+
462
+ /**
463
+ * Computes the priceAverageIn and priceAverageOut.
464
+ * Use case: you want to send an exact amount of tokenIn and know exactly how much you it will give you of tokenOut.
465
+ * Price averages are modified only if current timestamp does not match last timestamp
466
+ * @param {bigint} reserveFicIn the fictuve reserves of input token.
467
+ * @param {bigint} reserveFicOut the fictuve reserves of output token.
468
+ * @param {number} priceAverageLastTimestamp last timestamp in seconds of price average values.
469
+ * @param {bigint} priceAverageIn the latest price average of input token.
470
+ * @param {bigint} priceAverageOut the latest price average of output token.
471
+ * @param {number} currentTimestampInSecond current timestamp in seconds.
472
+ * @param {number} maxBlockDiffSeconds: Max block difference in seconds
473
+ * @returns {Array} [priceAverageIn, priceAverageOut]
474
+ */
475
+ export function getUpdatedPriceAverage(
476
+ reserveFicIn: bigint,
477
+ reserveFicOut: bigint,
478
+ priceAverageLastTimestamp: number,
479
+ priceAverageIn: bigint,
480
+ priceAverageOut: bigint,
481
+ currentTimestampInSecond: number,
482
+ maxBlockDiffSeconds: number,
483
+ ): [bigint, bigint] {
484
+ if (currentTimestampInSecond < priceAverageLastTimestamp) {
485
+ throw new SmardexError('INVALID_TIMESTAMP', 'SmarDexError');
486
+ }
487
+
488
+ // very first time
489
+ if (
490
+ priceAverageLastTimestamp === 0 ||
491
+ priceAverageIn === 0n ||
492
+ priceAverageOut === 0n
493
+ ) {
494
+ return [reserveFicIn, reserveFicOut];
495
+ }
496
+
497
+ // another tx has been done in the same block
498
+ if (priceAverageLastTimestamp === currentTimestampInSecond) {
499
+ return [priceAverageIn, priceAverageOut];
500
+ }
501
+
502
+ // need to compute new linear-average price
503
+ // compute new price:
504
+ const timeDiff = Math.min(
505
+ currentTimestampInSecond - priceAverageLastTimestamp,
506
+ maxBlockDiffSeconds,
507
+ );
508
+
509
+ const priceAverageInRet = reserveFicIn;
510
+ const priceAverageOutRet =
511
+ ((priceAverageOut *
512
+ priceAverageInRet *
513
+ BigInt(maxBlockDiffSeconds - timeDiff)) /
514
+ priceAverageIn +
515
+ reserveFicOut * BigInt(timeDiff)) /
516
+ BigInt(maxBlockDiffSeconds);
517
+
518
+ return [priceAverageInRet, priceAverageOutRet];
519
+ }
520
+
521
+ /**
522
+ * Computes the amount of tokenOut, at the precision of 1 wei.
523
+ * Use case: you want to send an exact amount of tokenIn and know exactly how much you it will give you of tokenOut.
524
+ * WARNING: token0 and token1 are pair tokens which addresses hexadecimal's values are sorted as token0 < token1.
525
+ * @param {string} token0 the currency address of token0.
526
+ * @param {string} token1 the currency address of token1.
527
+ * @param {bigint} reserve0 the reserves of token0.
528
+ * @param {bigint} reserve1 the reserves of token1.
529
+ * @param {bigint} reserve0Fic the fictionnal reserves of token0.
530
+ * @param {bigint} reserve1Fic the fictionnal reserves of token1.
531
+ * @param {bigint} tokenAmountIn the input amount of the trade.
532
+ * @param {bigint} tokenAddressIn address of the input token.
533
+ * @param {number} priceAverageLastTimestamp: timestamp in seconds of the latest price average.
534
+ * @param {bigint} priceAverage0 latest price average of token0.
535
+ * @param {bigint} priceAverage1 latest price average of token1.
536
+ * @param {bigint} feesLP LP fees
537
+ * @param {bigint} feesPool Pool fees
538
+ * @param {number} forcedPriceAverageTimestamp: current timestamp or timestamp of the trade in seconds.
539
+ * @param {number} maxBlockDiffSeconds: Max block difference in seconds
540
+ * @returns {Object} { currency, amount, amountMax, newResIn, newResOut, newResInFic, newResOutFic }
541
+ */
542
+ export function computeAmountOut(
543
+ token0: string,
544
+ token1: string,
545
+ reserve0: bigint,
546
+ reserve1: bigint,
547
+ reserve0Fic: bigint,
548
+ reserve1Fic: bigint,
549
+ tokenAmountIn: bigint,
550
+ tokenAddressIn: string,
551
+ priceAverageLastTimestamp: number,
552
+ priceAverage0: bigint,
553
+ priceAverage1: bigint,
554
+ feesLP: bigint,
555
+ feesPool: bigint,
556
+ forcedPriceAverageTimestamp: number = Math.ceil(Date.now() / 1000) +
557
+ LATENCY_OFFSET_SECONDS,
558
+ maxBlockDiffSeconds = 300,
559
+ ): CurrencyAmount {
560
+ if (tokenAddressIn === token0) {
561
+ const [newPriceAverage0, newPriceAverage1] = getUpdatedPriceAverage(
562
+ reserve0Fic,
563
+ reserve1Fic,
564
+ priceAverageLastTimestamp,
565
+ priceAverage0,
566
+ priceAverage1,
567
+ forcedPriceAverageTimestamp,
568
+ maxBlockDiffSeconds,
569
+ );
570
+
571
+ const [amountOut, newRes0, newRes1, newRes0Fic, newRes1Fic] = getAmountOut(
572
+ tokenAmountIn,
573
+ reserve0,
574
+ reserve1,
575
+ reserve0Fic,
576
+ reserve1Fic,
577
+ newPriceAverage0,
578
+ newPriceAverage1,
579
+ feesLP,
580
+ feesPool,
581
+ );
582
+ // const [amountMax] = getAmountOut(
583
+ // tokenAmountIn,
584
+ // reserve0,
585
+ // reserve1,
586
+ // reserve0Fic.sub(1).lt(0) ? reserve0Fic : reserve0Fic.sub(1),
587
+ // reserve1Fic,
588
+ // newPriceAverage0,
589
+ // newPriceAverage1,
590
+ // );
591
+
592
+ return {
593
+ currency: token1,
594
+ amount: amountOut,
595
+ amountMax: amountOut, // TODO is it still useful ?
596
+ newRes0,
597
+ newRes1,
598
+ newRes0Fic,
599
+ newRes1Fic,
600
+ newPriceAverage0,
601
+ newPriceAverage1,
602
+ };
603
+ }
604
+
605
+ // token1 is tokenIn
606
+ const [newPriceAverage1, newPriceAverage0] = getUpdatedPriceAverage(
607
+ reserve1Fic,
608
+ reserve0Fic,
609
+ priceAverageLastTimestamp,
610
+ priceAverage1,
611
+ priceAverage0,
612
+ forcedPriceAverageTimestamp,
613
+ maxBlockDiffSeconds,
614
+ );
615
+
616
+ const [amountOut, newRes1, newRes0, newRes1Fic, newRes0Fic] = getAmountOut(
617
+ tokenAmountIn,
618
+ reserve1,
619
+ reserve0,
620
+ reserve1Fic,
621
+ reserve0Fic,
622
+ newPriceAverage1,
623
+ newPriceAverage0,
624
+ feesLP,
625
+ feesPool,
626
+ );
627
+ // const [amountMax] = getAmountOut(
628
+ // tokenAmountIn,
629
+ // reserve1,
630
+ // reserve0,
631
+ // reserve1Fic.sub(1).lt(0) ? reserve1Fic : reserve1Fic.sub(1),
632
+ // reserve0Fic,
633
+ // newPriceAverage1,
634
+ // newPriceAverage0,
635
+ // );
636
+
637
+ return {
638
+ currency: token0,
639
+ amount: amountOut,
640
+ amountMax: amountOut, // TODO is it still useful ?
641
+ newRes0,
642
+ newRes1,
643
+ newRes0Fic,
644
+ newRes1Fic,
645
+ newPriceAverage0,
646
+ newPriceAverage1,
647
+ forcedPriceAverageTimestamp,
648
+ };
649
+ }
650
+
651
+ /**
652
+ * Computes the amount of tokenIn, at the precision of 1 wei.
653
+ * Use case: you want to receive exactly tokenOut amount and want to know the exact tokenIn amount to send.
654
+ * WARNING: token0 and token1 are pair tokens which addresses hexadecimal's values are sorted as token0 < token1.
655
+ * @param {string} token0 the currency address of token0.
656
+ * @param {string} token1 the currency address of token1.
657
+ * @param {bigint} reserve0 the reserves of token0.
658
+ * @param {bigint} reserve1 the reserves of token1.
659
+ * @param {bigint} reserve0Fic the fictionnal reserves of token0.
660
+ * @param {bigint} reserve1Fic the fictionnal reserves of token1.
661
+ * @param {bigint} tokenAmountOut the output amount of the trade.
662
+ * @param {bigint} tokenAddressOut address of the output token.
663
+ * @param {number} priceAverageLastTimestamp timestamp in seconds of the latest price average.
664
+ * @param {bigint} priceAverage0 latest price average of token0.
665
+ * @param {bigint} priceAverage1 latest price average of token1.
666
+ * @param {bigint} feesLP LP fees
667
+ * @param {bigint} feesPool Pool fees
668
+ * @param {number} forcedPriceAverageTimestamp current timestamp or timestamp of the trade in seconds.
669
+ * @param {number} maxBlockDiffSeconds: Max block difference in seconds
670
+ * @returns {Object} { currency, amount, amountMax, newResIn, newResOut, newResInFic, newResOutFic }
671
+ */
672
+ export function computeAmountIn(
673
+ token0: string,
674
+ token1: string,
675
+ reserve0: bigint,
676
+ reserve1: bigint,
677
+ reserve0Fic: bigint,
678
+ reserve1Fic: bigint,
679
+ tokenAmountOut: bigint,
680
+ tokenAddressOut: string,
681
+ priceAverageLastTimestamp: number,
682
+ priceAverage0: bigint,
683
+ priceAverage1: bigint,
684
+ feesLP: bigint,
685
+ feesPool: bigint,
686
+ forcedPriceAverageTimestamp: number = Math.ceil(Date.now() / 1000) +
687
+ LATENCY_OFFSET_SECONDS,
688
+ maxBlockDiffSeconds = 300,
689
+ ): CurrencyAmount {
690
+ if (tokenAddressOut === token0) {
691
+ const [newPriceAverage1, newPriceAverage0] = getUpdatedPriceAverage(
692
+ reserve1Fic,
693
+ reserve0Fic,
694
+ priceAverageLastTimestamp,
695
+ priceAverage1,
696
+ priceAverage0,
697
+ forcedPriceAverageTimestamp,
698
+ maxBlockDiffSeconds,
699
+ );
700
+
701
+ const [amountIn, newRes1, newRes0, newRes1Fic, newRes0Fic] = getAmountIn(
702
+ tokenAmountOut,
703
+ reserve1,
704
+ reserve0,
705
+ reserve1Fic,
706
+ reserve0Fic,
707
+ newPriceAverage1,
708
+ newPriceAverage0,
709
+ feesLP,
710
+ feesPool,
711
+ );
712
+ // const [amountMax] = getAmountIn(
713
+ // tokenAmountOut,
714
+ // reserve1,
715
+ // reserve0,
716
+ // reserve1Fic,
717
+ // reserve0Fic.sub(1).lt(0) ? reserve0Fic : reserve0Fic.sub(1),
718
+ // newPriceAverage1,
719
+ // newPriceAverage0,
720
+ // );
721
+
722
+ return {
723
+ currency: token1,
724
+ amount: amountIn,
725
+ amountMax: amountIn, // TODO is it still useful ?
726
+ newRes0,
727
+ newRes1,
728
+ newRes0Fic,
729
+ newRes1Fic,
730
+ newPriceAverage0,
731
+ newPriceAverage1,
732
+ };
733
+ }
734
+
735
+ // token1 is tokenOut
736
+ const [newPriceAverage0, newPriceAverage1] = getUpdatedPriceAverage(
737
+ reserve0Fic,
738
+ reserve1Fic,
739
+ priceAverageLastTimestamp,
740
+ priceAverage0,
741
+ priceAverage1,
742
+ forcedPriceAverageTimestamp,
743
+ maxBlockDiffSeconds,
744
+ );
745
+
746
+ const [amountIn, newRes0, newRes1, newRes0Fic, newRes1Fic] = getAmountIn(
747
+ tokenAmountOut,
748
+ reserve0,
749
+ reserve1,
750
+ reserve0Fic,
751
+ reserve1Fic,
752
+ newPriceAverage0,
753
+ newPriceAverage1,
754
+ feesLP,
755
+ feesPool,
756
+ );
757
+
758
+ // const [amountMax] = getAmountIn(
759
+ // tokenAmountOut,
760
+ // reserve0,
761
+ // reserve1,
762
+ // reserve0Fic,
763
+ // reserve1Fic.sub(1).lt(0) ? reserve1Fic : reserve1Fic.sub(1),
764
+ // newPriceAverage0,
765
+ // newPriceAverage1,
766
+ // );
767
+
768
+ return {
769
+ currency: token0,
770
+ amount: amountIn,
771
+ amountMax: amountIn, // TODO is it still useful ?
772
+ newRes0,
773
+ newRes1,
774
+ newRes0Fic,
775
+ newRes1Fic,
776
+ newPriceAverage0,
777
+ newPriceAverage1,
778
+ forcedPriceAverageTimestamp,
779
+ };
780
+ }
781
+
782
+ /**
783
+ * Extracts the token addresses composing the route ordered in the route's direction starting with inputCurrency.
784
+ * @param {Pair[]} pairs array of pairs composing the trade.
785
+ * @param {string} inputCurrency the currency from which the route starts.
786
+ * @return {string[]} Array of token addresses composing the route ordered in the route's direction starting with inputCurrency.
787
+ */
788
+ export function getPathFromInput(
789
+ pairs: Pair[],
790
+ inputCurrency: string,
791
+ ): string[] {
792
+ const path: string[] = [];
793
+ for (let i = 0; i < pairs.length; i += 1) {
794
+ const pairCurrencyIn =
795
+ path.length === 0 ? inputCurrency : path[path.length - 1];
796
+ const [tokenIn, tokenOut] =
797
+ pairCurrencyIn === pairs[i].token0
798
+ ? [pairs[i].token0, pairs[i].token1]
799
+ : [pairs[i].token1, pairs[i].token0];
800
+ if (path.length === 0) {
801
+ path.push(tokenIn);
802
+ }
803
+ path.push(tokenOut);
804
+ }
805
+ return path;
806
+ }
807
+
808
+ /**
809
+ * Extracts the token addresses composing the route ordered in the route's direction ending with outputCurrency.
810
+ * @param {Pair[]} pairs array of pairs composing the trade.
811
+ * @param {string} outputCurrency the currency for which the route finishes.
812
+ * @return {string[]} Array of token addresses composing the route ordered in the route's direction ending with outputCurrency.
813
+ */
814
+ export function getPathFromOutput(
815
+ pairs: Pair[],
816
+ outputCurrency: string,
817
+ ): string[] {
818
+ const path: string[] = [];
819
+ for (let i = pairs.length - 1; i >= 0; i -= 1) {
820
+ const pairCurrencyOut =
821
+ path.length === 0 ? outputCurrency : path[path.length - 1];
822
+ const [tokenOut, tokenIn] =
823
+ pairCurrencyOut === pairs[i].token0
824
+ ? [pairs[i].token0, pairs[i].token1]
825
+ : [pairs[i].token1, pairs[i].token0];
826
+ if (path.length === 0) {
827
+ path.push(tokenOut);
828
+ }
829
+ path.push(tokenIn);
830
+ }
831
+ return path.reverse();
832
+ }