@paraswap/dex-lib 3.8.1 → 3.8.3

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 (213) hide show
  1. package/.vscode/launch.json +9 -49
  2. package/.vscode/settings.json +2 -1
  3. package/build/abi/Uncompressor.json +250 -0
  4. package/build/abi/integral/factory.json +333 -0
  5. package/build/abi/integral/oracle.json +501 -0
  6. package/build/abi/integral/pool.json +1041 -0
  7. package/build/abi/{wombat/pool.json → integral/relayer.json} +720 -473
  8. package/build/abi/oswap/oswap.abi.json +452 -0
  9. package/build/dex/aave-v1/aave-v1.d.ts +1 -2
  10. package/build/dex/aave-v1/aave-v1.js +0 -23
  11. package/build/dex/aave-v1/aave-v1.js.map +1 -1
  12. package/build/dex/aave-v3/aave-v3.js +2 -1
  13. package/build/dex/aave-v3/aave-v3.js.map +1 -1
  14. package/build/dex/aave-v3-stata/aave-v3-stata.js +1 -0
  15. package/build/dex/aave-v3-stata/aave-v3-stata.js.map +1 -1
  16. package/build/dex/angle-staked-stable/angle-staked-stable.js +4 -1
  17. package/build/dex/angle-staked-stable/angle-staked-stable.js.map +1 -1
  18. package/build/dex/compound/compound.js +2 -1
  19. package/build/dex/compound/compound.js.map +1 -1
  20. package/build/dex/compound.js +1 -1
  21. package/build/dex/compound.js.map +1 -1
  22. package/build/dex/etherfi/etherfi.d.ts +26 -0
  23. package/build/dex/etherfi/etherfi.js +96 -0
  24. package/build/dex/etherfi/etherfi.js.map +1 -0
  25. package/build/dex/etherfi.js +4 -1
  26. package/build/dex/etherfi.js.map +1 -1
  27. package/build/dex/idle-dao/idle-dao.js +1 -0
  28. package/build/dex/idle-dao/idle-dao.js.map +1 -1
  29. package/build/dex/integral/config.d.ts +4 -0
  30. package/build/dex/integral/config.js +20 -0
  31. package/build/dex/integral/config.js.map +1 -0
  32. package/build/dex/integral/context.d.ts +33 -0
  33. package/build/dex/integral/context.js +98 -0
  34. package/build/dex/integral/context.js.map +1 -0
  35. package/build/dex/integral/helpers.d.ts +17 -0
  36. package/build/dex/integral/helpers.js +157 -0
  37. package/build/dex/integral/helpers.js.map +1 -0
  38. package/build/dex/integral/integral-factory.d.ts +21 -0
  39. package/build/dex/integral/integral-factory.js +92 -0
  40. package/build/dex/integral/integral-factory.js.map +1 -0
  41. package/build/dex/integral/integral-pool.d.ts +46 -0
  42. package/build/dex/integral/integral-pool.js +143 -0
  43. package/build/dex/integral/integral-pool.js.map +1 -0
  44. package/build/dex/integral/integral-pricing.d.ts +18 -0
  45. package/build/dex/integral/integral-pricing.js +114 -0
  46. package/build/dex/integral/integral-pricing.js.map +1 -0
  47. package/build/dex/integral/integral-relayer.d.ts +39 -0
  48. package/build/dex/integral/integral-relayer.js +189 -0
  49. package/build/dex/integral/integral-relayer.js.map +1 -0
  50. package/build/dex/integral/integral-token.d.ts +22 -0
  51. package/build/dex/integral/integral-token.js +55 -0
  52. package/build/dex/integral/integral-token.js.map +1 -0
  53. package/build/dex/integral/integral.d.ts +41 -0
  54. package/build/dex/integral/integral.js +382 -0
  55. package/build/dex/integral/integral.js.map +1 -0
  56. package/build/dex/integral/types.d.ts +84 -0
  57. package/build/dex/integral/types.js +9 -0
  58. package/build/dex/integral/types.js.map +1 -0
  59. package/build/dex/integral/utils.d.ts +6 -0
  60. package/build/dex/integral/utils.js +23 -0
  61. package/build/dex/integral/utils.js.map +1 -0
  62. package/build/dex/mStable.js +1 -1
  63. package/build/dex/mStable.js.map +1 -1
  64. package/build/dex/oswap/config.d.ts +5 -0
  65. package/build/dex/oswap/config.js +31 -0
  66. package/build/dex/oswap/config.js.map +1 -0
  67. package/build/dex/oswap/oswap-pool.d.ts +51 -0
  68. package/build/dex/oswap/oswap-pool.js +150 -0
  69. package/build/dex/oswap/oswap-pool.js.map +1 -0
  70. package/build/dex/oswap/oswap.d.ts +46 -0
  71. package/build/dex/oswap/oswap.js +266 -0
  72. package/build/dex/oswap/oswap.js.map +1 -0
  73. package/build/dex/oswap/types.d.ts +20 -0
  74. package/build/dex/oswap/types.js +3 -0
  75. package/build/dex/oswap/types.js.map +1 -0
  76. package/build/dex/paraswap-limit-orders/paraswap-limit-orders.js +3 -0
  77. package/build/dex/paraswap-limit-orders/paraswap-limit-orders.js.map +1 -1
  78. package/build/dex/platypus/platypus.d.ts +1 -2
  79. package/build/dex/platypus/platypus.js +0 -45
  80. package/build/dex/platypus/platypus.js.map +1 -1
  81. package/build/dex/sdai/config.d.ts +11 -0
  82. package/build/dex/sdai/config.js +21 -0
  83. package/build/dex/sdai/config.js.map +1 -0
  84. package/build/dex/sdai/constants.d.ts +2 -0
  85. package/build/dex/sdai/constants.js +6 -0
  86. package/build/dex/sdai/constants.js.map +1 -0
  87. package/build/dex/sdai/scripts/validate-state.js +102 -0
  88. package/build/dex/sdai/scripts/validate-state.js.map +1 -0
  89. package/build/dex/sdai/sdai-pool.d.ts +16 -0
  90. package/build/dex/sdai/sdai-pool.js +85 -0
  91. package/build/dex/sdai/sdai-pool.js.map +1 -0
  92. package/build/dex/sdai/sdai.d.ts +51 -0
  93. package/build/dex/sdai/sdai.js +172 -0
  94. package/build/dex/sdai/sdai.js.map +1 -0
  95. package/build/dex/sdai/types.d.ts +21 -0
  96. package/build/dex/sdai/types.js +11 -0
  97. package/build/dex/sdai/types.js.map +1 -0
  98. package/build/dex/sdai/utils.d.ts +4 -0
  99. package/build/dex/sdai/utils.js +39 -0
  100. package/build/dex/sdai/utils.js.map +1 -0
  101. package/build/dex/simple-exchange.d.ts +1 -1
  102. package/build/dex/simple-exchange.js +4 -2
  103. package/build/dex/simple-exchange.js.map +1 -1
  104. package/build/dex/spark/spark.js +2 -1
  105. package/build/dex/spark/spark.js.map +1 -1
  106. package/build/dex/stable-pool.js +8 -1
  107. package/build/dex/stable-pool.js.map +1 -1
  108. package/build/dex/swaap-v1/swaap-v1.d.ts +1 -2
  109. package/build/dex/swaap-v1/swaap-v1.js +0 -14
  110. package/build/dex/swaap-v1/swaap-v1.js.map +1 -1
  111. package/build/executor/Executor01BytecodeBuilder.js +3 -1
  112. package/build/executor/Executor01BytecodeBuilder.js.map +1 -1
  113. package/build/executor/Executor02BytecodeBuilder.js +3 -1
  114. package/build/executor/Executor02BytecodeBuilder.js.map +1 -1
  115. package/build/executor/Executor03BytecodeBuilder.js +2 -0
  116. package/build/executor/Executor03BytecodeBuilder.js.map +1 -1
  117. package/build/executor/ExecutorBytecodeBuilder.js +2 -0
  118. package/build/executor/ExecutorBytecodeBuilder.js.map +1 -1
  119. package/build/executor/compressor/Compressor.d.ts +23 -0
  120. package/build/executor/compressor/Compressor.js +144 -0
  121. package/build/executor/compressor/Compressor.js.map +1 -0
  122. package/build/executor/compressor/compress.d.ts +17 -0
  123. package/build/executor/compressor/compress.js +187 -0
  124. package/build/executor/compressor/compress.js.map +1 -0
  125. package/build/executor/compressor/compress_functions/addressSubstitution.d.ts +6 -0
  126. package/build/executor/compressor/compress_functions/addressSubstitution.js +29 -0
  127. package/build/executor/compressor/compress_functions/addressSubstitution.js.map +1 -0
  128. package/build/executor/compressor/compress_functions/addressSubstitutionFromObject.d.ts +10 -0
  129. package/build/executor/compressor/compress_functions/addressSubstitutionFromObject.js +40 -0
  130. package/build/executor/compressor/compress_functions/addressSubstitutionFromObject.js.map +1 -0
  131. package/build/executor/compressor/compress_functions/byteSubstitution.d.ts +11 -0
  132. package/build/executor/compressor/compress_functions/byteSubstitution.js +64 -0
  133. package/build/executor/compressor/compress_functions/byteSubstitution.js.map +1 -0
  134. package/build/executor/compressor/compress_functions/ffSubstitution.d.ts +7 -0
  135. package/build/executor/compressor/compress_functions/ffSubstitution.js +54 -0
  136. package/build/executor/compressor/compress_functions/ffSubstitution.js.map +1 -0
  137. package/build/executor/compressor/compress_functions/findLongestAndSubstitute.d.ts +8 -0
  138. package/build/executor/compressor/compress_functions/findLongestAndSubstitute.js +67 -0
  139. package/build/executor/compressor/compress_functions/findLongestAndSubstitute.js.map +1 -0
  140. package/build/executor/compressor/compress_functions/findLongestAndSubstitute_old.d.ts +8 -0
  141. package/build/executor/compressor/compress_functions/findLongestAndSubstitute_old.js +61 -0
  142. package/build/executor/compressor/compress_functions/findLongestAndSubstitute_old.js.map +1 -0
  143. package/build/executor/compressor/compress_functions/reverseAddressSubstitution.d.ts +6 -0
  144. package/build/executor/compressor/compress_functions/reverseAddressSubstitution.js +37 -0
  145. package/build/executor/compressor/compress_functions/reverseAddressSubstitution.js.map +1 -0
  146. package/build/executor/compressor/compress_functions/searchUnusedBytes.d.ts +9 -0
  147. package/build/executor/compressor/compress_functions/searchUnusedBytes.js +33 -0
  148. package/build/executor/compressor/compress_functions/searchUnusedBytes.js.map +1 -0
  149. package/build/executor/compressor/fetchSaved.js +17 -0
  150. package/build/executor/compressor/fetchSaved.js.map +1 -0
  151. package/build/executor/compressor/utils/computeCostL2.d.ts +2 -0
  152. package/build/executor/compressor/utils/computeCostL2.js +14 -0
  153. package/build/executor/compressor/utils/computeCostL2.js.map +1 -0
  154. package/build/executor/compressor/utils/findLongestDuplicatedString.d.ts +2 -0
  155. package/build/executor/compressor/utils/findLongestDuplicatedString.js +30 -0
  156. package/build/executor/compressor/utils/findLongestDuplicatedString.js.map +1 -0
  157. package/build/executor/compressor/utils/getAllIndexes.d.ts +2 -0
  158. package/build/executor/compressor/utils/getAllIndexes.js +12 -0
  159. package/build/executor/compressor/utils/getAllIndexes.js.map +1 -0
  160. package/build/executor/compressor/utils/getByteForAddress.d.ts +2 -0
  161. package/build/executor/compressor/utils/getByteForAddress.js +14 -0
  162. package/build/executor/compressor/utils/getByteForAddress.js.map +1 -0
  163. package/build/executor/compressor/utils/intTo2Bytes.d.ts +2 -0
  164. package/build/executor/compressor/utils/intTo2Bytes.js +14 -0
  165. package/build/executor/compressor/utils/intTo2Bytes.js.map +1 -0
  166. package/build/executor/compressor/utils/intTo3Bytes.d.ts +2 -0
  167. package/build/executor/compressor/utils/intTo3Bytes.js +18 -0
  168. package/build/executor/compressor/utils/intTo3Bytes.js.map +1 -0
  169. package/build/executor/compressor/utils/intToByte.d.ts +2 -0
  170. package/build/executor/compressor/utils/intToByte.js +10 -0
  171. package/build/executor/compressor/utils/intToByte.js.map +1 -0
  172. package/build/types.d.ts +1 -0
  173. package/package.json +1 -1
  174. package/src/dex/aave-v3/aave-v3-e2e.test.ts +4 -9
  175. package/src/dex/aave-v3/aave-v3.ts +5 -0
  176. package/src/dex/aave-v3-stata/aave-v3-stata.ts +1 -0
  177. package/src/dex/angle-staked-stable/angle-staked-stable.ts +8 -0
  178. package/src/dex/compound/compound.ts +5 -0
  179. package/src/dex/etherfi.ts +5 -0
  180. package/src/dex/idle-dao/idle-dao.ts +1 -0
  181. package/src/dex/paraswap-limit-orders/paraswap-limit-orders-e2e.test.ts +152 -68
  182. package/src/dex/paraswap-limit-orders/paraswap-limit-orders.ts +3 -0
  183. package/src/dex/simple-exchange.ts +5 -5
  184. package/src/dex/spark/spark-e2e.test.ts +9 -1
  185. package/src/dex/spark/spark.ts +5 -0
  186. package/src/executor/Executor01BytecodeBuilder.ts +3 -1
  187. package/src/executor/Executor02BytecodeBuilder.ts +3 -1
  188. package/src/executor/Executor03BytecodeBuilder.ts +2 -0
  189. package/src/executor/ExecutorBytecodeBuilder.ts +2 -0
  190. package/src/executor/executor01-bytecode-builder-e2e.test.ts +25 -0
  191. package/src/executor/executor02-bytecode-builder-e2e.test.ts +29 -0
  192. package/src/types.ts +1 -0
  193. package/tests/constants-e2e.ts +14 -14
  194. package/tests/utils-e2e.ts +1 -1
  195. package/.vscode/tasks.json +0 -15
  196. package/build/abi/uniswap-v3/AlienBaseV3Router.abi.json +0 -52
  197. package/build/dex/aave-v2/tokens-avalanche.json +0 -44
  198. package/build/dex/aave-v2/tokens-mainnet.json +0 -188
  199. package/build/dex/aave-v2/tokens-polygon.json +0 -44
  200. package/build/dex/maker-psm/scripts/gem.abi.json +0 -136
  201. package/build/dex/maker-psm/scripts/validate-state.js +0 -185
  202. package/build/dex/maker-psm/scripts/validate-state.js.map +0 -1
  203. package/build/dex/maker-psm/scripts/vat.abi.json +0 -243
  204. package/build/dex/solidly-v3/scripts/check-event-pool-event.js +0 -53
  205. package/build/dex/solidly-v3/scripts/check-event-pool-event.js.map +0 -1
  206. package/build/dex/uniswap-v3/forks/alien-base-v3/alien-base-v3.d.ts +0 -17
  207. package/build/dex/uniswap-v3/forks/alien-base-v3/alien-base-v3.js +0 -64
  208. package/build/dex/uniswap-v3/forks/alien-base-v3/alien-base-v3.js.map +0 -1
  209. package/build/dex/uniswap-v3/forks/alien-v3/alien-v3.d.ts +0 -17
  210. package/build/dex/uniswap-v3/forks/alien-v3/alien-v3.js +0 -79
  211. package/build/dex/uniswap-v3/forks/alien-v3/alien-v3.js.map +0 -1
  212. /package/build/dex/{solidly-v3/scripts/check-event-pool-event.d.ts → sdai/scripts/validate-state.d.ts} +0 -0
  213. /package/build/{dex/maker-psm/scripts/validate-state.d.ts → executor/compressor/fetchSaved.d.ts} +0 -0
