@paraswap/dex-lib 3.8.14 → 3.8.16-oswap

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 (219) hide show
  1. package/build/abi/concentrator/arUSD.json +568 -0
  2. package/build/abi/concentrator/arUSD5115.json +1746 -0
  3. package/build/abi/fx-protocol/FxMarket.json +1284 -0
  4. package/build/abi/{wombat/pool.json → fx-protocol/FxUSD.json} +541 -603
  5. package/build/abi/fx-protocol/weETHOralce.json +676 -0
  6. package/build/abi/inception/inception-ineth-pool.json +1062 -0
  7. package/build/abi/inception/inception-ineth.json +609 -0
  8. package/build/abi/inception/inception-ratio-feed.json +93 -0
  9. package/build/abi/inception/inception-vault.json +991 -0
  10. package/build/abi/infusion/InfusionFactory.json +147 -0
  11. package/build/abi/infusion/InfusionPair.json +658 -0
  12. package/build/abi/infusion/InfusionRouter.json +442 -0
  13. package/build/abi/oswap/oswap.abi.json +452 -0
  14. package/build/dex/aave-v1/aave-v1.js +0 -1
  15. package/build/dex/aave-v1/aave-v1.js.map +1 -1
  16. package/build/dex/angle-transmuter/angle-transmuter.js +1 -1
  17. package/build/dex/angle-transmuter/angle-transmuter.js.map +1 -1
  18. package/build/dex/concentrator-arusd/concentrator-arusd-event.d.ts +17 -0
  19. package/build/dex/concentrator-arusd/concentrator-arusd-event.js +66 -0
  20. package/build/dex/concentrator-arusd/concentrator-arusd-event.js.map +1 -0
  21. package/build/dex/concentrator-arusd/concentrator-arusd.d.ts +41 -0
  22. package/build/dex/concentrator-arusd/concentrator-arusd.js +188 -0
  23. package/build/dex/concentrator-arusd/concentrator-arusd.js.map +1 -0
  24. package/build/dex/concentrator-arusd/config.d.ts +3 -0
  25. package/build/dex/concentrator-arusd/config.js +14 -0
  26. package/build/dex/concentrator-arusd/config.js.map +1 -0
  27. package/build/dex/concentrator-arusd/types.d.ts +14 -0
  28. package/build/dex/concentrator-arusd/types.js +3 -0
  29. package/build/dex/concentrator-arusd/types.js.map +1 -0
  30. package/build/dex/concentrator-arusd/utils.d.ts +4 -0
  31. package/build/dex/concentrator-arusd/utils.js +27 -0
  32. package/build/dex/concentrator-arusd/utils.js.map +1 -0
  33. package/build/dex/fx-protocol-rusd/config.d.ts +3 -0
  34. package/build/dex/fx-protocol-rusd/config.js +15 -0
  35. package/build/dex/fx-protocol-rusd/config.js.map +1 -0
  36. package/build/dex/fx-protocol-rusd/fx-protocol-rusd-event.d.ts +18 -0
  37. package/build/dex/fx-protocol-rusd/fx-protocol-rusd-event.js +71 -0
  38. package/build/dex/fx-protocol-rusd/fx-protocol-rusd-event.js.map +1 -0
  39. package/build/dex/fx-protocol-rusd/fx-protocol-rusd.d.ts +39 -0
  40. package/build/dex/fx-protocol-rusd/fx-protocol-rusd.js +201 -0
  41. package/build/dex/fx-protocol-rusd/fx-protocol-rusd.js.map +1 -0
  42. package/build/dex/fx-protocol-rusd/types.d.ts +13 -0
  43. package/build/dex/fx-protocol-rusd/types.js +3 -0
  44. package/build/dex/fx-protocol-rusd/types.js.map +1 -0
  45. package/build/dex/fx-protocol-rusd/utils.d.ts +4 -0
  46. package/build/dex/fx-protocol-rusd/utils.js +26 -0
  47. package/build/dex/fx-protocol-rusd/utils.js.map +1 -0
  48. package/build/dex/idex.d.ts +11 -7
  49. package/build/dex/idle-dao/idle-dao-pool.d.ts +56 -0
  50. package/build/dex/idle-dao/idle-dao-pool.js +176 -0
  51. package/build/dex/idle-dao/idle-dao-pool.js.map +1 -0
  52. package/build/dex/idle-dao/idle-dao-pooling-pool.d.ts +16 -0
  53. package/build/dex/idle-dao/idle-dao-pooling-pool.js +57 -0
  54. package/build/dex/idle-dao/idle-dao-pooling-pool.js.map +1 -0
  55. package/build/dex/idle-dao/scripts.d.ts +9 -0
  56. package/build/dex/idle-dao/scripts.js +552 -0
  57. package/build/dex/idle-dao/scripts.js.map +1 -0
  58. package/build/dex/inception/config.d.ts +5 -0
  59. package/build/dex/inception/config.js +112 -0
  60. package/build/dex/inception/config.js.map +1 -0
  61. package/build/dex/inception/inception-event-pool.d.ts +23 -0
  62. package/build/dex/inception/inception-event-pool.js +34 -0
  63. package/build/dex/inception/inception-event-pool.js.map +1 -0
  64. package/build/dex/inception/inception-native.d.ts +43 -0
  65. package/build/dex/inception/inception-native.js +131 -0
  66. package/build/dex/inception/inception-native.js.map +1 -0
  67. package/build/dex/inception/inception-pool.d.ts +18 -0
  68. package/build/dex/inception/inception-pool.js +32 -0
  69. package/build/dex/inception/inception-pool.js.map +1 -0
  70. package/build/dex/inception/inception-price-feed.d.ts +19 -0
  71. package/build/dex/inception/inception-price-feed.js +51 -0
  72. package/build/dex/inception/inception-price-feed.js.map +1 -0
  73. package/build/dex/inception/inception.d.ts +44 -0
  74. package/build/dex/inception/inception.js +162 -0
  75. package/build/dex/inception/inception.js.map +1 -0
  76. package/build/dex/inception/tokens.d.ts +9 -0
  77. package/build/dex/inception/tokens.js +28 -0
  78. package/build/dex/inception/tokens.js.map +1 -0
  79. package/build/dex/inception/types.d.ts +22 -0
  80. package/build/dex/inception/types.js +3 -0
  81. package/build/dex/inception/types.js.map +1 -0
  82. package/build/dex/inception/utils.d.ts +7 -0
  83. package/build/dex/inception/utils.js +58 -0
  84. package/build/dex/inception/utils.js.map +1 -0
  85. package/build/dex/index.js +6 -0
  86. package/build/dex/index.js.map +1 -1
  87. package/build/dex/infusion/config.d.ts +4 -0
  88. package/build/dex/infusion/config.js +25 -0
  89. package/build/dex/infusion/config.js.map +1 -0
  90. package/build/dex/infusion/infusion-stable-pool.d.ts +4 -0
  91. package/build/dex/infusion/infusion-stable-pool.js +74 -0
  92. package/build/dex/infusion/infusion-stable-pool.js.map +1 -0
  93. package/build/dex/infusion/infusion.d.ts +54 -0
  94. package/build/dex/infusion/infusion.js +510 -0
  95. package/build/dex/infusion/infusion.js.map +1 -0
  96. package/build/dex/infusion/types.d.ts +47 -0
  97. package/build/dex/infusion/types.js +3 -0
  98. package/build/dex/infusion/types.js.map +1 -0
  99. package/build/dex/infusion/utils/isStablePair.d.ts +2 -0
  100. package/build/dex/infusion/utils/isStablePair.js +18 -0
  101. package/build/dex/infusion/utils/isStablePair.js.map +1 -0
  102. package/build/dex/oswap/config.d.ts +5 -0
  103. package/build/dex/oswap/config.js +31 -0
  104. package/build/dex/oswap/config.js.map +1 -0
  105. package/build/dex/oswap/oswap-pool.d.ts +51 -0
  106. package/build/dex/oswap/oswap-pool.js +150 -0
  107. package/build/dex/oswap/oswap-pool.js.map +1 -0
  108. package/build/dex/oswap/oswap.d.ts +46 -0
  109. package/build/dex/oswap/oswap.js +273 -0
  110. package/build/dex/oswap/oswap.js.map +1 -0
  111. package/build/dex/oswap/types.d.ts +20 -0
  112. package/build/dex/oswap/types.js +3 -0
  113. package/build/dex/oswap/types.js.map +1 -0
  114. package/build/dex/platypus/platypus.js +3 -17
  115. package/build/dex/platypus/platypus.js.map +1 -1
  116. package/build/dex/swaap-v1/swaap-v1.js +0 -4
  117. package/build/dex/swaap-v1/swaap-v1.js.map +1 -1
  118. package/build/dex/weth/config.js +3 -0
  119. package/build/dex/weth/config.js.map +1 -1
  120. package/package.json +1 -1
  121. package/src/abi/concentrator/arUSD.json +568 -0
  122. package/src/abi/concentrator/arUSD5115.json +1746 -0
  123. package/src/abi/fx-protocol/FxMarket.json +1284 -0
  124. package/src/abi/fx-protocol/FxUSD.json +1227 -0
  125. package/src/abi/fx-protocol/weETHOralce.json +676 -0
  126. package/src/abi/oswap/oswap.abi.json +452 -0
  127. package/src/dex/angle-transmuter/angle-transmuter.ts +1 -1
  128. package/src/dex/concentrator-arusd/concentrator-arusd-e2e.test.ts +92 -0
  129. package/src/dex/concentrator-arusd/concentrator-arusd-event.ts +100 -0
  130. package/src/dex/concentrator-arusd/concentrator-arusd-integration.test.ts +104 -0
  131. package/src/dex/concentrator-arusd/concentrator-arusd.ts +269 -0
  132. package/src/dex/concentrator-arusd/concetrator-arusd-events.test.ts +97 -0
  133. package/src/dex/concentrator-arusd/config.ts +13 -0
  134. package/src/dex/concentrator-arusd/types.ts +16 -0
  135. package/src/dex/concentrator-arusd/utils.ts +36 -0
  136. package/src/dex/fx-protocol-rusd/config.ts +14 -0
  137. package/src/dex/fx-protocol-rusd/fx-protocol-e2e.test.ts +96 -0
  138. package/src/dex/fx-protocol-rusd/fx-protocol-events.test.ts +101 -0
  139. package/src/dex/fx-protocol-rusd/fx-protocol-integration.test.ts +104 -0
  140. package/src/dex/fx-protocol-rusd/fx-protocol-rusd-event.ts +112 -0
  141. package/src/dex/fx-protocol-rusd/fx-protocol-rusd.ts +282 -0
  142. package/src/dex/fx-protocol-rusd/types.ts +16 -0
  143. package/src/dex/fx-protocol-rusd/utils.ts +47 -0
  144. package/src/dex/idex.ts +48 -41
  145. package/src/dex/index.ts +6 -0
  146. package/src/dex/oswap/config.ts +32 -0
  147. package/src/dex/oswap/oswap-e2e.test.ts +91 -0
  148. package/src/dex/oswap/oswap-events.test.ts +88 -0
  149. package/src/dex/oswap/oswap-integration.test.ts +269 -0
  150. package/src/dex/oswap/oswap-pool.ts +190 -0
  151. package/src/dex/oswap/oswap.ts +392 -0
  152. package/src/dex/oswap/types.ts +29 -0
  153. package/src/dex/weth/config.ts +3 -0
  154. package/src/dex/weth/weth-e2e.test.ts +156 -0
  155. package/src/dex/wsteth/wsteth-integration.test.ts +0 -1
  156. package/tests/constants-e2e.ts +10 -0
  157. package/.vscode/launch.json +0 -53
  158. package/.vscode/settings.json +0 -2
  159. package/.vscode/tasks.json +0 -15
  160. package/build/abi/maverick-v2/MaverickV2Router.json +0 -778
  161. package/build/abi/uniswap-v3/AlienBaseV3Router.abi.json +0 -52
  162. package/build/dex/aave-v2/tokens-avalanche.json +0 -44
  163. package/build/dex/aave-v2/tokens-mainnet.json +0 -188
  164. package/build/dex/aave-v2/tokens-polygon.json +0 -44
  165. package/build/dex/bProtocol.d.ts +0 -18
  166. package/build/dex/bProtocol.js +0 -39
  167. package/build/dex/bProtocol.js.map +0 -1
  168. package/build/dex/bancor.d.ts +0 -26
  169. package/build/dex/bancor.js +0 -58
  170. package/build/dex/bancor.js.map +0 -1
  171. package/build/dex/compound.d.ts +0 -18
  172. package/build/dex/compound.js +0 -46
  173. package/build/dex/compound.js.map +0 -1
  174. package/build/dex/curve-v2.d.ts +0 -58
  175. package/build/dex/curve-v2.js +0 -180
  176. package/build/dex/curve-v2.js.map +0 -1
  177. package/build/dex/dodo-v1.d.ts +0 -33
  178. package/build/dex/dodo-v1.js +0 -63
  179. package/build/dex/dodo-v1.js.map +0 -1
  180. package/build/dex/lido.d.ts +0 -19
  181. package/build/dex/lido.js +0 -42
  182. package/build/dex/lido.js.map +0 -1
  183. package/build/dex/maker-psm/scripts/gem.abi.json +0 -136
  184. package/build/dex/maker-psm/scripts/validate-state.d.ts +0 -0
  185. package/build/dex/maker-psm/scripts/validate-state.js +0 -185
  186. package/build/dex/maker-psm/scripts/validate-state.js.map +0 -1
  187. package/build/dex/maker-psm/scripts/vat.abi.json +0 -243
  188. package/build/dex/onebit.d.ts +0 -25
  189. package/build/dex/onebit.js +0 -42
  190. package/build/dex/onebit.js.map +0 -1
  191. package/build/dex/smoothy.d.ts +0 -26
  192. package/build/dex/smoothy.js +0 -48
  193. package/build/dex/smoothy.js.map +0 -1
  194. package/build/dex/solidly-v3/scripts/check-event-pool-event.d.ts +0 -1
  195. package/build/dex/solidly-v3/scripts/check-event-pool-event.js +0 -53
  196. package/build/dex/solidly-v3/scripts/check-event-pool-event.js.map +0 -1
  197. package/build/dex/stable-pool.d.ts +0 -28
  198. package/build/dex/stable-pool.js +0 -55
  199. package/build/dex/stable-pool.js.map +0 -1
  200. package/build/dex/trader-joe-v2.1/base.d.ts +0 -18
  201. package/build/dex/trader-joe-v2.1/base.js +0 -99
  202. package/build/dex/trader-joe-v2.1/base.js.map +0 -1
  203. package/build/dex/trader-joe-v2.1/trader-joe-v2.1-new.d.ts +0 -7
  204. package/build/dex/trader-joe-v2.1/trader-joe-v2.1-new.js +0 -20
  205. package/build/dex/trader-joe-v2.1/trader-joe-v2.1-new.js.map +0 -1
  206. package/build/dex/trader-joe-v2.1/trader-joe-v2.2.d.ts +0 -7
  207. package/build/dex/trader-joe-v2.1/trader-joe-v2.2.js +0 -20
  208. package/build/dex/trader-joe-v2.1/trader-joe-v2.2.js.map +0 -1
  209. package/build/dex/trader-joe-v2.1.d.ts +0 -43
  210. package/build/dex/trader-joe-v2.1.js +0 -79
  211. package/build/dex/trader-joe-v2.1.js.map +0 -1
  212. package/build/dex/uniswap-v3/forks/alien-base-v3/alien-base-v3.d.ts +0 -17
  213. package/build/dex/uniswap-v3/forks/alien-base-v3/alien-base-v3.js +0 -64
  214. package/build/dex/uniswap-v3/forks/alien-base-v3/alien-base-v3.js.map +0 -1
  215. package/build/dex/uniswap-v3/forks/alien-v3/alien-v3.d.ts +0 -17
  216. package/build/dex/uniswap-v3/forks/alien-v3/alien-v3.js +0 -79
  217. package/build/dex/uniswap-v3/forks/alien-v3/alien-v3.js.map +0 -1
  218. package/config.ts +0 -1946
  219. package/src/dex/dexs.txt +0 -58
