@paraswap/dex-lib 3.8.13 → 3.8.15

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 (287) hide show
  1. package/.vscode/launch.json +16 -0
  2. package/.vscode/settings.json +3 -0
  3. package/build/abi/Uncompressor.json +250 -0
  4. package/build/abi/concentrator/arUSD5115.json +1746 -0
  5. package/build/abi/fx-protocol/FxMarket.json +1284 -0
  6. package/build/abi/fx-protocol/weETHOralce.json +676 -0
  7. package/build/abi/integral/factory.json +333 -0
  8. package/build/abi/integral/oracle.json +501 -0
  9. package/build/abi/{inception/inception-ineth-pool.json → integral/pool.json} +522 -543
  10. package/build/abi/integral/relayer.json +1536 -0
  11. package/build/abi/maverick-v2/MaverickV2Router.json +778 -0
  12. package/build/dex/aave-v1/aave-v1.d.ts +1 -2
  13. package/build/dex/aave-v1/aave-v1.js +0 -22
  14. package/build/dex/aave-v1/aave-v1.js.map +1 -1
  15. package/build/dex/bProtocol.d.ts +18 -0
  16. package/build/dex/bProtocol.js +39 -0
  17. package/build/dex/bProtocol.js.map +1 -0
  18. package/build/dex/bancor.d.ts +26 -0
  19. package/build/dex/bancor.js +58 -0
  20. package/build/dex/bancor.js.map +1 -0
  21. package/build/dex/compound.d.ts +18 -0
  22. package/build/dex/compound.js +46 -0
  23. package/build/dex/compound.js.map +1 -0
  24. package/build/dex/concentrator-arusd/concentrator-arusd-event.d.ts +17 -0
  25. package/build/dex/concentrator-arusd/concentrator-arusd-event.js +66 -0
  26. package/build/dex/concentrator-arusd/concentrator-arusd-event.js.map +1 -0
  27. package/build/dex/concentrator-arusd/concentrator-arusd.d.ts +6 -3
  28. package/build/dex/concentrator-arusd/concentrator-arusd.js +45 -41
  29. package/build/dex/concentrator-arusd/concentrator-arusd.js.map +1 -1
  30. package/build/dex/concentrator-arusd/config.d.ts +1 -2
  31. package/build/dex/concentrator-arusd/config.js +2 -6
  32. package/build/dex/concentrator-arusd/config.js.map +1 -1
  33. package/build/dex/concentrator-arusd/types.d.ts +7 -3
  34. package/build/dex/concentrator-arusd/utils.d.ts +4 -0
  35. package/build/dex/concentrator-arusd/utils.js +27 -0
  36. package/build/dex/concentrator-arusd/utils.js.map +1 -0
  37. package/build/dex/curve-v2.d.ts +58 -0
  38. package/build/dex/curve-v2.js +180 -0
  39. package/build/dex/curve-v2.js.map +1 -0
  40. package/build/dex/dodo-v1.d.ts +33 -0
  41. package/build/dex/dodo-v1.js +63 -0
  42. package/build/dex/dodo-v1.js.map +1 -0
  43. package/build/dex/etherfi/etherfi.d.ts +26 -0
  44. package/build/dex/etherfi/etherfi.js +96 -0
  45. package/build/dex/etherfi/etherfi.js.map +1 -0
  46. package/build/dex/fx-protocol-rusd/config.d.ts +1 -2
  47. package/build/dex/fx-protocol-rusd/config.js +3 -6
  48. package/build/dex/fx-protocol-rusd/config.js.map +1 -1
  49. package/build/dex/fx-protocol-rusd/fx-protocol-rusd-event.d.ts +18 -0
  50. package/build/dex/fx-protocol-rusd/fx-protocol-rusd-event.js +71 -0
  51. package/build/dex/fx-protocol-rusd/fx-protocol-rusd-event.js.map +1 -0
  52. package/build/dex/fx-protocol-rusd/fx-protocol-rusd.d.ts +10 -10
  53. package/build/dex/fx-protocol-rusd/fx-protocol-rusd.js +75 -70
  54. package/build/dex/fx-protocol-rusd/fx-protocol-rusd.js.map +1 -1
  55. package/build/dex/fx-protocol-rusd/types.d.ts +6 -3
  56. package/build/dex/fx-protocol-rusd/utils.d.ts +4 -0
  57. package/build/dex/fx-protocol-rusd/utils.js +26 -0
  58. package/build/dex/fx-protocol-rusd/utils.js.map +1 -0
  59. package/build/dex/index.js +4 -0
  60. package/build/dex/index.js.map +1 -1
  61. package/build/dex/{infusion → integral}/config.d.ts +1 -1
  62. package/build/dex/integral/config.js +20 -0
  63. package/build/dex/integral/config.js.map +1 -0
  64. package/build/dex/integral/context.d.ts +40 -0
  65. package/build/dex/integral/context.js +158 -0
  66. package/build/dex/integral/context.js.map +1 -0
  67. package/build/dex/integral/helpers.d.ts +17 -0
  68. package/build/dex/integral/helpers.js +157 -0
  69. package/build/dex/integral/helpers.js.map +1 -0
  70. package/build/dex/integral/integral-factory.d.ts +24 -0
  71. package/build/dex/integral/integral-factory.js +95 -0
  72. package/build/dex/integral/integral-factory.js.map +1 -0
  73. package/build/dex/integral/integral-pool.d.ts +50 -0
  74. package/build/dex/integral/integral-pool.js +149 -0
  75. package/build/dex/integral/integral-pool.js.map +1 -0
  76. package/build/dex/integral/integral-pricing.d.ts +18 -0
  77. package/build/dex/integral/integral-pricing.js +114 -0
  78. package/build/dex/integral/integral-pricing.js.map +1 -0
  79. package/build/dex/integral/integral-relayer.d.ts +42 -0
  80. package/build/dex/integral/integral-relayer.js +192 -0
  81. package/build/dex/integral/integral-relayer.js.map +1 -0
  82. package/build/dex/integral/integral-token.d.ts +27 -0
  83. package/build/dex/integral/integral-token.js +59 -0
  84. package/build/dex/integral/integral-token.js.map +1 -0
  85. package/build/dex/{inception/inception-native.d.ts → integral/integral.d.ts} +19 -21
  86. package/build/dex/integral/integral.js +377 -0
  87. package/build/dex/integral/integral.js.map +1 -0
  88. package/build/dex/integral/types.d.ts +84 -0
  89. package/build/dex/integral/types.js +9 -0
  90. package/build/dex/integral/types.js.map +1 -0
  91. package/build/dex/integral/utils-e2e.d.ts +9 -0
  92. package/build/dex/integral/utils-e2e.js +131 -0
  93. package/build/dex/integral/utils-e2e.js.map +1 -0
  94. package/build/dex/integral/utils.d.ts +17 -0
  95. package/build/dex/integral/utils.js +94 -0
  96. package/build/dex/integral/utils.js.map +1 -0
  97. package/build/dex/lido.d.ts +19 -0
  98. package/build/dex/lido.js +42 -0
  99. package/build/dex/lido.js.map +1 -0
  100. package/build/dex/onebit.d.ts +25 -0
  101. package/build/dex/onebit.js +42 -0
  102. package/build/dex/onebit.js.map +1 -0
  103. package/build/dex/oswap/oswap.js +4 -1
  104. package/build/dex/oswap/oswap.js.map +1 -1
  105. package/build/dex/platypus/platypus.d.ts +1 -2
  106. package/build/dex/platypus/platypus.js +0 -31
  107. package/build/dex/platypus/platypus.js.map +1 -1
  108. package/build/dex/sdai/config.d.ts +11 -0
  109. package/build/dex/sdai/config.js +21 -0
  110. package/build/dex/sdai/config.js.map +1 -0
  111. package/build/dex/sdai/constants.d.ts +2 -0
  112. package/build/dex/sdai/constants.js +6 -0
  113. package/build/dex/sdai/constants.js.map +1 -0
  114. package/build/dex/sdai/scripts/validate-state.d.ts +1 -0
  115. package/build/dex/sdai/scripts/validate-state.js +102 -0
  116. package/build/dex/sdai/scripts/validate-state.js.map +1 -0
  117. package/build/dex/sdai/sdai-pool.d.ts +16 -0
  118. package/build/dex/sdai/sdai-pool.js +85 -0
  119. package/build/dex/sdai/sdai-pool.js.map +1 -0
  120. package/build/dex/sdai/sdai.d.ts +51 -0
  121. package/build/dex/sdai/sdai.js +172 -0
  122. package/build/dex/sdai/sdai.js.map +1 -0
  123. package/build/dex/sdai/types.d.ts +21 -0
  124. package/build/dex/sdai/types.js +11 -0
  125. package/build/dex/sdai/types.js.map +1 -0
  126. package/build/dex/sdai/utils.d.ts +4 -0
  127. package/build/dex/sdai/utils.js +39 -0
  128. package/build/dex/sdai/utils.js.map +1 -0
  129. package/build/dex/smoothy.d.ts +26 -0
  130. package/build/dex/smoothy.js +48 -0
  131. package/build/dex/smoothy.js.map +1 -0
  132. package/build/dex/stable-pool.d.ts +28 -0
  133. package/build/dex/stable-pool.js +62 -0
  134. package/build/dex/stable-pool.js.map +1 -0
  135. package/build/dex/swaap-v1/swaap-v1.d.ts +1 -2
  136. package/build/dex/swaap-v1/swaap-v1.js +0 -10
  137. package/build/dex/swaap-v1/swaap-v1.js.map +1 -1
  138. package/build/dex/trader-joe-v2.1.d.ts +43 -0
  139. package/build/dex/trader-joe-v2.1.js +79 -0
  140. package/build/dex/trader-joe-v2.1.js.map +1 -0
  141. package/build/executor/Executor01BytecodeBuilder.js +4 -5
  142. package/build/executor/Executor01BytecodeBuilder.js.map +1 -1
  143. package/build/executor/Executor02BytecodeBuilder.js +2 -3
  144. package/build/executor/Executor02BytecodeBuilder.js.map +1 -1
  145. package/build/executor/Executor03BytecodeBuilder.js +24 -14
  146. package/build/executor/Executor03BytecodeBuilder.js.map +1 -1
  147. package/build/executor/compressor/Compressor.d.ts +23 -0
  148. package/build/executor/compressor/Compressor.js +144 -0
  149. package/build/executor/compressor/Compressor.js.map +1 -0
  150. package/build/executor/compressor/compress.d.ts +17 -0
  151. package/build/executor/compressor/compress.js +187 -0
  152. package/build/executor/compressor/compress.js.map +1 -0
  153. package/build/executor/compressor/compress_functions/addressSubstitution.d.ts +6 -0
  154. package/build/executor/compressor/compress_functions/addressSubstitution.js +29 -0
  155. package/build/executor/compressor/compress_functions/addressSubstitution.js.map +1 -0
  156. package/build/executor/compressor/compress_functions/addressSubstitutionFromObject.d.ts +10 -0
  157. package/build/executor/compressor/compress_functions/addressSubstitutionFromObject.js +40 -0
  158. package/build/executor/compressor/compress_functions/addressSubstitutionFromObject.js.map +1 -0
  159. package/build/executor/compressor/compress_functions/byteSubstitution.d.ts +11 -0
  160. package/build/executor/compressor/compress_functions/byteSubstitution.js +64 -0
  161. package/build/executor/compressor/compress_functions/byteSubstitution.js.map +1 -0
  162. package/build/executor/compressor/compress_functions/ffSubstitution.d.ts +7 -0
  163. package/build/executor/compressor/compress_functions/ffSubstitution.js +54 -0
  164. package/build/executor/compressor/compress_functions/ffSubstitution.js.map +1 -0
  165. package/build/executor/compressor/compress_functions/findLongestAndSubstitute.d.ts +8 -0
  166. package/build/executor/compressor/compress_functions/findLongestAndSubstitute.js +67 -0
  167. package/build/executor/compressor/compress_functions/findLongestAndSubstitute.js.map +1 -0
  168. package/build/executor/compressor/compress_functions/findLongestAndSubstitute_old.d.ts +8 -0
  169. package/build/executor/compressor/compress_functions/findLongestAndSubstitute_old.js +61 -0
  170. package/build/executor/compressor/compress_functions/findLongestAndSubstitute_old.js.map +1 -0
  171. package/build/executor/compressor/compress_functions/reverseAddressSubstitution.d.ts +6 -0
  172. package/build/executor/compressor/compress_functions/reverseAddressSubstitution.js +37 -0
  173. package/build/executor/compressor/compress_functions/reverseAddressSubstitution.js.map +1 -0
  174. package/build/executor/compressor/compress_functions/searchUnusedBytes.d.ts +9 -0
  175. package/build/executor/compressor/compress_functions/searchUnusedBytes.js +33 -0
  176. package/build/executor/compressor/compress_functions/searchUnusedBytes.js.map +1 -0
  177. package/build/executor/compressor/fetchSaved.d.ts +0 -0
  178. package/build/executor/compressor/fetchSaved.js +17 -0
  179. package/build/executor/compressor/fetchSaved.js.map +1 -0
  180. package/build/executor/compressor/utils/computeCostL2.d.ts +2 -0
  181. package/build/executor/compressor/utils/computeCostL2.js +14 -0
  182. package/build/executor/compressor/utils/computeCostL2.js.map +1 -0
  183. package/build/executor/compressor/utils/findLongestDuplicatedString.d.ts +2 -0
  184. package/build/executor/compressor/utils/findLongestDuplicatedString.js +30 -0
  185. package/build/executor/compressor/utils/findLongestDuplicatedString.js.map +1 -0
  186. package/build/executor/compressor/utils/getAllIndexes.d.ts +2 -0
  187. package/build/executor/compressor/utils/getAllIndexes.js +12 -0
  188. package/build/executor/compressor/utils/getAllIndexes.js.map +1 -0
  189. package/build/executor/compressor/utils/getByteForAddress.d.ts +2 -0
  190. package/build/executor/compressor/utils/getByteForAddress.js +14 -0
  191. package/build/executor/compressor/utils/getByteForAddress.js.map +1 -0
  192. package/build/executor/compressor/utils/intTo2Bytes.d.ts +2 -0
  193. package/build/executor/compressor/utils/intTo2Bytes.js +14 -0
  194. package/build/executor/compressor/utils/intTo2Bytes.js.map +1 -0
  195. package/build/executor/compressor/utils/intTo3Bytes.d.ts +2 -0
  196. package/build/executor/compressor/utils/intTo3Bytes.js +18 -0
  197. package/build/executor/compressor/utils/intTo3Bytes.js.map +1 -0
  198. package/build/executor/compressor/utils/intToByte.d.ts +2 -0
  199. package/build/executor/compressor/utils/intToByte.js +10 -0
  200. package/build/executor/compressor/utils/intToByte.js.map +1 -0
  201. package/build/generic-swap-transaction-builder.d.ts +1 -1
  202. package/build/generic-swap-transaction-builder.js +10 -10
  203. package/build/generic-swap-transaction-builder.js.map +1 -1
  204. package/package.json +1 -1
  205. package/src/abi/concentrator/arUSD.json +568 -0
  206. package/src/abi/concentrator/arUSD5115.json +1746 -0
  207. package/src/abi/fx-protocol/FxMarket.json +1284 -0
  208. package/src/abi/fx-protocol/FxUSD.json +1227 -0
  209. package/src/abi/fx-protocol/weETHOralce.json +676 -0
  210. package/src/dex/concentrator-arusd/concentrator-arusd-e2e.test.ts +92 -0
  211. package/src/dex/concentrator-arusd/concentrator-arusd-event.ts +100 -0
  212. package/src/dex/concentrator-arusd/concentrator-arusd-integration.test.ts +104 -0
  213. package/src/dex/concentrator-arusd/concentrator-arusd.ts +269 -0
  214. package/src/dex/concentrator-arusd/concetrator-arusd-events.test.ts +97 -0
  215. package/src/dex/concentrator-arusd/config.ts +13 -0
  216. package/src/dex/concentrator-arusd/types.ts +16 -0
  217. package/src/dex/concentrator-arusd/utils.ts +36 -0
  218. package/src/dex/fx-protocol-rusd/config.ts +14 -0
  219. package/src/dex/fx-protocol-rusd/fx-protocol-e2e.test.ts +96 -0
  220. package/src/dex/fx-protocol-rusd/fx-protocol-events.test.ts +101 -0
  221. package/src/dex/fx-protocol-rusd/fx-protocol-integration.test.ts +104 -0
  222. package/src/dex/fx-protocol-rusd/fx-protocol-rusd-event.ts +112 -0
  223. package/src/dex/fx-protocol-rusd/fx-protocol-rusd.ts +282 -0
  224. package/src/dex/fx-protocol-rusd/types.ts +16 -0
  225. package/src/dex/fx-protocol-rusd/utils.ts +47 -0
  226. package/src/dex/index.ts +4 -0
  227. package/src/dex/wsteth/wsteth-integration.test.ts +0 -1
  228. package/src/executor/Executor01BytecodeBuilder.ts +4 -8
  229. package/src/executor/Executor02BytecodeBuilder.ts +2 -7
  230. package/src/executor/Executor03BytecodeBuilder.ts +34 -19
  231. package/src/generic-swap-transaction-builder.ts +3 -5
  232. package/tests/constants-e2e.ts +10 -0
  233. package/build/abi/inception/inception-ineth.json +0 -609
  234. package/build/abi/inception/inception-ratio-feed.json +0 -93
  235. package/build/abi/inception/inception-vault.json +0 -991
  236. package/build/abi/infusion/InfusionFactory.json +0 -147
  237. package/build/abi/infusion/InfusionPair.json +0 -658
  238. package/build/abi/infusion/InfusionRouter.json +0 -442
  239. package/build/dex/idle-dao/idle-dao-pool.d.ts +0 -56
  240. package/build/dex/idle-dao/idle-dao-pool.js +0 -176
  241. package/build/dex/idle-dao/idle-dao-pool.js.map +0 -1
  242. package/build/dex/idle-dao/idle-dao-pooling-pool.d.ts +0 -16
  243. package/build/dex/idle-dao/idle-dao-pooling-pool.js +0 -57
  244. package/build/dex/idle-dao/idle-dao-pooling-pool.js.map +0 -1
  245. package/build/dex/idle-dao/scripts.d.ts +0 -9
  246. package/build/dex/idle-dao/scripts.js +0 -552
  247. package/build/dex/idle-dao/scripts.js.map +0 -1
  248. package/build/dex/inception/config.d.ts +0 -5
  249. package/build/dex/inception/config.js +0 -112
  250. package/build/dex/inception/config.js.map +0 -1
  251. package/build/dex/inception/inception-event-pool.d.ts +0 -23
  252. package/build/dex/inception/inception-event-pool.js +0 -34
  253. package/build/dex/inception/inception-event-pool.js.map +0 -1
  254. package/build/dex/inception/inception-native.js +0 -131
  255. package/build/dex/inception/inception-native.js.map +0 -1
  256. package/build/dex/inception/inception-pool.d.ts +0 -18
  257. package/build/dex/inception/inception-pool.js +0 -32
  258. package/build/dex/inception/inception-pool.js.map +0 -1
  259. package/build/dex/inception/inception-price-feed.d.ts +0 -19
  260. package/build/dex/inception/inception-price-feed.js +0 -51
  261. package/build/dex/inception/inception-price-feed.js.map +0 -1
  262. package/build/dex/inception/inception.d.ts +0 -44
  263. package/build/dex/inception/inception.js +0 -162
  264. package/build/dex/inception/inception.js.map +0 -1
  265. package/build/dex/inception/tokens.d.ts +0 -9
  266. package/build/dex/inception/tokens.js +0 -28
  267. package/build/dex/inception/tokens.js.map +0 -1
  268. package/build/dex/inception/types.d.ts +0 -22
  269. package/build/dex/inception/types.js +0 -3
  270. package/build/dex/inception/types.js.map +0 -1
  271. package/build/dex/inception/utils.d.ts +0 -7
  272. package/build/dex/inception/utils.js +0 -58
  273. package/build/dex/inception/utils.js.map +0 -1
  274. package/build/dex/infusion/config.js +0 -25
  275. package/build/dex/infusion/config.js.map +0 -1
  276. package/build/dex/infusion/infusion-stable-pool.d.ts +0 -4
  277. package/build/dex/infusion/infusion-stable-pool.js +0 -74
  278. package/build/dex/infusion/infusion-stable-pool.js.map +0 -1
  279. package/build/dex/infusion/infusion.d.ts +0 -54
  280. package/build/dex/infusion/infusion.js +0 -532
  281. package/build/dex/infusion/infusion.js.map +0 -1
  282. package/build/dex/infusion/types.d.ts +0 -47
  283. package/build/dex/infusion/types.js +0 -3
  284. package/build/dex/infusion/types.js.map +0 -1
  285. package/build/dex/infusion/utils/isStablePair.d.ts +0 -2
  286. package/build/dex/infusion/utils/isStablePair.js +0 -18
  287. package/build/dex/infusion/utils/isStablePair.js.map +0 -1
