@defisaver/automation-sdk 3.1.3 → 3.2.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 (246) hide show
  1. package/.babelrc +3 -3
  2. package/.editorconfig +9 -9
  3. package/.env +5 -0
  4. package/.env.dev +4 -4
  5. package/.eslintignore +6 -6
  6. package/.eslintrc.js +39 -39
  7. package/.mocharc.json +4 -4
  8. package/.nvmrc +1 -1
  9. package/README.md +46 -46
  10. package/cjs/abis/Erc20.json +223 -223
  11. package/cjs/abis/SubStorage.json +21 -21
  12. package/cjs/abis/UniMulticall.json +17 -17
  13. package/cjs/abis/index.d.ts +9 -9
  14. package/cjs/abis/index.js +30 -30
  15. package/cjs/abis/legacy_AaveV2Subscriptions.json +8 -8
  16. package/cjs/abis/legacy_AuthCheck.json +8 -8
  17. package/cjs/abis/legacy_CompoundV2Subscriptions.json +9 -9
  18. package/cjs/abis/legacy_MakerSubscriptions.json +9 -9
  19. package/cjs/automation/private/Automation.d.ts +12 -12
  20. package/cjs/automation/private/Automation.js +42 -42
  21. package/cjs/automation/private/LegacyAutomation.d.ts +25 -25
  22. package/cjs/automation/private/LegacyAutomation.js +118 -118
  23. package/cjs/automation/private/LegacyProtocol.d.ts +22 -22
  24. package/cjs/automation/private/LegacyProtocol.js +41 -41
  25. package/cjs/automation/private/LegacyProtocol.test.d.ts +1 -1
  26. package/cjs/automation/private/LegacyProtocol.test.js +25 -25
  27. package/cjs/automation/private/Protocol.d.ts +22 -22
  28. package/cjs/automation/private/Protocol.js +41 -41
  29. package/cjs/automation/private/Protocol.test.d.ts +1 -1
  30. package/cjs/automation/private/Protocol.test.js +25 -25
  31. package/cjs/automation/private/StrategiesAutomation.d.ts +33 -33
  32. package/cjs/automation/private/StrategiesAutomation.js +190 -181
  33. package/cjs/automation/private/StrategiesAutomation.test.d.ts +1 -1
  34. package/cjs/automation/private/StrategiesAutomation.test.js +671 -671
  35. package/cjs/automation/public/ArbitrumStrategies.d.ts +5 -5
  36. package/cjs/automation/public/ArbitrumStrategies.js +13 -13
  37. package/cjs/automation/public/BaseStrategies.d.ts +5 -5
  38. package/cjs/automation/public/BaseStrategies.js +13 -13
  39. package/cjs/automation/public/EthereumStrategies.d.ts +5 -5
  40. package/cjs/automation/public/EthereumStrategies.js +13 -13
  41. package/cjs/automation/public/OptimismStrategies.d.ts +5 -5
  42. package/cjs/automation/public/OptimismStrategies.js +13 -13
  43. package/cjs/automation/public/Strategies.test.d.ts +1 -0
  44. package/cjs/automation/public/Strategies.test.js +61 -0
  45. package/cjs/automation/public/legacy/LegacyAaveAutomation.d.ts +6 -6
  46. package/cjs/automation/public/legacy/LegacyAaveAutomation.js +20 -20
  47. package/cjs/automation/public/legacy/LegacyCompoundAutomation.d.ts +6 -6
  48. package/cjs/automation/public/legacy/LegacyCompoundAutomation.js +20 -20
  49. package/cjs/automation/public/legacy/LegacyMakerAutomation.d.ts +6 -6
  50. package/cjs/automation/public/legacy/LegacyMakerAutomation.js +20 -20
  51. package/cjs/configuration.d.ts +1 -1
  52. package/cjs/configuration.js +12 -12
  53. package/cjs/constants/index.d.ts +28 -28
  54. package/cjs/constants/index.js +494 -489
  55. package/cjs/index.d.ts +23 -23
  56. package/cjs/index.js +65 -65
  57. package/cjs/services/contractService.d.ts +12 -12
  58. package/cjs/services/contractService.js +54 -54
  59. package/cjs/services/ethereumService.d.ts +7 -7
  60. package/cjs/services/ethereumService.js +49 -49
  61. package/cjs/services/ethereumService.test.d.ts +1 -1
  62. package/cjs/services/ethereumService.test.js +242 -242
  63. package/cjs/services/strategiesService.d.ts +2 -2
  64. package/cjs/services/strategiesService.js +724 -723
  65. package/cjs/services/strategiesService.test.d.ts +1 -1
  66. package/cjs/services/strategiesService.test.js +110 -110
  67. package/cjs/services/strategySubService.d.ts +100 -100
  68. package/cjs/services/strategySubService.js +267 -267
  69. package/cjs/services/strategySubService.test.d.ts +1 -1
  70. package/cjs/services/strategySubService.test.js +936 -936
  71. package/cjs/services/subDataService.d.ts +192 -192
  72. package/cjs/services/subDataService.js +475 -475
  73. package/cjs/services/subDataService.test.d.ts +1 -1
  74. package/cjs/services/subDataService.test.js +1282 -1282
  75. package/cjs/services/triggerService.d.ts +191 -191
  76. package/cjs/services/triggerService.js +367 -367
  77. package/cjs/services/triggerService.test.d.ts +1 -1
  78. package/cjs/services/triggerService.test.js +926 -926
  79. package/cjs/services/utils.d.ts +25 -25
  80. package/cjs/services/utils.js +131 -131
  81. package/cjs/services/utils.test.d.ts +1 -1
  82. package/cjs/services/utils.test.js +376 -376
  83. package/cjs/types/contracts/generated/Erc20.d.ts +53 -53
  84. package/cjs/types/contracts/generated/Erc20.js +5 -5
  85. package/cjs/types/contracts/generated/Legacy_AaveV2Subscriptions.d.ts +129 -129
  86. package/cjs/types/contracts/generated/Legacy_AaveV2Subscriptions.js +5 -5
  87. package/cjs/types/contracts/generated/Legacy_AuthCheck.d.ts +20 -20
  88. package/cjs/types/contracts/generated/Legacy_AuthCheck.js +5 -5
  89. package/cjs/types/contracts/generated/Legacy_CompoundV2Subscriptions.d.ts +128 -128
  90. package/cjs/types/contracts/generated/Legacy_CompoundV2Subscriptions.js +5 -5
  91. package/cjs/types/contracts/generated/Legacy_MakerSubscriptions.d.ts +246 -246
  92. package/cjs/types/contracts/generated/Legacy_MakerSubscriptions.js +5 -5
  93. package/cjs/types/contracts/generated/SubStorage.d.ts +110 -114
  94. package/cjs/types/contracts/generated/SubStorage.js +5 -5
  95. package/cjs/types/contracts/generated/UniMulticall.d.ts +55 -55
  96. package/cjs/types/contracts/generated/UniMulticall.js +5 -5
  97. package/cjs/types/contracts/generated/index.d.ts +7 -7
  98. package/cjs/types/contracts/generated/index.js +2 -2
  99. package/cjs/types/contracts/generated/types.d.ts +54 -54
  100. package/cjs/types/contracts/generated/types.js +2 -2
  101. package/cjs/types/enums.d.ts +186 -184
  102. package/cjs/types/enums.js +208 -206
  103. package/cjs/types/index.d.ts +224 -224
  104. package/cjs/types/index.js +2 -2
  105. package/esm/abis/Erc20.json +223 -223
  106. package/esm/abis/SubStorage.json +21 -21
  107. package/esm/abis/UniMulticall.json +17 -17
  108. package/esm/abis/index.d.ts +9 -9
  109. package/esm/abis/index.js +18 -18
  110. package/esm/abis/legacy_AaveV2Subscriptions.json +8 -8
  111. package/esm/abis/legacy_AuthCheck.json +8 -8
  112. package/esm/abis/legacy_CompoundV2Subscriptions.json +9 -9
  113. package/esm/abis/legacy_MakerSubscriptions.json +9 -9
  114. package/esm/automation/private/Automation.d.ts +12 -12
  115. package/esm/automation/private/Automation.js +39 -39
  116. package/esm/automation/private/LegacyAutomation.d.ts +25 -25
  117. package/esm/automation/private/LegacyAutomation.js +112 -112
  118. package/esm/automation/private/LegacyProtocol.d.ts +22 -22
  119. package/esm/automation/private/LegacyProtocol.js +38 -38
  120. package/esm/automation/private/LegacyProtocol.test.d.ts +1 -1
  121. package/esm/automation/private/LegacyProtocol.test.js +20 -20
  122. package/esm/automation/private/Protocol.d.ts +22 -22
  123. package/esm/automation/private/Protocol.js +38 -38
  124. package/esm/automation/private/Protocol.test.d.ts +1 -1
  125. package/esm/automation/private/Protocol.test.js +20 -20
  126. package/esm/automation/private/StrategiesAutomation.d.ts +33 -33
  127. package/esm/automation/private/StrategiesAutomation.js +184 -175
  128. package/esm/automation/private/StrategiesAutomation.test.d.ts +1 -1
  129. package/esm/automation/private/StrategiesAutomation.test.js +666 -666
  130. package/esm/automation/public/ArbitrumStrategies.d.ts +5 -5
  131. package/esm/automation/public/ArbitrumStrategies.js +7 -7
  132. package/esm/automation/public/BaseStrategies.d.ts +5 -5
  133. package/esm/automation/public/BaseStrategies.js +7 -7
  134. package/esm/automation/public/EthereumStrategies.d.ts +5 -5
  135. package/esm/automation/public/EthereumStrategies.js +7 -7
  136. package/esm/automation/public/OptimismStrategies.d.ts +5 -5
  137. package/esm/automation/public/OptimismStrategies.js +7 -7
  138. package/esm/automation/public/Strategies.test.d.ts +1 -0
  139. package/esm/automation/public/Strategies.test.js +56 -0
  140. package/esm/automation/public/legacy/LegacyAaveAutomation.d.ts +6 -6
  141. package/esm/automation/public/legacy/LegacyAaveAutomation.js +14 -14
  142. package/esm/automation/public/legacy/LegacyCompoundAutomation.d.ts +6 -6
  143. package/esm/automation/public/legacy/LegacyCompoundAutomation.js +14 -14
  144. package/esm/automation/public/legacy/LegacyMakerAutomation.d.ts +6 -6
  145. package/esm/automation/public/legacy/LegacyMakerAutomation.js +14 -14
  146. package/esm/configuration.d.ts +1 -1
  147. package/esm/configuration.js +7 -7
  148. package/esm/constants/index.d.ts +28 -28
  149. package/esm/constants/index.js +488 -483
  150. package/esm/index.d.ts +23 -23
  151. package/esm/index.js +23 -23
  152. package/esm/services/contractService.d.ts +12 -12
  153. package/esm/services/contractService.js +45 -45
  154. package/esm/services/ethereumService.d.ts +7 -7
  155. package/esm/services/ethereumService.js +41 -41
  156. package/esm/services/ethereumService.test.d.ts +1 -1
  157. package/esm/services/ethereumService.test.js +237 -237
  158. package/esm/services/strategiesService.d.ts +2 -2
  159. package/esm/services/strategiesService.js +697 -696
  160. package/esm/services/strategiesService.test.d.ts +1 -1
  161. package/esm/services/strategiesService.test.js +108 -108
  162. package/esm/services/strategySubService.d.ts +100 -100
  163. package/esm/services/strategySubService.js +238 -238
  164. package/esm/services/strategySubService.test.d.ts +1 -1
  165. package/esm/services/strategySubService.test.js +908 -908
  166. package/esm/services/subDataService.d.ts +192 -192
  167. package/esm/services/subDataService.js +469 -469
  168. package/esm/services/subDataService.test.d.ts +1 -1
  169. package/esm/services/subDataService.test.js +1254 -1254
  170. package/esm/services/triggerService.d.ts +191 -191
  171. package/esm/services/triggerService.js +338 -338
  172. package/esm/services/triggerService.test.d.ts +1 -1
  173. package/esm/services/triggerService.test.js +901 -901
  174. package/esm/services/utils.d.ts +25 -25
  175. package/esm/services/utils.js +82 -82
  176. package/esm/services/utils.test.d.ts +1 -1
  177. package/esm/services/utils.test.js +348 -348
  178. package/esm/types/contracts/generated/Erc20.d.ts +53 -53
  179. package/esm/types/contracts/generated/Erc20.js +4 -4
  180. package/esm/types/contracts/generated/Legacy_AaveV2Subscriptions.d.ts +129 -129
  181. package/esm/types/contracts/generated/Legacy_AaveV2Subscriptions.js +4 -4
  182. package/esm/types/contracts/generated/Legacy_AuthCheck.d.ts +20 -20
  183. package/esm/types/contracts/generated/Legacy_AuthCheck.js +4 -4
  184. package/esm/types/contracts/generated/Legacy_CompoundV2Subscriptions.d.ts +128 -128
  185. package/esm/types/contracts/generated/Legacy_CompoundV2Subscriptions.js +4 -4
  186. package/esm/types/contracts/generated/Legacy_MakerSubscriptions.d.ts +246 -246
  187. package/esm/types/contracts/generated/Legacy_MakerSubscriptions.js +4 -4
  188. package/esm/types/contracts/generated/SubStorage.d.ts +110 -114
  189. package/esm/types/contracts/generated/SubStorage.js +4 -4
  190. package/esm/types/contracts/generated/UniMulticall.d.ts +55 -55
  191. package/esm/types/contracts/generated/UniMulticall.js +4 -4
  192. package/esm/types/contracts/generated/index.d.ts +7 -7
  193. package/esm/types/contracts/generated/index.js +1 -1
  194. package/esm/types/contracts/generated/types.d.ts +54 -54
  195. package/esm/types/contracts/generated/types.js +1 -1
  196. package/esm/types/enums.d.ts +186 -184
  197. package/esm/types/enums.js +205 -203
  198. package/esm/types/index.d.ts +224 -224
  199. package/esm/types/index.js +1 -1
  200. package/package.json +62 -61
  201. package/scripts/generateContractTypes.js +39 -39
  202. package/src/abis/Erc20.json +222 -222
  203. package/src/abis/SubStorage.json +21 -21
  204. package/src/abis/UniMulticall.json +17 -17
  205. package/src/abis/index.ts +28 -28
  206. package/src/abis/legacy_AaveV2Subscriptions.json +7 -7
  207. package/src/abis/legacy_AuthCheck.json +7 -7
  208. package/src/abis/legacy_CompoundV2Subscriptions.json +8 -8
  209. package/src/abis/legacy_MakerSubscriptions.json +8 -8
  210. package/src/automation/private/Automation.ts +44 -44
  211. package/src/automation/private/LegacyAutomation.ts +135 -135
  212. package/src/automation/private/LegacyProtocol.test.ts +23 -23
  213. package/src/automation/private/LegacyProtocol.ts +51 -51
  214. package/src/automation/private/Protocol.test.ts +23 -23
  215. package/src/automation/private/Protocol.ts +51 -51
  216. package/src/automation/private/StrategiesAutomation.test.ts +663 -663
  217. package/src/automation/private/StrategiesAutomation.ts +254 -242
  218. package/src/automation/public/ArbitrumStrategies.ts +10 -10
  219. package/src/automation/public/BaseStrategies.ts +10 -10
  220. package/src/automation/public/EthereumStrategies.ts +10 -10
  221. package/src/automation/public/OptimismStrategies.ts +10 -10
  222. package/src/automation/public/Strategies.test.ts +49 -0
  223. package/src/automation/public/legacy/LegacyAaveAutomation.ts +20 -20
  224. package/src/automation/public/legacy/LegacyCompoundAutomation.ts +20 -20
  225. package/src/automation/public/legacy/LegacyMakerAutomation.ts +20 -20
  226. package/src/configuration.ts +8 -8
  227. package/src/constants/index.ts +523 -507
  228. package/src/index.ts +39 -39
  229. package/src/services/contractService.ts +77 -77
  230. package/src/services/ethereumService.test.ts +257 -257
  231. package/src/services/ethereumService.ts +69 -69
  232. package/src/services/strategiesService.test.ts +105 -105
  233. package/src/services/strategiesService.ts +935 -934
  234. package/src/services/strategySubService.test.ts +1122 -1122
  235. package/src/services/strategySubService.ts +524 -524
  236. package/src/services/subDataService.test.ts +1387 -1387
  237. package/src/services/subDataService.ts +645 -645
  238. package/src/services/triggerService.test.ts +1004 -1004
  239. package/src/services/triggerService.ts +449 -449
  240. package/src/services/utils.test.ts +430 -430
  241. package/src/services/utils.ts +103 -103
  242. package/src/types/enums.ts +202 -200
  243. package/src/types/index.ts +279 -279
  244. package/tsconfig.esm.json +8 -8
  245. package/tsconfig.json +22 -22
  246. package/umd/index.js +0 -34103
