@paraswap/dex-lib 2.23.4 → 2.24.0

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 (62) hide show
  1. package/build/abi/algebra/AlgebraPool.abi.json +727 -0
  2. package/build/abi/algebra/AlgebraQuoter.abi.json +138 -0
  3. package/build/abi/algebra/AlgebraStateMulticall.abi.json +801 -0
  4. package/build/config.js +2 -2
  5. package/build/dex/algebra/algebra-pool.d.ts +41 -0
  6. package/build/dex/algebra/algebra-pool.js +272 -0
  7. package/build/dex/algebra/algebra-pool.js.map +1 -0
  8. package/build/dex/algebra/algebra.d.ts +53 -0
  9. package/build/dex/algebra/algebra.js +460 -0
  10. package/build/dex/algebra/algebra.js.map +1 -0
  11. package/build/dex/algebra/config.d.ts +4 -0
  12. package/build/dex/algebra/config.js +41 -0
  13. package/build/dex/algebra/config.js.map +1 -0
  14. package/build/dex/algebra/lib/AlgebraMath.d.ts +13 -0
  15. package/build/dex/algebra/lib/AlgebraMath.js +440 -0
  16. package/build/dex/algebra/lib/AlgebraMath.js.map +1 -0
  17. package/build/dex/algebra/lib/AlgebraXUniV3.d.ts +5 -0
  18. package/build/dex/algebra/lib/AlgebraXUniV3.js +45 -0
  19. package/build/dex/algebra/lib/AlgebraXUniV3.js.map +1 -0
  20. package/build/dex/algebra/lib/Constants.d.ts +5 -0
  21. package/build/dex/algebra/lib/Constants.js +10 -0
  22. package/build/dex/algebra/lib/Constants.js.map +1 -0
  23. package/build/dex/algebra/lib/DataStorage.d.ts +19 -0
  24. package/build/dex/algebra/lib/DataStorage.js +466 -0
  25. package/build/dex/algebra/lib/DataStorage.js.map +1 -0
  26. package/build/dex/algebra/lib/DataStorageOperator.d.ts +10 -0
  27. package/build/dex/algebra/lib/DataStorageOperator.js +93 -0
  28. package/build/dex/algebra/lib/DataStorageOperator.js.map +1 -0
  29. package/build/dex/algebra/lib/Sqrt.d.ts +3 -0
  30. package/build/dex/algebra/lib/Sqrt.js +60 -0
  31. package/build/dex/algebra/lib/Sqrt.js.map +1 -0
  32. package/build/dex/algebra/lib/TickManager.d.ts +10 -0
  33. package/build/dex/algebra/lib/TickManager.js +3 -0
  34. package/build/dex/algebra/lib/TickManager.js.map +1 -0
  35. package/build/dex/algebra/types.d.ts +75 -0
  36. package/build/dex/{pancakeswap-v3 → algebra}/types.js.map +1 -1
  37. package/build/dex/algebra/utils.d.ts +4 -0
  38. package/build/dex/algebra/utils.js +60 -0
  39. package/build/dex/algebra/utils.js.map +1 -0
  40. package/build/dex/uniswap-v3/config.js +15 -0
  41. package/build/dex/uniswap-v3/config.js.map +1 -1
  42. package/package.json +1 -1
  43. package/src/config.ts +2 -2
  44. package/src/dex/uniswap-v3/config.ts +16 -0
  45. package/src/dex/uniswap-v3/uniswap-v3-e2e.test.ts +86 -0
  46. package/.idea/aws.xml +0 -17
  47. package/.idea/codeStyles/Project.xml +0 -19
  48. package/.idea/codeStyles/codeStyleConfig.xml +0 -5
  49. package/.idea/misc.xml +0 -6
  50. package/.idea/modules.xml +0 -8
  51. package/.idea/paraswap-dex-lib.iml +0 -9
  52. package/.idea/vcs.xml +0 -6
  53. package/build/dex/aave-v3/tokens/arbitrum.json +0 -50
  54. package/build/dex/aave-v3/tokens/avalanche.json +0 -74
  55. package/build/dex/aave-v3/tokens/fantom.json +0 -62
  56. package/build/dex/aave-v3/tokens/optimism.json +0 -50
  57. package/build/dex/aave-v3/tokens/polygon.json +0 -116
  58. package/build/dex/pancakeswap-v3/types.d.ts +0 -14
  59. package/build/dex/solidly/forks-override/ramses.d.ts +0 -8
  60. package/build/dex/solidly/forks-override/ramses.js +0 -15
  61. package/build/dex/solidly/forks-override/ramses.js.map +0 -1
  62. /package/build/dex/{pancakeswap-v3 → algebra}/types.js +0 -0
