@paraswap/dex-lib 2.31.3 → 2.31.4-zkevm-revive.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 (84) hide show
  1. package/build/abi/algebra/AlgebraFactory-v1_1.abi.json +250 -0
  2. package/build/config.js +27 -0
  3. package/build/config.js.map +1 -1
  4. package/build/dex/aave-v3/tokens/arbitrum.json +20 -20
  5. package/build/dex/aave-v3/tokens/avalanche.json +44 -20
  6. package/build/dex/aave-v3/tokens/fantom.json +30 -30
  7. package/build/dex/aave-v3/tokens/optimism.json +18 -18
  8. package/build/dex/aave-v3/tokens/polygon.json +60 -42
  9. package/build/dex/algebra/algebra-pool-v1_1.d.ts +13 -2
  10. package/build/dex/algebra/algebra-pool-v1_1.js +134 -4
  11. package/build/dex/algebra/algebra-pool-v1_1.js.map +1 -1
  12. package/build/dex/algebra/algebra.js +3 -3
  13. package/build/dex/algebra/algebra.js.map +1 -1
  14. package/build/dex/algebra/types.d.ts +3 -2
  15. package/build/dex/algebra/utils.d.ts +3 -1
  16. package/build/dex/algebra/utils.js +59 -1
  17. package/build/dex/algebra/utils.js.map +1 -1
  18. package/build/dex/balancer-v2/balancer-v2.js +64 -7
  19. package/build/dex/balancer-v2/balancer-v2.js.map +1 -1
  20. package/build/dex/{test-aave-v3 → test-dex}/config.d.ts +1 -1
  21. package/build/dex/{test-aave-v3 → test-dex}/config.js +3 -3
  22. package/build/dex/test-dex/config.js.map +1 -0
  23. package/build/dex/{test-aave-v3/test-aave-v3-pool.d.ts → test-dex/test-dex-pool.d.ts} +3 -3
  24. package/build/dex/{test-aave-v3/test-aave-v3-pool.js → test-dex/test-dex-pool.js} +7 -7
  25. package/build/dex/test-dex/test-dex-pool.js.map +1 -0
  26. package/build/dex/{test-aave-v3/test-aave-v3.d.ts → test-dex/test-dex.d.ts} +8 -8
  27. package/build/dex/{test-aave-v3/test-aave-v3.js → test-dex/test-dex.js} +7 -7
  28. package/build/dex/test-dex/test-dex.js.map +1 -0
  29. package/build/dex/{test-aave-v3 → test-dex}/types.d.ts +1 -1
  30. package/build/dex/{test-aave-v3 → test-dex}/types.js.map +1 -1
  31. package/build/dex/woo-fi-v2/woo-fi-math.d.ts +16 -0
  32. package/build/dex/woo-fi-v2/woo-fi-math.js +137 -0
  33. package/build/dex/woo-fi-v2/woo-fi-math.js.map +1 -0
  34. package/build/lib/decoders.d.ts +2 -0
  35. package/build/lib/decoders.js +9 -1
  36. package/build/lib/decoders.js.map +1 -1
  37. package/build/stateful-event-subscriber.d.ts +1 -0
  38. package/build/stateful-event-subscriber.js +6 -0
  39. package/build/stateful-event-subscriber.js.map +1 -1
  40. package/package.json +1 -1
  41. package/src/abi/algebra/AlgebraFactory-v1_1.abi.json +250 -0
  42. package/src/config.ts +30 -0
  43. package/src/dex/algebra/algebra-integration.test.ts +74 -0
  44. package/src/dex/algebra/algebra-pool-v1_1.ts +192 -8
  45. package/src/dex/algebra/algebra.ts +3 -2
  46. package/src/dex/algebra/types.ts +3 -2
  47. package/src/dex/algebra/utils.ts +83 -2
  48. package/src/dex/balancer-v2/balancer-v2.ts +71 -7
  49. package/src/dex/generic-rfq/example-api.test.ts +1 -1
  50. package/src/lib/decoders.ts +12 -0
  51. package/src/stateful-event-subscriber.ts +8 -0
  52. package/.idea/codeStyles/codeStyleConfig.xml +0 -5
  53. package/.idea/misc.xml +0 -6
  54. package/.idea/modules.xml +0 -8
  55. package/.idea/vcs.xml +0 -6
  56. package/.vscode/launch.json +0 -21
  57. package/build/abi/AugustusRFQRouter.abi.json +0 -1248
  58. package/build/abi/algebra/AlgebraPool.abi.json +0 -727
  59. package/build/dex/aave-v3/tokens/mainnet.json +0 -44
  60. package/build/dex/algebra/algebra-pool.d.ts +0 -41
  61. package/build/dex/algebra/algebra-pool.js +0 -277
  62. package/build/dex/algebra/algebra-pool.js.map +0 -1
  63. package/build/dex/algebra/lib/AlgebraXUniV3.d.ts +0 -5
  64. package/build/dex/algebra/lib/AlgebraXUniV3.js +0 -45
  65. package/build/dex/algebra/lib/AlgebraXUniV3.js.map +0 -1
  66. package/build/dex/algebra/lib/DataStorage.d.ts +0 -24
  67. package/build/dex/algebra/lib/DataStorage.js +0 -397
  68. package/build/dex/algebra/lib/DataStorage.js.map +0 -1
  69. package/build/dex/algebra/lib/DataStorageOperator.d.ts +0 -9
  70. package/build/dex/algebra/lib/DataStorageOperator.js +0 -66
  71. package/build/dex/algebra/lib/DataStorageOperator.js.map +0 -1
  72. package/build/dex/algebra/lib/Sqrt.d.ts +0 -3
  73. package/build/dex/algebra/lib/Sqrt.js +0 -60
  74. package/build/dex/algebra/lib/Sqrt.js.map +0 -1
  75. package/build/dex/balancer-v2/VirtualBoostedPool.d.ts +0 -79
  76. package/build/dex/balancer-v2/VirtualBoostedPool.js +0 -382
  77. package/build/dex/balancer-v2/VirtualBoostedPool.js.map +0 -1
  78. package/build/dex/generic-rfq/constants.d.ts +0 -1
  79. package/build/dex/generic-rfq/constants.js +0 -5
  80. package/build/dex/generic-rfq/constants.js.map +0 -1
  81. package/build/dex/test-aave-v3/config.js.map +0 -1
  82. package/build/dex/test-aave-v3/test-aave-v3-pool.js.map +0 -1
  83. package/build/dex/test-aave-v3/test-aave-v3.js.map +0 -1
  84. /package/build/dex/{test-aave-v3 → test-dex}/types.js +0 -0