@@ -0,0 +1,158 @@
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.IntegralContext = void 0;
7
+ const integral_pool_1 = require("./integral-pool");
8
+ const integral_pricing_1 = require("./integral-pricing");
9
+ const integral_factory_1 = require("./integral-factory");
10
+ const integral_relayer_1 = require("./integral-relayer");
11
+ const integral_token_1 = require("./integral-token");
12
+ const utils_1 = require("./utils");
13
+ const lodash_1 = __importDefault(require("lodash"));
14
+ class IntegralContext {
15
+ constructor(network, dexKey, dexHelper, erc20Interface, factoryAddress, relayerAddress) {
16
+ this.network = network;
17
+ this.dexKey = dexKey;
18
+ this.dexHelper = dexHelper;
19
+ this.erc20Interface = erc20Interface;
20
+ this.factoryAddress = factoryAddress;
21
+ this.relayerAddress = relayerAddress;
22
+ this.pools = {};
23
+ this.tokens = {};
24
+ this.logger = dexHelper.getLogger(dexKey);
25
+ this.factory = new integral_factory_1.IntegralFactory(dexHelper, dexKey, this.factoryAddress, this.onPoolCreatedAddPool, this.logger);
26
+ this.relayer = new integral_relayer_1.IntegralRelayer(dexHelper, dexKey, this.erc20Interface, this.relayerAddress, {}, this.onRelayerPoolEnabledSet, this.logger);
27
+ }
28
+ async addPools(pools, blockNumber, initPhase = false) {
29
+ this.relayer.addPools(pools);
30
+ if (initPhase) {
31
+ await this.relayer.initialize(blockNumber);
32
+ }
33
+ const _relayerState = this.relayer.getState(blockNumber);
34
+ const relayerState = _relayerState
35
+ ? _relayerState
36
+ : await this.relayer.generateState(blockNumber);
37
+ if (!_relayerState) {
38
+ this.relayer.setState(relayerState, blockNumber);
39
+ }
40
+ const poolInitProps = this.removeDisabledPoolInitProps(relayerState, pools);
41
+ const bases = Object.entries(poolInitProps).map(([poolAddress, p]) => {
42
+ const poolId = (0, utils_1.getPoolIdentifier)(this.dexKey, p.token0, p.token1);
43
+ const base = (this.pools[poolId] && this.pools[poolId].base) ||
44
+ new integral_pool_1.IntegralEventPool(this.dexKey, this.network, this.dexHelper, poolAddress, p.token0, p.token1, this.logger);
45
+ this.pools[poolId] = { base, enabled: true };
46
+ return base;
47
+ });
48
+ await Promise.all(bases.map(base => !base.isInitialized && base.initialize(blockNumber)));
49
+ const pricings = await Promise.all(bases.map(async (base) => {
50
+ const _poolState = base.getState(blockNumber);
51
+ const poolState = _poolState
52
+ ? _poolState
53
+ : await base.generateState(blockNumber);
54
+ const poolId = (0, utils_1.getPoolIdentifier)(this.dexKey, base.token0, base.token1);
55
+ const pricing = (this.pools[poolId] && this.pools[poolId].pricing) ||
56
+ new integral_pricing_1.IntegralPricing(this.dexHelper, poolId, this.erc20Interface, poolState.uniswapPool, base.token0, base.token1, poolState.uniswapPoolFee, this.logger, this.network);
57
+ this.pools[poolId].pricing = pricing;
58
+ return pricing;
59
+ }));
60
+ await Promise.all(pricings.map(pricing => !pricing.isInitialized && pricing.initialize(blockNumber)));
61
+ const initIntegralToken = (token) => new integral_token_1.IntegralToken(this.network, this.dexHelper, this.dexKey, this.erc20Interface, token, this.relayerAddress, this.onTransferUpdateBalance, this.logger);
62
+ bases.map(base => {
63
+ this.tokens[base.token0] =
64
+ this.tokens[base.token0] || initIntegralToken(base.token0);
65
+ this.tokens[base.token1] =
66
+ this.tokens[base.token1] || initIntegralToken(base.token1);
67
+ });
68
+ await Promise.all(Object.values(this.tokens).map(token => !token.isInitialized && token.initialize(blockNumber)));
69
+ }
70
+ getPoolAddresses() {
71
+ return Object.values(this.pools)
72
+ .filter((pool) => !!pool.base && pool.enabled)
73
+ .map(({ base }) => base.poolAddress);
74
+ }
75
+ removeDisabledPoolInitProps(state, props) {
76
+ Object.entries(state.pools).forEach(([poolAddress, poolState]) => !poolState.isEnabled && delete props[poolAddress]);
77
+ return props;
78
+ }
79
+ static initialize(network, dexKey, dexHelper, erc20Interface, factoryAddress, relayerAddress) {
80
+ if (!this.instances[network]) {
81
+ this.instances[network] = new IntegralContext(network, dexKey, dexHelper, erc20Interface, factoryAddress, relayerAddress);
82
+ }
83
+ return this.instances[network];
84
+ }
85
+ static getInstance(network) {
86
+ if (!this.instances[network]) {
87
+ throw new Error('IntegralContext instance not initialized');
88
+ }
89
+ return this.instances[network];
90
+ }
91
+ async onRelayerPoolEnabledSet(poolAddress, state, blockNumber) {
92
+ const poolEntry = (0, utils_1.getPoolBackReferencedFrom)(this, poolAddress);
93
+ if (state.isEnabled && (!poolEntry || !poolEntry[1].enabled)) {
94
+ const _factoryState = this.factory.getStaleState();
95
+ const factoryState = _factoryState
96
+ ? _factoryState
97
+ : await this.factory.generateState(blockNumber);
98
+ const { token0, token1 } = factoryState.pools[poolAddress];
99
+ await this.addPools({ [poolAddress]: { token0, token1 } }, blockNumber);
100
+ }
101
+ else if (!state.isEnabled && poolEntry && poolEntry[1].enabled) {
102
+ this.pools[poolEntry[0]].enabled = false;
103
+ }
104
+ }
105
+ onRebalanceSellOrderExecuted(blockNumber, orderId) {
106
+ this.relayer.executeOrder(orderId, blockNumber);
107
+ }
108
+ async onPoolCreatedAddPool(token0, token1, poolAddress, blockNumber) {
109
+ await this.addPools({ [poolAddress]: { token0, token1 } }, blockNumber);
110
+ }
111
+ async onPoolSwapForRelayer(blockNumber, poolAddress, recipient, amount0Out, amount1Out) {
112
+ if (recipient.toLowerCase() === this.relayerAddress.toLowerCase()) {
113
+ const pools = this.relayer.getPools();
114
+ if (pools[poolAddress.toLowerCase()]) {
115
+ const token0 = pools[poolAddress.toLowerCase()].token0;
116
+ const token1 = pools[poolAddress.toLowerCase()].token1;
117
+ let _state = this.relayer.getStaleState();
118
+ if (!_state) {
119
+ _state = await this.relayer.generateState(blockNumber);
120
+ this.relayer.setState(_state, blockNumber);
121
+ return;
122
+ }
123
+ else {
124
+ blockNumber = this.relayer.getStateBlockNumber();
125
+ }
126
+ const state = lodash_1.default.cloneDeep(_state);
127
+ if (amount1Out > 0n) {
128
+ state.tokens[token1].balance += amount1Out;
129
+ }
130
+ else {
131
+ state.tokens[token0].balance += amount0Out;
132
+ }
133
+ this.relayer.setState(state, blockNumber);
134
+ }
135
+ else {
136
+ this.logger.error('Integral Relayer: Pool address not found for', poolAddress);
137
+ }
138
+ }
139
+ }
140
+ async onTransferUpdateBalance(token, from, to, amount, blockNumber) {
141
+ let _state = this.relayer.getStaleState();
142
+ if (!_state) {
143
+ this.logger.error('Integral Token: Relayer stale state not found');
144
+ return;
145
+ }
146
+ const state = lodash_1.default.cloneDeep(_state);
147
+ if (this.relayer.relayerAddress.toLowerCase() === from) {
148
+ state.tokens[token].balance -= amount;
149
+ }
150
+ else if (this.relayer.relayerAddress.toLowerCase() === to) {
151
+ state.tokens[token].balance += amount;
152
+ }
153
+ this.relayer.setState(state, blockNumber);
154
+ }
155
+ }
156
+ exports.IntegralContext = IntegralContext;
157
+ IntegralContext.instances = {};
158
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.js","sourceRoot":"","sources":["../../../src/dex/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C,OAAO,IAAI,MAAM,CAAC;SACvC;QACD,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;IAC5C,CAAC;;AAzQH,0CA0QC;AAzQQ,yBAAS,GAA2C,EAAE,CAAC"}
@@ -0,0 +1,17 @@
1
+ import { Address } from '../../types';
2
+ import { PoolState as UniswapPoolState } from '../uniswap-v3/types';
3
+ import { IntegralContext } from './context';
4
+ import { PoolStates, RelayerPoolState } from './types';
5
+ export declare function sortTokens(srcAddress: Address, destAddress: Address): string[];
6
+ export declare function getDecimalsConverter(decimals0: number, decimals1: number, inverted: boolean): bigint;
7
+ export declare function getPrice(states: PoolStates, inverted: boolean): bigint;
8
+ export declare function getSpotPrice(pricing: UniswapPoolState, decimalsConverter: bigint): bigint;
9
+ export declare function getAveragePrice(relayer: RelayerPoolState, pricing: UniswapPoolState, decimalsConverter: bigint): bigint;
10
+ export declare function getTickCumulatives(poolState: UniswapPoolState, secondsAgos: bigint[]): bigint[];
11
+ export declare function isInverted(tokenIn: Address, tokenOut: Address): boolean;
12
+ export declare function getPoolIdentifier(dexKey: string, srcAddress: Address, destAddress: Address): string;
13
+ export declare function onPoolSwapForRelayer(blockNumber: number, poolAddress: Address, recipient: Address, amount0Out: bigint, amount1Out: bigint, _context?: IntegralContext): Promise<void>;
14
+ export declare function onRelayerPoolEnabledSet(poolAddress: Address, state: RelayerPoolState, blockNumber: number): Promise<void>;
15
+ export declare function onRebalanceSellOrderExecuted(blockNumber: number, orderId: bigint): void;
16
+ export declare function onPoolCreatedAddPool(token0: Address, token1: Address, poolAddress: Address, blockNumber: number): Promise<void>;
17
+ export declare function onTransferUpdateBalance(token: Address, from: Address, to: Address, amount: bigint, blockNumber: number, _context?: IntegralContext): Promise<void>;
@@ -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,CA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AAC;AArBD,0DAqBC"}
@@ -0,0 +1,24 @@
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
+ protected getPoolIdentifierData(): {
19
+ factory: string;
20
+ };
21
+ generateState(blockNumber?: number | 'latest'): Promise<FactoryState>;
22
+ protected processLog(state: FactoryState, log: Readonly<Log>, blockHeader: Readonly<BlockHeader>): Promise<FactoryState>;
23
+ handlePairCreated(event: LogDescription, state: FactoryState, blockHeader: Readonly<BlockHeader>): Promise<FactoryState>;
24
+ }
@@ -0,0 +1,95 @@
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
+ getPoolIdentifierData() {
25
+ return { factory: this.factoryAddress };
26
+ }
27
+ async generateState(blockNumber) {
28
+ const factory = new this.dexHelper.web3Provider.eth.Contract(factory_json_1.default, this.factoryAddress);
29
+ const poolCountResult = await factory.methods
30
+ .allPairsLength()
31
+ .call(undefined, blockNumber);
32
+ const poolCount = Number(poolCountResult);
33
+ const poolAddressCallDatas = [
34
+ ...Array(poolCount),
35
+ ].map((_, i) => {
36
+ return {
37
+ target: this.factoryAddress,
38
+ callData: factory.methods.allPairs(i).encodeABI(),
39
+ decodeFunction: decoders_1.addressDecode,
40
+ };
41
+ });
42
+ const poolAddresses = await this.dexHelper.multiWrapper.tryAggregate(false, poolAddressCallDatas, blockNumber, this.dexHelper.multiWrapper.defaultBatchSize, false);
43
+ const poolIface = new abi_1.Interface(pool_json_1.default);
44
+ const poolInfosCallDatas = poolAddresses
45
+ .map(poolAddress => {
46
+ return [
47
+ {
48
+ target: poolAddress.returnData,
49
+ callData: poolIface.encodeFunctionData('token0', []),
50
+ decodeFunction: decoders_1.addressDecode,
51
+ },
52
+ {
53
+ target: poolAddress.returnData,
54
+ callData: poolIface.encodeFunctionData('token1', []),
55
+ decodeFunction: decoders_1.addressDecode,
56
+ },
57
+ ];
58
+ })
59
+ .flat();
60
+ const poolInfos = await this.dexHelper.multiWrapper.aggregate(poolInfosCallDatas, blockNumber);
61
+ const state = { pools: {} };
62
+ poolAddresses.forEach((poolAddress, i) => {
63
+ const tokens = [
64
+ poolInfos[i * 2].toLowerCase(),
65
+ poolInfos[i * 2 + 1].toLowerCase(),
66
+ ];
67
+ state.pools[poolAddress.returnData.toLowerCase()] = {
68
+ token0: tokens[0],
69
+ token1: tokens[1],
70
+ };
71
+ });
72
+ return state;
73
+ }
74
+ async processLog(state, log, blockHeader) {
75
+ const event = this.logDecoder(log);
76
+ if (event.name in this.handlers) {
77
+ return await this.handlers[event.name](event, state, blockHeader);
78
+ }
79
+ return state;
80
+ }
81
+ async handlePairCreated(event, state, blockHeader) {
82
+ const tokens = [
83
+ event.args.token0.toLowerCase(),
84
+ event.args.token1.toLowerCase(),
85
+ ];
86
+ state.pools[event.args.pair.toLowerCase()] = {
87
+ token0: tokens[0],
88
+ token1: tokens[1],
89
+ };
90
+ await this.onPoolCreated(tokens[0], tokens[1], event.args.pair.toLowerCase(), blockHeader.number);
91
+ return state;
92
+ }
93
+ }
94
+ exports.IntegralFactory = IntegralFactory;
95
+ //# 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,CA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,KAAmB,EACnB,GAAkB,EAClB,WAAkC;QAElC,MAAM,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;QACnC,IAAI,KAAK,CAAC,IAAI,IAAI,IAAI,CAAC,QAAQ,EAAE;YAC/B,OAAO,MAAM,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,WAAW,CAAC,CAAC;SACnE;QAED,OAAO,KAAK,CAAC;IACf,CAAC;IAED,KAAK,CAAC,iBAAiB,CACrB,KAAqB,EACrB,KAAmB,EACnB,WAAkC;QAElC,MAAM,MAAM,GAAuB;YACjC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE;YAC/B,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE;SAChC,CAAC;QACF,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,GAAG;YAC3C,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;YACjB,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;SAClB,CAAC;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;AAnID,0CAmIC"}
@@ -0,0 +1,50 @@
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
+ protected getPoolIdentifierData(): {
24
+ token0: string;
25
+ token1: string;
26
+ };
27
+ /**
28
+ * The function is called every time any of the subscribed
29
+ * addresses release log. The function accepts the current
30
+ * state, updates the state according to the log, and returns
31
+ * the updated state.
32
+ * @param state - Current state of event subscriber
33
+ * @param log - Log released by one of the subscribed addresses
34
+ * @returns Updates state of the event subscriber after the log
35
+ */
36
+ protected processLog(state: PoolState, log: Readonly<Log>, blockHeader: Readonly<BlockHeader>): Promise<PoolState | null>;
37
+ /**
38
+ * The function generates state using on-chain calls. This
39
+ * function is called to regenerate state if the event based
40
+ * system fails to fetch events and the local state is no
41
+ * more correct.
42
+ * @param blockNumber - Blocknumber for which the state should
43
+ * should be generated
44
+ * @returns state of the event subscriber at blocknumber
45
+ */
46
+ generateState(blockNumber: number): Promise<Readonly<PoolState>>;
47
+ handleSetSwapFee(event: LogDescription, pool: PoolState): PoolState;
48
+ handleSetMintFee(event: LogDescription, pool: PoolState): PoolState;
49
+ handleSetBurnFee(event: LogDescription, pool: PoolState): PoolState;
50
+ }