@@ -1,242 +1,254 @@
1
- import Dec from 'decimal.js';
2
- import type Web3 from 'web3';
3
- import type { PastEventOptions } from 'web3-eth-contract';
4
- import type {
5
- Position, Interfaces, EthereumAddress, SubscriptionOptions, Contract, ParseData, PlaceholderType, BlockNumber,
6
- } from '../../types';
7
- import type {
8
- StrategyModel, SubStorage,
9
- } from '../../types/contracts/generated/SubStorage';
10
- import type { ChainId } from '../../types/enums';
11
- import { Strategies, ProtocolIdentifiers } from '../../types/enums';
12
-
13
- import { addToObjectIf, isDefined, isUndefined } from '../../services/utils';
14
- import { getAbiItem, makeSubStorageContract } from '../../services/contractService';
15
- import { getEventsFromContract, multicall } from '../../services/ethereumService';
16
- import { parseStrategiesAutomatedPosition } from '../../services/strategiesService';
17
-
18
- import Automation from './Automation';
19
-
20
- interface IStrategiesAutomation extends Interfaces.Automation {
21
- chainId: ChainId,
22
- providerFork: Web3,
23
- }
24
-
25
- export default class StrategiesAutomation extends Automation {
26
- protected chainId: ChainId;
27
-
28
- protected web3: Web3;
29
-
30
- protected web3Fork: Web3;
31
-
32
- protected subStorageContract: Contract.WithMeta<SubStorage>;
33
-
34
- protected subStorageContractFork: Contract.WithMeta<SubStorage> | null;
35
-
36
- constructor(args: IStrategiesAutomation) {
37
- super();
38
-
39
- this.web3 = args.provider;
40
- this.web3Fork = args.providerFork;
41
- this.chainId = args.chainId;
42
- this.subStorageContract = makeSubStorageContract(this.web3, this.chainId);
43
- this.subStorageContractFork = this.web3Fork ? makeSubStorageContract(this.web3Fork, this.chainId) : null;
44
-
45
- this.assert();
46
- }
47
-
48
- protected async getEventFromSubStorage(event: string, options?: PastEventOptions) {
49
- // only used for backfilling, so in case options?.fromBlock in undefined
50
- // (just like we omit fromBlock when we call from app when not on fork), we still want to fetch events
51
- if (new Dec(this.subStorageContract.createdBlock.toString()).gt(options?.fromBlock?.toString() || this.subStorageContract.createdBlock.toString())) {
52
- return [];
53
- }
54
- return getEventsFromContract<SubStorage>(this.subStorageContract, this.subStorageContractFork, event, options);
55
- }
56
-
57
- protected async getStrategiesSubs(subIds: number[], fromBlock: BlockNumber = 'latest'): Promise<StrategyModel.StoredSubDataStructOutputStruct[]> {
58
- let options : any;
59
- let web3: Web3;
60
-
61
- if (this.web3Fork && this.subStorageContractFork) {
62
- options = {
63
- target: this.subStorageContractFork.address,
64
- abiItem: getAbiItem(this.subStorageContractFork.abi, 'strategiesSubs'),
65
- };
66
- web3 = this.web3Fork;
67
- } else {
68
- options = {
69
- target: this.subStorageContract.address,
70
- abiItem: getAbiItem(this.subStorageContract.abi, 'strategiesSubs'),
71
- };
72
- web3 = this.web3;
73
- }
74
-
75
- const multicallCalls = subIds.map((subId) => ({ ...options, params: [subId] }));
76
- return multicall(web3, this.chainId, multicallCalls, fromBlock);
77
- }
78
-
79
- protected async getSubscriptionEventsFromSubStorage(options?: PastEventOptions) {
80
- return this.getEventFromSubStorage('Subscribe', options);
81
- }
82
-
83
- protected async getUpdateDataEventsFromSubStorage(options?: PastEventOptions) {
84
- const events = await this.getEventFromSubStorage('UpdateData', options);
85
- /** @dev - Some RPCs sort events differently */
86
- return events.sort((a, b) => a.blockNumber - b.blockNumber);
87
- }
88
-
89
- protected getParsedSubscriptions(parseData: ParseData) {
90
- return parseStrategiesAutomatedPosition(parseData);
91
- }
92
-
93
- /**
94
- * @description Removes expired Limit Order subscriptions
95
- */
96
- protected removeExpiredSubscriptions(subscriptions: (Position.Automated | null)[]) {
97
- return subscriptions.filter((subscription: Position.Automated | null) => {
98
- if (!subscription) {
99
- return true;
100
- }
101
-
102
- const { protocol, strategy, strategyData } = subscription;
103
-
104
- if (
105
- protocol.id === ProtocolIdentifiers.StrategiesAutomation.Exchange
106
- && strategy.strategyId === Strategies.Identifiers.LimitOrder
107
- ) {
108
- return new Dec(strategyData.decoded.triggerData.goodUntil).gt(new Dec(Date.now()).div(1000));
109
- }
110
-
111
- return true;
112
- });
113
- }
114
-
115
- private _mergeCheck(s:Position.Automated, current:Position.Automated) {
116
- return s.owner === current.owner
117
- && s.strategy.strategyId === current.strategy.strategyId
118
- && s.protocol.id === current.protocol.id
119
- && s.specific.mergeId === current.specific.mergeWithId
120
- && (
121
- s.protocol.id !== ProtocolIdentifiers.StrategiesAutomation.MakerDAO // reflexer needs to get added if we have it
122
- || s.strategyData.decoded.subData.vaultId === current.strategyData.decoded.triggerData.vaultId
123
- )
124
- && (
125
- s.protocol.id !== ProtocolIdentifiers.StrategiesAutomation.CrvUSD // merge only crvUSD leverage management for the same market
126
- || s.strategyData.decoded.subData.controller.toLowerCase() === current.strategyData.decoded.triggerData.controller.toLowerCase()
127
- )
128
- && (
129
- s.protocol.id !== ProtocolIdentifiers.StrategiesAutomation.MorphoBlue // merge morpho blue with the same marketId
130
- || s.strategyData.decoded.triggerData.marketId.toLowerCase() === current.strategyData.decoded.triggerData.marketId.toLowerCase()
131
- );
132
- }
133
-
134
- protected mergeSubs(_subscriptions:(Position.Automated | null)[]) {
135
- const mergeBase = _subscriptions.filter(s => isDefined(s) && isDefined(s.specific.mergeWithId)) as Position.Automated[];
136
- const mergeExtension = _subscriptions.filter(s => isDefined(s) && isDefined(s.specific.mergeId)) as Position.Automated[];
137
-
138
- let subscriptions:Position.Automated[] = (_subscriptions.filter(s => isDefined(s) && isUndefined(s.specific.mergeWithId) && isUndefined(s.specific.mergeId)) as Position.Automated[]).map((s) => ({
139
- ...s,
140
- subIds: [s.subId],
141
- }));
142
- mergeBase.forEach((current) => {
143
- const mergePairIndexSubEnabled = mergeExtension.findIndex(s => this._mergeCheck(s, current) && s.isEnabled === current.isEnabled);
144
- const mergePairIndexSubDisabled = mergeExtension.findIndex(s => this._mergeCheck(s, current));
145
-
146
- const mergePairIndex = mergePairIndexSubEnabled !== -1 ? mergePairIndexSubEnabled : mergePairIndexSubDisabled;
147
-
148
- if (mergePairIndex !== -1) {
149
- const mergePair = mergeExtension[mergePairIndex];
150
- mergeExtension.splice(mergePairIndex, 1);
151
- subscriptions.push({
152
- ...mergePair,
153
- ...current,
154
- // @ts-ignore
155
- blockNumber: Dec.max(mergePair.blockNumber, current.blockNumber).toNumber(),
156
- subIds: [current.subId, mergePair.subId],
157
- isEnabled: mergePair.isEnabled || current.isEnabled,
158
- specific: {
159
- ...mergePair.specific,
160
- ...current.specific,
161
- },
162
- });
163
- } else {
164
- subscriptions.push({
165
- ...current,
166
- subIds: [current.subId],
167
- });
168
- }
169
- });
170
- if (mergeExtension.length > 0) {
171
- console.error('Not all merge-able extensions were used', mergeExtension);
172
- subscriptions = [...subscriptions, ...mergeExtension.map((s) => ({
173
- ...s,
174
- subIds: [s.subId],
175
- }))];
176
- }
177
- return subscriptions;
178
- }
179
-
180
- protected async _getSubscriptions(addresses?: EthereumAddress[], options?: SubscriptionOptions): Promise<(Position.Automated | null)[]> {
181
- const _options = {
182
- ...addToObjectIf(isDefined(options), options),
183
- ...addToObjectIf(isDefined(addresses), { filter: { proxy: addresses } }),
184
- } as SubscriptionOptions & PastEventOptions;
185
-
186
- let subscriptionEvents = (await this.getSubscriptionEventsFromSubStorage(_options)) as PlaceholderType; // TODO PlaceholderType
187
-
188
- let subscriptions: (Position.Automated | null)[] = [];
189
-
190
- if (subscriptionEvents) {
191
- let strategiesSubs = await this.getStrategiesSubs(
192
- subscriptionEvents.map((e: { returnValues: { subId: number } }) => e.returnValues.subId), _options.toBlock,
193
- );
194
-
195
- if (_options.enabledOnly) {
196
- const filteredSubscriptionEvents = [] as PlaceholderType;
197
-
198
- strategiesSubs = strategiesSubs.filter((sub, index) => {
199
- if (sub?.isEnabled) filteredSubscriptionEvents.push(subscriptionEvents[index]);
200
- return sub?.isEnabled;
201
- });
202
-
203
- subscriptionEvents = filteredSubscriptionEvents;
204
- }
205
-
206
- subscriptions = await Promise.all(strategiesSubs.map(async (sub, index: number) => {
207
- let latestUpdate = subscriptionEvents[index].returnValues;
208
-
209
- if (latestUpdate.subHash !== sub?.strategySubHash) {
210
- const updates = await this.getUpdateDataEventsFromSubStorage({
211
- ...addToObjectIf(!!_options, _options),
212
- filter: { subId: latestUpdate.subId },
213
- });
214
- latestUpdate = {
215
- ...latestUpdate, // Update is missing proxy, hence this
216
- ...updates?.[updates.length - 1]?.returnValues,
217
- };
218
- }
219
- return this.getParsedSubscriptions({
220
- chainId: this.chainId,
221
- blockNumber: subscriptionEvents[index].blockNumber,
222
- subscriptionEventData: latestUpdate,
223
- strategiesSubsData: sub,
224
- });
225
- }));
226
-
227
- if (options?.mergeSubs) {
228
- subscriptions = this.mergeSubs(subscriptions);
229
- }
230
- }
231
-
232
- return _options.unexpiredOnly ? this.removeExpiredSubscriptions(subscriptions) : subscriptions;
233
- }
234
-
235
- public async getSubscriptions(options?: SubscriptionOptions): Promise<(Position.Automated | null)[]> {
236
- return this._getSubscriptions(undefined, options);
237
- }
238
-
239
- public async getSubscriptionsFor(addresses: EthereumAddress[], options?: SubscriptionOptions): Promise<(Position.Automated | null)[]> {
240
- return this._getSubscriptions(addresses, options);
241
- }
242
- }
1
+ import Dec from 'decimal.js';
2
+ import type Web3 from 'web3';
3
+ import type { PastEventOptions } from 'web3-eth-contract';
4
+ import PromisePool from 'es6-promise-pool';
5
+ import type {
6
+ Position, Interfaces, EthereumAddress, SubscriptionOptions, Contract, ParseData, PlaceholderType, BlockNumber,
7
+ } from '../../types';
8
+ import type {
9
+ StrategyModel, Subscribe, SubStorage, UpdateData,
10
+ } from '../../types/contracts/generated/SubStorage';
11
+ import type { ChainId } from '../../types/enums';
12
+ import { Strategies, ProtocolIdentifiers } from '../../types/enums';
13
+
14
+ import { addToObjectIf, isDefined, isUndefined } from '../../services/utils';
15
+ import { getAbiItem, makeSubStorageContract } from '../../services/contractService';
16
+ import { getEventsFromContract, multicall } from '../../services/ethereumService';
17
+ import { parseStrategiesAutomatedPosition } from '../../services/strategiesService';
18
+
19
+ import Automation from './Automation';
20
+
21
+ interface IStrategiesAutomation extends Interfaces.Automation {
22
+ chainId: ChainId,
23
+ providerFork?: Web3,
24
+ }
25
+
26
+ export default class StrategiesAutomation extends Automation {
27
+ protected chainId: ChainId;
28
+
29
+ protected web3: Web3;
30
+
31
+ protected web3Fork?: Web3;
32
+
33
+ protected subStorageContract: Contract.WithMeta<SubStorage>;
34
+
35
+ protected subStorageContractFork: Contract.WithMeta<SubStorage> | null;
36
+
37
+ constructor(args: IStrategiesAutomation) {
38
+ super();
39
+
40
+ this.web3 = args.provider;
41
+ this.web3Fork = args.providerFork;
42
+ this.chainId = args.chainId;
43
+ this.subStorageContract = makeSubStorageContract(this.web3, this.chainId);
44
+ this.subStorageContractFork = this.web3Fork ? makeSubStorageContract(this.web3Fork, this.chainId) : null;
45
+
46
+ this.assert();
47
+ }
48
+
49
+ protected async getEventFromSubStorage(event: string, options?: PastEventOptions) {
50
+ // only used for backfilling, so in case options?.fromBlock in undefined
51
+ // (just like we omit fromBlock when we call from app when not on fork), we still want to fetch events
52
+ if (new Dec(this.subStorageContract.createdBlock.toString()).gt(options?.fromBlock?.toString() || this.subStorageContract.createdBlock.toString())) {
53
+ return [];
54
+ }
55
+ return getEventsFromContract<SubStorage>(this.subStorageContract, this.subStorageContractFork, event, options);
56
+ }
57
+
58
+ protected async getStrategiesSubs(subIds: number[], fromBlock: BlockNumber = 'latest'): Promise<StrategyModel.StoredSubDataStructOutputStruct[]> {
59
+ let options : any;
60
+ let web3: Web3;
61
+
62
+ if (this.web3Fork && this.subStorageContractFork) {
63
+ options = {
64
+ target: this.subStorageContractFork.address,
65
+ abiItem: getAbiItem(this.subStorageContractFork.abi, 'strategiesSubs'),
66
+ };
67
+ web3 = this.web3Fork;
68
+ } else {
69
+ options = {
70
+ target: this.subStorageContract.address,
71
+ abiItem: getAbiItem(this.subStorageContract.abi, 'strategiesSubs'),
72
+ };
73
+ web3 = this.web3;
74
+ }
75
+
76
+ const multicallCalls = subIds.map((subId) => ({ ...options, params: [subId] }));
77
+ return multicall(web3, this.chainId, multicallCalls, fromBlock);
78
+ }
79
+
80
+ protected async getSubscriptionEventsFromSubStorage(options?: PastEventOptions) {
81
+ return this.getEventFromSubStorage('Subscribe', options) as Promise<Subscribe[]>;
82
+ }
83
+
84
+ protected async getUpdateDataEventsFromSubStorage(options?: PastEventOptions) {
85
+ const events = await this.getEventFromSubStorage('UpdateData', options);
86
+ /** @dev - Some RPCs sort events differently */
87
+ return events.sort((a, b) => a.blockNumber - b.blockNumber) as UpdateData[];
88
+ }
89
+
90
+ protected getParsedSubscriptions(parseData: ParseData) {
91
+ return parseStrategiesAutomatedPosition(parseData);
92
+ }
93
+
94
+ /**
95
+ * @description Removes expired Limit Order subscriptions
96
+ */
97
+ protected removeExpiredSubscriptions(subscriptions: (Position.Automated | null)[]) {
98
+ return subscriptions.filter((subscription: Position.Automated | null) => {
99
+ if (!subscription) {
100
+ return true;
101
+ }
102
+
103
+ const { protocol, strategy, strategyData } = subscription;
104
+
105
+ if (
106
+ protocol.id === ProtocolIdentifiers.StrategiesAutomation.Exchange
107
+ && strategy.strategyId === Strategies.Identifiers.LimitOrder
108
+ ) {
109
+ return new Dec(strategyData.decoded.triggerData.goodUntil).gt(new Dec(Date.now()).div(1000));
110
+ }
111
+
112
+ return true;
113
+ });
114
+ }
115
+
116
+ private _mergeCheck(s:Position.Automated, current:Position.Automated) {
117
+ return s.owner === current.owner
118
+ && s.strategy.strategyId === current.strategy.strategyId
119
+ && s.protocol.id === current.protocol.id
120
+ && s.specific.mergeId === current.specific.mergeWithId
121
+ && (
122
+ s.protocol.id !== ProtocolIdentifiers.StrategiesAutomation.MakerDAO // reflexer needs to get added if we have it
123
+ || s.strategyData.decoded.subData.vaultId === current.strategyData.decoded.triggerData.vaultId
124
+ )
125
+ && (
126
+ s.protocol.id !== ProtocolIdentifiers.StrategiesAutomation.CrvUSD // merge only crvUSD leverage management for the same market
127
+ || s.strategyData.decoded.subData.controller.toLowerCase() === current.strategyData.decoded.triggerData.controller.toLowerCase()
128
+ )
129
+ && (
130
+ s.protocol.id !== ProtocolIdentifiers.StrategiesAutomation.MorphoBlue // merge morpho blue with the same marketId
131
+ || s.strategyData.decoded.triggerData.marketId.toLowerCase() === current.strategyData.decoded.triggerData.marketId.toLowerCase()
132
+ );
133
+ }
134
+
135
+ protected mergeSubs(_subscriptions:(Position.Automated | null)[]) {
136
+ const mergeBase = _subscriptions.filter(s => isDefined(s) && isDefined(s.specific.mergeWithId)) as Position.Automated[];
137
+ const mergeExtension = _subscriptions.filter(s => isDefined(s) && isDefined(s.specific.mergeId)) as Position.Automated[];
138
+
139
+ let subscriptions:Position.Automated[] = (_subscriptions.filter(s => isDefined(s) && isUndefined(s.specific.mergeWithId) && isUndefined(s.specific.mergeId)) as Position.Automated[]).map((s) => ({
140
+ ...s,
141
+ subIds: [s.subId],
142
+ }));
143
+ mergeBase.forEach((current) => {
144
+ const mergePairIndexSubEnabled = mergeExtension.findIndex(s => this._mergeCheck(s, current) && s.isEnabled === current.isEnabled);
145
+ const mergePairIndexSubDisabled = mergeExtension.findIndex(s => this._mergeCheck(s, current));
146
+
147
+ const mergePairIndex = mergePairIndexSubEnabled !== -1 ? mergePairIndexSubEnabled : mergePairIndexSubDisabled;
148
+
149
+ if (mergePairIndex !== -1) {
150
+ const mergePair = mergeExtension[mergePairIndex];
151
+ mergeExtension.splice(mergePairIndex, 1);
152
+ subscriptions.push({
153
+ ...mergePair,
154
+ ...current,
155
+ // @ts-ignore
156
+ blockNumber: Dec.max(mergePair.blockNumber, current.blockNumber).toNumber(),
157
+ subIds: [current.subId, mergePair.subId],
158
+ isEnabled: mergePair.isEnabled || current.isEnabled,
159
+ specific: {
160
+ ...mergePair.specific,
161
+ ...current.specific,
162
+ },
163
+ });
164
+ } else {
165
+ subscriptions.push({
166
+ ...current,
167
+ subIds: [current.subId],
168
+ });
169
+ }
170
+ });
171
+ if (mergeExtension.length > 0) {
172
+ console.error('Not all merge-able extensions were used', mergeExtension);
173
+ subscriptions = [...subscriptions, ...mergeExtension.map((s) => ({
174
+ ...s,
175
+ subIds: [s.subId],
176
+ }))];
177
+ }
178
+ return subscriptions;
179
+ }
180
+
181
+ protected async _getSubscriptions(addresses?: EthereumAddress[], options?: SubscriptionOptions): Promise<(Position.Automated | null)[]> {
182
+ const _options = {
183
+ ...addToObjectIf(isDefined(options), options),
184
+ ...addToObjectIf(isDefined(addresses), { filter: { proxy: addresses } }),
185
+ } as SubscriptionOptions & PastEventOptions;
186
+
187
+ let subscriptionEvents = await this.getSubscriptionEventsFromSubStorage(_options);
188
+
189
+ let subscriptions: (Position.Automated | null)[] = [];
190
+
191
+ if (subscriptionEvents) {
192
+ let strategiesSubs = await this.getStrategiesSubs(
193
+ subscriptionEvents.map((e) => +e.returnValues.subId), _options.toBlock,
194
+ );
195
+
196
+ if (_options.enabledOnly) {
197
+ const filteredSubscriptionEvents = [] as PlaceholderType;
198
+
199
+ strategiesSubs = strategiesSubs.filter((sub, index) => {
200
+ if (sub?.isEnabled) filteredSubscriptionEvents.push(subscriptionEvents[index]);
201
+ return sub?.isEnabled;
202
+ });
203
+
204
+ subscriptionEvents = filteredSubscriptionEvents;
205
+ }
206
+
207
+ const replaceSubWithUpdate = async (index: number) => {
208
+ const sub = strategiesSubs[index];
209
+ let latestUpdate = subscriptionEvents[index].returnValues;
210
+
211
+ if (latestUpdate.subHash !== sub?.strategySubHash) {
212
+ const updates = await this.getUpdateDataEventsFromSubStorage({
213
+ ...addToObjectIf(!!_options, _options),
214
+ filter: { subId: latestUpdate.subId },
215
+ });
216
+ latestUpdate = {
217
+ ...latestUpdate, // Update is missing proxy, hence this
218
+ ...updates?.[updates.length - 1]?.returnValues,
219
+ };
220
+ }
221
+ subscriptions.push(
222
+ this.getParsedSubscriptions({
223
+ chainId: this.chainId,
224
+ blockNumber: subscriptionEvents[index].blockNumber,
225
+ subscriptionEventData: latestUpdate,
226
+ strategiesSubsData: sub,
227
+ }),
228
+ );
229
+ };
230
+
231
+ const generatePromises = function* () {
232
+ for (let index = 0; index < strategiesSubs.length; index++) {
233
+ yield replaceSubWithUpdate(index);
234
+ }
235
+ };
236
+ const pool = new PromisePool(generatePromises as any, 50);
237
+ await pool.start();
238
+
239
+ if (options?.mergeSubs) {
240
+ subscriptions = this.mergeSubs(subscriptions);
241
+ }
242
+ }
243
+
244
+ return _options.unexpiredOnly ? this.removeExpiredSubscriptions(subscriptions) : subscriptions;
245
+ }
246
+
247
+ public async getSubscriptions(options?: SubscriptionOptions): Promise<(Position.Automated | null)[]> {
248
+ return this._getSubscriptions(undefined, options);
249
+ }
250
+
251
+ public async getSubscriptionsFor(addresses: EthereumAddress[], options?: SubscriptionOptions): Promise<(Position.Automated | null)[]> {
252
+ return this._getSubscriptions(addresses, options);
253
+ }
254
+ }
@@ -1,10 +1,10 @@
1
- import type { Interfaces } from '../../types';
2
-
3
- import StrategiesAutomation from '../private/StrategiesAutomation';
4
- import { ChainId } from '../../types/enums';
5
-
6
- export default class ArbitrumStrategies extends StrategiesAutomation {
7
- constructor(args: Interfaces.Automation) {
8
- super({ ...args, chainId: ChainId.Arbitrum });
9
- }
10
- }
1
+ import type { Interfaces } from '../../types';
2
+
3
+ import StrategiesAutomation from '../private/StrategiesAutomation';
4
+ import { ChainId } from '../../types/enums';
5
+
6
+ export default class ArbitrumStrategies extends StrategiesAutomation {
7
+ constructor(args: Interfaces.Automation) {
8
+ super({ ...args, chainId: ChainId.Arbitrum });
9
+ }
10
+ }
@@ -1,10 +1,10 @@
1
- import type { Interfaces } from '../../types';
2
-
3
- import StrategiesAutomation from '../private/StrategiesAutomation';
4
- import { ChainId } from '../../types/enums';
5
-
6
- export default class BaseStrategies extends StrategiesAutomation {
7
- constructor(args: Interfaces.Automation) {
8
- super({ ...args, chainId: ChainId.Base });
9
- }
10
- }
1
+ import type { Interfaces } from '../../types';
2
+
3
+ import StrategiesAutomation from '../private/StrategiesAutomation';
4
+ import { ChainId } from '../../types/enums';
5
+
6
+ export default class BaseStrategies extends StrategiesAutomation {
7
+ constructor(args: Interfaces.Automation) {
8
+ super({ ...args, chainId: ChainId.Base });
9
+ }
10
+ }
@@ -1,10 +1,10 @@
1
- import type { Interfaces } from '../../types';
2
-
3
- import StrategiesAutomation from '../private/StrategiesAutomation';
4
- import { ChainId } from '../../types/enums';
5
-
6
- export default class EthereumStrategies extends StrategiesAutomation {
7
- constructor(args: Interfaces.Automation) {
8
- super({ ...args, chainId: ChainId.Ethereum });
9
- }
10
- }
1
+ import type { Interfaces } from '../../types';
2
+
3
+ import StrategiesAutomation from '../private/StrategiesAutomation';
4
+ import { ChainId } from '../../types/enums';
5
+
6
+ export default class EthereumStrategies extends StrategiesAutomation {
7
+ constructor(args: Interfaces.Automation) {
8
+ super({ ...args, chainId: ChainId.Ethereum });
9
+ }
10
+ }
@@ -1,10 +1,10 @@
1
- import type { Interfaces } from '../../types';
2
-
3
- import StrategiesAutomation from '../private/StrategiesAutomation';
4
- import { ChainId } from '../../types/enums';
5
-
6
- export default class OptimismStrategies extends StrategiesAutomation {
7
- constructor(args: Interfaces.Automation) {
8
- super({ ...args, chainId: ChainId.Optimism });
9
- }
10
- }
1
+ import type { Interfaces } from '../../types';
2
+
3
+ import StrategiesAutomation from '../private/StrategiesAutomation';
4
+ import { ChainId } from '../../types/enums';
5
+
6
+ export default class OptimismStrategies extends StrategiesAutomation {
7
+ constructor(args: Interfaces.Automation) {
8
+ super({ ...args, chainId: ChainId.Optimism });
9
+ }
10
+ }
@@ -0,0 +1,49 @@
1
+ import Web3 from 'web3';
2
+ import { expect } from 'chai';
3
+
4
+ import {ChainId} from '../../types/enums';
5
+
6
+ import '../../configuration';
7
+ import EthereumStrategies from './EthereumStrategies';
8
+ import ArbitrumStrategies from './ArbitrumStrategies';
9
+ import OptimismStrategies from './OptimismStrategies';
10
+ import BaseStrategies from './BaseStrategies';
11
+
12
+ require('dotenv').config({ path: '.env' });
13
+
14
+ const Web3_1 = new Web3(process.env.RPC_1!);
15
+ const Web3_42161 = new Web3(process.env.RPC_42161!);
16
+ const Web3_10 = new Web3(process.env.RPC_10!);
17
+ const Web3_8453 = new Web3(process.env.RPC_8453!);
18
+
19
+ describe('Feature: StrategiesAutomation.ts', () => {
20
+ describe('Fetching subscriptions', () => {
21
+ it('can fetch subscriptions on Mainnet', async function () {
22
+ this.timeout(120000);
23
+ const ethStrategies = new EthereumStrategies({provider: Web3_1});
24
+ const subs = await ethStrategies.getSubscriptions({mergeSubs: true})
25
+ console.log(subs.length);
26
+ });
27
+
28
+ it('can fetch subscriptions on Arbitrum', async function () {
29
+ this.timeout(120000);
30
+ const arbiStrategies = new ArbitrumStrategies({provider: Web3_42161});
31
+ const subs = await arbiStrategies.getSubscriptions({mergeSubs: true})
32
+ console.log(subs.length);
33
+ });
34
+
35
+ it('can fetch subscriptions on Optimism', async function () {
36
+ this.timeout(120000);
37
+ const optimismStrategies = new OptimismStrategies({provider: Web3_10});
38
+ const subs = await optimismStrategies.getSubscriptions({mergeSubs: true})
39
+ console.log(subs.length);
40
+ });
41
+
42
+ it('can fetch subscriptions on Base', async function () {
43
+ this.timeout(120000);
44
+ const baseStrategies = new BaseStrategies({provider: Web3_8453});
45
+ const subs = await baseStrategies.getSubscriptions({mergeSubs: true})
46
+ console.log(subs.length);
47
+ });
48
+ });
49
+ });