@@ -14,6 +14,8 @@ import {
14
14
  } from '../../../tests/utils';
15
15
  import { Tokens } from '../../../tests/constants-e2e';
16
16
  import { Address } from '@paraswap/core';
17
+ import { AlgebraEventPoolV1_1 } from './algebra-pool-v1_1';
18
+ import { DecodedStateMultiCallResultWithRelativeBitmapsV1_1 } from './types';
17
19
 
18
20
  function getReaderCalldata(
19
21
  exchangeAddress: string,
@@ -432,5 +434,77 @@ describe('Algebra', function () {
432
434
  );
433
435
  }
434
436
  });
437
+
438
+ it('both generate state result match', async function () {
439
+ const pool = (await algebra.getPool(
440
+ tokens[srcTokenSymbol].address,
441
+ tokens[destTokenSymbol].address,
442
+ blockNumber,
443
+ )) as AlgebraEventPoolV1_1;
444
+
445
+ const [balance0, balance1, stateMulticallFull] =
446
+ await pool.fetchPoolStateSingleStep(blockNumber);
447
+
448
+ const stateMulticall = {
449
+ pool: stateMulticallFull.pool.toLowerCase(),
450
+ globalState: {
451
+ price: stateMulticallFull.globalState.price,
452
+ tick: stateMulticallFull.globalState.tick,
453
+ fee: stateMulticallFull.globalState.fee,
454
+ communityFeeToken0: stateMulticallFull.globalState.communityFeeToken0,
455
+ communityFeeToken1: stateMulticallFull.globalState.communityFeeToken1,
456
+ },
457
+ liquidity: stateMulticallFull.liquidity,
458
+ tickSpacing: stateMulticallFull.tickSpacing,
459
+ maxLiquidityPerTick: stateMulticallFull.maxLiquidityPerTick,
460
+ tickBitmap: stateMulticallFull.tickBitmap.map(t => ({
461
+ index: t.index,
462
+ value: t.value,
463
+ })),
464
+ ticks: stateMulticallFull.ticks.map(t => ({
465
+ index: t.index,
466
+ value: {
467
+ liquidityNet: t.value.liquidityNet,
468
+ liquidityGross: t.value.liquidityGross,
469
+ secondsOutside: t.value.secondsOutside,
470
+ secondsPerLiquidityOutsideX128:
471
+ t.value.secondsPerLiquidityOutsideX128,
472
+ tickCumulativeOutside: t.value.tickCumulativeOutside,
473
+ initialized: t.value.initialized,
474
+ },
475
+ })),
476
+ };
477
+
478
+ const stateMulticallWithBalance = [balance0, balance1, stateMulticall];
479
+ const stateManually = await pool.fetchStateManually(blockNumber);
480
+ // @ts-ignore
481
+ delete stateManually[2]['blockTimestamp'];
482
+ stateManually[2].pool = stateManually[2].pool.toLowerCase();
483
+
484
+ expect(stateMulticallWithBalance).toStrictEqual(stateManually);
485
+ });
486
+ });
487
+
488
+ describe('ZKEVM', () => {
489
+ const network = Network.ZKEVM;
490
+ const dexHelper = new DummyDexHelper(network);
491
+
492
+ beforeAll(async () => {
493
+ blockNumber = await dexHelper.web3Provider.eth.getBlockNumber();
494
+ algebra = new Algebra(network, dexKey, dexHelper);
495
+ if (algebra.initializePricing) {
496
+ await algebra.initializePricing(blockNumber);
497
+ }
498
+ });
499
+
500
+ it('both generate state result match', async function () {
501
+ const pool = (await algebra.getPool(
502
+ '0x4F9A0e7FD2Bf6067db6994CF12E4495Df938E6e9',
503
+ '0xc5015b9d9161dca7e18e32f6f25c4ad850731fd4',
504
+ blockNumber,
505
+ )) as AlgebraEventPoolV1_1;
506
+
507
+ const stateManually = await pool.fetchStateManually(blockNumber);
508
+ });
435
509
  });
