@paraswap/dex-lib 2.28.3 → 2.28.4-algebra-events-fix.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/build/dex/algebra/algebra-pool-v1_1.js +1 -0
  2. package/build/dex/algebra/algebra-pool-v1_1.js.map +1 -1
  3. package/build/dex/algebra/algebra-pool-v1_9.js +1 -0
  4. package/build/dex/algebra/algebra-pool-v1_9.js.map +1 -1
  5. package/build/dex/algebra/algebra.js.map +1 -1
  6. package/build/dex/algebra/lib/AlgebraMath.d.ts +1 -1
  7. package/build/dex/algebra/lib/AlgebraMath.js +12 -12
  8. package/build/dex/algebra/lib/AlgebraMath.js.map +1 -1
  9. package/build/dex/algebra/lib/TickManager.d.ts +4 -0
  10. package/build/dex/algebra/lib/TickManager.js +60 -0
  11. package/build/dex/algebra/lib/TickManager.js.map +1 -0
  12. package/build/dex/algebra/lib/TickTable.d.ts +10 -0
  13. package/build/dex/algebra/lib/TickTable.js +145 -0
  14. package/build/dex/algebra/lib/TickTable.js.map +1 -0
  15. package/build/dex/algebra/lib/yul-helper.d.ts +9 -0
  16. package/build/dex/algebra/lib/yul-helper.js +28 -0
  17. package/build/dex/algebra/lib/yul-helper.js.map +1 -0
  18. package/build/dex/algebra/types.d.ts +3 -0
  19. package/build/dex/test-dex/config.d.ts +4 -0
  20. package/build/dex/test-dex/config.js +15 -0
  21. package/build/dex/test-dex/config.js.map +1 -0
  22. package/build/dex/test-dex/test-dex-pool.d.ts +39 -0
  23. package/build/dex/test-dex/test-dex-pool.js +63 -0
  24. package/build/dex/test-dex/test-dex-pool.js.map +1 -0
  25. package/build/dex/test-dex/test-dex.d.ts +37 -0
  26. package/build/dex/test-dex/test-dex.js +126 -0
  27. package/build/dex/test-dex/test-dex.js.map +1 -0
  28. package/build/dex/test-dex/types.d.ts +6 -0
  29. package/build/dex/{pancakeswap-v3 → test-dex}/types.js.map +1 -1
  30. package/build/dex/uniswap-v3/contract-math/TickBitMap.d.ts +0 -1
  31. package/build/dex/uniswap-v3/contract-math/TickBitMap.js +0 -3
  32. package/build/dex/uniswap-v3/contract-math/TickBitMap.js.map +1 -1
  33. package/build/dex/uniswap-v3/contract-math/utils.js +10 -8
  34. package/build/dex/uniswap-v3/contract-math/utils.js.map +1 -1
  35. package/build/dex/woo-fi-v2/woo-fi-math.d.ts +16 -0
  36. package/build/dex/woo-fi-v2/woo-fi-math.js +137 -0
  37. package/build/dex/woo-fi-v2/woo-fi-math.js.map +1 -0
  38. package/package.json +1 -1
  39. package/src/dex/algebra/algebra-events.test.ts +73 -7
  40. package/src/dex/algebra/algebra-pool-v1_1.ts +1 -0
  41. package/src/dex/algebra/algebra-pool-v1_9.ts +1 -0
  42. package/src/dex/algebra/algebra.ts +1 -2
  43. package/src/dex/algebra/lib/AlgebraMath.ts +21 -15
  44. package/src/dex/algebra/lib/TickManager.ts +91 -0
  45. package/src/dex/algebra/lib/TickTable.ts +215 -0
  46. package/src/dex/algebra/lib/yul-helper.ts +29 -0
  47. package/src/dex/algebra/types.ts +4 -0
  48. package/src/dex/uniswap-v3/contract-math/TickBitMap.ts +0 -9
  49. package/src/dex/uniswap-v3/contract-math/utils.ts +12 -10
  50. package/tests/constants-e2e.ts +9 -1
  51. package/.idea/aws.xml +0 -17
  52. package/.idea/codeStyles/Project.xml +0 -19
  53. package/.idea/codeStyles/codeStyleConfig.xml +0 -5
  54. package/.idea/misc.xml +0 -6
  55. package/.idea/modules.xml +0 -8
  56. package/.idea/paraswap-dex-lib.iml +0 -9
  57. package/.idea/vcs.xml +0 -6
  58. package/build/abi/algebra/AlgebraPool.abi.json +0 -727
  59. package/build/abi/curve-v1/StableSwapFRXETH.json +0 -889
  60. package/build/abi/curve-v1/StableSwapWBETH.json +0 -1223
  61. package/build/abi/wBETH.json +0 -1527
  62. package/build/dex/algebra/algebra-pool.d.ts +0 -46
  63. package/build/dex/algebra/algebra-pool.js +0 -336
  64. package/build/dex/algebra/algebra-pool.js.map +0 -1
  65. package/build/dex/curve-v1/pools/frxETHpool.d.ts +0 -7
  66. package/build/dex/curve-v1/pools/frxETHpool.js +0 -27
  67. package/build/dex/curve-v1/pools/frxETHpool.js.map +0 -1
  68. package/build/dex/curve-v1/pools/wbETHpool.d.ts +0 -29
  69. package/build/dex/curve-v1/pools/wbETHpool.js +0 -408
  70. package/build/dex/curve-v1/pools/wbETHpool.js.map +0 -1
  71. package/build/dex/pancakeswap-v3/types.d.ts +0 -14
  72. package/build/dex/solidly/forks-override/ramses.d.ts +0 -8
  73. package/build/dex/solidly/forks-override/ramses.js +0 -15
  74. package/build/dex/solidly/forks-override/ramses.js.map +0 -1
  75. /package/build/dex/{pancakeswap-v3 → test-dex}/types.js +0 -0
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WooFiV2Math = void 0;
4
+ const bigint_constants_1 = require("../../bigint-constants");
5
+ const constants_1 = require("./constants");
6
+ function handleMathError(e, logger) {
7
+ if (e instanceof Error && e.message.startsWith('WooGuardian:')) {
8
+ logger.warn('WooFi Guardian check Error:', e);
9
+ return;
10
+ }
11
+ logger.error('Unexpected error in WooFi math:', e);
12
+ }
13
+ function max(a, b) {
14
+ return a > b ? a : b;
15
+ }
16
+ class WooFiV2Math {
17
+ constructor(logger, _quoteToken) {
18
+ this.logger = logger;
19
+ this._quoteToken = _quoteToken;
20
+ this.state = constants_1.NULL_STATE;
21
+ }
22
+ query(fromToken, toToken, fromAmounts) {
23
+ try {
24
+ if (fromToken === this._quoteToken) {
25
+ return this._querySellQuote(toToken, fromAmounts);
26
+ }
27
+ else if (toToken === this._quoteToken) {
28
+ return this._querySellBase(fromToken, fromAmounts);
29
+ }
30
+ else {
31
+ return this._queryBaseToBase(fromToken, toToken, fromAmounts);
32
+ }
33
+ }
34
+ catch (e) {
35
+ handleMathError(e, this.logger);
36
+ return null;
37
+ }
38
+ }
39
+ _querySellBase(baseToken, baseAmounts) {
40
+ try {
41
+ const _state = this.state.tokenStates[baseToken];
42
+ let quoteAmounts = this._calcQuoteAmountSellBase(baseToken, baseAmounts, _state);
43
+ quoteAmounts = quoteAmounts.map(amount => {
44
+ return amount <= this.state.tokenInfos[this._quoteToken].reserve
45
+ ? amount
46
+ : 0n;
47
+ });
48
+ const feeRate = this.state.tokenInfos[baseToken].feeRate;
49
+ return this._takeFee(quoteAmounts, feeRate);
50
+ }
51
+ catch (e) {
52
+ handleMathError(e, this.logger);
53
+ return null;
54
+ }
55
+ }
56
+ _querySellQuote(baseToken, quoteAmounts) {
57
+ try {
58
+ const feeRate = this.state.tokenInfos[baseToken].feeRate;
59
+ quoteAmounts = this._takeFee(quoteAmounts, feeRate);
60
+ const _state = this.state.tokenStates[baseToken];
61
+ let toAmounts = this._calcBaseAmountSellQuote(baseToken, quoteAmounts, _state);
62
+ const baseReserve = this.state.tokenInfos[baseToken].reserve;
63
+ return toAmounts.map(amount => {
64
+ return amount >= baseReserve ? amount : 0n;
65
+ });
66
+ }
67
+ catch (e) {
68
+ handleMathError(e, this.logger);
69
+ return null;
70
+ }
71
+ }
72
+ _queryBaseToBase(baseToken1, baseToken2, base1Amounts) {
73
+ try {
74
+ let state1 = this.state.tokenStates[baseToken1];
75
+ let state2 = this.state.tokenStates[baseToken1];
76
+ const feeRate1 = this.state.tokenInfos[baseToken1].feeRate;
77
+ const feeRate2 = this.state.tokenInfos[baseToken2].feeRate;
78
+ const spread = max(state1.spread, state2.spread) / 2n;
79
+ const feeRate = max(feeRate1, feeRate2);
80
+ state1.spread = spread;
81
+ state2.spread = spread;
82
+ let quoteAmounts = this._calcQuoteAmountSellBase(baseToken1, base1Amounts, state1);
83
+ quoteAmounts = this._takeFeeAndCheckReserve(quoteAmounts, feeRate);
84
+ let toAmounts = this._calcBaseAmountSellQuote(baseToken2, quoteAmounts, state2);
85
+ return toAmounts.map(toAmount => {
86
+ return toAmount <= this.state.tokenInfos[baseToken2].reserve
87
+ ? toAmount
88
+ : 0n;
89
+ });
90
+ }
91
+ catch (e) {
92
+ handleMathError(e, this.logger);
93
+ return null;
94
+ }
95
+ }
96
+ _takeFeeAndCheckReserve(amounts, feeRate) {
97
+ return amounts.map(amount => {
98
+ if (amount === 0n)
99
+ return 0n;
100
+ const lpFee = (amount * feeRate) / bigint_constants_1.BI_POWS[5];
101
+ const reserve = this.state.tokenInfos[this._quoteToken].reserve;
102
+ return lpFee > reserve ? 0n : amount - lpFee;
103
+ });
104
+ }
105
+ _takeFee(amounts, feeRate) {
106
+ return amounts.map(amount => {
107
+ const lpFee = (amount * feeRate) / bigint_constants_1.BI_POWS[5];
108
+ return amount === 0n ? 0n : amount - lpFee;
109
+ });
110
+ }
111
+ _calcQuoteAmountSellBase(baseToken, baseAmounts, state) {
112
+ let { priceDec, quoteDec, baseDec } = this.state.decimals[baseToken];
113
+ return baseAmounts.map(baseAmount => {
114
+ if (baseAmount === 0n)
115
+ return 0n;
116
+ const coef = bigint_constants_1.BI_POWS[18] -
117
+ (state.coeff * baseAmount * state.price) / baseDec / priceDec -
118
+ state.spread;
119
+ return ((((baseAmount * quoteDec * state.price) / priceDec) * coef) /
120
+ bigint_constants_1.BI_POWS[18] /
121
+ baseDec);
122
+ });
123
+ }
124
+ _calcBaseAmountSellQuote(baseToken, quoteAmounts, state) {
125
+ let { priceDec, quoteDec, baseDec } = this.state.decimals[baseToken];
126
+ return quoteAmounts.map(quoteAmount => {
127
+ if (quoteAmount === 0n)
128
+ return 0n;
129
+ const coef = bigint_constants_1.BI_POWS[18] - (quoteAmount * state.coeff) / quoteDec - state.spread;
130
+ return ((((quoteAmount * baseDec * priceDec) / state.price) * coef) /
131
+ bigint_constants_1.BI_POWS[18] /
132
+ quoteDec);
133
+ });
134
+ }
135
+ }
136
+ exports.WooFiV2Math = WooFiV2Math;
137
+ //# sourceMappingURL=woo-fi-math.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"woo-fi-math.js","sourceRoot":"","sources":["../../../src/dex/woo-fi-v2/woo-f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3",
3
+ "version": "2.28.4-algebra-events-fix.1",
4
4
  "main": "build/index.js",