@@ -0,0 +1,157 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.onTransferUpdateBalance = exports.onPoolCreatedAddPool = exports.onRebalanceSellOrderExecuted = exports.onRelayerPoolEnabledSet = exports.onPoolSwapForRelayer = exports.getPoolIdentifier = exports.isInverted = exports.getTickCumulatives = exports.getAveragePrice = exports.getSpotPrice = exports.getPrice = exports.getDecimalsConverter = exports.sortTokens = void 0;
7
+ const lodash_1 = __importDefault(require("lodash"));
8
+ const utils_1 = require("../../utils");
9
+ const FullMath_1 = require("../uniswap-v3/contract-math/FullMath");
10
+ const Oracle_1 = require("../uniswap-v3/contract-math/Oracle");
11
+ const TickMath_1 = require("../uniswap-v3/contract-math/TickMath");
12
+ const context_1 = require("./context");
13
+ function sortTokens(srcAddress, destAddress) {
14
+ return [srcAddress, destAddress].sort((a, b) => (a < b ? -1 : 1));
15
+ }
16
+ exports.sortTokens = sortTokens;
17
+ function getDecimalsConverter(decimals0, decimals1, inverted) {
18
+ return (10n **
19
+ (18n + BigInt(inverted ? decimals1 - decimals0 : decimals0 - decimals1)));
20
+ }
21
+ exports.getDecimalsConverter = getDecimalsConverter;
22
+ function getPrice(states, inverted) {
23
+ const { base, pricing, relayer } = states;
24
+ const decimalsConverter = getDecimalsConverter(base.decimals0, base.decimals1, false);
25
+ const spotPrice = getSpotPrice(pricing, decimalsConverter);
26
+ const averagePrice = getAveragePrice(relayer, pricing, decimalsConverter);
27
+ if (inverted) {
28
+ return 10n ** 36n / (spotPrice > averagePrice ? spotPrice : averagePrice);
29
+ }
30
+ else {
31
+ return spotPrice < averagePrice ? spotPrice : averagePrice;
32
+ }
33
+ }
34
+ exports.getPrice = getPrice;
35
+ function getSpotPrice(pricing, decimalsConverter) {
36
+ const sqrtPriceX96 = pricing.slot0.sqrtPriceX96;
37
+ const priceX128 = FullMath_1.FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, 2n ** 64n);
38
+ return FullMath_1.FullMath.mulDiv(priceX128, decimalsConverter, 2n ** 128n);
39
+ }
40
+ exports.getSpotPrice = getSpotPrice;
41
+ function getAveragePrice(relayer, pricing, decimalsConverter) {
42
+ (0, utils_1._require)(relayer.twapInterval > 0, 'Twap Interval not set');
43
+ const secondsAgo = BigInt(relayer.twapInterval);
44
+ const secondsAgos = [secondsAgo, 0n];
45
+ const tickCumulatives = getTickCumulatives(pricing, secondsAgos);
46
+ const delta = tickCumulatives[1] - tickCumulatives[0];
47
+ let arithmeticMeanTick = delta / secondsAgo;
48
+ if (delta < 0 && delta % secondsAgo != 0n) {
49
+ --arithmeticMeanTick;
50
+ }
51
+ const sqrtRatioX96 = TickMath_1.TickMath.getSqrtRatioAtTick(arithmeticMeanTick);
52
+ const ratioX128 = FullMath_1.FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 2n ** 64n);
53
+ return FullMath_1.FullMath.mulDiv(ratioX128, decimalsConverter, 2n ** 128n);
54
+ }
55
+ exports.getAveragePrice = getAveragePrice;
56
+ function getTickCumulatives(poolState, secondsAgos) {
57
+ const { tickCumulatives } = secondsAgos.reduce((memo, secondsAgo, i) => {
58
+ [memo.tickCumulatives[i], memo.secondsPerLiquidityCumulativeX128s[i]] =
59
+ Oracle_1.Oracle.observeSingle(poolState, BigInt.asUintN(32, poolState.blockTimestamp), secondsAgo, poolState.slot0.tick, poolState.slot0.observationIndex, poolState.liquidity, poolState.slot0.observationCardinality);
60
+ return memo;
61
+ }, {
62
+ tickCumulatives: Array(secondsAgos.length),
63
+ secondsPerLiquidityCumulativeX128s: Array(secondsAgos.length),
64
+ });
65
+ return tickCumulatives;
66
+ }
67
+ exports.getTickCumulatives = getTickCumulatives;
68
+ function isInverted(tokenIn, tokenOut) {
69
+ const [, token1] = tokenIn.toLowerCase() < tokenOut.toLowerCase()
70
+ ? [tokenIn, tokenOut]
71
+ : [tokenOut, tokenIn];
72
+ return tokenIn === token1;
73
+ }
74
+ exports.isInverted = isInverted;
75
+ function getPoolIdentifier(dexKey, srcAddress, destAddress) {
76
+ const tokenAddresses = sortTokens(srcAddress.toLowerCase(), destAddress.toLowerCase()).join('_');
77
+ return `${dexKey}_${tokenAddresses}`;
78
+ }
79
+ exports.getPoolIdentifier = getPoolIdentifier;
80
+ async function onPoolSwapForRelayer(blockNumber, poolAddress, recipient, amount0Out, amount1Out, _context) {
81
+ const context = _context || context_1.IntegralContext.getInstance();
82
+ if (recipient.toLowerCase() === context.relayerAddress.toLowerCase()) {
83
+ const pools = context.relayer.getPools();
84
+ if (pools[poolAddress.toLowerCase()]) {
85
+ const token0 = pools[poolAddress.toLowerCase()].token0;
86
+ const token1 = pools[poolAddress.toLowerCase()].token1;
87
+ let _state = context.relayer.getStaleState();
88
+ if (!_state) {
89
+ _state = await context.relayer.generateState(blockNumber);
90
+ context.relayer.setState(_state, blockNumber);
91
+ return;
92
+ }
93
+ else {
94
+ blockNumber = context.relayer.getStateBlockNumber();
95
+ }
96
+ const state = lodash_1.default.cloneDeep(_state);
97
+ if (amount1Out > 0n) {
98
+ state.tokens[token1].balance += amount1Out;
99
+ }
100
+ else {
101
+ state.tokens[token0].balance += amount0Out;
102
+ }
103
+ context.relayer.setState(state, blockNumber);
104
+ }
105
+ else {
106
+ context.logger.error('Integral Relayer: Pool address not found for', poolAddress);
107
+ }
108
+ }
109
+ }
110
+ exports.onPoolSwapForRelayer = onPoolSwapForRelayer;
111
+ function getPoolBackReferencedFrom(context, poolAddress) {
112
+ return Object.entries(context.pools).find(([, pool]) => pool.base?.poolAddress === poolAddress);
113
+ }
114
+ async function onRelayerPoolEnabledSet(poolAddress, state, blockNumber) {
115
+ const context = context_1.IntegralContext.getInstance();
116
+ const poolEntry = getPoolBackReferencedFrom(context, poolAddress);
117
+ if (state.isEnabled && (!poolEntry || !poolEntry[1].enabled)) {
118
+ const _factoryState = context.factory.getStaleState();
119
+ const factoryState = _factoryState
120
+ ? _factoryState
121
+ : await context.factory.generateState(blockNumber);
122
+ const { token0, token1 } = factoryState.pools[poolAddress];
123
+ await context.addPools({ [poolAddress]: { token0, token1 } }, blockNumber);
124
+ }
125
+ else if (!state.isEnabled && poolEntry && poolEntry[1].enabled) {
126
+ context.pools[poolEntry[0]].enabled = false;
127
+ }
128
+ }
129
+ exports.onRelayerPoolEnabledSet = onRelayerPoolEnabledSet;
130
+ function onRebalanceSellOrderExecuted(blockNumber, orderId) {
131
+ const context = context_1.IntegralContext.getInstance();
132
+ context.relayer.executeOrder(orderId, blockNumber);
133
+ }
134
+ exports.onRebalanceSellOrderExecuted = onRebalanceSellOrderExecuted;
135
+ async function onPoolCreatedAddPool(token0, token1, poolAddress, blockNumber) {
136
+ const context = context_1.IntegralContext.getInstance();
137
+ await context.addPools({ [poolAddress]: { token0, token1 } }, blockNumber);
138
+ }
139
+ exports.onPoolCreatedAddPool = onPoolCreatedAddPool;
140
+ async function onTransferUpdateBalance(token, from, to, amount, blockNumber, _context) {
141
+ const context = _context || context_1.IntegralContext.getInstance();
142
+ let _state = context.relayer.getStaleState();
143
+ if (!_state) {
144
+ context.logger.error('Integral Token: Relayer stale state not found');
145
+ return;
146
+ }
147
+ const state = lodash_1.default.cloneDeep(_state);
148
+ if (context.relayer.relayerAddress.toLowerCase() === from) {
149
+ state.tokens[token].balance -= amount;
150
+ }
151
+ else if (context.relayer.relayerAddress.toLowerCase() === to) {
152
+ state.tokens[token].balance += amount;
153
+ }
154
+ context.relayer.setState(state, blockNumber);
155
+ }
156
+ exports.onTransferUpdateBalance = onTransferUpdateBalance;
157
+ //# sourceMappingURL=helpers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../../src/dex/integral/helpers.ts"],"names":[],"mappings":";;;;;;AAAA,oDAAuB;AAEvB,uCAAuC;AACvC,mEAAgE;AAChE,+DAA4D;AAC5D,mEAAgE;AAEhE,uCAA4C;AAG5C,SAAgB,UAAU,CAAC,UAAmB,EAAE,WAAoB;IAClE,OAAO,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACpE,CAAC;AAFD,gCAEC;AAED,SAAgB,oBAAoB,CAClC,SAAiB,EACjB,SAAiB,EACjB,QAAiB;IAEjB,OAAO,CACL,GAAG;QACH,CAAC,GAAG,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,GAAG,SAAS,CAAC,CAAC,CAAC,SAAS,GAAG,SAAS,CAAC,CAAC,CACzE,CAAC;AACJ,CAAC;AATD,oDASC;AAED,SAAgB,QAAQ,CAAC,MAAkB,EAAE,QAAiB;IAC5D,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;IAC1C,MAAM,iBAAiB,GAAG,oBAAoB,CAC5C,IAAI,CAAC,S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M,OAAO,GAAG,QAAQ,IAAI,yBAAe,CAAC,WAAW,EAAE,CAAC;IAC1D,IAAI,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC;IAC7C,IAAI,CAAC,MAAM,EAAE;QACX,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,+CAA+C,CAAC,CAAC;QACtE,OAAO;KACR;IACD,MAAM,KAAK,GAAiB,gBAAC,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;IAChD,IAAI,OAAO,CAAC,OAAO,CAAC,cAAc,CAAC,WAAW,EAAE,KAAK,IAAI,EAAE;QACzD,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,OAAO,IAAI,MAAM,CAAC;KACvC;SAAM,IAAI,OAAO,CAAC,OAAO,CAAC,cAAc,CAAC,WAAW,EAAE,KAAK,EAAE,EAAE;QAC9D,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,OAAO,IAAI,MAAM,CAAC;KACvC;IACD,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;AAC/C,CAAC;AArBD,0DAqBC"}
@@ -0,0 +1,21 @@
1
+ import { Interface } from '@ethersproject/abi';
2
+ import { LogDescription } from 'ethers/lib/utils';
3
+ import { IDexHelper } from '../../dex-helper';
4
+ import { StatefulEventSubscriber } from '../../stateful-event-subscriber';
5
+ import { Address, BlockHeader, Log, Logger } from '../../types';
6
+ import { FactoryState } from './types';
7
+ export declare type OnPoolCreatedCallback = (token0: Address, token1: Address, poolAddress: Address, blockNumber: number) => Promise<void>;
8
+ export declare class IntegralFactory extends StatefulEventSubscriber<FactoryState> {
9
+ readonly dexHelper: IDexHelper;
10
+ protected readonly factoryAddress: Address;
11
+ protected readonly onPoolCreated: OnPoolCreatedCallback;
12
+ handlers: {
13
+ [event: string]: (event: any, state: FactoryState, blockHeader: Readonly<BlockHeader>) => Promise<FactoryState>;
14
+ };
15
+ logDecoder: (log: Log) => any;
16
+ readonly factoryIface: Interface;
17
+ constructor(dexHelper: IDexHelper, parentName: string, factoryAddress: Address, onPoolCreated: OnPoolCreatedCallback, logger: Logger, mapKey?: string);
18
+ generateState(blockNumber?: number | 'latest'): Promise<FactoryState>;
19
+ protected processLog(state: FactoryState, log: Readonly<Log>, blockHeader: Readonly<BlockHeader>): Promise<FactoryState>;
20
+ handlePairCreated(event: LogDescription, state: FactoryState, blockHeader: Readonly<BlockHeader>): Promise<FactoryState>;
21
+ }
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.IntegralFactory = void 0;
7
+ const abi_1 = require("@ethersproject/abi");
8
+ const stateful_event_subscriber_1 = require("../../stateful-event-subscriber");
9
+ const factory_json_1 = __importDefault(require("../../abi/integral/factory.json"));
10
+ const pool_json_1 = __importDefault(require("../../abi/integral/pool.json"));
11
+ const decoders_1 = require("../../lib/decoders");
12
+ class IntegralFactory extends stateful_event_subscriber_1.StatefulEventSubscriber {
13
+ constructor(dexHelper, parentName, factoryAddress, onPoolCreated, logger, mapKey = '') {
14
+ super(parentName, `${parentName} Factory`, dexHelper, logger, true, mapKey);
15
+ this.dexHelper = dexHelper;
16
+ this.factoryAddress = factoryAddress;
17
+ this.onPoolCreated = onPoolCreated;
18
+ this.handlers = {};
19
+ this.factoryIface = new abi_1.Interface(factory_json_1.default);
20
+ this.addressesSubscribed = [factoryAddress];
21
+ this.logDecoder = (log) => this.factoryIface.parseLog(log);
22
+ this.handlers['PairCreated'] = this.handlePairCreated.bind(this);
23
+ }
24
+ async generateState(blockNumber) {
25
+ const factory = new this.dexHelper.web3Provider.eth.Contract(factory_json_1.default, this.factoryAddress);
26
+ const poolCountResult = await factory.methods
27
+ .allPairsLength()
28
+ .call(undefined, blockNumber);
29
+ const poolCount = Number(poolCountResult);
30
+ const poolAddressCallDatas = [
31
+ ...Array(poolCount),
32
+ ].map((_, i) => {
33
+ return {
34
+ target: this.factoryAddress,
35
+ callData: factory.methods.allPairs(i).encodeABI(),
36
+ decodeFunction: decoders_1.addressDecode,
37
+ };
38
+ });
39
+ const poolAddresses = await this.dexHelper.multiWrapper.tryAggregate(false, poolAddressCallDatas, blockNumber, this.dexHelper.multiWrapper.defaultBatchSize, false);
40
+ const poolIface = new abi_1.Interface(pool_json_1.default);
41
+ const poolInfosCallDatas = poolAddresses
42
+ .map(poolAddress => {
43
+ return [
44
+ {
45
+ target: poolAddress.returnData,
46
+ callData: poolIface.encodeFunctionData('token0', []),
47
+ decodeFunction: decoders_1.addressDecode,
48
+ },
49
+ {
50
+ target: poolAddress.returnData,
51
+ callData: poolIface.encodeFunctionData('token1', []),
52
+ decodeFunction: decoders_1.addressDecode,
53
+ },
54
+ ];
55
+ })
56
+ .flat();
57
+ const poolInfos = await this.dexHelper.multiWrapper.aggregate(poolInfosCallDatas, blockNumber);
58
+ const state = { pools: {} };
59
+ poolAddresses.forEach((poolAddress, i) => {
60
+ const tokens = [
61
+ poolInfos[i * 2].toLowerCase(),
62
+ poolInfos[i * 2 + 1].toLowerCase(),
63
+ ];
64
+ state.pools[poolAddress.returnData.toLowerCase()] = {
65
+ token0: tokens[0],
66
+ token1: tokens[1],
67
+ };
68
+ });
69
+ return state;
70
+ }
71
+ async processLog(state, log, blockHeader) {
72
+ const event = this.logDecoder(log);
73
+ if (event.name in this.handlers) {
74
+ return await this.handlers[event.name](event, state, blockHeader);
75
+ }
76
+ return state;
77
+ }
78
+ async handlePairCreated(event, state, blockHeader) {
79
+ const tokens = [
80
+ event.args.token0.toLowerCase(),
81
+ event.args.token1.toLowerCase(),
82
+ ];
83
+ state.pools[event.args.pair.toLowerCase()] = {
84
+ token0: tokens[0],
85
+ token1: tokens[1],
86
+ };
87
+ await this.onPoolCreated(tokens[0], tokens[1], event.args.pair.toLowerCase(), blockHeader.number);
88
+ return state;
89
+ }
90
+ }
91
+ exports.IntegralFactory = IntegralFactory;
92
+ //# sourceMappingURL=integral-factory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"integral-factory.js","sourceRoot":"","sources":["../../../src/dex/integral/integral-factory.ts"],"names":[],"mappings":";;;;;;AAAA,4CAA+C;AAG/C,+EAA0E;AAG1E,mFAAiE;AACjE,6EAA2D;AAC3D,iDAAmD;AAUnD,MAAa,eAAgB,SAAQ,mDAAqC;IAaxE,YACW,SAAqB,EAC9B,UAAkB,EACC,cAAuB,EACvB,aAAoC,EACvD,MAAc,EACd,SAAiB,EAAE;QAEnB,KAAK,CAAC,UAAU,EAAE,GAAG,UAAU,UAAU,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;QAPnE,cAAS,GAAT,SAAS,CAAY;QAEX,mBAAc,GAAd,cAAc,CAAS;QACvB,kBAAa,GAAb,aAAa,CAAuB;QAhBzD,aAAQ,GAMJ,EAAE,CAAC;QAIS,iBAAY,GAAG,IAAI,eAAS,CAAC,sBAAkB,CAAC,CAAC;QAY/D,IAAI,CAAC,mBAAmB,GAAG,CAAC,cAAc,CAAC,CAAC;QAE5C,IAAI,CAAC,UAAU,GAAG,CAAC,GAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;QAEhE,IAAI,CAAC,QAAQ,CAAC,aAAa,CAAC,GAAG,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACnE,CAAC;IAED,KAAK,CAAC,aAAa,CAAC,WAA+B;QACjD,MAAM,OAAO,GAAG,IAAI,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC,GAAG,CAAC,QAAQ,CAC1D,sBAAyB,EACzB,IAAI,CAAC,cAAc,CACpB,CAAC;QACF,MAAM,eAAe,GAAG,MAAM,OAAO,CAAC,OAAO;aAC1C,cAAc,EAAE;aAChB,IAAI,CAAC,SAAS,EAAE,WA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;QACF,MAAM,IAAI,CAAC,aAAa,CACtB,MAAM,CAAC,CAAC,CAAC,EACT,MAAM,CAAC,CAAC,CAAC,EACT,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,EAC7B,WAAW,CAAC,MAAM,CACnB,CAAC;QACF,OAAO,KAAK,CAAC;IACf,CAAC;CACF;AA/HD,0CA+HC"}
@@ -0,0 +1,46 @@
1
+ import { Interface } from '@ethersproject/abi';
2
+ import { LogDescription } from 'ethers/lib/utils';
3
+ import { AsyncOrSync } from 'ts-essentials';
4
+ import { BlockHeader, Log, Logger } from '../../types';
5
+ import { StatefulEventSubscriber } from '../../stateful-event-subscriber';
6
+ import { IDexHelper } from '../../dex-helper/idex-helper';
7
+ import { PoolState } from './types';
8
+ import { Address } from '../../types';
9
+ export declare class IntegralEventPool extends StatefulEventSubscriber<PoolState> {
10
+ parentName: string;
11
+ protected network: number;
12
+ protected dexHelper: IDexHelper;
13
+ protected poolIface: Interface;
14
+ handlers: {
15
+ [event: string]: (event: any, pool: PoolState, blockHeader: Readonly<BlockHeader>) => AsyncOrSync<PoolState>;
16
+ };
17
+ logDecoder: (log: Log) => any;
18
+ addressesSubscribed: string[];
19
+ readonly poolAddress: Address;
20
+ readonly token0: Address;
21
+ readonly token1: Address;
22
+ constructor(parentName: string, network: number, dexHelper: IDexHelper, poolAddress: Address, token0: Address, token1: Address, logger: Logger, poolIface?: Interface);
23
+ /**
24
+ * The function is called every time any of the subscribed
25
+ * addresses release log. The function accepts the current
26
+ * state, updates the state according to the log, and returns
27
+ * the updated state.
28
+ * @param state - Current state of event subscriber
29
+ * @param log - Log released by one of the subscribed addresses
30
+ * @returns Updates state of the event subscriber after the log
31
+ */
32
+ protected processLog(state: PoolState, log: Readonly<Log>, blockHeader: Readonly<BlockHeader>): Promise<PoolState | null>;
33
+ /**
34
+ * The function generates state using on-chain calls. This
35
+ * function is called to regenerate state if the event based
36
+ * system fails to fetch events and the local state is no
37
+ * more correct.
38
+ * @param blockNumber - Blocknumber for which the state should
39
+ * should be generated
40
+ * @returns state of the event subscriber at blocknumber
41
+ */
42
+ generateState(blockNumber: number): Promise<Readonly<PoolState>>;
43
+ handleSetSwapFee(event: LogDescription, pool: PoolState): PoolState;
44
+ handleSetMintFee(event: LogDescription, pool: PoolState): PoolState;
45
+ handleSetBurnFee(event: LogDescription, pool: PoolState): PoolState;
46
+ }
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.IntegralEventPool = void 0;
7
+ const abi_1 = require("@ethersproject/abi");
8
+ const stateful_event_subscriber_1 = require("../../stateful-event-subscriber");
9
+ const pool_json_1 = __importDefault(require("../../abi/integral/pool.json"));
10
+ const oracle_json_1 = __importDefault(require("../../abi/integral/oracle.json"));
11
+ const UniswapV3Pool_abi_json_1 = __importDefault(require("../../abi/uniswap-v3/UniswapV3Pool.abi.json"));
12
+ const decoders_1 = require("../../lib/decoders");
13
+ const ethers_1 = require("ethers");
14
+ class IntegralEventPool extends stateful_event_subscriber_1.StatefulEventSubscriber {
15
+ constructor(parentName, network, dexHelper, poolAddress, token0, token1, logger, poolIface = new abi_1.Interface(pool_json_1.default)) {
16
+ super(parentName, `${token0}_${token1}`, dexHelper, logger);
17
+ this.parentName = parentName;
18
+ this.network = network;
19
+ this.dexHelper = dexHelper;
20
+ this.poolIface = poolIface;
21
+ this.handlers = {};
22
+ this.token0 = token0.toLowerCase();
23
+ this.token1 = token1.toLowerCase();
24
+ this.poolAddress = poolAddress.toLowerCase();
25
+ this.logDecoder = (log) => this.poolIface.parseLog(log);
26
+ this.addressesSubscribed = [this.poolAddress];
27
+ this.handlers['SetSwapFee'] = this.handleSetSwapFee.bind(this);
28
+ this.handlers['SetMintFee'] = this.handleSetMintFee.bind(this);
29
+ this.handlers['SetBurnFee'] = this.handleSetBurnFee.bind(this);
30
+ }
31
+ /**
32
+ * The function is called every time any of the subscribed
33
+ * addresses release log. The function accepts the current
34
+ * state, updates the state according to the log, and returns
35
+ * the updated state.
36
+ * @param state - Current state of event subscriber
37
+ * @param log - Log released by one of the subscribed addresses
38
+ * @returns Updates state of the event subscriber after the log
39
+ */
40
+ async processLog(state, log, blockHeader) {
41
+ try {
42
+ const event = this.logDecoder(log);
43
+ if (event.name in this.handlers) {
44
+ return await this.handlers[event.name](event, state, blockHeader);
45
+ }
46
+ return state;
47
+ }
48
+ catch (e) {
49
+ this.logger.error(`Error_${this.parentName}_processLog could not parse the log with topic ${log.topics}:`, e);
50
+ return null;
51
+ }
52
+ }
53
+ /**
54
+ * The function generates state using on-chain calls. This
55
+ * function is called to regenerate state if the event based
56
+ * system fails to fetch events and the local state is no
57
+ * more correct.
58
+ * @param blockNumber - Blocknumber for which the state should
59
+ * should be generated
60
+ * @returns state of the event subscriber at blocknumber
61
+ */
62
+ async generateState(blockNumber) {
63
+ const state = {};
64
+ const pool = new this.dexHelper.web3Provider.eth.Contract(pool_json_1.default, this.poolAddress);
65
+ const poolInfoCallDatas = [
66
+ {
67
+ target: this.poolAddress,
68
+ callData: pool.methods.oracle().encodeABI(),
69
+ decodeFunction: decoders_1.addressDecode,
70
+ },
71
+ {
72
+ target: this.poolAddress,
73
+ callData: pool.methods.mintFee().encodeABI(),
74
+ decodeFunction: decoders_1.uint256ToBigInt,
75
+ },
76
+ {
77
+ target: this.poolAddress,
78
+ callData: pool.methods.burnFee().encodeABI(),
79
+ decodeFunction: decoders_1.uint256ToBigInt,
80
+ },
81
+ {
82
+ target: this.poolAddress,
83
+ callData: pool.methods.swapFee().encodeABI(),
84
+ decodeFunction: decoders_1.uint256ToBigInt,
85
+ },
86
+ ];
87
+ const poolInfos = await this.dexHelper.multiWrapper.aggregate(poolInfoCallDatas, blockNumber);
88
+ const oracleAddress = poolInfos[0].toString();
89
+ state.mintFee = BigInt(poolInfos[1]);
90
+ state.burnFee = BigInt(poolInfos[2]);
91
+ state.swapFee = BigInt(poolInfos[3]);
92
+ state.oracle = oracleAddress;
93
+ const historyState = this.getStaleState();
94
+ if (!historyState) {
95
+ const oracle = new this.dexHelper.web3Provider.eth.Contract(oracle_json_1.default, oracleAddress);
96
+ const oracleInfosCallDatas = [
97
+ {
98
+ target: oracleAddress,
99
+ callData: oracle.methods.xDecimals().encodeABI(),
100
+ decodeFunction: decoders_1.uint8ToNumber,
101
+ },
102
+ {
103
+ target: oracleAddress,
104
+ callData: oracle.methods.yDecimals().encodeABI(),
105
+ decodeFunction: decoders_1.uint8ToNumber,
106
+ },
107
+ {
108
+ target: oracleAddress,
109
+ callData: oracle.methods.uniswapPair().encodeABI(),
110
+ decodeFunction: decoders_1.addressDecode,
111
+ },
112
+ ];
113
+ const oracleInfos = await this.dexHelper.multiWrapper.aggregate(oracleInfosCallDatas, blockNumber);
114
+ state.uniswapPool = oracleInfos[2].toString();
115
+ state.decimals0 = Number(oracleInfos[0]);
116
+ state.decimals1 = Number(oracleInfos[1]);
117
+ const uniswapPool = new this.dexHelper.web3Provider.eth.Contract(UniswapV3Pool_abi_json_1.default, state.uniswapPool);
118
+ const fee = await uniswapPool.methods.fee().call(undefined, blockNumber);
119
+ state.uniswapPoolFee = BigInt(fee);
120
+ }
121
+ else {
122
+ state.uniswapPool = historyState.uniswapPool;
123
+ state.decimals0 = historyState.decimals0;
124
+ state.decimals1 = historyState.decimals1;
125
+ state.uniswapPoolFee = historyState.uniswapPoolFee;
126
+ }
127
+ return state;
128
+ }
129
+ handleSetSwapFee(event, pool) {
130
+ pool.swapFee = BigInt(ethers_1.BigNumber.from(event.args.fee).toString());
131
+ return pool;
132
+ }
133
+ handleSetMintFee(event, pool) {
134
+ pool.mintFee = BigInt(ethers_1.BigNumber.from(event.args.fee).toString());
135
+ return pool;
136
+ }
137
+ handleSetBurnFee(event, pool) {
138
+ pool.burnFee = BigInt(ethers_1.BigNumber.from(event.args.fee).toString());
139
+ return pool;
140
+ }
141
+ }
142
+ exports.IntegralEventPool = IntegralEventPool;
143
+ //# sourceMappingURL=integral-pool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"integral-pool.js","sourceRoot":"","sources":["../../../src/dex/integral/integral-pool.ts"],"names":[],"mappings":";;;;;;AACA,4CAA+C;AAI/C,+EAA0E;AAG1E,6EAA2D;AAC3D,iFAA+D;AAC/D,yGAA2E;AAG3E,iDAI4B;AAE5B,mCAAmC;AAEnC,MAAa,iBAAkB,SAAQ,mDAAkC;IAiBvE,YACS,UAAkB,EACf,OAAe,EACf,SAAqB,EAC/B,WAAoB,EACpB,MAAe,EACf,MAAe,EACf,MAAc,EACJ,YAAY,IAAI,eAAS,CAAC,mBAAe,CAAC;QAEpD,KAAK,CAAC,UAAU,EAAE,GAAG,MAAM,IAAI,MAAM,EAAE,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;QATrD,eAAU,GAAV,UAAU,CAAQ;QACf,YAAO,GAAP,OAAO,CAAQ;QACf,cAAS,GAAT,SAAS,CAAY;QAKrB,cAAS,GAAT,SAAS,CAAiC;QAxBtD,aAAQ,GAMJ,EAAE,CAAC;QAqBL,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,WAAW,EAAE,CAAC;QACnC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,WAAW,EAAE,CAAC;QACnC,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC,WAAW,EAAE,CAAC;QAE7C,IAAI,CAAC,UAAU,GAAG,CAAC,GAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;QAC7D,IAAI,CAAC,mBAAmB,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QAC9C,IAAI,CAAC,QAAQ,CAAC,YAAY,CAAC,GAAG,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC/D,IAAI,CAAC,QAAQ,CAAC,YAAY,CAAC,GAAG,IAAI,C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AI,CAAC,OAAO,GAAG,MAAM,CAAC,kBAAS,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC;QACjE,OAAO,IAAI,CAAC;IACd,CAAC;IAED,gBAAgB,CAAC,KAAqB,EAAE,IAAe;QACrD,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,kBAAS,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC;QACjE,OAAO,IAAI,CAAC;IACd,CAAC;IAED,gBAAgB,CAAC,KAAqB,EAAE,IAAe;QACrD,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,kBAAS,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC;QACjE,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAhLD,8CAgLC"}
@@ -0,0 +1,18 @@
1
+ import { Interface } from '@ethersproject/abi';
2
+ import { IDexHelper } from '../../dex-helper';
3
+ import { Address, Logger } from '../../types';
4
+ import { UniswapV3EventPool } from '../uniswap-v3/uniswap-v3-pool';
5
+ import { Network } from '../../constants';
6
+ import { PoolState } from '../uniswap-v3/types';
7
+ import { Observation } from './types';
8
+ import { MultiResult } from '../../lib/multi-wrapper';
9
+ import { BytesLike } from 'ethers';
10
+ export declare function decodeStateMultiCallResultWithObservation(result: MultiResult<BytesLike> | BytesLike): Observation;
11
+ export declare class IntegralPricing extends UniswapV3EventPool {
12
+ readonly dexHelper: IDexHelper;
13
+ private readonly providedPoolAddress;
14
+ constructor(dexHelper: IDexHelper, parentName: string, erc20Interface: Interface, poolAddress: Address, token0: Address, token1: Address, feeCode: bigint, logger: Logger, network: Network, mapKey?: string);
15
+ get poolAddress(): Address;
16
+ set poolAddress(_address: Address);
17
+ generateState(blockNumber: number): Promise<Readonly<PoolState>>;
18
+ }
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.IntegralPricing = exports.decodeStateMultiCallResultWithObservation = void 0;
7
+ const uniswap_v3_pool_1 = require("../uniswap-v3/uniswap-v3-pool");
8
+ const config_1 = require("../uniswap-v3/config");
9
+ const UniswapV3StateMulticall_abi_json_1 = __importDefault(require("../../abi/uniswap-v3/UniswapV3StateMulticall.abi.json"));
10
+ const utils_1 = require("../uniswap-v3/contract-math/utils");
11
+ const utils_2 = require("../../utils");
12
+ const TickBitMap_1 = require("../uniswap-v3/contract-math/TickBitMap");
13
+ const ethers_1 = require("ethers");
14
+ const decoders_1 = require("../../lib/decoders");
15
+ function decodeStateMultiCallResultWithObservation(result) {
16
+ const [isSuccess, toDecode] = (0, decoders_1.extractSuccessAndValue)(result);
17
+ if (!isSuccess || toDecode === '0x')
18
+ throw new Error(`decodeStateMultiCallResultWithRelativeBitmaps failed to get decodable result: ${result}`);
19
+ const decoded = ethers_1.ethers.utils.defaultAbiCoder.decode([
20
+ `
21
+ tuple(
22
+ uint32 blockTimestamp,
23
+ int56 tickCumulative,
24
+ uint160 secondsPerLiquidityCumulativeX128,
25
+ bool initialized,
26
+ )
27
+ `,
28
+ ], toDecode)[0];
29
+ return decoded;
30
+ }
31
+ exports.decodeStateMultiCallResultWithObservation = decodeStateMultiCallResultWithObservation;
32
+ class IntegralPricing extends uniswap_v3_pool_1.UniswapV3EventPool {
33
+ constructor(dexHelper, parentName, erc20Interface, poolAddress, token0, token1, feeCode, logger, network, mapKey = '') {
34
+ const uniswapConfig = config_1.UniswapV3Config['UniswapV3'][network];
35
+ const stateMultiContract = new dexHelper.web3Provider.eth.Contract(uniswapConfig.stateMultiCallAbi !== undefined
36
+ ? uniswapConfig.stateMultiCallAbi
37
+ : UniswapV3StateMulticall_abi_json_1.default, uniswapConfig.stateMulticall);
38
+ super(dexHelper, parentName, stateMultiContract, undefined, erc20Interface, uniswapConfig.factory, feeCode, token0, token1, logger, mapKey, uniswapConfig.initHash);
39
+ this.dexHelper = dexHelper;
40
+ this.providedPoolAddress = poolAddress;
41
+ }
42
+ get poolAddress() {
43
+ return this.providedPoolAddress;
44
+ }
45
+ set poolAddress(_address) { }
46
+ async generateState(blockNumber) {
47
+ const callData = this._getStateRequestCallData();
48
+ const [resBalance0, resBalance1, resState] = await this.dexHelper.multiWrapper.tryAggregate(false, callData, blockNumber, this.dexHelper.multiWrapper.defaultBatchSize, false);
49
+ if (!resState.success)
50
+ throw new Error('Pool does not exist');
51
+ const [balance0, balance1, _state] = [
52
+ resBalance0.returnData,
53
+ resBalance1.returnData,
54
+ resState.returnData,
55
+ ];
56
+ const observationsCallData = [
57
+ ...Array(_state.slot0.observationCardinality),
58
+ ].map((_, i) => {
59
+ return {
60
+ target: this.poolAddress,
61
+ callData: this.poolIface.encodeFunctionData('observations', [i]),
62
+ decodeFunction: decodeStateMultiCallResultWithObservation,
63
+ };
64
+ });
65
+ const resObservations = await this.dexHelper.multiWrapper.tryAggregate(false, observationsCallData, blockNumber, 13107, false);
66
+ const observations = resObservations.reduce((memo, obs, i) => {
67
+ memo[i] = {
68
+ blockTimestamp: BigInt(obs.returnData.blockTimestamp),
69
+ tickCumulative: BigInt(obs.returnData.tickCumulative.toString()),
70
+ secondsPerLiquidityCumulativeX128: BigInt(obs.returnData.secondsPerLiquidityCumulativeX128.toString()),
71
+ initialized: obs.returnData.initialized,
72
+ };
73
+ return memo;
74
+ }, {});
75
+ const tickBitmap = {};
76
+ const ticks = {};
77
+ (0, utils_1._reduceTickBitmap)(tickBitmap, _state.tickBitmap);
78
+ (0, utils_1._reduceTicks)(ticks, _state.ticks);
79
+ const currentTick = (0, utils_2.bigIntify)(_state.slot0.tick);
80
+ const tickSpacing = (0, utils_2.bigIntify)(_state.tickSpacing);
81
+ const startTickBitmap = TickBitMap_1.TickBitMap.position(currentTick / tickSpacing)[0];
82
+ const requestedRange = this.getBitmapRangeToRequest();
83
+ return {
84
+ pool: _state.pool,
85
+ blockTimestamp: (0, utils_2.bigIntify)(_state.blockTimestamp),
86
+ slot0: {
87
+ sqrtPriceX96: (0, utils_2.bigIntify)(_state.slot0.sqrtPriceX96),
88
+ tick: currentTick,
89
+ observationIndex: +_state.slot0.observationIndex,
90
+ observationCardinality: +_state.slot0.observationCardinality,
91
+ observationCardinalityNext: +_state.slot0.observationCardinalityNext,
92
+ feeProtocol: (0, utils_2.bigIntify)(_state.slot0.feeProtocol),
93
+ },
94
+ liquidity: (0, utils_2.bigIntify)(_state.liquidity),
95
+ fee: this.feeCode,
96
+ tickSpacing,
97
+ maxLiquidityPerTick: (0, utils_2.bigIntify)(_state.maxLiquidityPerTick),
98
+ tickBitmap,
99
+ ticks,
100
+ observations,
101
+ isValid: true,
102
+ startTickBitmap,
103
+ lowestKnownTick: (BigInt.asIntN(24, startTickBitmap - requestedRange) << 8n) *
104
+ tickSpacing,
105
+ highestKnownTick: ((BigInt.asIntN(24, startTickBitmap + requestedRange) << 8n) +
106
+ BigInt.asIntN(24, 255n)) *
107
+ tickSpacing,
108
+ balance0,
109
+ balance1,
110
+ };
111
+ }
112
+ }
113
+ exports.IntegralPricing = IntegralPricing;
114
+ //# sourceMappingURL=integral-pricing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"integral-pricing.js","sourceRoot":"","sources":["../../../src/dex/integral/integral-pricing.ts"],"names":[],"mappings":";;;;;;AAGA,mEAAmE;AACnE,iDAAuD;AACvD,6HAA+F;AAQ/F,6DAG2C;AAC3C,uCAAwC;AACxC,uEAAoE;AAGpE,mCAA2C;AAC3C,iDAA4D;AAE5D,SAAgB,yCAAyC,CACvD,MAA0C;IAE1C,MAAM,CAAC,SAAS,EAAE,QAAQ,CAAC,GAAG,IAAA,iCAAsB,EAAC,MAAM,CAAC,CAAC;IAE7D,IAAI,CAAC,SAAS,IAAI,QAAQ,KAAK,IAAI;QACjC,MAAM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