@@ -0,0 +1,190 @@
1
+ import { Interface } from '@ethersproject/abi';
2
+ import { DeepReadonly } from 'ts-essentials';
3
+ import { Log, Logger, Token } from '../../types';
4
+ import { catchParseLogError } from '../../utils';
5
+ import { StatefulEventSubscriber } from '../../stateful-event-subscriber';
6
+ import { IDexHelper } from '../../dex-helper/idex-helper';
7
+ import { MultiCallParams } from '../../lib/multi-wrapper';
8
+ import { uint256ToBigInt } from '../../lib/decoders';
9
+ import { OSwapPool, OSwapPoolState } from './types';
10
+ import OSwapABI from '../../abi/oswap/oswap.abi.json';
11
+ import ERC20ABI from '../../abi/ERC20.abi.json';
12
+
13
+ export class OSwapEventPool extends StatefulEventSubscriber<OSwapPoolState> {
14
+ handlers: {
15
+ [event: string]: (
16
+ event: any,
17
+ state: DeepReadonly<OSwapPoolState>,
18
+ log: Readonly<Log>,
19
+ ) => DeepReadonly<OSwapPoolState> | null;
20
+ } = {};
21
+
22
+ logDecoder: (log: Log) => any;
23
+
24
+ addressesSubscribed: string[];
25
+
26
+ constructor(
27
+ readonly parentName: string,
28
+ readonly pool: OSwapPool,
29
+ protected network: number,
30
+ protected dexHelper: IDexHelper,
31
+ logger: Logger,
32
+ protected iOSwap = new Interface(OSwapABI),
33
+ protected iERC20 = new Interface(ERC20ABI),
34
+ ) {
35
+ super(parentName, pool.id, dexHelper, logger);
36
+
37
+ this.logDecoder = (log: Log) => this.parseLog(log);
38
+
39
+ this.addressesSubscribed = [pool.address, pool.token0, pool.token1];
40
+ this.handlers['TraderateChanged'] = this.handleTraderateChanged.bind(this);
41
+ this.handlers['Transfer'] = this.handleTransfer.bind(this);
42
+ }
43
+
44
+ protected parseLog(log: Log) {
45
+ if (log.address.toLowerCase() === this.pool.address) {
46
+ return this.iOSwap.parseLog(log);
47
+ }
48
+ return this.iERC20.parseLog(log);
49
+ }
50
+
51
+ /**
52
+ * The function is called every time any of the subscribed
53
+ * addresses release log. The function accepts the current
54
+ * state, updates the state according to the log, and returns
55
+ * the updated state.
56
+ * @param state - Current state of event subscriber
57
+ * @param log - Log released by one of the subscribed addresses
58
+ * @returns Updates state of the event subscriber after the log
59
+ */
60
+ protected processLog(
61
+ state: DeepReadonly<OSwapPoolState>,
62
+ log: Readonly<Log>,
63
+ ): DeepReadonly<OSwapPoolState> | null {
64
+ try {
65
+ const event = this.logDecoder(log);
66
+ if (event.name in this.handlers) {
67
+ return this.handlers[event.name](event, state, log);
68
+ }
69
+ } catch (e) {
70
+ catchParseLogError(e, this.logger);
71
+ }
72
+
73
+ return null;
74
+ }
75
+
76
+ /**
77
+ * The function generates state using on-chain calls. This
78
+ * function is called to regenerate state if the event based
79
+ * system fails to fetch events and the local state is no
80
+ * more correct.
81
+ * @param blockNumber - Blocknumber for which the state should
82
+ * should be generated
83
+ * @returns state of the event subscriber at blocknumber
84
+ */
85
+ async generateState(
86
+ blockNumber: number,
87
+ ): Promise<DeepReadonly<OSwapPoolState>> {
88
+ const iERC20 = new Interface(ERC20ABI);
89
+ const callData: MultiCallParams<bigint>[] = [
90
+ {
91
+ target: this.pool.token0,
92
+ callData: iERC20.encodeFunctionData('balanceOf', [this.pool.address]),
93
+ decodeFunction: uint256ToBigInt,
94
+ },
95
+ {
96
+ target: this.pool.token1,
97
+ callData: iERC20.encodeFunctionData('balanceOf', [this.pool.address]),
98
+ decodeFunction: uint256ToBigInt,
99
+ },
100
+ {
101
+ target: this.pool.address,
102
+ callData: this.iOSwap.encodeFunctionData('traderate0', []),
103
+ decodeFunction: uint256ToBigInt,
104
+ },
105
+ {
106
+ target: this.pool.address,
107
+ callData: this.iOSwap.encodeFunctionData('traderate1', []),
108
+ decodeFunction: uint256ToBigInt,
109
+ },
110
+ ];
111
+
112
+ const results = await this.dexHelper.multiWrapper.aggregate<bigint>(
113
+ callData,
114
+ blockNumber,
115
+ this.dexHelper.multiWrapper.defaultBatchSize,
116
+ );
117
+
118
+ return {
119
+ balance0: results[0],
120
+ balance1: results[1],
121
+ traderate0: results[2],
122
+ traderate1: results[3],
123
+ };
124
+ }
125
+
126
+ async getStateOrGenerate(
127
+ blockNumber: number,
128
+ readonly: boolean = true,
129
+ ): Promise<OSwapPoolState> {
130
+ let state = this.getState(blockNumber);
131
+ if (!state) {
132
+ state = await this.generateState(blockNumber);
133
+ if (!readonly) this.setState(state, blockNumber);
134
+ }
135
+ return state;
136
+ }
137
+
138
+ /**
139
+ * Handle a trade rate change on the pool.
140
+ */
141
+ handleTraderateChanged(
142
+ event: any,
143
+ state: DeepReadonly<OSwapPoolState>,
144
+ log: Readonly<Log>,
145
+ ): DeepReadonly<OSwapPoolState> | null {
146
+ return {
147
+ ...state,
148
+ traderate0: event.args.traderate0.toBigInt(),
149
+ traderate1: event.args.traderate1.toBigInt(),
150
+ };
151
+ }
152
+
153
+ /**
154
+ * Process the transfer events for tokens in/out of the pool
155
+ * to keep the state's token balances up to date.
156
+ */
157
+ handleTransfer(
158
+ event: any,
159
+ state: DeepReadonly<OSwapPoolState>,
160
+ log: Readonly<Log>,
161
+ ): DeepReadonly<OSwapPoolState> | null {
162
+ let balance0: bigint = state.balance0;
163
+ let balance1: bigint = state.balance1;
164
+
165
+ const tokenAddress = log.address.toLowerCase();
166
+ const fromAddress = event.args.from.toLowerCase();
167
+ const toAddress = event.args.to.toLowerCase();
168
+ const amount = event.args.value.toBigInt();
169
+
170
+ if (fromAddress == this.pool.address) {
171
+ if (tokenAddress === this.pool.token0) {
172
+ balance0 -= amount;
173
+ } else if (tokenAddress === this.pool.token1) {
174
+ balance1 -= amount;
175
+ }
176
+ } else if (toAddress == this.pool.address) {
177
+ if (tokenAddress === this.pool.token0) {
178
+ balance0 += amount;
179
+ } else if (tokenAddress === this.pool.token1) {
180
+ balance1 += amount;
181
+ }
182
+ }
183
+
184
+ return {
185
+ ...state,
186
+ balance0,
187
+ balance1,
188
+ };
189
+ }
190
+ }
@@ -0,0 +1,392 @@
1
+ import { Interface } from '@ethersproject/abi';
2
+ import { AsyncOrSync } from 'ts-essentials';
3
+ import {
4
+ Token,
5
+ Address,
6
+ ExchangePrices,
7
+ PoolPrices,
8
+ AdapterExchangeParam,
9
+ PoolLiquidity,
10
+ Logger,
11
+ NumberAsString,
12
+ DexExchangeParam,
13
+ } from '../../types';
14
+ import { SwapSide, Network } from '../../constants';
15
+ import * as CALLDATA_GAS_COST from '../../calldata-gas-cost';
16
+ import { getDexKeysWithNetwork, getBigIntPow } from '../../utils';
17
+ import { Context, IDex } from '../../dex/idex';
18
+ import { IDexHelper } from '../../dex-helper/idex-helper';
19
+ import { OSwapData, OSwapPool, OSwapPoolState } from './types';
20
+ import {
21
+ SimpleExchange,
22
+ getLocalDeadlineAsFriendlyPlaceholder,
23
+ } from '../simple-exchange';
24
+ import { OSwapConfig, Adapters, OSWAP_GAS_COST } from './config';
25
+ import { OSwapEventPool } from './oswap-pool';
26
+ import OSwapABI from '../../abi/oswap/oswap.abi.json';
27
+ import { extractReturnAmountPosition } from '../../executor/utils';
28
+
29
+ export class OSwap extends SimpleExchange implements IDex<OSwapData> {
30
+ readonly eventPools: { [id: string]: OSwapEventPool } = {};
31
+
32
+ readonly hasConstantPriceLargeAmounts = false;
33
+
34
+ // This may change in the future, but currently OSwap does not support native ETH.
35
+ readonly needWrapNative = true;
36
+
37
+ readonly isFeeOnTransferSupported = false;
38
+
39
+ public static dexKeysWithNetwork: { key: string; networks: Network[] }[] =
40
+ getDexKeysWithNetwork(OSwapConfig);
41
+
42
+ logger: Logger;
43
+
44
+ readonly iOSwap: Interface;
45
+
46
+ readonly pools: [OSwapPool];
47
+
48
+ constructor(
49
+ readonly network: Network,
50
+ readonly dexKey: string,
51
+ readonly dexHelper: IDexHelper,
52
+ protected adapters = Adapters[network] || {},
53
+ ) {
54
+ super(dexHelper, dexKey);
55
+ this.logger = dexHelper.getLogger(dexKey);
56
+ this.iOSwap = new Interface(OSwapABI);
57
+
58
+ this.pools = OSwapConfig[dexKey][network].pools;
59
+
60
+ // Create an OSwapEventPool per pool, to track each pool's state by subscribing to on-chain events.
61
+ for (const pool of this.pools) {
62
+ this.eventPools[pool.id] = new OSwapEventPool(
63
+ dexKey,
64
+ pool,
65
+ network,
66
+ dexHelper,
67
+ this.logger,
68
+ );
69
+ }
70
+ }
71
+
72
+ // Returns the list of contract adapters (name and index)
73
+ // for a buy/sell. Return null if there are no adapters.
74
+ getAdapters(side: SwapSide): { name: string; index: number }[] | null {
75
+ return null;
76
+ }
77
+
78
+ // Returns the pool matching the specified token pair or null if none found.
79
+ // Note: OSwap V1 does not support more than 1 pool per pair.
80
+ getPoolByTokenPair(srcToken: Token, destToken: Token): OSwapPool | null {
81
+ const srcAddress = srcToken.address.toLowerCase();
82
+ const destAddress = destToken.address.toLowerCase();
83
+
84
+ // A pair must have 2 different tokens.
85
+ if (srcAddress === destAddress) return null;
86
+
87
+ for (const pool of this.pools) {
88
+ if (
89
+ (srcAddress === pool.token0 && destAddress === pool.token1) ||
90
+ (srcAddress === pool.token1 && destAddress === pool.token0)
91
+ ) {
92
+ return pool;
93
+ }
94
+ }
95
+ return null;
96
+ }
97
+
98
+ getPoolById(id: string): OSwapPool | null {
99
+ for (const pool of this.pools) {
100
+ if (pool.id === id) return pool;
101
+ }
102
+ return null;
103
+ }
104
+
105
+ // Returns a list of pool using the token.
106
+ getPoolsByTokenAddress(tokenAddress: Address): OSwapPool[] {
107
+ const address = tokenAddress.toLowerCase();
108
+ let pools: OSwapPool[] = [];
109
+ for (const pool of this.pools) {
110
+ if (address === pool.token0 || address === pool.token1) {
111
+ pools.push(pool);
112
+ }
113
+ }
114
+ return pools;
115
+ }
116
+
117
+ // Returns the list of pool identifiers that can be used
118
+ // for a given swap. poolIdentifiers must be unique
119
+ // across DEXes. It is recommended to use
120
+ // ${dexKey}_${poolAddress} as a poolIdentifier
121
+ async getPoolIdentifiers(
122
+ srcToken: Token,
123
+ destToken: Token,
124
+ side: SwapSide,
125
+ blockNumber: number,
126
+ ): Promise<string[]> {
127
+ const pool = this.getPoolByTokenPair(srcToken, destToken);
128
+ return pool ? [pool.id] : [];
129
+ }
130
+
131
+ // Sell: Given "amount" of "from" token, how much of "to" token will be received by the trader.
132
+ // Buy: Given "amount" of "dest" token, how much of "to" token is required from the trader.
133
+ // Note: OSwap traderate is at precision 36.
134
+ calcPrice(
135
+ pool: OSwapPool,
136
+ state: OSwapPoolState,
137
+ from: Token,
138
+ amount: bigint,
139
+ side: SwapSide,
140
+ checkLiquidity = true,
141
+ ): bigint {
142
+ const rate =
143
+ from.address.toLowerCase() === pool.token0
144
+ ? state.traderate0
145
+ : state.traderate1;
146
+
147
+ const price =
148
+ side === SwapSide.SELL
149
+ ? (amount * rate) / getBigIntPow(36)
150
+ : (amount * getBigIntPow(36)) / rate;
151
+
152
+ if (
153
+ checkLiquidity &&
154
+ !this.hasEnoughLiquidity(pool, state, from, amount, price, side)
155
+ ) {
156
+ throw new Error('Not enough liquidity');
157
+ }
158
+
159
+ return price;
160
+ }
161
+
162
+ // Returns true if the pool has enough liquidity for the swap. False otherwise.
163
+ hasEnoughLiquidity(
164
+ pool: OSwapPool,
165
+ state: OSwapPoolState,
166
+ from: Token,
167
+ amount: bigint,
168
+ needed: bigint,
169
+ side: SwapSide,
170
+ ): boolean {
171
+ if (side === SwapSide.SELL) {
172
+ return from.address.toLowerCase() === pool.token0
173
+ ? needed <= state.balance1
174
+ : needed <= state.balance0;
175
+ }
176
+ // SwapSide.BUY
177
+ return from.address.toLowerCase() === pool.token0
178
+ ? amount <= state.balance1
179
+ : amount <= state.balance0;
180
+ }
181
+
182
+ // Returns pool prices for amounts.
183
+ // If limitPools is defined only pools in limitPools
184
+ // should be used. If limitPools is undefined then
185
+ // any pool can be used.
186
+ async getPricesVolume(
187
+ srcToken: Token,
188
+ destToken: Token,
189
+ amounts: bigint[],
190
+ side: SwapSide,
191
+ blockNumber: number,
192
+ limitPools?: string[],
193
+ ): Promise<null | ExchangePrices<OSwapData>> {
194
+ try {
195
+ // Get the pool to use.
196
+ const pool = this.getPoolByTokenPair(srcToken, destToken);
197
+ if (!pool) return null;
198
+
199
+ // Make sure the pool meets the optional limitPools filter.
200
+ if (limitPools && !limitPools.includes(pool.id)) return null;
201
+
202
+ const eventPool = this.eventPools[pool.id];
203
+
204
+ if (!eventPool) {
205
+ this.logger.error(`OSwap pool ${pool.id}: No EventPool found.`);
206
+
207
+ return null;
208
+ }
209
+
210
+ const state = await eventPool.getStateOrGenerate(blockNumber);
211
+
212
+ // Calculate the prices
213
+ const unitAmount = getBigIntPow(18);
214
+ const unitPrice = this.calcPrice(
215
+ pool,
216
+ state,
217
+ srcToken,
218
+ unitAmount,
219
+ side,
220
+ false,
221
+ );
222
+ const prices = amounts.map(amount =>
223
+ this.calcPrice(pool, state, srcToken, amount, side),
224
+ );
225
+
226
+ return [
227
+ {
228
+ prices,
229
+ unit: unitPrice,
230
+ data: {
231
+ pool: pool.address,
232
+ path: [srcToken.address, destToken.address],
233
+ },
234
+ exchange: this.dexKey,
235
+ poolIdentifier: pool.id,
236
+ gasCost: OSWAP_GAS_COST,
237
+ poolAddresses: [pool.address],
238
+ },
239
+ ];
240
+ } catch (e) {
241
+ this.logger.error(
242
+ `Error_getPricesVolume ${srcToken.address || srcToken.symbol}, ${
243
+ destToken.address || destToken.symbol
244
+ }, ${side}:`,
245
+ e,
246
+ );
247
+
248
+ return null;
249
+ }
250
+ }
251
+
252
+ // Returns estimated gas cost of calldata for this DEX in multiSwap
253
+ getCalldataGasCost(poolPrices: PoolPrices<OSwapData>): number | number[] {
254
+ return (
255
+ CALLDATA_GAS_COST.DEX_OVERHEAD +
256
+ // ParentStruct header
257
+ CALLDATA_GAS_COST.OFFSET_SMALL +
258
+ // ParentStruct -> path[] header
259
+ CALLDATA_GAS_COST.OFFSET_SMALL +
260
+ // ParentStruct -> path length
261
+ CALLDATA_GAS_COST.LENGTH_SMALL +
262
+ // ParentStruct -> path[0]
263
+ CALLDATA_GAS_COST.ADDRESS +
264
+ // ParentStruct -> path[1]
265
+ CALLDATA_GAS_COST.ADDRESS +
266
+ // ParentStruct -> receiver header
267
+ CALLDATA_GAS_COST.OFFSET_SMALL +
268
+ // ParentStruct -> receiver
269
+ CALLDATA_GAS_COST.ADDRESS
270
+ );
271
+ }
272
+
273
+ // Encode params required by the exchange adapter
274
+ // Used for multiSwap, buy & megaSwap
275
+ getAdapterParam(
276
+ srcToken: string,
277
+ destToken: string,
278
+ srcAmount: string,
279
+ destAmount: string,
280
+ data: OSwapData,
281
+ side: SwapSide,
282
+ ): AdapterExchangeParam {
283
+ return {
284
+ targetExchange: data.pool,
285
+ payload: '',
286
+ networkFee: '0',
287
+ };
288
+ }
289
+
290
+ // Encode call data used by simpleSwap like routers
291
+ // Used for simpleSwap & simpleBuy
292
+ getDexParam(
293
+ srcToken: Address,
294
+ destToken: Address,
295
+ srcAmount: NumberAsString,
296
+ destAmount: NumberAsString,
297
+ recipient: Address,
298
+ data: OSwapData,
299
+ side: SwapSide,
300
+ _: Context,
301
+ executorAddress: Address,
302
+ ): DexExchangeParam {
303
+ let method: string;
304
+ let args: any;
305
+ let returnAmountPos: number | undefined = undefined;
306
+
307
+ const deadline = getLocalDeadlineAsFriendlyPlaceholder();
308
+ if (side === SwapSide.SELL) {
309
+ method = 'swapExactTokensForTokens';
310
+ returnAmountPos = extractReturnAmountPosition(
311
+ this.iOSwap,
312
+ method,
313
+ 'amounts',
314
+ 1,
315
+ );
316
+ args = [srcAmount, destAmount, data.path, recipient, deadline];
317
+ } else {
318
+ method = 'swapTokensForExactTokens';
319
+ args = [destAmount, srcAmount, data.path, recipient, deadline];
320
+ }
321
+
322
+ const swapData = this.iOSwap.encodeFunctionData(method, args);
323
+
324
+ return {
325
+ needWrapNative: this.needWrapNative,
326
+ dexFuncHasRecipient: true,
327
+ exchangeData: swapData,
328
+ targetExchange: data.pool,
329
+ returnAmountPos,
330
+ };
331
+ }
332
+
333
+ // This is called once before getTopPoolsForToken is
334
+ // called for multiple tokens. This can be helpful to
335
+ // update common state required for calculating
336
+ // getTopPoolsForToken. It is optional for a DEX
337
+ // to implement this
338
+ async updatePoolState(): Promise<void> {
339
+ return Promise.resolve();
340
+ }
341
+
342
+ // Returns a list of top pools based on liquidity. Max
343
+ // limit number pools should be returned.
344
+ async getTopPoolsForToken(
345
+ tokenAddress: Address,
346
+ limit: number,
347
+ ): Promise<PoolLiquidity[]> {
348
+ // Get the list of pools using the token.
349
+ const pools = this.getPoolsByTokenAddress(tokenAddress);
350
+ if (!pools.length) return [];
351
+
352
+ const results = await Promise.all<PoolLiquidity>(
353
+ pools.map(async pool => {
354
+ // Get the pool's balance and its USD value.
355
+ const eventPool = this.eventPools[pool.id];
356
+ const blockNumber =
357
+ await this.dexHelper.web3Provider.eth.getBlockNumber();
358
+ const state = await eventPool.getStateOrGenerate(blockNumber);
359
+
360
+ const usd0 = await this.dexHelper.getTokenUSDPrice(
361
+ { address: pool.token0, decimals: 18 },
362
+ state.balance0,
363
+ );
364
+ const usd1 = await this.dexHelper.getTokenUSDPrice(
365
+ { address: pool.token1, decimals: 18 },
366
+ state.balance1,
367
+ );
368
+
369
+ // Get the other token in the pair.
370
+ const pairedToken =
371
+ pool.token0 === tokenAddress.toLowerCase()
372
+ ? { address: pool.token1, decimals: 18 }
373
+ : { address: pool.token0, decimals: 18 };
374
+
375
+ return {
376
+ exchange: this.dexKey,
377
+ address: pool.address,
378
+ connectorTokens: [pairedToken],
379
+ liquidityUSD: usd0 + usd1,
380
+ };
381
+ }),
382
+ );
383
+ return results
384
+ .filter(r => r)
385
+ .sort((a, b) => a.liquidityUSD - b.liquidityUSD)
386
+ .slice(0, limit);
387
+ }
388
+
389
+ // This is optional function in case if your implementation has acquired any resources
390
+ // you need to release for graceful shutdown. For example, it may be any interval timer
391
+ releaseResources(): AsyncOrSync<void> {}
392
+ }
@@ -0,0 +1,29 @@
1
+ import { Address } from '../../types';
2
+
3
+ // OSwapPoolState is the state of the event subscriber. It is the minimum
4
+ // set of parameters required to compute pool prices.
5
+ export type OSwapPoolState = {
6
+ traderate0: bigint;
7
+ traderate1: bigint;
8
+ balance0: bigint;
9
+ balance1: bigint;
10
+ };
11
+
12
+ // OSwapPoolState is the state of the event subscriber. It is the minimum
13
+ // set of parameters required to compute pool prices.
14
+ export type OSwapData = {
15
+ pool: Address;
16
+ path: Address[];
17
+ };
18
+
19
+ // Each pool has a contract address and token pairs.
20
+ export type OSwapPool = {
21
+ id: string;
22
+ address: Address;
23
+ token0: Address;
24
+ token1: Address;
25
+ };
26
+
27
+ export type DexParams = {
28
+ pools: [OSwapPool];
29
+ };
@@ -73,4 +73,7 @@ export const Adapters: {
73
73
  [Network.BASE]: {
74
74
  [SwapSide.SELL]: [{ name: 'BaseAdapter02', index: 2 }],
75
75
  },
76
+ [Network.ZKEVM]: {
77
+ [SwapSide.SELL]: [{ name: 'PolygonZkEvmAdapter01', index: 3 }],
78
+ },
76
79
  };