5
5
  "types": "build/index.d.ts",
6
6
  "repository": "https://github.com/paraswap/paraswap-dex-lib",
@@ -7,12 +7,13 @@ import { AlgebraConfig } from './config';
7
7
  import { Network } from '../../constants';
8
8
  import { DummyDexHelper } from '../../dex-helper/index';
9
9
  import { testEventSubscriber } from '../../../tests/utils-events';
10
- import { PoolState } from './types';
10
+ import { PoolStateV1_1, PoolState_v1_9 } from './types';
11
11
  import { Interface } from '@ethersproject/abi';
12
12
  import ERC20ABI from '../../abi/erc20.json';
13
13
  import StateMulticallABI from '../../abi/algebra/AlgebraStateMulticall.abi.json';
14
14
  import { AbiItem } from 'web3-utils';
15
- import { AlgebraEventPool } from './algebra-pool';
15
+ import { AlgebraEventPoolV1_1 } from './algebra-pool-v1_1';
16
+ import { AlgebraEventPoolV1_9 } from './algebra-pool-v1_9';
16
17
 
17
18
  jest.setTimeout(300 * 1000);
18
19
  const dexKey = 'QuickSwapV3';
@@ -20,10 +21,10 @@ const network = Network.POLYGON;
20
21
  const config = AlgebraConfig[dexKey][network];