@@ -0,0 +1,466 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DataStorage = exports.TIMEPOINT_ZERO = void 0;
4
+ const utils_1 = require("../../../utils");
5
+ exports.TIMEPOINT_ZERO = {
6
+ // averageTick: 0n,
7
+ blockTimestamp: 0n,
8
+ initialized: false,
9
+ secondsPerLiquidityCumulative: 0n,
10
+ tickCumulative: 0n,
11
+ // volatilityCumulative: 0n,
12
+ // volumePerLiquidityCumulative: 0n,
13
+ };
14
+ const WINDOW = 24n * 60n;
15
+ const UINT16_MODULO = 65536n;
16
+ class DataStorage {
17
+ /// @notice Calculates volatility between two sequential timepoints with resampling to 1 sec frequency
18
+ /// @param dt Timedelta between timepoints, must be within uint32 range
19
+ /// @param tick0 The tick at the left timepoint, must be within int24 range
20
+ /// @param tick1 The tick at the right timepoint, must be within int24 range
21
+ /// @param avgTick0 The average tick at the left timepoint, must be within int24 range
22
+ /// @param avgTick1 The average tick at the right timepoint, must be within int24 range
23
+ /// @return volatility The volatility between two sequential timepoints
24
+ /// If the requirements for the parameters are met, it always fits 88 bits
25
+ static _volatilityOnRange(dt, tick0, tick1, avgTick0, avgTick1) {
26
+ // On the time interval from the previous timepoint to the current
27
+ // we can represent tick and average tick change as two straight lines:
28
+ // tick = k*t + b, where k and b are some constants
29
+ // avgTick = p*t + q, where p and q are some constants
30
+ // we want to get sum of (tick(t) - avgTick(t))^2 for every t in the interval (0; dt]
31
+ // so: (tick(t) - avgTick(t))^2 = ((k*t + b) - (p*t + q))^2 = (k-p)^2 * t^2 + 2(k-p)(b-q)t + (b-q)^2
32
+ // since everything except t is a constant, we need to use progressions for t and t^2:
33
+ // sum(t) for t from 1 to dt = dt*(dt + 1)/2 = sumOfSequence
34
+ // sum(t^2) for t from 1 to dt = dt*(dt+1)*(2dt + 1)/6 = sumOfSquares
35
+ // so result will be: (k-p)^2 * sumOfSquares + 2(k-p)(b-q)*sumOfSequence + dt*(b-q)^2
36
+ const K = tick1 - tick0 - (avgTick1 - avgTick0); // (k - p)*dt
37
+ const B = (tick0 - avgTick0) * dt; // (b - q)*dt
38
+ const sumOfSquares = dt * (dt + 1n) * (2n * dt + 1n); // sumOfSquares * 6
39
+ const sumOfSequence = dt * (dt + 1n); // sumOfSequence * 2
40
+ const volatility = (0, utils_1.uint256)((K ** 2n * sumOfSquares +
41
+ 6n * B * K * sumOfSequence +
42
+ 6n * dt * B ** 2n) /
43
+ (6n * dt ** 2n));
44
+ return volatility;
45
+ }
46
+ /// @notice Transforms a previous timepoint into a new timepoint, given the passage of time and the current tick and liquidity values
47
+ /// @dev blockTimestamp _must_ be chronologically equal to or greater than last.blockTimestamp, safe for 0 or 1 overflows
48
+ /// @param last The specified timepoint to be used in creation of new timepoint
49
+ /// @param blockTimestamp The timestamp of the new timepoint
50
+ /// @param tick The active tick at the time of the new timepoint
51
+ /// @param prevTick The active tick at the time of the last timepoint
52
+ /// @param liquidity The total in-range liquidity at the time of the new timepoint
53
+ /// @param averageTick The average tick at the time of the new timepoint
54
+ /// @param volumePerLiquidity The gmean(volumes)/liquidity at the time of the new timepoint
55
+ /// @return Timepoint The newly populated timepoint
56
+ static createNewTimepoint(last, blockTimestamp, tick, prevTick, liquidity) {
57
+ const delta = blockTimestamp - last.blockTimestamp;
58
+ last.initialized = true;
59
+ last.blockTimestamp = blockTimestamp;
60
+ last.tickCumulative += (0, utils_1.int56)(tick) * delta;
61
+ last.secondsPerLiquidityCumulative +=
62
+ ((0, utils_1.uint160)(delta) << 128n) / (liquidity > 0n ? liquidity : 1n); // just timedelta if liquidity == 0
63
+ // last.volatilityCumulative += uint88(
64
+ // this._volatilityOnRange(
65
+ // delta,
66
+ // prevTick,
67
+ // tick,
68
+ // last.averageTick,
69
+ // averageTick,
70
+ // ),
71
+ // ); // always fits 88 bits
72
+ // last.averageTick = averageTick;
73
+ // last.volumePerLiquidityCumulative += volumePerLiquidity;
74
+ return last;
75
+ }
76
+ /// @notice comparator for 32-bit timestamps
77
+ /// @dev safe for 0 or 1 overflows, a and b _must_ be chronologically before or equal to currentTime
78
+ /// @param a A comparison timestamp from which to determine the relative position of `currentTime`
79
+ /// @param b From which to determine the relative position of `currentTime`
80
+ /// @param currentTime A timestamp truncated to 32 bits
81
+ /// @return res Whether `a` is chronologically <= `b`
82
+ static lteConsideringOverflow(a, b, currentTime) {
83
+ let res = a > currentTime;
84
+ if (res == b > currentTime)
85
+ res = a <= b; // if both are on the same side
86
+ return res;
87
+ }
88
+ /// @dev guaranteed that the result is within the bounds of int24
89
+ /// returns int256 for fuzzy tests
90
+ static _getAverageTick(self, time, tick, index, oldestIndex, lastTimestamp, lastTickCumulative) {
91
+ if (Object.keys(self).length < 2)
92
+ return tick; // MITIGATIONS OFF CONTRACT
93
+ const oldestTimestamp = (self[Number(oldestIndex)] || exports.TIMEPOINT_ZERO)
94
+ .blockTimestamp;
95
+ const oldestTickCumulative = self[Number(oldestIndex)]?.tickCumulative || 0n;
96
+ let avgTick;
97
+ if (this.lteConsideringOverflow(oldestTimestamp, time - WINDOW, time)) {
98
+ if (this.lteConsideringOverflow(lastTimestamp, time - WINDOW, time)) {
99
+ index -= 1n; // considering underflow
100
+ const startTimepoint = self[Number(index)] || exports.TIMEPOINT_ZERO;
101
+ avgTick = startTimepoint.initialized
102
+ ? (lastTickCumulative - startTimepoint.tickCumulative) /
103
+ (lastTimestamp - startTimepoint.blockTimestamp)
104
+ : tick;
105
+ }
106
+ else {
107
+ const startOfWindow = this.getSingleTimepoint(self, time, WINDOW, tick, index, oldestIndex, 0n);
108
+ // current-WINDOW last current
109
+ // _________*____________*_______*_
110
+ // ||||||||||||
111
+ avgTick =
112
+ (lastTickCumulative - startOfWindow.tickCumulative) /
113
+ (lastTimestamp - time + WINDOW);
114
+ }
115
+ }
116
+ else {
117
+ avgTick =
118
+ lastTimestamp == oldestTimestamp
119
+ ? tick
120
+ : (lastTickCumulative - oldestTickCumulative) /
121
+ (lastTimestamp - oldestTimestamp);
122
+ }
123
+ return avgTick;
124
+ }
125
+ /// @notice Fetches the timepoints beforeOrAt and atOrAfter a target, i.e. where [beforeOrAt, atOrAfter] is satisfied.
126
+ /// The result may be the same timepoint, or adjacent timepoints.
127
+ /// @dev The answer must be contained in the array, used when the target is located within the stored timepoint
128
+ /// boundaries: older than the most recent timepoint and younger, or the same age as, the oldest timepoint
129
+ /// @param self The stored dataStorage array
130
+ /// @param time The current block.timestamp
131
+ /// @param target The timestamp at which the reserved timepoint should be for
132
+ /// @param lastIndex The index of the timepoint that was most recently written to the timepoints array
133
+ /// @param oldestIndex The index of the oldest timepoint in the timepoints array
134
+ /// @return beforeOrAt The timepoint recorded before, or at, the target
135
+ /// @return atOrAfter The timepoint recorded at, or after, the target
136
+ static binarySearch(self, time, target, lastIndex, oldestIndex) {
137
+ let left = oldestIndex; // oldest timepoint
138
+ let right = lastIndex >= oldestIndex ? lastIndex : lastIndex + UINT16_MODULO; // newest timepoint considering one index overflow
139
+ let current = (left + right) >> 1n; // "middle" point between the boundaries
140
+ do {
141
+ let beforeOrAt = self[Number((0, utils_1.uint16)(current))] || exports.TIMEPOINT_ZERO; // checking the "middle" point between the boundaries
142
+ let [initializedBefore, timestampBefore] = [
143
+ beforeOrAt.initialized,
144
+ beforeOrAt.blockTimestamp,
145
+ ];
146
+ if (initializedBefore) {
147
+ if (this.lteConsideringOverflow(timestampBefore, target, time)) {
148
+ // is current point before or at `target`?
149
+ let atOrAfter = self[Number((0, utils_1.uint16)(current + 1n))] || exports.TIMEPOINT_ZERO; // checking the next point after "middle"
150
+ let [initializedAfter, timestampAfter] = [
151
+ atOrAfter.initialized,
152
+ atOrAfter.blockTimestamp,
153
+ ];
154
+ if (initializedAfter) {
155
+ if (this.lteConsideringOverflow(target, timestampAfter, time)) {
156
+ // is the "next" point after or at `target`?
157
+ return [beforeOrAt, atOrAfter]; // the only fully correct way to finish
158
+ }
159
+ left = current + 1n; // "next" point is before the `target`, so looking in the right half
160
+ }
161
+ else {
162
+ // beforeOrAt is initialized and <= target, and next timepoint is uninitialized
163
+ // should be impossible if initial boundaries and `target` are correct
164
+ return [beforeOrAt, beforeOrAt];
165
+ }
166
+ }
167
+ else {
168
+ right = current - 1n; // current point is after the `target`, so looking in the left half
169
+ }
170
+ }
171
+ else {
172
+ // we've landed on an uninitialized timepoint, keep searching higher
173
+ // should be impossible if initial boundaries and `target` are correct
174
+ left = current + 1n;
175
+ }
176
+ current = (left + right) >> 1n; // calculating the new "middle" point index after updating the bounds
177
+ } while (true); // protect with max nb of iterations?
178
+ // unreachable code here
179
+ // atOrAfter = beforeOrAt; // code is unreachable, to suppress compiler warning
180
+ // assert(false);
181
+ // return [beforeOrAt, atOrAfter]
182
+ }
183
+ /// @dev Reverts if an timepoint at or before the desired timepoint timestamp does not exist.
184
+ /// 0 may be passed as `secondsAgo' to return the current cumulative values.
185
+ /// If called with a timestamp falling between two timepoints, returns the counterfactual accumulator values
186
+ /// at exactly the timestamp between the two timepoints.
187
+ /// @param self The stored dataStorage array
188
+ /// @param time The current block timestamp
189
+ /// @param secondsAgo The amount of time to look back, in seconds, at which point to return an timepoint
190
+ /// @param tick The current tick
191
+ /// @param index The index of the timepoint that was most recently written to the timepoints array
192
+ /// @param oldestIndex The index of the oldest timepoint
193
+ /// @param liquidity The current in-range pool liquidity
194
+ /// @return targetTimepoint desired timepoint or it's approximation
195
+ static getSingleTimepoint(self, time, secondsAgo, tick, index, oldestIndex, liquidity) {
196
+ let target = time - secondsAgo;
197
+ // if target is newer than last timepoint
198
+ if (secondsAgo == 0n ||
199
+ this.lteConsideringOverflow((self[Number(index)] || exports.TIMEPOINT_ZERO).blockTimestamp, target, time)) {
200
+ let last = self[Number(index)] || exports.TIMEPOINT_ZERO;
201
+ if (last.blockTimestamp == target) {
202
+ return last;
203
+ }
204
+ else {
205
+ // otherwise, we need to add new timepoint
206
+ // let avgTick = 0n;
207
+ // int24(
208
+ // this._getAverageTick(
209
+ // self,
210
+ // time,
211
+ // tick,
212
+ // index,
213
+ // oldestIndex,
214
+ // last.blockTimestamp,
215
+ // last.tickCumulative,
216
+ // ),
217
+ // );
218
+ let prevTick = tick;
219
+ {
220
+ if (index != oldestIndex) {
221
+ // FIXME?
222
+ let prevLast = {
223
+ // averageTick: 0n,
224
+ blockTimestamp: 0n,
225
+ initialized: false,
226
+ secondsPerLiquidityCumulative: 0n,
227
+ tickCumulative: 0n,
228
+ // volatilityCumulative: 0n,
229
+ // volumePerLiquidityCumulative: 0n,
230
+ };
231
+ let _prevLast = self[Number(index - 1n)] || exports.TIMEPOINT_ZERO; // considering index underflow
232
+ prevLast.blockTimestamp = _prevLast.blockTimestamp;
233
+ prevLast.tickCumulative = _prevLast.tickCumulative;
234
+ console.log(`QuickSwapV3 denom ${JSON.stringify({ last, prevLast })}`);
235
+ prevTick = (0, utils_1.int24)((last.tickCumulative - prevLast.tickCumulative) /
236
+ (last.blockTimestamp - prevLast.blockTimestamp));
237
+ }
238
+ }
239
+ return this.createNewTimepoint(last, target, tick, prevTick, liquidity);
240
+ }
241
+ }
242
+ (0, utils_1._require)(this.lteConsideringOverflow((self[Number(oldestIndex)] || exports.TIMEPOINT_ZERO).blockTimestamp, target, time), 'OLD');
243
+ let [beforeOrAt, atOrAfter] = this.binarySearch(self, time, target, index, oldestIndex);
244
+ if (target == atOrAfter.blockTimestamp) {
245
+ return atOrAfter; // we're at the right boundary
246
+ }
247
+ if (target != beforeOrAt.blockTimestamp) {
248
+ // we're in the middle
249
+ let timepointTimeDelta = atOrAfter.blockTimestamp - beforeOrAt.blockTimestamp;
250
+ let targetDelta = target - beforeOrAt.blockTimestamp;
251
+ // For gas savings the resulting point is written to beforeAt
252
+ beforeOrAt.tickCumulative +=
253
+ ((atOrAfter.tickCumulative - beforeOrAt.tickCumulative) /
254
+ timepointTimeDelta) *
255
+ targetDelta;
256
+ beforeOrAt.secondsPerLiquidityCumulative += (0, utils_1.uint160)(((0, utils_1.uint256)(atOrAfter.secondsPerLiquidityCumulative -
257
+ beforeOrAt.secondsPerLiquidityCumulative) *
258
+ targetDelta) /
259
+ timepointTimeDelta);
260
+ // beforeOrAt.volatilityCumulative +=
261
+ // ((atOrAfter.volatilityCumulative - beforeOrAt.volatilityCumulative) /
262
+ // timepointTimeDelta) *
263
+ // targetDelta;
264
+ // beforeOrAt.volumePerLiquidityCumulative +=
265
+ // ((atOrAfter.volumePerLiquidityCumulative -
266
+ // beforeOrAt.volumePerLiquidityCumulative) /
267
+ // timepointTimeDelta) *
268
+ // targetDelta;
269
+ }
270
+ // we're at the left boundary or at the middle
271
+ return beforeOrAt;
272
+ }
273
+ /// @notice Returns the accumulator values as of each time seconds ago from the given time in the array of `secondsAgos`
274
+ /// @dev Reverts if `secondsAgos` > oldest timepoint
275
+ /// @param self The stored dataStorage array
276
+ /// @param time The current block.timestamp
277
+ /// @param secondsAgos Each amount of time to look back, in seconds, at which point to return an timepoint
278
+ /// @param tick The current tick
279
+ /// @param index The index of the timepoint that was most recently written to the timepoints array
280
+ /// @param liquidity The current in-range pool liquidity
281
+ /// @return tickCumulatives The tick * time elapsed since the pool was first initialized, as of each `secondsAgo`
282
+ /// @return secondsPerLiquidityCumulatives The cumulative seconds / max(1, liquidity) since the pool was first initialized, as of each `secondsAgo`
283
+ /// @return volatilityCumulatives The cumulative volatility values since the pool was first initialized, as of each `secondsAgo`
284
+ /// @return volumePerAvgLiquiditys The cumulative volume per liquidity values since the pool was first initialized, as of each `secondsAgo`
285
+ // static getTimepoints(
286
+ // self: Record<number, Timepoint>,
287
+ // time: bigint,
288
+ // secondsAgos: bigint[],
289
+ // tick: bigint,
290
+ // index: bigint,
291
+ // liquidity: bigint,
292
+ // ): [bigint[], bigint[], bigint[], bigint[]] {
293
+ // let tickCumulatives = new Array<bigint>(secondsAgos.length);
294
+ // let secondsPerLiquidityCumulatives = new Array<bigint>(secondsAgos.length);
295
+ // let volatilityCumulatives = new Array<bigint>(secondsAgos.length);
296
+ // let volumePerAvgLiquiditys = new Array<bigint>(secondsAgos.length);
297
+ // let oldestIndex = 0n; // solidity default
298
+ // // check if we have overflow in the past
299
+ // let nextIndex = index + 1n; // considering overflow
300
+ // if ((self[Number(nextIndex)] || TIMEPOINT_ZERO).initialized) {
301
+ // oldestIndex = nextIndex;
302
+ // }
303
+ // let current: Timepoint;
304
+ // for (let i = 0; i < secondsAgos.length; i++) {
305
+ // current = this.getSingleTimepoint(
306
+ // self,
307
+ // time,
308
+ // secondsAgos[i],
309
+ // tick,
310
+ // index,
311
+ // oldestIndex,
312
+ // liquidity,
313
+ // );
314
+ // [
315
+ // tickCumulatives[i],
316
+ // secondsPerLiquidityCumulatives[i],
317
+ // // volatilityCumulatives[i],
318
+ // // volumePerAvgLiquiditys[i],
319
+ // ] = [
320
+ // current.tickCumulative,
321
+ // current.secondsPerLiquidityCumulative,
322
+ // // current.volatilityCumulative,
323
+ // // current.volumePerLiquidityCumulative,
324
+ // ];
325
+ // }
326
+ // return [
327
+ // tickCumulatives,
328
+ // secondsPerLiquidityCumulatives,
329
+ // volatilityCumulatives,
330
+ // volumePerAvgLiquiditys,
331
+ // ];
332
+ // }
333
+ /// @notice Returns average volatility in the range from time-WINDOW to time
334
+ /// @param self The stored dataStorage array
335
+ /// @param time The current block.timestamp
336
+ /// @param tick The current tick
337
+ /// @param index The index of the timepoint that was most recently written to the timepoints array
338
+ /// @param liquidity The current in-range pool liquidity
339
+ /// @return volatilityAverage The average volatility in the recent range
340
+ /// @return volumePerLiqAverage The average volume per liquidity in the recent range
341
+ // static getAverages(
342
+ // self: Record<number, Timepoint>,
343
+ // time: bigint,
344
+ // tick: bigint,
345
+ // index: bigint,
346
+ // liquidity: bigint,
347
+ // ): [bigint, bigint] {
348
+ // let oldestIndex;
349
+ // let oldest = self[0];
350
+ // let nextIndex = index + 1n; // considering overflow
351
+ // if ((self[Number(nextIndex)] || TIMEPOINT_ZERO).initialized) {
352
+ // oldest = self[Number(nextIndex)] || TIMEPOINT_ZERO;
353
+ // oldestIndex = nextIndex;
354
+ // }
355
+ // assert(oldestIndex); // FIXME ?
356
+ // let endOfWindow = this.getSingleTimepoint(
357
+ // self,
358
+ // time,
359
+ // 0n,
360
+ // tick,
361
+ // index,
362
+ // oldestIndex,
363
+ // liquidity,
364
+ // );
365
+ // let oldestTimestamp = oldest.blockTimestamp;
366
+ // if (this.lteConsideringOverflow(oldestTimestamp, time - WINDOW, time)) {
367
+ // let startOfWindow = this.getSingleTimepoint(
368
+ // self,
369
+ // time,
370
+ // WINDOW,
371
+ // tick,
372
+ // index,
373
+ // oldestIndex,
374
+ // liquidity,
375
+ // );
376
+ // return [
377
+ // (endOfWindow.volatilityCumulative -
378
+ // startOfWindow.volatilityCumulative) /
379
+ // WINDOW,
380
+ // uint256(
381
+ // endOfWindow.volumePerLiquidityCumulative -
382
+ // startOfWindow.volumePerLiquidityCumulative,
383
+ // ) >> 57n,
384
+ // ];
385
+ // } else if (time != oldestTimestamp) {
386
+ // let _oldestVolatilityCumulative = oldest.volatilityCumulative;
387
+ // let _oldestVolumePerLiquidityCumulative =
388
+ // oldest.volumePerLiquidityCumulative;
389
+ // return [
390
+ // (endOfWindow.volatilityCumulative - _oldestVolatilityCumulative) /
391
+ // (time - oldestTimestamp),
392
+ // uint256(
393
+ // endOfWindow.volumePerLiquidityCumulative -
394
+ // _oldestVolumePerLiquidityCumulative,
395
+ // ) >> 57n,
396
+ // ];
397
+ // }
398
+ // return [0n, 0n]; // should not enter here ?
399
+ // }
400
+ /// @notice Initialize the dataStorage array by writing the first slot. Called once for the lifecycle of the timepoints array
401
+ /// @param self The stored dataStorage array
402
+ /// @param time The time of the dataStorage initialization, via block.timestamp truncated to uint32
403
+ /// @param tick Initial tick
404
+ // static initialize(
405
+ // Timepoint[UINT16_MODULO] storage self,
406
+ // uint32 time,
407
+ // int24 tick
408
+ // ) internal {
409
+ // require(!self[0].initialized);
410
+ // self[0].initialized = true;
411
+ // self[0].blockTimestamp = time;
412
+ // self[0].averageTick = tick;
413
+ // }
414
+ /// @notice Writes an dataStorage timepoint to the array
415
+ /// @dev Writable at most once per block. Index represents the most recently written element. index must be tracked externally.
416
+ /// @param self The stored dataStorage array
417
+ /// @param index The index of the timepoint that was most recently written to the timepoints array
418
+ /// @param blockTimestamp The timestamp of the new timepoint
419
+ /// @param tick The active tick at the time of the new timepoint
420
+ /// @param liquidity The total in-range liquidity at the time of the new timepoint
421
+ /// @param volumePerLiquidity The gmean(volumes)/liquidity at the time of the new timepoint
422
+ /// @return indexUpdated The new index of the most recently written element in the dataStorage array
423
+ static write(self, index, blockTimestamp, tick, liquidity) {
424
+ let _last = self[Number(index)] || exports.TIMEPOINT_ZERO;
425
+ // early return if we've already written an timepoint this block
426
+ if (_last.blockTimestamp == blockTimestamp) {
427
+ return index;
428
+ }
429
+ let last = _last;
430
+ // get next index considering overflow
431
+ let indexUpdated = index + 1n;
432
+ let oldestIndex = 0n; // default in evm
433
+ // check if we have overflow in the past
434
+ if ((self[Number(indexUpdated)] || exports.TIMEPOINT_ZERO).initialized) {
435
+ oldestIndex = indexUpdated;
436
+ }
437
+ // let avgTick = 0n;
438
+ // int24(
439
+ // this._getAverageTick(
440
+ // self,
441
+ // blockTimestamp,
442
+ // tick,
443
+ // index,
444
+ // oldestIndex,
445
+ // last.blockTimestamp,
446
+ // last.tickCumulative,
447
+ // ),
448
+ // );
449
+ let prevTick = tick;
450
+ if (index != oldestIndex) {
451
+ let _prevLast = self[Number(index - 1n)] || exports.TIMEPOINT_ZERO; // considering index underflow
452
+ let _prevLastBlockTimestamp = _prevLast.blockTimestamp;
453
+ let _prevLastTickCumulative = _prevLast.tickCumulative;
454
+ prevTick = (0, utils_1.int24)((last.tickCumulative - _prevLastTickCumulative) /
455
+ (last.blockTimestamp - _prevLastBlockTimestamp));
456
+ }
457
+ self[Number(indexUpdated)] = this.createNewTimepoint(last, blockTimestamp, tick, prevTick, liquidity);
458
+ // FIXME should delete ?
459
+ // delete self[Number(index)];
460
+ return indexUpdated;
461
+ }
462
+ }
463
+ exports.DataStorage = DataStorage;
464
+ DataStorage.WINDOW = WINDOW;
465
+ DataStorage.UINT16_MODULO = UINT16_MODULO;
466
+ //# sourceMappingURL=DataStorage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DataStorage.js","sourceRoot":"","sources":["../../../../src/dex/algebra/lib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C;IACtB,CAAC;;AA3kBH,kCA4kBC;AA3kBQ,kBAAM,GAAG,MAAM,CAAC;AAChB,yBAAa,GAAG,aAAa,CAAC"}
@@ -0,0 +1,10 @@
1
+ import { PoolState } from '../types';
2
+ export declare class DataStorageOperator {
3
+ static getSingleTimepoint(state: PoolState, time: bigint, secondsAgo: bigint, tick: bigint, index: bigint, liquidity: bigint): [
4
+ bigint,
5
+ bigint
6
+ ];
7
+ static write(state: PoolState, index: bigint, blockTimestamp: bigint, tick: bigint, liquidity: bigint): bigint;
8
+ static calculateVolumePerLiquidity(liquidity: bigint, amount0: bigint, amount1: bigint): bigint;
9
+ static window(): bigint;
10
+ }
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DataStorageOperator = void 0;
4
+ const DataStorage_1 = require("./DataStorage");
5
+ const bigint_constants_1 = require("../../../bigint-constants");
6
+ const utils_1 = require("../../../utils");
7
+ const Sqrt_1 = require("./Sqrt");
8
+ // TO COMPARE WITH https://github.com/cryptoalgebra/Algebra/blob/3cd9a65bb5bb39d26fb4346e8f7d6d2a28672cc6/src/core/contracts/DataStorageOperator.sol#L16-L17
9
+ const MAX_VOLUME_PER_LIQUIDITY = 100000 << 64; // maximum meaningful ratio of volume to liquidity
10
+ class DataStorageOperator {
11
+ /// @inheritdoc IDataStorageOperator
12
+ static getSingleTimepoint(state, time, secondsAgo, tick, index, liquidity) {
13
+ let oldestIndex = 0n;
14
+ // check if we have overflow in the past
15
+ let nextIndex = index + 1n; // considering overflow
16
+ if ((state.timepoints[Number(nextIndex)] || DataStorage_1.TIMEPOINT_ZERO).initialized) {
17
+ oldestIndex = nextIndex;
18
+ }
19
+ let result = DataStorage_1.DataStorage.getSingleTimepoint(state.timepoints, time, secondsAgo, tick, index, oldestIndex, liquidity);
20
+ let [tickCumulative, secondsPerLiquidityCumulative,
21
+ // volatilityCumulative,
22
+ // volumePerAvgLiquidity,
23
+ ] = [
24
+ result.tickCumulative,
25
+ result.secondsPerLiquidityCumulative,
26
+ // result.volatilityCumulative,
27
+ // result.volumePerLiquidityCumulative,
28
+ ];
29
+ return [
30
+ tickCumulative,
31
+ secondsPerLiquidityCumulative,
32
+ // volatilityCumulative,
33
+ // volumePerAvgLiquidity,
34
+ ];
35
+ }
36
+ /// @inheritdoc IDataStorageOperator
37
+ // static getTimepoints(
38
+ // state: PoolState,
39
+ // time: bigint,
40
+ // secondsAgos: bigint[],
41
+ // tick: bigint,
42
+ // index: bigint,
43
+ // liquidity: bigint,
44
+ // ): [bigint[], bigint[], bigint[], bigint[]] {
45
+ // return DataStorage.getTimepoints(
46
+ // state.timepoints,
47
+ // time,
48
+ // secondsAgos,
49
+ // tick,
50
+ // index,
51
+ // liquidity,
52
+ // );
53
+ // }
54
+ // /// @inheritdoc IDataStorageOperator
55
+ // static getAverages(
56
+ // state: PoolState,
57
+ // time: bigint,
58
+ // tick: bigint,
59
+ // index: bigint,
60
+ // liquidity: bigint,
61
+ // ): [bigint, bigint] {
62
+ // return DataStorage.getAverages(
63
+ // state.timepoints,
64
+ // time,
65
+ // tick,
66
+ // index,
67
+ // liquidity,
68
+ // );
69
+ // }
70
+ /// @inheritdoc IDataStorageOperator
71
+ static write(state, index, blockTimestamp, tick, liquidity) {
72
+ return DataStorage_1.DataStorage.write(state.timepoints, index, blockTimestamp, tick, liquidity);
73
+ }
74
+ /// @inheritdoc IDataStorageOperator
75
+ static calculateVolumePerLiquidity(liquidity, amount0, amount1) {
76
+ let volume = Sqrt_1.Sqrt.sqrtAbs(amount0) * Sqrt_1.Sqrt.sqrtAbs(amount1);
77
+ let volumeShifted;
78
+ if (volume >= 2n ** 192n)
79
+ volumeShifted = bigint_constants_1.BI_MAX_UINT256 / (liquidity > 0n ? liquidity : 1n);
80
+ else
81
+ volumeShifted = (volume << 64n) / (liquidity > 0n ? liquidity : 1n);
82
+ if (volumeShifted >= MAX_VOLUME_PER_LIQUIDITY)
83
+ return BigInt(MAX_VOLUME_PER_LIQUIDITY);
84
+ else
85
+ return (0, utils_1.uint128)(volumeShifted);
86
+ }
87
+ /// @inheritdoc IDataStorageOperator
88
+ static window() {
89
+ return DataStorage_1.DataStorage.WINDOW;
90
+ }
91
+ }
92
+ exports.DataStorageOperator = DataStorageOperator;
93
+ //# sourceMappingURL=DataStorageOperator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DataStorageOperator.js","sourceRoot":"","sources":["../../../../src/dex/algebra/lib/DataStorageOperator.ts"],"names":[],"mappings":";;;AACA,+CAA4D;AAC5D,gEAA2D;AAC3D,0CAAyC;AACzC,iCAA8B;AAE9B,4JAA4J;AAE5J,MAAM,wBAAwB,GAAG,MAAM,IAAI,EAAE,CAAC,CAAC,kDAAkD;AAEjG,MAAa,mBAAmB;IAC9B,oCAAoC;IACpC,MAAM,CAAC,kBAAkB,CACvB,KAAgB,EAChB,IAAY,EACZ,UAAkB,EAClB,IAAY,EACZ,KAAa,EACb,SAAiB;QAMjB,IAAI,WAAW,GAAG,EAAE,CAAC;QACrB,wCAAwC;QACxC,IAAI,SAAS,GAAG,KAAK,GAAG,EAAE,CAAC,CAAC,uBAAuB;QACnD,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,IAAI,4BAAc,CAAC,CAAC,WAAW,EAAE;YACvE,WAAW,GAAG,SAAS,CAAC;SACzB;QAED,IAAI,MAAM,GAAG,yBAAW,CAAC,kBAAkB,CACzC,KAAK,CAAC,UAAU,EAChB,IAAI,EACJ,UAAU,EACV,IAAI,EACJ,KAAK,EACL,WAAW,EACX,SAAS,CACV,CAAC;QACF,IAAI,CACF,cAAc,EACd,6BAA6B;QAC7B,wBAAwB;QACxB,yBAAyB;SAC1B,GAAG;YACF,MAAM,CAAC,cAAc;YACrB,MAAM,CAAC,6BAA6B;YACpC,+BAA+B;YAC/B,uCAAuC;SACxC,CAAC;QAEF,OAAO;YACL,cAAc;YACd,6BAA6B;YAC7B,wBAAwB;YACxB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