@paraswap/dex-lib 2.16.8-pancakeswapv3.0 → 2.17.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 (198) hide show
  1. package/.idea/aws.xml +17 -0
  2. package/.idea/codeStyles/Project.xml +19 -0
  3. package/.idea/codeStyles/codeStyleConfig.xml +5 -0
  4. package/.idea/misc.xml +6 -0
  5. package/.idea/modules.xml +8 -0
  6. package/.idea/paraswap-dex-lib.iml +9 -0
  7. package/.idea/vcs.xml +6 -0
  8. package/build/abi/woo-fi/WooFeeManager.abi.json +318 -0
  9. package/build/abi/woo-fi/WooPP.abi.json +548 -0
  10. package/build/abi/woo-fi/Wooracle.abi.json +260 -0
  11. package/build/config.js +4 -4
  12. package/build/dex/aave-v3/tokens/arbitrum.json +50 -0
  13. package/build/dex/aave-v3/tokens/avalanche.json +74 -0
  14. package/build/dex/aave-v3/tokens/fantom.json +62 -0
  15. package/build/dex/aave-v3/tokens/optimism.json +50 -0
  16. package/build/dex/aave-v3/tokens/polygon.json +116 -0
  17. package/build/dex/balancer-v2/balancer-v2.d.ts +14 -19
  18. package/build/dex/balancer-v2/balancer-v2.js +27 -22
  19. package/build/dex/balancer-v2/balancer-v2.js.map +1 -1
  20. package/build/dex/balancer-v2/config.d.ts +2 -7
  21. package/build/dex/balancer-v2/config.js +20 -30
  22. package/build/dex/balancer-v2/config.js.map +1 -1
  23. package/build/dex/balancer-v2/pools/balancer-v2-pool.d.ts +25 -0
  24. package/build/dex/balancer-v2/pools/balancer-v2-pool.js +107 -0
  25. package/build/dex/balancer-v2/pools/balancer-v2-pool.js.map +1 -0
  26. package/build/dex/balancer-v2/pools/linear/LinearMath.d.ts +20 -0
  27. package/build/dex/balancer-v2/pools/linear/LinearMath.js +179 -0
  28. package/build/dex/balancer-v2/pools/linear/LinearMath.js.map +1 -0
  29. package/build/dex/balancer-v2/pools/linear/LinearPool.d.ts +50 -0
  30. package/build/dex/balancer-v2/pools/linear/LinearPool.js +458 -0
  31. package/build/dex/balancer-v2/pools/linear/LinearPool.js.map +1 -0
  32. package/build/dex/balancer-v2/pools/phantom-stable/PhantomStableMath.d.ts +10 -0
  33. package/build/dex/balancer-v2/pools/phantom-stable/PhantomStableMath.js +314 -0
  34. package/build/dex/balancer-v2/pools/phantom-stable/PhantomStableMath.js.map +1 -0
  35. package/build/dex/balancer-v2/pools/phantom-stable/PhantomStablePool.d.ts +50 -0
  36. package/build/dex/balancer-v2/pools/phantom-stable/PhantomStablePool.js +367 -0
  37. package/build/dex/balancer-v2/pools/phantom-stable/PhantomStablePool.js.map +1 -0
  38. package/build/dex/balancer-v2/pools/stable/StableMath.d.ts +7 -0
  39. package/build/dex/balancer-v2/pools/stable/StableMath.js +111 -0
  40. package/build/dex/balancer-v2/pools/stable/StableMath.js.map +1 -0
  41. package/build/dex/balancer-v2/pools/stable/StablePool.d.ts +30 -0
  42. package/build/dex/balancer-v2/pools/stable/StablePool.js +129 -0
  43. package/build/dex/balancer-v2/pools/stable/StablePool.js.map +1 -0
  44. package/build/dex/balancer-v2/pools/weighted/WeightedMath.d.ts +6 -0
  45. package/build/dex/balancer-v2/pools/weighted/WeightedMath.js +61 -0
  46. package/build/dex/balancer-v2/pools/weighted/WeightedMath.js.map +1 -0
  47. package/build/dex/balancer-v2/pools/weighted/WeightedPool.d.ts +30 -0
  48. package/build/dex/balancer-v2/pools/weighted/WeightedPool.js +112 -0
  49. package/build/dex/balancer-v2/pools/weighted/WeightedPool.js.map +1 -0
  50. package/build/dex/balancer-v2/types.d.ts +1 -0
  51. package/build/dex/balancer-v2/types.js.map +1 -1
  52. package/build/dex/balancer-v2/utils.d.ts +3 -2
  53. package/build/dex/balancer-v2/utils.js +6 -4
  54. package/build/dex/balancer-v2/utils.js.map +1 -1
  55. package/build/dex/index.js +1 -1
  56. package/build/dex/index.js.map +1 -1
  57. package/build/dex/quickswap-v3.d.ts +21 -0
  58. package/build/dex/quickswap-v3.js +40 -0
  59. package/build/dex/quickswap-v3.js.map +1 -0
  60. package/build/dex/uniswap-v3/config.js +28 -0
  61. package/build/dex/uniswap-v3/config.js.map +1 -1
  62. package/build/dex/uniswap-v3/uniswap-v3-pool.d.ts +2 -1
  63. package/build/dex/uniswap-v3/uniswap-v3-pool.js +3 -2
  64. package/build/dex/uniswap-v3/uniswap-v3-pool.js.map +1 -1
  65. package/build/dex/uniswap-v3/uniswap-v3.js +1 -1
  66. package/build/dex/uniswap-v3/uniswap-v3.js.map +1 -1
  67. package/build/dex/{pancakeswap-v3 → woo-fi}/config.d.ts +2 -2
  68. package/build/dex/woo-fi/config.js +141 -0
  69. package/build/dex/woo-fi/config.js.map +1 -0
  70. package/build/dex/woo-fi/constants.d.ts +5 -0
  71. package/build/dex/woo-fi/constants.js +20 -0
  72. package/build/dex/woo-fi/constants.js.map +1 -0
  73. package/build/dex/woo-fi/types.d.ts +48 -0
  74. package/build/dex/woo-fi/types.js +3 -0
  75. package/build/dex/woo-fi/types.js.map +1 -0
  76. package/build/dex/woo-fi/woo-fi-decimal-math.d.ts +14 -0
  77. package/build/dex/woo-fi/woo-fi-decimal-math.js +42 -0
  78. package/build/dex/woo-fi/woo-fi-decimal-math.js.map +1 -0
  79. package/build/dex/woo-fi/woo-fi-math.d.ts +31 -0
  80. package/build/dex/woo-fi/woo-fi-math.js +300 -0
  81. package/build/dex/woo-fi/woo-fi-math.js.map +1 -0
  82. package/build/dex/woo-fi/woo-fi.d.ts +65 -0
  83. package/build/dex/woo-fi/woo-fi.js +480 -0
  84. package/build/dex/woo-fi/woo-fi.js.map +1 -0
  85. package/package.json +1 -1
  86. package/src/config.ts +4 -4
  87. package/src/dex/balancer-v2/balancer-v2-e2e.test.ts +538 -225
  88. package/src/dex/balancer-v2/balancer-v2-integration.test.ts +305 -122
  89. package/src/dex/balancer-v2/balancer-v2.ts +60 -56
  90. package/src/dex/balancer-v2/config.ts +23 -35
  91. package/src/dex/balancer-v2/pools/balancer-v2-pool.ts +274 -0
  92. package/src/dex/balancer-v2/{LinearMath.ts → pools/linear/LinearMath.ts} +11 -10
  93. package/src/dex/balancer-v2/{LinearPool.ts → pools/linear/LinearPool.ts} +210 -6
  94. package/src/dex/balancer-v2/{StableMath.ts → pools/phantom-stable/PhantomStableMath.ts} +101 -21
  95. package/src/dex/balancer-v2/{PhantomStablePool.ts → pools/phantom-stable/PhantomStablePool.ts} +167 -12
  96. package/src/dex/balancer-v2/pools/stable/StableMath.ts +204 -0
  97. package/src/dex/balancer-v2/pools/stable/StablePool.ts +221 -0
  98. package/src/dex/balancer-v2/pools/weighted/WeightedMath.ts +84 -0
  99. package/src/dex/balancer-v2/pools/weighted/WeightedPool.ts +189 -0
  100. package/src/dex/balancer-v2/types.ts +1 -0
  101. package/src/dex/balancer-v2/utils.ts +7 -1
  102. package/src/dex/index.ts +1 -1
  103. package/src/dex/uniswap-v3/config.ts +32 -0
  104. package/src/dex/uniswap-v3/forks/pancakeswap-v3/pancakeswap-v3.ts +28 -0
  105. package/src/dex/uniswap-v3/uniswap-v3-e2e.test.ts +156 -0
  106. package/src/dex/uniswap-v3/uniswap-v3-events.test.ts +0 -4
  107. package/src/dex/uniswap-v3/uniswap-v3-pool.ts +2 -1
  108. package/src/dex/uniswap-v3/uniswap-v3.ts +1 -0
  109. package/tests/constants-e2e.ts +33 -8
  110. package/build/abi/pancakeswap-v3/PancakeV3StateMulticall.abi.json +0 -781
  111. package/build/abi/pancakeswap-v3/PancakeswapV3Pool.abi.json +0 -1039
  112. package/build/abi/pancakeswap-v3/PancakeswapV3Quoter.abi.json +0 -285
  113. package/build/abi/pancakeswap-v3/PancakeswapV3Router.abi.json +0 -583
  114. package/build/dex/pancakeswap-v3/config.js +0 -62
  115. package/build/dex/pancakeswap-v3/config.js.map +0 -1
  116. package/build/dex/pancakeswap-v3/constants.d.ts +0 -23
  117. package/build/dex/pancakeswap-v3/constants.js +0 -29
  118. package/build/dex/pancakeswap-v3/constants.js.map +0 -1
  119. package/build/dex/pancakeswap-v3/contract-math/BitMath.d.ts +0 -4
  120. package/build/dex/pancakeswap-v3/contract-math/BitMath.js +0 -93
  121. package/build/dex/pancakeswap-v3/contract-math/BitMath.js.map +0 -1
  122. package/build/dex/pancakeswap-v3/contract-math/FixedPoint128.d.ts +0 -3
  123. package/build/dex/pancakeswap-v3/contract-math/FixedPoint128.js +0 -8
  124. package/build/dex/pancakeswap-v3/contract-math/FixedPoint128.js.map +0 -1
  125. package/build/dex/pancakeswap-v3/contract-math/FixedPoint96.d.ts +0 -4
  126. package/build/dex/pancakeswap-v3/contract-math/FixedPoint96.js +0 -9
  127. package/build/dex/pancakeswap-v3/contract-math/FixedPoint96.js.map +0 -1
  128. package/build/dex/pancakeswap-v3/contract-math/FullMath.d.ts +0 -4
  129. package/build/dex/pancakeswap-v3/contract-math/FullMath.js +0 -19
  130. package/build/dex/pancakeswap-v3/contract-math/FullMath.js.map +0 -1
  131. package/build/dex/pancakeswap-v3/contract-math/LiquidityMath.d.ts +0 -3
  132. package/build/dex/pancakeswap-v3/contract-math/LiquidityMath.js +0 -22
  133. package/build/dex/pancakeswap-v3/contract-math/LiquidityMath.js.map +0 -1
  134. package/build/dex/pancakeswap-v3/contract-math/Oracle.d.ts +0 -10
  135. package/build/dex/pancakeswap-v3/contract-math/Oracle.js +0 -133
  136. package/build/dex/pancakeswap-v3/contract-math/Oracle.js.map +0 -1
  137. package/build/dex/pancakeswap-v3/contract-math/SqrtPriceMath.d.ts +0 -10
  138. package/build/dex/pancakeswap-v3/contract-math/SqrtPriceMath.js +0 -91
  139. package/build/dex/pancakeswap-v3/contract-math/SqrtPriceMath.js.map +0 -1
  140. package/build/dex/pancakeswap-v3/contract-math/SwapMath.d.ts +0 -8
  141. package/build/dex/pancakeswap-v3/contract-math/SwapMath.js +0 -70
  142. package/build/dex/pancakeswap-v3/contract-math/SwapMath.js.map +0 -1
  143. package/build/dex/pancakeswap-v3/contract-math/Tick.d.ts +0 -7
  144. package/build/dex/pancakeswap-v3/contract-math/Tick.js +0 -45
  145. package/build/dex/pancakeswap-v3/contract-math/Tick.js.map +0 -1
  146. package/build/dex/pancakeswap-v3/contract-math/TickBitMap.d.ts +0 -8
  147. package/build/dex/pancakeswap-v3/contract-math/TickBitMap.js +0 -87
  148. package/build/dex/pancakeswap-v3/contract-math/TickBitMap.js.map +0 -1
  149. package/build/dex/pancakeswap-v3/contract-math/TickMath.d.ts +0 -8
  150. package/build/dex/pancakeswap-v3/contract-math/TickMath.js +0 -162
  151. package/build/dex/pancakeswap-v3/contract-math/TickMath.js.map +0 -1
  152. package/build/dex/pancakeswap-v3/contract-math/UnsafeMath.d.ts +0 -3
  153. package/build/dex/pancakeswap-v3/contract-math/UnsafeMath.js +0 -10
  154. package/build/dex/pancakeswap-v3/contract-math/UnsafeMath.js.map +0 -1
  155. package/build/dex/pancakeswap-v3/contract-math/pancakeswap-v3-math.d.ts +0 -18
  156. package/build/dex/pancakeswap-v3/contract-math/pancakeswap-v3-math.js +0 -407
  157. package/build/dex/pancakeswap-v3/contract-math/pancakeswap-v3-math.js.map +0 -1
  158. package/build/dex/pancakeswap-v3/contract-math/utils.d.ts +0 -3
  159. package/build/dex/pancakeswap-v3/contract-math/utils.js +0 -16
  160. package/build/dex/pancakeswap-v3/contract-math/utils.js.map +0 -1
  161. package/build/dex/pancakeswap-v3/pancakeswap-v3-pool.d.ts +0 -45
  162. package/build/dex/pancakeswap-v3/pancakeswap-v3-pool.js +0 -340
  163. package/build/dex/pancakeswap-v3/pancakeswap-v3-pool.js.map +0 -1
  164. package/build/dex/pancakeswap-v3/pancakeswap-v3.d.ts +0 -55
  165. package/build/dex/pancakeswap-v3/pancakeswap-v3.js +0 -605
  166. package/build/dex/pancakeswap-v3/pancakeswap-v3.js.map +0 -1
  167. package/build/dex/pancakeswap-v3/types.d.ts +0 -137
  168. package/build/dex/pancakeswap-v3/types.js +0 -9
  169. package/build/dex/pancakeswap-v3/types.js.map +0 -1
  170. package/build/dex/pancakeswap-v3/utils.d.ts +0 -6
  171. package/build/dex/pancakeswap-v3/utils.js +0 -65
  172. package/build/dex/pancakeswap-v3/utils.js.map +0 -1
  173. package/src/abi/pancakeswap-v3/PancakeV3StateMulticall.abi.json +0 -781
  174. package/src/abi/pancakeswap-v3/PancakeswapV3Pool.abi.json +0 -1039
  175. package/src/dex/balancer-v2/balancer-v2-pool.ts +0 -744
  176. package/src/dex/pancakeswap-v3/config.ts +0 -68
  177. package/src/dex/pancakeswap-v3/constants.ts +0 -35
  178. package/src/dex/pancakeswap-v3/contract-math/BitMath.ts +0 -90
  179. package/src/dex/pancakeswap-v3/contract-math/FixedPoint128.ts +0 -3
  180. package/src/dex/pancakeswap-v3/contract-math/FixedPoint96.ts +0 -4
  181. package/src/dex/pancakeswap-v3/contract-math/FullMath.ts +0 -30
  182. package/src/dex/pancakeswap-v3/contract-math/LiquidityMath.ts +0 -17
  183. package/src/dex/pancakeswap-v3/contract-math/Oracle.ts +0 -226
  184. package/src/dex/pancakeswap-v3/contract-math/SqrtPriceMath.ts +0 -226
  185. package/src/dex/pancakeswap-v3/contract-math/SwapMath.ts +0 -139
  186. package/src/dex/pancakeswap-v3/contract-math/Tick.ts +0 -82
  187. package/src/dex/pancakeswap-v3/contract-math/TickBitMap.ts +0 -128
  188. package/src/dex/pancakeswap-v3/contract-math/TickMath.ts +0 -211
  189. package/src/dex/pancakeswap-v3/contract-math/UnsafeMath.ts +0 -5
  190. package/src/dex/pancakeswap-v3/contract-math/pancakeswap-v3-math.ts +0 -691
  191. package/src/dex/pancakeswap-v3/contract-math/utils.ts +0 -11
  192. package/src/dex/pancakeswap-v3/pancakeswap-v3-e2e.test.ts +0 -168
  193. package/src/dex/pancakeswap-v3/pancakeswap-v3-events.test.ts +0 -124
  194. package/src/dex/pancakeswap-v3/pancakeswap-v3-integration.test.ts +0 -338
  195. package/src/dex/pancakeswap-v3/pancakeswap-v3-pool.ts +0 -554
  196. package/src/dex/pancakeswap-v3/pancakeswap-v3.ts +0 -1000
  197. /package/src/abi/{pancakeswap-v3/PancakeswapV3Quoter.abi.json → uniswap-v3/pancakeswap-v3/PancakeswapV3QuoterV2.abi.json} +0 -0
  198. /package/src/abi/{pancakeswap-v3 → uniswap-v3/pancakeswap-v3}/PancakeswapV3Router.abi.json +0 -0