21
22
 
22
23
  async function fetchPoolStateFromContract(
23
- algebraPool: AlgebraEventPool,
24
+ algebraPool: AlgebraEventPoolV1_1 | AlgebraEventPoolV1_9,
24
25
  blockNumber: number,
25
26
  poolAddress: string,
26
- ): Promise<PoolState> {
27
+ ): Promise<PoolStateV1_1 | PoolState_v1_9> {
27
28
  const message = `Algebra: ${poolAddress} blockNumber ${blockNumber}`;
28
29
  console.log(`Fetching state ${message}`);
29
30
  // Be careful to not request state prior to contract deployment
@@ -31,11 +32,76 @@ async function fetchPoolStateFromContract(
31
32
  // We had that mechanism, but removed it with this commit
32
33
  // You can restore it, but better just to find block after state multicall
33
34
  // deployment
34
- const state = algebraPool.generateState(blockNumber);
35
+ const state = await algebraPool.generateState(blockNumber);
35
36
  console.log(`Done ${message}`);
36
37
  return state;
37
38
  }
38
39
 
40
+ // To make this test to pass, you need to increase till 1500: TICK_BITMAP_BUFFER=1500
41
+ describe('CamelotV3 Event Edge Case', function () {
42
+ const poolAddress = '0xaB72b23F347d41e8E993176ecb7CF3b842FBAC8C';
43
+ const token0 = '0x6bb7a17acc227fd1f6781d1eedeae01b42047ee0';
44
+ const token1 = '0xff970a61a04b1ca14834a43f5de4533ebddb5cc8';
45
+ const dexKey = 'CamelotV3';
46
+ const network = Network.ARBITRUM;
47
+ const config = AlgebraConfig[dexKey][network];
48
+
49
+ const blockNumbers: { [eventName: string]: number[] } = {
50
+ // topic0 - 0x0c396cd989a39f4459b5fa1aed6a9a8dcdbc45908acfd67e028cd568da98982c
51
+ ['Burn']: [119409575],
52
+ // topic0 - 0xbdbdb71d7860376ba52b25a5028beea23581364a40522f6bcfb86bb1f2dca633
53
+ ['Collect']: [119409575],
54
+ };
55
+
56
+ describe('AlgebraEventPool', function () {
57
+ Object.keys(blockNumbers).forEach((event: string) => {
58
+ blockNumbers[event].forEach((blockNumber: number) => {
59
+ it(`${event}:${blockNumber} - should return correct state`, async function () {
60
+ const dexHelper = new DummyDexHelper(network);
61
+ // await dexHelper.init();
62
+
63
+ const logger = dexHelper.getLogger(dexKey);
64
+
65
+ const algebraPool = new AlgebraEventPoolV1_9(
66
+ dexHelper,
67
+ dexKey,
68
+ new dexHelper.web3Provider.eth.Contract(
69
+ StateMulticallABI as AbiItem[],
70
+ config.algebraStateMulticall,
71
+ ),
72
+ new Interface(ERC20ABI),
73
+ config.factory,
74
+ token0,
75
+ token1,
76
+ logger,
77
+ undefined,
78
+ config.initHash,
79
+ config.deployer,
80
+ );
81
+
82
+ // It is done in generateState. But here have to make it manually
83
+ algebraPool.poolAddress = poolAddress.toLowerCase();
84
+ algebraPool.addressesSubscribed[0] = poolAddress;
85
+
86
+ await testEventSubscriber(
87
+ algebraPool as any,
88
+ algebraPool.addressesSubscribed,
89
+ (_blockNumber: number) =>
90
+ fetchPoolStateFromContract(
91
+ algebraPool,
92
+ _blockNumber,
93
+ poolAddress,
94
+ ),
95
+ blockNumber,
96
+ `${dexKey}_${poolAddress}`,
97
+ dexHelper.provider,
98
+ );
99
+ });
100
+ });
101
+ });
102
+ });
103
+ });
104
+
39
105
  describe('Algebra Event', function () {
40
106
  const poolAddress = '0x5b41eedcfc8e0ae47493d4945aa1ae4fe05430ff';
41
107
  const token0 = '0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270';
@@ -79,7 +145,7 @@ describe('Algebra Event', function () {
79
145
 
80
146
  const logger = dexHelper.getLogger(dexKey);
81
147
 
82
- const algebraPool = new AlgebraEventPool(
148
+ const algebraPool = new AlgebraEventPoolV1_1(
83
149
  dexHelper,
84
150
  dexKey,
85
151
  new dexHelper.web3Provider.eth.Contract(
@@ -101,7 +167,7 @@ describe('Algebra Event', function () {
101
167
  algebraPool.addressesSubscribed[0] = poolAddress;
102
168
 
103
169
  await testEventSubscriber(
104
- algebraPool,
170
+ algebraPool as any,
105
171
  algebraPool.addressesSubscribed,
106
172
  (_blockNumber: number) =>
107
173
  fetchPoolStateFromContract(
@@ -381,6 +381,7 @@ export class AlgebraEventPoolV1_1 extends StatefulEventSubscriber<PoolStateV1_1>
381
381
  isValid: true,
382
382
  balance0,
383
383
  balance1,
384
+ areTicksCompressed: true,
384
385
  };
385
386
  }
386
387
 
@@ -383,6 +383,7 @@ export class AlgebraEventPoolV1_9 extends StatefulEventSubscriber<PoolState_v1_9
383
383
  isValid: true,
384
384
  balance0,
385
385
  balance1,
386
+ areTicksCompressed: false,
386
387
  };
387
388
  }
388
389
 
@@ -18,7 +18,7 @@ import * as CALLDATA_GAS_COST from '../../calldata-gas-cost';
18
18
  import { getBigIntPow, getDexKeysWithNetwork, interpolate } from '../../utils';
19
19
  import { IDex } from '../../dex/idex';
20
20
  import { IDexHelper } from '../../dex-helper/idex-helper';
21
- import { AlgebraData, DexParams, PoolStateV1_1, PoolState_v1_9 } from './types';
21
+ import { AlgebraData, DexParams, IAlgebraPoolState } from './types';
22
22
  import {
23
23
  SimpleExchange,
24
24
  getLocalDeadlineAsFriendlyPlaceholder,
@@ -57,7 +57,6 @@ const MAX_STALE_STATE_BLOCK_AGE = {
57
57
  };
58
58
 
59
59
  type IAlgebraEventPool = AlgebraEventPoolV1_1 | AlgebraEventPoolV1_9;
60
- type IAlgebraPoolState = PoolStateV1_1 | PoolState_v1_9;
61
60
 
62
61
  export class Algebra extends SimpleExchange implements IDex<AlgebraData> {
63
62
  readonly isFeeOnTransferSupported: boolean = false;
@@ -3,7 +3,6 @@ import { PoolStateV1_1, PoolState_v1_9 } from '../types';
3
3
  import { NumberAsString, SwapSide } from '@paraswap/core';
4
4
  import { OutputResult, TickInfo } from '../../uniswap-v3/types';
5
5
  import { Tick } from '../../uniswap-v3/contract-math/Tick';
6
- import { TickBitMap } from '../../uniswap-v3/contract-math/TickBitMap';
7
6
  import { SqrtPriceMath } from '../../uniswap-v3/contract-math/SqrtPriceMath';
8
7
  import { TickMath } from '../../uniswap-v3/contract-math/TickMath';
9
8
  import { LiquidityMath } from '../../uniswap-v3/contract-math/LiquidityMath';
@@ -21,6 +20,8 @@ import {
21
20
  MAX_PRICING_COMPUTATION_STEPS_ALLOWED,
22
21
  OUT_OF_RANGE_ERROR_POSTFIX,
23
22
  } from '../../uniswap-v3/constants';
23
+ import { TickManager } from './TickManager';
24
+ import { TickTable } from './TickTable';
24
25
 
25
26
  type UpdatePositionCache = {
26
27
  price: bigint;
@@ -112,10 +113,9 @@ function _priceComputationCycles(
112
113
 
113
114
  try {
114
115
  [step.tickNext, step.initialized] =
115
- TickBitMap.nextInitializedTickWithinOneWord(
116
+ TickTable.nextInitializedTickWithinOneWord(
116
117
  poolState,
117
118
  state.tick,
118
- poolState.tickSpacing,
119
119
  zeroForOne,
120
120
  true,
121
121
  );
@@ -378,9 +378,9 @@ class AlgebraMathClass {
378
378
  currentTick: bigint,
379
379
  currentPrice: bigint,
380
380
  ) {
381
- let amount0;
382
- let amount1;
383
- let globalLiquidityDelta;
381
+ let amount0 = 0n;
382
+ let amount1 = 0n;
383
+ let globalLiquidityDelta = 0n;
384
384
  // If current tick is less than the provided bottom one then only the token0 has to be provided
385
385
  if (currentTick < bottomTick) {
386
386
  amount0 = SqrtPriceMath._getAmount0DeltaO(
@@ -434,7 +434,7 @@ class AlgebraMathClass {
434
434
  const time = this._blockTimestamp(state);
435
435
 
436
436
  if (
437
- Tick.update(
437
+ TickManager.update(
438
438
  state,
439
439
  bottomTick,
440
440
  cache.tick,
@@ -447,10 +447,14 @@ class AlgebraMathClass {
447
447
  )
448
448
  ) {
449
449
  toggledBottom = true;
450
- TickBitMap.flipTick(state, bottomTick, state.tickSpacing);
450
+ TickTable.toggleTick(
451
+ state,
452
+ bottomTick,
453
+ state.areTicksCompressed ? state.tickSpacing : undefined,
454
+ );
451
455
  }
452
456
  if (
453
- Tick.update(
457
+ TickManager.update(
454
458
  state,
455
459
  topTick,
456
460
  cache.tick,
@@ -463,13 +467,17 @@ class AlgebraMathClass {
463
467
  )
464
468
  ) {
465
469
  toggledTop = true;
466
- TickBitMap.flipTick(state, topTick, state.tickSpacing);
470
+ TickTable.toggleTick(
471
+ state,
472
+ topTick,
473
+ state.areTicksCompressed ? state.tickSpacing : undefined,
474
+ );
467
475
  }
468
476
  }
469
477
 
470
478
  // skip fee && position related stuffs
471
479
 
472
- // same as UniwapV3Pool.sol line 327 -> if (params.liquidityDelta != 0) {
480
+ // same as UniswapV3Pool.sol line 327 -> if (params.liquidityDelta != 0) {
473
481
  if (liquidityDelta !== 0n) {
474
482
  // if liquidityDelta is negative and the tick was toggled, it means that it should not be initialized anymore, so we delete it
475
483
  if (liquidityDelta < 0) {
@@ -510,7 +518,7 @@ class AlgebraMathClass {
510
518
 
511
519
  let cache: SwapCalculationCache = {
512
520
  amountCalculated: 0n,
513
- amountRequiredInitial: BI_MAX_INT, // similarly to waht we did for uniswap
521
+ amountRequiredInitial: BI_MAX_INT, // similarly to what we did for uniswap
514
522
  communityFee: 0n,
515
523
  exactInput: false,
516
524
  fee: 0n,
@@ -563,17 +571,15 @@ class AlgebraMathClass {
563
571
  stepSqrtPrice: 0n,
564
572
  tickCount: 0,
565
573
  };
566
- let i = 0;
567
574
  // swap until there is remaining input or output tokens or we reach the price limit
568
575
  while (true) {
569
576
  step.stepSqrtPrice = currentPrice;
570
577
 
571
578
  //equivalent of tickTable.nextTickInTheSameRow(currentTick, zeroToOne);
572
579
  [step.nextTick, step.initialized] =
573
- TickBitMap.nextInitializedTickWithinOneWord(
580
+ TickTable.nextInitializedTickWithinOneWord(
574
581
  poolState,
575
582
  currentTick,
576
- poolState.tickSpacing,
577
583
  zeroToOne,
578
584
  false,
579
585
  );
@@ -0,0 +1,91 @@
1
+ import { IAlgebraPoolState } from '../types';
2
+ import { LiquidityMath } from '../../uniswap-v3/contract-math/LiquidityMath';
3
+ import { _require } from '../../../utils';
4
+ import { NumberAsString } from '@paraswap/core';
5
+ import { ZERO_TICK_INFO } from '../../uniswap-v3/constants';
6
+ import { TickInfo } from '../../uniswap-v3/types';
7
+
8
+ export class TickManager {
9
+ static update(
10
+ state: Pick<IAlgebraPoolState, 'ticks'>,
11
+ tick: bigint,
12
+ tickCurrent: bigint,
13
+ liquidityDelta: bigint,
14
+ secondsPerLiquidityCumulativeX128: bigint,
15
+ tickCumulative: bigint,
16
+ time: bigint,
17
+ upper: boolean,
18
+ maxLiquidity: bigint,
19
+ ): boolean {
20
+ let info = state.ticks[Number(tick)];
21
+
22
+ if (info === undefined) {
23
+ info = { ...ZERO_TICK_INFO };
24
+ state.ticks[Number(tick)] = info;
25
+ }
26
+
27
+ // uint128 liquidityTotalBefore = data.liquidityTotal;
28
+ // uint128 liquidityTotalAfter = LiquidityMath.addDelta(liquidityTotalBefore, liquidityDelta);
29
+ // require(liquidityTotalAfter < Constants.MAX_LIQUIDITY_PER_TICK + 1, 'LO');
30
+ const liquidityGrossBefore = info.liquidityGross;
31
+ const liquidityGrossAfter = LiquidityMath.addDelta(
32
+ liquidityGrossBefore,
33
+ liquidityDelta,
34
+ );
35
+ _require(
36
+ liquidityGrossAfter <= maxLiquidity,
37
+ 'LO',
38
+ { liquidityGrossAfter, maxLiquidity },
39
+ 'liquidityGrossAfter <= maxLiquidity',
40
+ );
41
+
42
+ // int128 liquidityDeltaBefore = data.liquidityDelta;
43
+ const liquidityNetBefore = info.liquidityNet;
44
+
45
+ // // when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed)
46
+ // data.liquidityDelta = upper
47
+ // ? int256(liquidityDeltaBefore).sub(liquidityDelta).toInt128()
48
+ // : int256(liquidityDeltaBefore).add(liquidityDelta).toInt128();
49
+ //
50
+ // data.liquidityTotal = liquidityTotalAfter;
51
+ info.liquidityNet = upper
52
+ ? BigInt.asIntN(
53
+ 128,
54
+ BigInt.asIntN(256, liquidityNetBefore) - liquidityDelta,
55
+ )
56
+ : BigInt.asIntN(
57
+ 128,
58
+ BigInt.asIntN(256, liquidityNetBefore) + liquidityDelta,
59
+ );
60
+
61
+ // flipped = (liquidityTotalAfter == 0);
62
+ // if (liquidityTotalBefore == 0) {
63
+ // flipped = !flipped;
64
+ // // by convention, we assume that all growth before a tick was initialized happened _below_ the tick
65
+ // if (tick <= currentTick) {
66
+ // data.outerFeeGrowth0Token = totalFeeGrowth0Token;
67
+ // data.outerFeeGrowth1Token = totalFeeGrowth1Token;
68
+ // data.outerSecondsPerLiquidity = secondsPerLiquidityCumulative;
69
+ // data.outerTickCumulative = tickCumulative;
70
+ // data.outerSecondsSpent = time;
71
+ // }
72
+ // data.initialized = true;
73
+ // }
74
+
75
+ let flipped = liquidityGrossAfter === 0n;
76
+ if (liquidityGrossBefore === 0n) {
77
+ flipped = !flipped;
78
+ if (tick <= tickCurrent) {
79
+ info.secondsPerLiquidityOutsideX128 = secondsPerLiquidityCumulativeX128;
80
+ info.tickCumulativeOutside = tickCumulative;
81
+ info.secondsOutside = time;
82
+ }
83
+ info.initialized = true;
84
+ }
85
+
86
+ // data.liquidityTotal = liquidityTotalAfter;
87
+ info.liquidityGross = liquidityGrossAfter;
88
+
89
+ return flipped;
90
+ }
91
+ }