436
510
  });
@@ -2,29 +2,41 @@ import _ from 'lodash';
2
2
  import { Interface } from '@ethersproject/abi';
3
3
  import { DeepReadonly, assert } from 'ts-essentials';
4
4
  import { Address, BlockHeader, Log, Logger } from '../../types';
5
- import { bigIntify, catchParseLogError, int16 } from '../../utils';
5
+ import { bigIntify, catchParseLogError, int16, uint128 } from '../../utils';
6
6
  import {
7
7
  InitializeStateOptions,
8
8
  StatefulEventSubscriber,
9
9
  } from '../../stateful-event-subscriber';
10
10
  import { IDexHelper } from '../../dex-helper/idex-helper';
11
11
  import {
12
+ DecodedGlobalStateV1_1,
12
13
  PoolStateV1_1,
13
14
  TickBitMapMappingsWithBigNumber,
14
15
  TickInfoMappingsWithBigNumber,
16
+ TickInfoWithBigNumber,
15
17
  } from './types';
16
- import { ethers } from 'ethers';
18
+ import { BigNumber, ethers } from 'ethers';
17
19
  import { Contract } from 'web3-eth-contract';
18
20
  import AlgebraABI from '../../abi/algebra/AlgebraPool-v1_1.abi.json';
21
+ import FactoryABI from '../../abi/algebra/AlgebraFactory-v1_1.abi.json';
19
22
  import { DecodedStateMultiCallResultWithRelativeBitmapsV1_1 } from './types';
20
23
  import {
21
24
  OUT_OF_RANGE_ERROR_POSTFIX,
22
25
  TICK_BITMAP_BUFFER,
23
26
  TICK_BITMAP_TO_USE,
24
27
  } from '../uniswap-v3/constants';
25
- import { uint256ToBigInt } from '../../lib/decoders';
28
+ import {
29
+ addressDecode,
30
+ uint256ToBigInt,
31
+ uint128ToBigInt,
32
+ int24ToBigInt,
33
+ } from '../../lib/decoders';
26
34
  import { MultiCallParams } from '../../lib/multi-wrapper';
27
- import { decodeStateMultiCallResultWithRelativeBitmapsV1_1 } from './utils';
35
+ import {
36
+ decodeGlobalStateV1_1,
37
+ decodeStateMultiCallResultWithRelativeBitmapsV1_1,
38
+ decodeTicksV1_1,
39
+ } from './utils';
28
40
  import { AlgebraMath } from './lib/AlgebraMath';
29
41
  import {
30
42
  _reduceTickBitmap,
@@ -53,6 +65,7 @@ export class AlgebraEventPoolV1_1 extends StatefulEventSubscriber<PoolStateV1_1>
53
65
  readonly token1: Address;
54
66
 
55
67
  public readonly poolIface = new Interface(AlgebraABI);
68
+ public readonly factoryIface = new Interface(FactoryABI);
56
69
 
57
70
  public initFailed = false;
58
71
  public initRetryAttemptCount = 0;
@@ -69,6 +82,7 @@ export class AlgebraEventPoolV1_1 extends StatefulEventSubscriber<PoolStateV1_1>
69
82
  mapKey: string = '',
70
83
  readonly poolInitCodeHash: string,
71
84
  readonly poolDeployer: string,
85
+ private readonly forceManualStateGeneration: boolean = false,
72
86
  ) {
73
87
  super(parentName, `${token0}_${token1}`, dexHelper, logger, true, mapKey);
74
88
  this.token0 = token0.toLowerCase();
@@ -174,7 +188,7 @@ export class AlgebraEventPoolV1_1 extends StatefulEventSubscriber<PoolStateV1_1>
174
188
  return TICK_BITMAP_TO_USE + TICK_BITMAP_BUFFER;
175
189
  }
176
190
 
177
- private async _fetchPoolStateSingleStep(
191
+ async fetchPoolStateSingleStep(
178
192
  blockNumber: number,
179
193
  ): Promise<
180
194
  [bigint, bigint, DecodedStateMultiCallResultWithRelativeBitmapsV1_1]
@@ -330,13 +344,14 @@ export class AlgebraEventPoolV1_1 extends StatefulEventSubscriber<PoolStateV1_1>
330
344
  return [balance0, balance1, _state];
331
345
  }
332
346
 
347
+ // FIXME: Here happens double conversion in types, but for prototyping and to check if this approach helps, it is nor very important
333
348
  async _fetchInitStateMultiStrategies(
334
349
  blockNumber: number,
335
350
  ): Promise<
336
351
  [bigint, bigint, DecodedStateMultiCallResultWithRelativeBitmapsV1_1]
337
352
  > {
338
353
  try {
339
- return await this._fetchPoolStateSingleStep(blockNumber);
354
+ return await this.fetchPoolStateSingleStep(blockNumber);
340
355
  } catch (e) {
341
356
  if (e instanceof Error && e.message.includes('Pool does not exist'))
342
357
  throw e;
@@ -347,9 +362,178 @@ export class AlgebraEventPoolV1_1 extends StatefulEventSubscriber<PoolStateV1_1>
347
362
  }
348
363
  }