@@ -1,554 +0,0 @@
1
- import _ from 'lodash';
2
- import { Contract } from 'web3-eth-contract';
3
- import { Interface } from '@ethersproject/abi';
4
- import { ethers } from 'ethers';
5
- import { assert, DeepReadonly } from 'ts-essentials';
6
- import { Log, Logger, BlockHeader, Address } from '../../types';
7
- import {
8
- InitializeStateOptions,
9
- StatefulEventSubscriber,
10
- } from '../../stateful-event-subscriber';
11
- import { IDexHelper } from '../../dex-helper/idex-helper';
12
- import PancakeswapV3PoolABI from '../../abi/pancakeswap-v3/PancakeswapV3Pool.abi.json';
13
- import { bigIntify, catchParseLogError, isSampled } from '../../utils';
14
- import { pancakeswapV3Math } from './contract-math/pancakeswap-v3-math';
15
- import { MultiCallParams } from '../../lib/multi-wrapper';
16
- import { NumberAsString } from '@paraswap/core';
17
- import {
18
- DEFAULT_POOL_INIT_CODE_HASH,
19
- OUT_OF_RANGE_ERROR_POSTFIX,
20
- TICK_BITMAP_BUFFER,
21
- TICK_BITMAP_TO_USE,
22
- } from './constants';
23
- import { TickBitMap } from './contract-math/TickBitMap';
24
- import { uint256ToBigInt } from '../../lib/decoders';
25
- import {
26
- DecodedStateMultiCallResultWithRelativeBitmaps,
27
- PoolState,
28
- TickBitMapMappingsWithBigNumber,
29
- TickInfo,
30
- TickInfoMappingsWithBigNumber,
31
- } from '../uniswap-v3/types';
32
- import { decodeStateMultiCallResultWithRelativeBitmaps } from '../uniswap-v3/utils';
33
-
34
- export class PancakeSwapV3EventPool extends StatefulEventSubscriber<PoolState> {
35
- handlers: {
36
- [event: string]: (
37
- event: any,
38
- pool: PoolState,
39
- log: Log,
40
- blockHeader: Readonly<BlockHeader>,
41
- ) => PoolState;
42
- } = {};
43
-
44
- logDecoder: (log: Log) => any;
45
-
46
- readonly token0: Address;
47
-
48
- readonly token1: Address;
49
-
50
- private _poolAddress?: Address;
51
-
52
- private _stateRequestCallData?: MultiCallParams<
53
- bigint | DecodedStateMultiCallResultWithRelativeBitmaps
54
- >[];
55
-
56
- public readonly poolIface = new Interface(PancakeswapV3PoolABI);
57
-
58
- public readonly feeCodeAsString;
59
-
60
- constructor(
61
- readonly dexHelper: IDexHelper,
62
- parentName: string,
63
- readonly stateMultiContract: Contract,
64
- readonly erc20Interface: Interface,
65
- protected readonly factoryAddress: Address,
66
- public readonly feeCode: bigint,
67
- token0: Address,
68
- token1: Address,
69
- logger: Logger,
70
- mapKey: string = '',
71
- readonly poolInitCodeHash: string,
72
- readonly poolDeployer?: string,
73
- ) {
74
- super(
75
- parentName,
76
- `${token0}_${token1}_${feeCode}`,
77
- dexHelper,
78
- logger,
79
- true,
80
- mapKey,
81
- );
82
- this.feeCodeAsString = feeCode.toString();
83
- this.token0 = token0.toLowerCase();
84
- this.token1 = token1.toLowerCase();
85
- this.logDecoder = (log: Log) => this.poolIface.parseLog(log);
86
- this.addressesSubscribed = new Array<Address>(1);
87
-
88
- // Add handlers
89
- this.handlers['Swap'] = this.handleSwapEvent.bind(this);
90
- this.handlers['Burn'] = this.handleBurnEvent.bind(this);
91
- this.handlers['Mint'] = this.handleMintEvent.bind(this);
92
- this.handlers['SetFeeProtocol'] = this.handleSetFeeProtocolEvent.bind(this);
93
- this.handlers['IncreaseObservationCardinalityNext'] =
94
- this.handleIncreaseObservationCardinalityNextEvent.bind(this);
95
-
96
- // Wen need them to keep balance of the pool up to date
97
- this.handlers['Collect'] = this.handleCollectEvent.bind(this);
98
- // Almost the same as Collect, but for pool owners
99
- this.handlers['CollectProtocol'] = this.handleCollectEvent.bind(this);
100
- this.handlers['Flash'] = this.handleFlashEvent.bind(this);
101
- }
102
-
103
- get poolAddress() {
104
- if (this._poolAddress === undefined) {
105
- this._poolAddress = this._computePoolAddress(
106
- this.token0,
107
- this.token1,
108
- this.feeCode,
109
- );
110
- }
111
- return this._poolAddress;
112
- }
113
-
114
- set poolAddress(address: Address) {
115
- this._poolAddress = address.toLowerCase();
116
- }
117
-
118
- async initialize(
119
- blockNumber: number,
120
- options?: InitializeStateOptions<PoolState>,
121
- ) {
122
- await super.initialize(blockNumber, options);
123
- }
124
-
125
- protected async processBlockLogs(
126
- state: DeepReadonly<PoolState>,
127
- logs: Readonly<Log>[],
128
- blockHeader: Readonly<BlockHeader>,
129
- ): Promise<DeepReadonly<PoolState> | null> {
130
- const newState = await super.processBlockLogs(state, logs, blockHeader);
131
- if (newState && !newState.isValid) {
132
- return await this.generateState(blockHeader.number);
133
- }
134
- return newState;
135
- }
136
-
137
- protected processLog(
138
- state: DeepReadonly<PoolState>,
139
- log: Readonly<Log>,
140
- blockHeader: Readonly<BlockHeader>,
141
- ): DeepReadonly<PoolState> | null {
142
- try {
143
- const event = this.logDecoder(log);
144
-
145
- const uniswapV3EventLoggingSampleRate =
146
- this.dexHelper.config.data.uniswapV3EventLoggingSampleRate;
147
- if (
148
- !this.dexHelper.config.isSlave &&
149
- uniswapV3EventLoggingSampleRate &&
150
- isSampled(uniswapV3EventLoggingSampleRate)
151
- ) {
152
- this.logger.info(
153
- `event=${event.name} - block=${
154
- blockHeader.number
155
- }. Log sampled at rate ${uniswapV3EventLoggingSampleRate * 100}%`,
156
- );
157
- }
158
-
159
- if (event.name in this.handlers) {
160
- // Because we have observations in array which is mutable by nature, there is a
161
- // ts compile error: https://stackoverflow.com/questions/53412934/disable-allowing-assigning-readonly-types-to-non-readonly-types
162
- // And there is no good workaround, so turn off the type checker for this line
163
- const _state = _.cloneDeep(state) as PoolState;
164
- try {
165
- return this.handlers[event.name](event, _state, log, blockHeader);
166
- } catch (e) {
167
- if (
168
- e instanceof Error &&
169
- e.message.endsWith(OUT_OF_RANGE_ERROR_POSTFIX)
170
- ) {
171
- this.logger.warn(
172
- `${this.parentName}: Pool ${this.poolAddress} on ${
173
- this.dexHelper.config.data.network
174
- } is out of TickBitmap requested range. Re-query the state. ${JSON.stringify(
175
- event,
176
- )}`,
177
- e,
178
- );
179
- } else {
180
- this.logger.error(
181
- `${this.parentName}: Pool ${this.poolAddress}, ` +
182
- `network=${this.dexHelper.config.data.network}: Unexpected ` +
183
- `error while handling event on blockNumber=${blockHeader.number}, ` +
184
- `blockHash=${blockHeader.hash} and parentHash=${
185
- blockHeader.parentHash
186
- } for UniswapV3, ${JSON.stringify(event)}`,
187
- e,
188
- );
189
- }
190
- _state.isValid = false;
191
- return _state;
192
- }
193
- }
194
- } catch (e) {
195
- catchParseLogError(e, this.logger);
196
- }
197
- return null; // ignore unrecognized event
198
- }
199
-
200
- private _getStateRequestCallData() {
201
- if (!this._stateRequestCallData) {
202
- const callData: MultiCallParams<
203
- bigint | DecodedStateMultiCallResultWithRelativeBitmaps
204
- >[] = [
205
- {
206
- target: this.token0,
207
- callData: this.erc20Interface.encodeFunctionData('balanceOf', [
208
- this.poolAddress,
209
- ]),
210
- decodeFunction: uint256ToBigInt,
211
- },
212
- {
213
- target: this.token1,
214
- callData: this.erc20Interface.encodeFunctionData('balanceOf', [
215
- this.poolAddress,
216
- ]),
217
- decodeFunction: uint256ToBigInt,
218
- },
219
- {
220
- target: this.stateMultiContract.options.address,
221
- callData: this.stateMultiContract.methods
222
- .getFullStateWithRelativeBitmaps(
223
- this.factoryAddress,
224
- this.token0,
225
- this.token1,
226
- this.feeCode,
227
- this.getBitmapRangeToRequest(),
228
- this.getBitmapRangeToRequest(),
229
- )
230
- .encodeABI(),
231
- decodeFunction: decodeStateMultiCallResultWithRelativeBitmaps,
232
- },
233
- ];
234
- this._stateRequestCallData = callData;
235
- }
236
- return this._stateRequestCallData;
237
- }
238
-
239
- getBitmapRangeToRequest() {
240
- return TICK_BITMAP_TO_USE + TICK_BITMAP_BUFFER;
241
- }
242
-
243
- async generateState(blockNumber: number): Promise<Readonly<PoolState>> {
244
- const callData = this._getStateRequestCallData();
245
-
246
- const [resBalance0, resBalance1, resState] =
247
- await this.dexHelper.multiWrapper.tryAggregate<
248
- bigint | DecodedStateMultiCallResultWithRelativeBitmaps
249
- >(
250
- false,
251
- callData,
252
- blockNumber,
253
- this.dexHelper.multiWrapper.defaultBatchSize,
254
- false,
255
- );
256
-
257
- // Quite ugly solution, but this is the one that fits to current flow.
258
- // I think UniswapV3 callbacks subscriptions are complexified for no reason.
259
- // Need to be revisited later
260
- assert(resState.success, 'Pool does not exist');
261
-
262
- const [balance0, balance1, _state] = [
263
- resBalance0.returnData,
264
- resBalance1.returnData,
265
- resState.returnData,
266
- ] as [bigint, bigint, DecodedStateMultiCallResultWithRelativeBitmaps];
267
-
268
- const tickBitmap = {};
269
- const ticks = {};
270
-
271
- this._reduceTickBitmap(tickBitmap, _state.tickBitmap);
272
- this._reduceTicks(ticks, _state.ticks);
273
-
274
- const observations = {
275
- [_state.slot0.observationIndex]: {
276
- blockTimestamp: bigIntify(_state.observation.blockTimestamp),
277
- tickCumulative: bigIntify(_state.observation.tickCumulative),
278
- secondsPerLiquidityCumulativeX128: bigIntify(
279
- _state.observation.secondsPerLiquidityCumulativeX128,
280
- ),
281
- initialized: _state.observation.initialized,
282
- },
283
- };
284
-
285
- const currentTick = bigIntify(_state.slot0.tick);
286
- const tickSpacing = bigIntify(_state.tickSpacing);
287
-
288
- const startTickBitmap = TickBitMap.position(currentTick / tickSpacing)[0];
289
- const requestedRange = this.getBitmapRangeToRequest();
290
-
291
- return {
292
- pool: _state.pool,
293
- blockTimestamp: bigIntify(_state.blockTimestamp),
294
- slot0: {
295
- sqrtPriceX96: bigIntify(_state.slot0.sqrtPriceX96),
296
- tick: currentTick,
297
- observationIndex: +_state.slot0.observationIndex,
298
- observationCardinality: +_state.slot0.observationCardinality,
299
- observationCardinalityNext: +_state.slot0.observationCardinalityNext,
300
- feeProtocol: bigIntify(_state.slot0.feeProtocol),
301
- },
302
- liquidity: bigIntify(_state.liquidity),
303
- fee: this.feeCode,
304
- tickSpacing,
305
- maxLiquidityPerTick: bigIntify(_state.maxLiquidityPerTick),
306
- tickBitmap,
307
- ticks,
308
- observations,
309
- isValid: true,
310
- startTickBitmap,
311
- lowestKnownTick:
312
- (BigInt.asIntN(24, startTickBitmap - requestedRange) << 8n) *
313
- tickSpacing,
314
- highestKnownTick:
315
- ((BigInt.asIntN(24, startTickBitmap + requestedRange) << 8n) +
316
- BigInt.asIntN(24, 255n)) *
317
- tickSpacing,
318
- balance0,
319
- balance1,
320
- };
321
- }
322
-
323
- handleSwapEvent(
324
- event: any,
325
- pool: PoolState,
326
- log: Log,
327
- blockHeader: BlockHeader,
328
- ) {
329
- const newSqrtPriceX96 = bigIntify(event.args.sqrtPriceX96);
330
- const amount0 = bigIntify(event.args.amount0);
331
- const amount1 = bigIntify(event.args.amount1);
332
- const newTick = bigIntify(event.args.tick);
333
- const newLiquidity = bigIntify(event.args.liquidity);
334
-
335
- pool.blockTimestamp = bigIntify(blockHeader.timestamp);
336
-
337
- if (amount0 <= 0n && amount1 <= 0n) {
338
- this.logger.error(
339
- `${this.parentName}: amount0 <= 0n && amount1 <= 0n for ` +
340
- `${this.poolAddress} and ${blockHeader.number}. Check why it happened`,
341
- );
342
- pool.isValid = false;
343
- return pool;
344
- } else {
345
- const zeroForOne = amount0 > 0n;
346
-
347
- pancakeswapV3Math.swapFromEvent(
348
- pool,
349
- newSqrtPriceX96,
350
- newTick,
351
- newLiquidity,
352
- zeroForOne,
353
- );
354
-
355
- if (zeroForOne) {
356
- if (amount1 < 0n) {
357
- pool.balance1 -= BigInt.asUintN(256, -amount1);
358
- } else {
359
- this.logger.error(
360
- `In swapEvent for pool ${pool.pool} received incorrect values ${zeroForOne} and ${amount1}`,
361
- );
362
- pool.isValid = false;
363
- }
364
- // This is not correct fully, because pool may get more tokens then it needs, but
365
- // it is not accounted in internal state, it should be good enough
366
- pool.balance0 += BigInt.asUintN(256, amount0);
367
- } else {
368
- if (amount0 < 0n) {
369
- pool.balance0 -= BigInt.asUintN(256, -amount0);
370
- } else {
371
- this.logger.error(
372
- `In swapEvent for pool ${pool.pool} received incorrect values ${zeroForOne} and ${amount0}`,
373
- );
374
- pool.isValid = false;
375
- }
376
- pool.balance1 += BigInt.asUintN(256, amount1);
377
- }
378
-
379
- return pool;
380
- }
381
- }
382
-
383
- handleBurnEvent(
384
- // TODO DONE
385
- event: any,
386
- pool: PoolState,
387
- log: Log,
388
- blockHeader: BlockHeader,
389
- ) {
390
- const amount = bigIntify(event.args.amount);
391
- const tickLower = bigIntify(event.args.tickLower);
392
- const tickUpper = bigIntify(event.args.tickUpper);
393
- pool.blockTimestamp = bigIntify(blockHeader.timestamp);
394
-
395
- pancakeswapV3Math._modifyPosition(pool, {
396
- tickLower,
397
- tickUpper,
398
- liquidityDelta: -BigInt.asIntN(128, BigInt.asIntN(256, amount)),
399
- });
400
-
401
- // From this transaction I conclude that there is no balance change from
402
- // Burn event: https://dashboard.tenderly.co/tx/mainnet/0xfccf5341147ac3ad0e66452273d12dfc3219e81f8fb369a6cdecfb24b9b9d078/logs
403
- // And it aligns with UniswapV3 doc:
404
- // https://github.com/Uniswap/v3-core/blob/05c10bf6d547d6121622ac51c457f93775e1df09/contracts/interfaces/pool/IUniswapV3PoolActions.sol#L59
405
- // It just updates positions and tokensOwed which may be requested calling collect
406
- // So, we don't need to update pool.balances0 and pool.balances1 here
407
-
408
- return pool;
409
- }
410
-
411
- handleMintEvent(
412
- // TODO DONE
413
- event: any,
414
- pool: PoolState,
415
- log: Log,
416
- blockHeader: BlockHeader,
417
- ) {
418
- const amount = bigIntify(event.args.amount);
419
- const tickLower = bigIntify(event.args.tickLower);
420
- const tickUpper = bigIntify(event.args.tickUpper);
421
- const amount0 = bigIntify(event.args.amount0);
422
- const amount1 = bigIntify(event.args.amount1);
423
- pool.blockTimestamp = bigIntify(blockHeader.timestamp);
424
-
425
- pancakeswapV3Math._modifyPosition(pool, {
426
- tickLower,
427
- tickUpper,
428
- liquidityDelta: amount,
429
- });
430
-
431
- pool.balance0 += amount0;
432
- pool.balance1 += amount1;
433
-
434
- return pool;
435
- }
436
-
437
- handleSetFeeProtocolEvent(
438
- // TODO DONE
439
- event: any,
440
- pool: PoolState,
441
- log: Log,
442
- blockHeader: BlockHeader,
443
- ) {
444
- const feeProtocol0 = bigIntify(event.args.feeProtocol0New);
445
- const feeProtocol1 = bigIntify(event.args.feeProtocol1New);
446
- pool.slot0.feeProtocol = feeProtocol0 + (feeProtocol1 << 16n); // TODO CHANGED
447
- pool.blockTimestamp = bigIntify(blockHeader.timestamp);
448
-
449
- return pool;
450
- }
451
-
452
- handleCollectEvent(
453
- // TODO DONE
454
- event: any,
455
- pool: PoolState,
456
- log: Log,
457
- blockHeader: BlockHeader,
458
- ) {
459
- const amount0 = bigIntify(event.args.amount0);
460
- const amount1 = bigIntify(event.args.amount1);
461
- pool.balance0 -= amount0;
462
- pool.balance1 -= amount1;
463
- pool.blockTimestamp = bigIntify(blockHeader.timestamp);
464
-
465
- return pool;
466
- }
467
-
468
- handleFlashEvent(
469
- // TODO DONE
470
- event: any,
471
- pool: PoolState,
472
- log: Log,
473
- blockHeader: BlockHeader,
474
- ) {
475
- const paid0 = bigIntify(event.args.paid0);
476
- const paid1 = bigIntify(event.args.paid1);
477
- pool.balance0 += paid0;
478
- pool.balance1 += paid1;
479
- pool.blockTimestamp = bigIntify(blockHeader.timestamp);
480
-
481
- return pool;
482
- }
483
-
484
- handleIncreaseObservationCardinalityNextEvent(
485
- // TODO DONE
486
- event: any,
487
- pool: PoolState,
488
- log: Log,
489
- blockHeader: BlockHeader,
490
- ) {
491
- pool.slot0.observationCardinalityNext = parseInt(
492
- event.args.observationCardinalityNextNew,
493
- 10,
494
- );
495
- pool.blockTimestamp = bigIntify(blockHeader.timestamp);
496
- return pool;
497
- }
498
-
499
- private _reduceTickBitmap(
500
- tickBitmap: Record<NumberAsString, bigint>,
501
- tickBitmapToReduce: TickBitMapMappingsWithBigNumber[],
502
- ) {
503
- return tickBitmapToReduce.reduce<Record<NumberAsString, bigint>>(
504
- (acc, curr) => {
505
- const { index, value } = curr;
506
- acc[index] = bigIntify(value);
507
- return acc;
508
- },
509
- tickBitmap,
510
- );
511
- }
512
-
513
- private _reduceTicks(
514
- ticks: Record<NumberAsString, TickInfo>,
515
- ticksToReduce: TickInfoMappingsWithBigNumber[],
516
- ) {
517
- return ticksToReduce.reduce<Record<string, TickInfo>>((acc, curr) => {
518
- const { index, value } = curr;
519
- acc[index] = {
520
- liquidityGross: bigIntify(value.liquidityGross),
521
- liquidityNet: bigIntify(value.liquidityNet),
522
- tickCumulativeOutside: bigIntify(value.tickCumulativeOutside),
523
- secondsPerLiquidityOutsideX128: bigIntify(
524
- value.secondsPerLiquidityOutsideX128,
525
- ),
526
- secondsOutside: bigIntify(value.secondsOutside),
527
- initialized: value.initialized,
528
- };
529
- return acc;
530
- }, ticks);
531
- }
532
-
533
- private _computePoolAddress(
534
- token0: Address,
535
- token1: Address,
536
- fee: bigint,
537
- ): Address {
538
- // https://github.com/Uniswap/v3-periphery/blob/main/contracts/libraries/PoolAddress.sol
539
- if (token0 > token1) [token0, token1] = [token1, token0];
540
-
541
- const encodedKey = ethers.utils.keccak256(
542
- ethers.utils.defaultAbiCoder.encode(
543
- ['address', 'address', 'uint24'],
544
- [token0, token1, BigInt.asUintN(24, fee)],
545
- ),
546
- );
547
-
548
- return ethers.utils.getCreate2Address(
549
- this.poolDeployer ? this.poolDeployer : this.factoryAddress,
550
- encodedKey,
551
- this.poolInitCodeHash,
552
- );
553
- }
554
- }