349
364
 
365
+ async fetchStateManually(
366
+ blockNumber: number,
367
+ ): Promise<
368
+ [bigint, bigint, DecodedStateMultiCallResultWithRelativeBitmapsV1_1]
369
+ > {
370
+ // FIXME: If this approach works, need to add caching of multicalls
371
+ const [poolAddress] = await this.dexHelper.multiWrapper.aggregate([
372
+ {
373
+ target: this.factoryAddress,
374
+ callData: this.factoryIface.encodeFunctionData('poolByPair', [
375
+ this.token0,
376
+ this.token1,
377
+ ]),
378
+ decodeFunction: addressDecode,
379
+ },
380
+ ]);
381
+ assert(
382
+ poolAddress === this.poolAddress,
383
+ `Pool address mismatch: ${poolAddress} != ${this.poolAddress}`,
384
+ );
385
+
386
+ const [
387
+ balance0,
388
+ balance1,
389
+ liquidity,
390
+ tickSpacing,
391
+ maxLiquidityPerTick,
392
+ globalState,
393
+ ] = (await this.dexHelper.multiWrapper.aggregate<
394
+ bigint | number | DecodedGlobalStateV1_1
395
+ >([
396
+ {
397
+ target: this.token0,
398
+ callData: this.erc20Interface.encodeFunctionData('balanceOf', [
399
+ this.poolAddress,
400
+ ]),
401
+ decodeFunction: uint256ToBigInt,
402
+ },
403
+ {
404
+ target: this.token1,
405
+ callData: this.erc20Interface.encodeFunctionData('balanceOf', [
406
+ this.poolAddress,
407
+ ]),
408
+ decodeFunction: uint256ToBigInt,
409
+ },
410
+ {
411
+ target: poolAddress,
412
+ callData: this.poolIface.encodeFunctionData('liquidity', []),
413
+ decodeFunction: uint128ToBigInt,
414
+ },
415
+ {
416
+ target: poolAddress,
417
+ callData: this.poolIface.encodeFunctionData('tickSpacing', []),
418
+ decodeFunction: int24ToBigInt,
419
+ },
420
+ {
421
+ target: poolAddress,
422
+ callData: this.poolIface.encodeFunctionData('maxLiquidityPerTick', []),
423
+ decodeFunction: uint128ToBigInt,
424
+ },
425
+ {
426
+ target: poolAddress,
427
+ callData: this.poolIface.encodeFunctionData('globalState', []),
428
+ decodeFunction: decodeGlobalStateV1_1,
429
+ },
430
+ ])) as [bigint, bigint, bigint, bigint, bigint, DecodedGlobalStateV1_1];
431
+
432
+ const currentBitMapIndex = TickTable.position(
433
+ BigInt(BigInt(globalState.tick) / BigInt(tickSpacing)),
434
+ )[0];
435
+
436
+ const leftBitMapIndex = currentBitMapIndex - this.getBitmapRangeToRequest();
437
+ const rightBitMapIndex =
438
+ currentBitMapIndex + this.getBitmapRangeToRequest();
439
+
440
+ const allTickBitMaps = await this.dexHelper.multiWrapper.aggregate(
441
+ _.range(Number(leftBitMapIndex), Number(rightBitMapIndex + 1n)).map(
442
+ index => {
443
+ return {
444
+ target: poolAddress,
445
+ callData: this.poolIface.encodeFunctionData('tickTable', [
446
+ int16(BigInt(index)),
447
+ ]),
448
+ decodeFunction: uint256ToBigInt,
449
+ };
450
+ },
451
+ ),
452
+ );
453
+
454
+ const tickBitmap: TickBitMapMappingsWithBigNumber[] = [];
455
+
456
+ let globalIndex = 0;
457
+
458
+ for (let i = leftBitMapIndex; i <= rightBitMapIndex; i++) {
459
+ const index = int16(i);
460
+ const bitmap = allTickBitMaps[globalIndex];
461
+ globalIndex++;
462
+ if (bitmap == 0n) continue;
463
+ tickBitmap.push({ index: Number(index), value: BigNumber.from(bitmap) });
464
+ }
465
+
466
+ const tickIndexes: bigint[] = [];
467
+ const ticksValues = await this.dexHelper.multiWrapper.aggregate(
468
+ tickBitmap
469
+ .map(tb => {
470
+ const allBits: MultiCallParams<TickInfoWithBigNumber>[] = [];
471
+ if (tb.value === BigNumber.from(0)) return allBits;
472
+
473
+ _.range(0, 256).forEach(j => {
474
+ if ((tb.value.toBigInt() & (1n << BigInt(j))) > 0n) {
475
+ const populatedTick =
476
+ (BigInt.asIntN(16, BigInt(tb.index) << 8n) + BigInt(j)) *
477
+ tickSpacing;
478
+
479
+ tickIndexes.push(populatedTick);
480
+ allBits.push({
481
+ target: poolAddress,
482
+ callData: this.poolIface.encodeFunctionData('ticks', [
483
+ populatedTick,
484
+ ]),
485
+ decodeFunction: decodeTicksV1_1,
486
+ });
487
+ }
488
+ });
489
+ return allBits;
490
+ })
491
+ .flat(),
492
+ );
493
+ assert(
494
+ tickIndexes.length === ticksValues.length,
495
+ `Tick indexes mismatch: ${tickIndexes.length} != ${ticksValues.length}`,
496
+ );
497
+
498
+ const ticks: TickInfoMappingsWithBigNumber[] = new Array(
499
+ tickIndexes.length,
500
+ );
501
+
502
+ tickIndexes.forEach((tickIndex, index) => {
503
+ ticks[index] = {
504
+ index: Number(tickIndex),
505
+ value: ticksValues[index],
506
+ };
507
+ });
508
+
509
+ return [
510
+ balance0,
511
+ balance1,
512
+ // FIXME: If we validate that this is working, remove redundant conversions
513
+ {
514
+ pool: poolAddress,
515
+ blockTimestamp: BigNumber.from(Date.now()),
516
+ globalState,
517
+ liquidity: BigNumber.from(liquidity),
518
+ tickSpacing: Number(tickSpacing),
519
+ maxLiquidityPerTick: BigNumber.from(maxLiquidityPerTick),
520
+ tickBitmap,
521
+ ticks,
522
+ },
523
+ ];
524
+ }
525
+
350
526
  async generateState(blockNumber: number): Promise<Readonly<PoolStateV1_1>> {
351
- const [balance0, balance1, _state] =
352
- await this._fetchInitStateMultiStrategies(blockNumber);
527
+ let balance0 = 0n;
528
+ let balance1 = 0n;
529
+ let _state: DecodedStateMultiCallResultWithRelativeBitmapsV1_1;
530
+ if (this.forceManualStateGeneration) {
531
+ [balance0, balance1, _state] = await this.fetchStateManually(blockNumber);
532
+ } else {
533
+ [balance0, balance1, _state] = await this._fetchInitStateMultiStrategies(
534
+ blockNumber,
535
+ );
536
+ }
353
537
 
354
538
  const tickBitmap = {};
355
539
  const ticks = {};
@@ -167,7 +167,7 @@ export class Algebra extends SimpleExchange implements IDex<AlgebraData> {
167
167
  /* reload state, on zkEVM this would most likely timeout during request life
168
168
  * but would allow to rely on staleState for couple of min for next requests
169
169
  */
170
- await pool.initialize(blockNumber);
170
+ await pool.initialize(blockNumber, { forceRegenerate: true });
171
171
  }
172
172
 
173
173
  return pool;
@@ -226,6 +226,7 @@ export class Algebra extends SimpleExchange implements IDex<AlgebraData> {
226
226
  this.cacheStateKey,
227
227
  this.config.initHash,
228
228
  this.config.deployer,
229
+ this.config.forceManualStateGenerate,
229
230
  );
230
231
 
231
232
  try {
@@ -258,7 +259,7 @@ export class Algebra extends SimpleExchange implements IDex<AlgebraData> {
258
259
  // on unkown error mark as failed and increase retryCount for retry init strategy
259
260
  // note: state would be null by default which allows to fallback
260
261
  this.logger.warn(
261
- `${this.dexKey}: Can not generate pool state for srcAddress=${srcAddress}, destAddress=${destAddress}pool fallback to rpc and retry every ${this.config.initRetryFrequency} times, initRetryAttemptCount=${pool.initRetryAttemptCount}`,
262
+ `${this.dexKey}: Can not generate pool state for srcAddress=${srcAddress}, destAddress=${destAddress} pool fallback to rpc and retry every ${this.config.initRetryFrequency} times, initRetryAttemptCount=${pool.initRetryAttemptCount}`,
262
263
  e,
263
264
  );
264
265
  pool.initFailed = true;
@@ -2,7 +2,7 @@ import { BigNumber } from 'ethers';
2
2
  import { Address, NumberAsString } from '../../types';
3
3
  import { TickInfo } from '../uniswap-v3/types';
4
4
 
5
- type GlobalStateV1_1 = {
5
+ export type GlobalStateV1_1 = {
6
6
  price: bigint; // The square root of the current price in Q64.96 format
7
7
  tick: bigint; // The current tick
8
8
  fee: bigint; // The current fee in hundredths of a bip, i.e. 1e-6
@@ -72,6 +72,7 @@ export type DexParams = {
72
72
  initHash: string;
73
73
  version: 'v1.1' | 'v1.9';
74
74
  forceRPC?: boolean;
75
+ forceManualStateGenerate?: boolean;
75
76
  };
76
77
 
77
78
  export type IAlgebraPoolState = PoolStateV1_1 | PoolState_v1_9;
@@ -95,7 +96,7 @@ export type TickInfoMappingsWithBigNumber = {
95
96
  value: TickInfoWithBigNumber;
96
97
  };
97
98
 
98
- type DecodedGlobalStateV1_1 = {
99
+ export type DecodedGlobalStateV1_1 = {
99
100
  price: BigNumber;
100
101
  tick: number;
101
102
  fee: number;
@@ -1,11 +1,12 @@
1
- import { BytesLike, ethers } from 'ethers';
1
+ import { BigNumber, BytesLike, ethers } from 'ethers';
2
2
  import { assert } from 'ts-essentials';
3
3
  import { extractSuccessAndValue } from '../../lib/decoders';
4
4
  import { MultiResult } from '../../lib/multi-wrapper';
5
5
  import {
6
- DecodedGlobalStateV1_9,
6
+ DecodedGlobalStateV1_1,
7
7
  DecodedStateMultiCallResultWithRelativeBitmapsV1_1,
8
8
  DecodedStateMultiCallResultWithRelativeBitmapsV1_9,
9
+ TickInfoWithBigNumber,
9
10
  } from './types';
10
11
 
11
12
  export function decodeStateMultiCallResultWithRelativeBitmapsV1_1(
@@ -134,3 +135,83 @@ export function decodeStateMultiCallResultWithRelativeBitmapsV1_9(
134
135
  // But I typed only the ones that are used later
135
136
  return decoded as DecodedStateMultiCallResultWithRelativeBitmapsV1_9;
136
137
  }
138
+
139
+ export function decodeGlobalStateV1_1(
140
+ result: MultiResult<BytesLike> | BytesLike,
141
+ ): DecodedGlobalStateV1_1 {
142
+ const [isSuccess, toDecode] = extractSuccessAndValue(result);
143
+
144
+ assert(
145
+ isSuccess && toDecode !== '0x',
146
+ `decodeGlobalStateV1_1 failed to get decodable result: ${result}`,
147
+ );
148
+
149
+ const results: DecodedGlobalStateV1_1 = {
150
+ price: BigNumber.from(0),
151
+ tick: 0,
152
+ fee: 0,
153
+ communityFeeToken0: 0,
154
+ communityFeeToken1: 0,
155
+ };
156
+
157
+ [
158
+ results.price,
159
+ results.tick,
160
+ results.fee,
161
+ ,
162
+ results.communityFeeToken0,
163
+ results.communityFeeToken1,
164
+ ] = ethers.utils.defaultAbiCoder.decode(
165
+ [`uint160`, `int24`, `uint16`, `uint16`, `uint8`, `uint8`, `bool`],
166
+ toDecode,
167
+ );
168
+ // This conversion is not precise, because when we decode, we have more values
169
+ // But used later
170
+ return results;
171
+ }
172
+
173
+ export function decodeTicksV1_1(
174
+ result: MultiResult<BytesLike> | BytesLike,
175
+ ): TickInfoWithBigNumber {
176
+ const [isSuccess, toDecode] = extractSuccessAndValue(result);
177
+
178
+ assert(
179
+ isSuccess && toDecode !== '0x',
180
+ `decodeGlobalStateV1_1 failed to get decodable result: ${result}`,
181
+ );
182
+
183
+ const results: TickInfoWithBigNumber = {
184
+ liquidityNet: BigNumber.from(0),
185
+ liquidityGross: BigNumber.from(0),
186
+ secondsOutside: 0,
187
+ secondsPerLiquidityOutsideX128: BigNumber.from(0),
188
+ tickCumulativeOutside: BigNumber.from(0),
189
+ initialized: false,
190
+ };
191
+
192
+ [
193
+ results.liquidityGross,
194
+ results.liquidityNet,
195
+ ,
196
+ ,
197
+ results.tickCumulativeOutside,
198
+ results.secondsPerLiquidityOutsideX128,
199
+ results.secondsOutside,
200
+ results.initialized,
201
+ ] = ethers.utils.defaultAbiCoder.decode(
202
+ [
203
+ `uint128`,
204
+ `int128`,
205
+ `uint256`,
206
+ `uint256`,
207
+ `int256`,
208
+ `uint160`,
209
+ `uint32`,
210
+ `bool`,
211
+ ],
212
+ toDecode,
213
+ );
214
+ // This conversion is not precise, because when we decode, we have more values
215
+ // But used later
216
+ return results;
217
+ }
@@ -74,16 +74,16 @@ import { NumberAsString, OptimalSwapExchange } from '@paraswap/core';
74
74
 
75
75
  // If you disable some pool, don't forget to clear the cache, otherwise changes won't be applied immediately
76
76
  const enabledPoolTypes = [
77
- // BalancerPoolTypes.MetaStable,
78
- // BalancerPoolTypes.Stable,
77
+ // BalancerPoolTypes.MetaStable, // BOOSTED POOLS Disabled since vulnerability https://github.com/BalancerMaxis/multisig-ops/blob/main/BIPs/00notGov/2023-08-mitigation.md
78
+ BalancerPoolTypes.Stable,
79
79
  BalancerPoolTypes.Weighted,
80
- // BalancerPoolTypes.LiquidityBootstrapping,
81
- // BalancerPoolTypes.Investment,
82
- // BalancerPoolTypes.StablePhantom,
80
+ BalancerPoolTypes.LiquidityBootstrapping,
81
+ BalancerPoolTypes.Investment,
82
+ BalancerPoolTypes.StablePhantom,
83
83
  BalancerPoolTypes.AaveLinear,
84
84
  BalancerPoolTypes.ERC4626Linear,
85
85
  BalancerPoolTypes.Linear,
86
- // BalancerPoolTypes.ComposableStable,
86
+ BalancerPoolTypes.ComposableStable,
87
87
  BalancerPoolTypes.BeefyLinear,
88
88
  BalancerPoolTypes.GearboxLinear,
89
89
  BalancerPoolTypes.MidasLinear,
@@ -93,6 +93,70 @@ const enabledPoolTypes = [
93
93
  BalancerPoolTypes.YearnLinear,
94
94
  ];
95
95
 
96
+ const disabledPoolIds = [
97
+ // broken ?
98
+ '0xbd482ffb3e6e50dc1c437557c3bea2b68f3683ee0000000000000000000003c6',
99
+
100
+ /* DISABLED POOLS SINCE VULNERABILITY https://github.com/BalancerMaxis/multisig-ops/blob/main/BIPs/00notGov/2023-08-mitigation.md*/
101
+ /* START:2023-08-mitigation */
102
+ //mainnet
103
+ '0xbf2ef8bdc2fc0f3203b3a01778e3ec5009aeef3300000000000000000000058d',
104
+ '0x99c88ad7dc566616548adde8ed3effa730eb6c3400000000000000000000049a',
105
+ '0x60683b05e9a39e3509d8fdb9c959f23170f8a0fa000000000000000000000489',
106
+ '0xa13a9247ea42d743238089903570127dda72fe4400000000000000000000035d',
107
+ '0x7b50775383d3d6f0215a8f290f2c9e2eebbeceb20000000000000000000000fe',
108
+ '0x25accb7943fd73dda5e23ba6329085a3c24bfb6a000200000000000000000387',
109
+ '0x50cf90b954958480b8df7958a9e965752f62712400000000000000000000046f',
110
+ '0x133d241f225750d2c92948e464a5a80111920331000000000000000000000476',
111
+ '0x8a6b25e33b12d1bb6929a8793961076bd1f9d3eb0002000000000000000003e8',
112
+ '0x959216bb492b2efa72b15b7aacea5b5c984c3cca000200000000000000000472',
113
+ '0x9b692f571b256140a39a34676bffa30634c586e100000000000000000000059d',
114
+
115
+ // polygon
116
+ '0xb3d658d5b95bf04e2932370dd1ff976fe18dd66a000000000000000000000ace',
117
+ '0x48e6b98ef6329f8f0a30ebb8c7c960330d64808500000000000000000000075b',
118
+ '0xb54b2125b711cd183edd3dd09433439d5396165200000000000000000000075e',
119
+
120
+ // arbitrum
121
+ '0xa8af146d79ac0bb981e4e0d8b788ec5711b1d5d000000000000000000000047b',
122
+ '0x077794c30afeccdf5ad2abc0588e8cee7197b71a000000000000000000000352',
123
+ '0x519cce718fcd11ac09194cff4517f12d263be067000000000000000000000382',
124
+
125
+ // optimism
126
+ '0x23ca0306b21ea71552b148cf3c4db4fc85ae19290000000000000000000000ac',
127
+ '0x62cf35db540152e94936de63efc90d880d4e241b0000000000000000000000ef',
128
+ '0x098f32d98d0d64dba199fc1923d3bf4192e787190001000000000000000000d2',
129
+ '0x43da214fab3315aa6c02e0b8f2bfb7ef2e3c60a50000000000000000000000ae',
130
+ '0xb1c9ac57594e9b1ec0f3787d9f6744ef4cb0a02400000000000000000000006e',
131
+ '0xde45f101250f2ca1c0f8adfc172576d10c12072d00000000000000000000003f',
132
+ '0x05e7732bf9ae5592e6aa05afe8cd80f7ab0a7bea00020000000000000000005a',
133
+ '0x981fb05b738e981ac532a99e77170ecb4bc27aef00010000000000000000004b',
134
+ '0x6222ae1d2a9f6894da50aa25cb7b303497f9bebd000000000000000000000046',
135
+ '0x3c74c4ed512050eb843d89fb9dcd5ebb4668eb6d0002000000000000000000cc',
136
+
137
+ // fantom
138
+ '0xc0064b291bd3d4ba0e44ccfc81bf8e7f7a579cd200000000000000000000042c',
139
+ '0x6e6dc948ce85c62125ff7a1e543d761a88f0a4cb000000000000000000000743',
140
+ '0x78ab08bf98f90f29a09c9b1d85b3b549369b03a3000100000000000000000354',
141
+ '0x302b8b64795b064cadc32f74993a6372498608070001000000000000000003e0',
142
+ '0x5ddb92a5340fd0ead3987d3661afcd6104c3b757000000000000000000000187',
143
+ '0xdfc65c1f15ad3507754ef0fd4ba67060c108db7e000000000000000000000406',
144
+ '0x6da14f5acd58dd5c8e486cfa1dc1c550f5c61c1c0000000000000000000003cf',
145
+ '0x592fa9f9d58065096f2b7838709c116957d7b5cf00020000000000000000043c',
146
+ '0xf47f4d59c863c02cbfa3eefe6771b9c9fbe7b97800000000000000000000072b',
147
+ '0xff2753aaba51c9f84689b9bd0a21b3cf380a1cff00000000000000000000072e',
148
+ '0x10441785a928040b456a179691141c48356eb3a50001000000000000000002fa',
149
+ '0x64b301e21d640f9bef90458b0987d81fb4cf1b9e00020000000000000000022e',
150
+ '0xba0e9aea8a7fa1daab4edf244191f2387a4e472b000100000000000000000737',
151
+ '0x1e2576344d49779bdbb71b1b76193d27e6f996b700020000000000000000032d',
152
+ '0xa10285f445bcb521f1d623300dc4998b02f11c8f00000000000000000000043b',
153
+
154
+ // zkevm
155
+ '0x6f34a44fce1506352a171232163e7716dd073ade000200000000000000000015',
156
+ '0xe274c9deb6ed34cfe4130f8d0a8a948dea5bb28600000000000000000000000d',
157
+ /* END:2023-08-mitigation */
158
+ ];
159
+
96
160
  const fetchAllPools = `query ($count: Int) {
97
161
  pools: pools(
98
162
  first: $count
@@ -102,7 +166,7 @@ const fetchAllPools = `query ($count: Int) {
102
166
  totalLiquidity_gt: ${MIN_USD_LIQUIDITY_TO_FETCH.toString()},
103
167
  totalShares_not_in: ["0", "0.000000000001"],
104
168
  id_not_in: [
105
- "0xbd482ffb3e6e50dc1c437557c3bea2b68f3683ee0000000000000000000003c6"
169
+ ${disabledPoolIds.map(p => `"${p}"`).join(', ')}
106
170
  ],
107
171
  address_not_in: [
108
172
  "0x0afbd58beca09545e4fb67772faf3858e610bcd0",
@@ -157,7 +157,7 @@ export const startTestServer = (account: ethers.Wallet) => {
157
157
  new BigNumber(_prices.asks![0][0]),
158
158
  );
159
159
  } else {
160
- const reversedPrices = _prices.bids!.map(price =>
160
+ const reversedPrices = _prices.asks!.map(price =>
161
161
  reversePrice([new BigNumber(price[0]), new BigNumber(price[1])]),
162
162
  );
163
163
  value = new BigNumber(payload.makerAmount).times(
@@ -50,6 +50,18 @@ export const uint256ToBigInt = (
50
50
  return generalDecoder(result, ['uint256'], 0n, value => value[0].toBigInt());
51
51
  };
52
52
 
53
+ export const uint128ToBigInt = (
54
+ result: MultiResult<BytesLike> | BytesLike,
55
+ ): bigint => {
56
+ return generalDecoder(result, ['uint128'], 0n, value => value[0].toBigInt());
57
+ };
58
+
59
+ export const int24ToBigInt = (
60
+ result: MultiResult<BytesLike> | BytesLike,
61
+ ): bigint => {
62
+ return generalDecoder(result, ['int24'], 0n, value => BigInt(value[0]));
63
+ };
64
+
53
65
  export const uint256ArrayDecode = (
54
66
  result: MultiResult<BytesLike> | BytesLike,
55
67
  ): bigint => {
@@ -18,6 +18,7 @@ type StateCache<State> = {
18
18
  export type InitializeStateOptions<State> = {
19
19
  state?: DeepReadonly<State>;
20
20
  initCallback?: (state: DeepReadonly<State>) => void;
21
+ forceRegenerate?: boolean;
21
22
  };
22
23
 
23
24
  export abstract class StatefulEventSubscriber<State>
@@ -89,6 +90,13 @@ export abstract class StatefulEventSubscriber<State>
89
90
  let masterBn: undefined | number = undefined;
90
91
  if (options && options.state) {
91
92
  this.setState(options.state, blockNumber);
93
+ } else if (options && options.forceRegenerate) {
94
+ // ZkEVM forces to always regenerate state when it is old
95
+ this.logger.debug(
96
+ `${this.parentName}: ${this.name}: forced to regenerate state`,
97
+ );
98
+ const state = await this.generateState(blockNumber);
99
+ this.setState(state, blockNumber);
92
100
  } else {
93
101
  if (this.dexHelper.config.isSlave && this.masterPoolNeeded) {
94
102
  let stateAsString = await this.dexHelper.cache.hget(
@@ -1,5 +0,0 @@
1
- <component name="ProjectCodeStyleConfiguration">
2
- <state>
3
- <option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
4
- </state>
5
- </component>
package/.idea/misc.xml DELETED
@@ -1,6 +0,0 @@
1
- <?xml version="1.0" encoding="UTF-8"?>
2
- <project version="4">
3
- <component name="ProjectRootManager">
4
- <output url="file://$PROJECT_DIR$/out" />
5
- </component>
6
- </project>
package/.idea/modules.xml DELETED
@@ -1,8 +0,0 @@
1
- <?xml version="1.0" encoding="UTF-8"?>
2
- <project version="4">
3
- <component name="ProjectModuleManager">
4
- <modules>
5
- <module fileurl="file://$PROJECT_DIR$/paraswap-dex-lib.iml" filepath="$PROJECT_DIR$/paraswap-dex-lib.iml" />
6
- </modules>
7
- </component>
8
- </project>