@paraswap/dex-lib 3.7.7-skip-approval.3 → 3.7.8-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 (222) hide show
  1. package/build/abi/inception/inception-ineth-pool.json +1062 -0
  2. package/build/abi/inception/inception-ineth.json +609 -0
  3. package/build/abi/inception/inception-vault.json +991 -0
  4. package/build/abi/oswap/oswap.abi.json +452 -0
  5. package/build/dex/aave-v1/aave-v1.d.ts +2 -1
  6. package/build/dex/aave-v1/aave-v1.js +22 -0
  7. package/build/dex/aave-v1/aave-v1.js.map +1 -1
  8. package/build/dex/aave-v3/aave-v3.js +1 -2
  9. package/build/dex/aave-v3/aave-v3.js.map +1 -1
  10. package/build/dex/aave-v3-stata/aave-v3-stata.js +0 -1
  11. package/build/dex/aave-v3-stata/aave-v3-stata.js.map +1 -1
  12. package/build/dex/angle-staked-stable/angle-staked-stable.js +1 -4
  13. package/build/dex/angle-staked-stable/angle-staked-stable.js.map +1 -1
  14. package/build/dex/compound/compound.js +1 -2
  15. package/build/dex/compound/compound.js.map +1 -1
  16. package/build/dex/etherfi.js +1 -4
  17. package/build/dex/etherfi.js.map +1 -1
  18. package/build/dex/idle-dao/idle-dao-pool.d.ts +56 -0
  19. package/build/dex/idle-dao/idle-dao-pool.js +176 -0
  20. package/build/dex/idle-dao/idle-dao-pool.js.map +1 -0
  21. package/build/dex/idle-dao/idle-dao-pooling-pool.d.ts +16 -0
  22. package/build/dex/idle-dao/idle-dao-pooling-pool.js +57 -0
  23. package/build/dex/idle-dao/idle-dao-pooling-pool.js.map +1 -0
  24. package/build/dex/idle-dao/idle-dao.js +0 -1
  25. package/build/dex/idle-dao/idle-dao.js.map +1 -1
  26. package/build/dex/idle-dao/scripts.d.ts +9 -0
  27. package/build/dex/idle-dao/scripts.js +552 -0
  28. package/build/dex/idle-dao/scripts.js.map +1 -0
  29. package/build/dex/inception/config.d.ts +5 -0
  30. package/build/dex/inception/config.js +100 -0
  31. package/build/dex/inception/config.js.map +1 -0
  32. package/build/dex/inception/inception-native.d.ts +43 -0
  33. package/build/dex/inception/inception-native.js +131 -0
  34. package/build/dex/inception/inception-native.js.map +1 -0
  35. package/build/dex/inception/inception-pool.d.ts +18 -0
  36. package/build/dex/inception/inception-pool.js +32 -0
  37. package/build/dex/inception/inception-pool.js.map +1 -0
  38. package/build/dex/inception/inception.d.ts +42 -0
  39. package/build/dex/inception/inception.js +128 -0
  40. package/build/dex/inception/inception.js.map +1 -0
  41. package/build/dex/inception/types.d.ts +11 -0
  42. package/build/dex/inception/types.js +3 -0
  43. package/build/dex/inception/types.js.map +1 -0
  44. package/build/dex/inception/utils.d.ts +4 -0
  45. package/build/dex/inception/utils.js +22 -0
  46. package/build/dex/inception/utils.js.map +1 -0
  47. package/build/dex/index.js +2 -0
  48. package/build/dex/index.js.map +1 -1
  49. package/build/dex/mStable.js +1 -1
  50. package/build/dex/mStable.js.map +1 -1
  51. package/build/dex/oswap/config.d.ts +5 -0
  52. package/build/dex/oswap/config.js +31 -0
  53. package/build/dex/oswap/config.js.map +1 -0
  54. package/build/dex/oswap/oswap-pool.d.ts +51 -0
  55. package/build/dex/oswap/oswap-pool.js +150 -0
  56. package/build/dex/oswap/oswap-pool.js.map +1 -0
  57. package/build/dex/oswap/oswap.d.ts +46 -0
  58. package/build/dex/oswap/oswap.js +263 -0
  59. package/build/dex/oswap/oswap.js.map +1 -0
  60. package/build/dex/oswap/types.d.ts +20 -0
  61. package/build/dex/oswap/types.js +3 -0
  62. package/build/dex/oswap/types.js.map +1 -0
  63. package/build/dex/platypus/platypus.d.ts +2 -1
  64. package/build/dex/platypus/platypus.js +31 -0
  65. package/build/dex/platypus/platypus.js.map +1 -1
  66. package/build/dex/simple-exchange.d.ts +1 -1
  67. package/build/dex/simple-exchange.js +2 -4
  68. package/build/dex/simple-exchange.js.map +1 -1
  69. package/build/dex/spark/spark.js +1 -1
  70. package/build/dex/spark/spark.js.map +1 -1
  71. package/build/dex/swaap-v1/swaap-v1.d.ts +2 -1
  72. package/build/dex/swaap-v1/swaap-v1.js +10 -0
  73. package/build/dex/swaap-v1/swaap-v1.js.map +1 -1
  74. package/build/executor/Executor01BytecodeBuilder.js +0 -1
  75. package/build/executor/Executor01BytecodeBuilder.js.map +1 -1
  76. package/build/executor/Executor02BytecodeBuilder.js +0 -1
  77. package/build/executor/Executor02BytecodeBuilder.js.map +1 -1
  78. package/build/executor/Executor03BytecodeBuilder.js +0 -1
  79. package/build/executor/Executor03BytecodeBuilder.js.map +1 -1
  80. package/build/generic-swap-transaction-builder.js +2 -2
  81. package/build/generic-swap-transaction-builder.js.map +1 -1
  82. package/build/types.d.ts +0 -1
  83. package/build/utils.d.ts +1 -1
  84. package/package.json +1 -1
  85. package/src/abi/oswap/oswap.abi.json +452 -0
  86. package/src/dex/aave-v3/aave-v3-e2e.test.ts +9 -4
  87. package/src/dex/aave-v3/aave-v3.ts +0 -5
  88. package/src/dex/aave-v3-stata/aave-v3-stata.ts +0 -1
  89. package/src/dex/angle-staked-stable/angle-staked-stable.ts +0 -8
  90. package/src/dex/compound/compound.ts +0 -5
  91. package/src/dex/etherfi.ts +0 -5
  92. package/src/dex/idle-dao/idle-dao.ts +0 -1
  93. package/src/dex/index.ts +2 -0
  94. package/src/dex/mStable.ts +0 -4
  95. package/src/dex/oswap/config.ts +32 -0
  96. package/src/dex/oswap/oswap-e2e.test.ts +91 -0
  97. package/src/dex/oswap/oswap-events.test.ts +88 -0
  98. package/src/dex/oswap/oswap-integration.test.ts +287 -0
  99. package/src/dex/oswap/oswap-pool.ts +190 -0
  100. package/src/dex/oswap/oswap.ts +359 -0
  101. package/src/dex/oswap/types.ts +29 -0
  102. package/src/dex/simple-exchange.ts +5 -5
  103. package/src/dex/spark/spark-e2e.test.ts +1 -9
  104. package/src/dex/spark/spark.ts +0 -4
  105. package/src/executor/Executor01BytecodeBuilder.ts +0 -1
  106. package/src/executor/Executor02BytecodeBuilder.ts +0 -1
  107. package/src/executor/Executor03BytecodeBuilder.ts +0 -1
  108. package/src/executor/executor01-bytecode-builder-e2e.test.ts +0 -25
  109. package/src/executor/executor02-bytecode-builder-e2e.test.ts +0 -29
  110. package/src/generic-swap-transaction-builder.ts +1 -2
  111. package/src/types.ts +0 -1
  112. package/tests/constants-e2e.ts +13 -13
  113. package/tests/utils-e2e.ts +1 -1
  114. package/build/abi/Uncompressor.json +0 -250
  115. package/build/dex/bProtocol.d.ts +0 -18
  116. package/build/dex/bProtocol.js +0 -39
  117. package/build/dex/bProtocol.js.map +0 -1
  118. package/build/dex/bancor.d.ts +0 -26
  119. package/build/dex/bancor.js +0 -58
  120. package/build/dex/bancor.js.map +0 -1
  121. package/build/dex/compound.d.ts +0 -18
  122. package/build/dex/compound.js +0 -46
  123. package/build/dex/compound.js.map +0 -1
  124. package/build/dex/curve-v2.d.ts +0 -58
  125. package/build/dex/curve-v2.js +0 -180
  126. package/build/dex/curve-v2.js.map +0 -1
  127. package/build/dex/dodo-v1.d.ts +0 -33
  128. package/build/dex/dodo-v1.js +0 -63
  129. package/build/dex/dodo-v1.js.map +0 -1
  130. package/build/dex/etherfi/etherfi.d.ts +0 -26
  131. package/build/dex/etherfi/etherfi.js +0 -96
  132. package/build/dex/etherfi/etherfi.js.map +0 -1
  133. package/build/dex/lido.d.ts +0 -19
  134. package/build/dex/lido.js +0 -42
  135. package/build/dex/lido.js.map +0 -1
  136. package/build/dex/onebit.d.ts +0 -25
  137. package/build/dex/onebit.js +0 -42
  138. package/build/dex/onebit.js.map +0 -1
  139. package/build/dex/sdai/config.d.ts +0 -11
  140. package/build/dex/sdai/config.js +0 -21
  141. package/build/dex/sdai/config.js.map +0 -1
  142. package/build/dex/sdai/constants.d.ts +0 -2
  143. package/build/dex/sdai/constants.js +0 -6
  144. package/build/dex/sdai/constants.js.map +0 -1
  145. package/build/dex/sdai/scripts/validate-state.d.ts +0 -1
  146. package/build/dex/sdai/scripts/validate-state.js +0 -102
  147. package/build/dex/sdai/scripts/validate-state.js.map +0 -1
  148. package/build/dex/sdai/sdai-pool.d.ts +0 -16
  149. package/build/dex/sdai/sdai-pool.js +0 -85
  150. package/build/dex/sdai/sdai-pool.js.map +0 -1
  151. package/build/dex/sdai/sdai.d.ts +0 -51
  152. package/build/dex/sdai/sdai.js +0 -172
  153. package/build/dex/sdai/sdai.js.map +0 -1
  154. package/build/dex/sdai/types.d.ts +0 -21
  155. package/build/dex/sdai/types.js +0 -11
  156. package/build/dex/sdai/types.js.map +0 -1
  157. package/build/dex/sdai/utils.d.ts +0 -4
  158. package/build/dex/sdai/utils.js +0 -39
  159. package/build/dex/sdai/utils.js.map +0 -1
  160. package/build/dex/smoothy.d.ts +0 -26
  161. package/build/dex/smoothy.js +0 -48
  162. package/build/dex/smoothy.js.map +0 -1
  163. package/build/dex/stable-pool.d.ts +0 -28
  164. package/build/dex/stable-pool.js +0 -62
  165. package/build/dex/stable-pool.js.map +0 -1
  166. package/build/dex/trader-joe-v2.1.d.ts +0 -43
  167. package/build/dex/trader-joe-v2.1.js +0 -79
  168. package/build/dex/trader-joe-v2.1.js.map +0 -1
  169. package/build/executor/compressor/Compressor.d.ts +0 -23
  170. package/build/executor/compressor/Compressor.js +0 -144
  171. package/build/executor/compressor/Compressor.js.map +0 -1
  172. package/build/executor/compressor/compress.d.ts +0 -17
  173. package/build/executor/compressor/compress.js +0 -187
  174. package/build/executor/compressor/compress.js.map +0 -1
  175. package/build/executor/compressor/compress_functions/addressSubstitution.d.ts +0 -6
  176. package/build/executor/compressor/compress_functions/addressSubstitution.js +0 -29
  177. package/build/executor/compressor/compress_functions/addressSubstitution.js.map +0 -1
  178. package/build/executor/compressor/compress_functions/addressSubstitutionFromObject.d.ts +0 -10
  179. package/build/executor/compressor/compress_functions/addressSubstitutionFromObject.js +0 -40
  180. package/build/executor/compressor/compress_functions/addressSubstitutionFromObject.js.map +0 -1
  181. package/build/executor/compressor/compress_functions/byteSubstitution.d.ts +0 -11
  182. package/build/executor/compressor/compress_functions/byteSubstitution.js +0 -64
  183. package/build/executor/compressor/compress_functions/byteSubstitution.js.map +0 -1
  184. package/build/executor/compressor/compress_functions/ffSubstitution.d.ts +0 -7
  185. package/build/executor/compressor/compress_functions/ffSubstitution.js +0 -54
  186. package/build/executor/compressor/compress_functions/ffSubstitution.js.map +0 -1
  187. package/build/executor/compressor/compress_functions/findLongestAndSubstitute.d.ts +0 -8
  188. package/build/executor/compressor/compress_functions/findLongestAndSubstitute.js +0 -67
  189. package/build/executor/compressor/compress_functions/findLongestAndSubstitute.js.map +0 -1
  190. package/build/executor/compressor/compress_functions/findLongestAndSubstitute_old.d.ts +0 -8
  191. package/build/executor/compressor/compress_functions/findLongestAndSubstitute_old.js +0 -61
  192. package/build/executor/compressor/compress_functions/findLongestAndSubstitute_old.js.map +0 -1
  193. package/build/executor/compressor/compress_functions/reverseAddressSubstitution.d.ts +0 -6
  194. package/build/executor/compressor/compress_functions/reverseAddressSubstitution.js +0 -37
  195. package/build/executor/compressor/compress_functions/reverseAddressSubstitution.js.map +0 -1
  196. package/build/executor/compressor/compress_functions/searchUnusedBytes.d.ts +0 -9
  197. package/build/executor/compressor/compress_functions/searchUnusedBytes.js +0 -33
  198. package/build/executor/compressor/compress_functions/searchUnusedBytes.js.map +0 -1
  199. package/build/executor/compressor/fetchSaved.d.ts +0 -0
  200. package/build/executor/compressor/fetchSaved.js +0 -17
  201. package/build/executor/compressor/fetchSaved.js.map +0 -1
  202. package/build/executor/compressor/utils/computeCostL2.d.ts +0 -2
  203. package/build/executor/compressor/utils/computeCostL2.js +0 -14
  204. package/build/executor/compressor/utils/computeCostL2.js.map +0 -1
  205. package/build/executor/compressor/utils/findLongestDuplicatedString.d.ts +0 -2
  206. package/build/executor/compressor/utils/findLongestDuplicatedString.js +0 -30
  207. package/build/executor/compressor/utils/findLongestDuplicatedString.js.map +0 -1
  208. package/build/executor/compressor/utils/getAllIndexes.d.ts +0 -2
  209. package/build/executor/compressor/utils/getAllIndexes.js +0 -12
  210. package/build/executor/compressor/utils/getAllIndexes.js.map +0 -1
  211. package/build/executor/compressor/utils/getByteForAddress.d.ts +0 -2
  212. package/build/executor/compressor/utils/getByteForAddress.js +0 -14
  213. package/build/executor/compressor/utils/getByteForAddress.js.map +0 -1
  214. package/build/executor/compressor/utils/intTo2Bytes.d.ts +0 -2
  215. package/build/executor/compressor/utils/intTo2Bytes.js +0 -14
  216. package/build/executor/compressor/utils/intTo2Bytes.js.map +0 -1
  217. package/build/executor/compressor/utils/intTo3Bytes.d.ts +0 -2
  218. package/build/executor/compressor/utils/intTo3Bytes.js +0 -18
  219. package/build/executor/compressor/utils/intTo3Bytes.js.map +0 -1
  220. package/build/executor/compressor/utils/intToByte.d.ts +0 -2
  221. package/build/executor/compressor/utils/intToByte.js +0 -10
  222. package/build/executor/compressor/utils/intToByte.js.map +0 -1
@@ -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,359 @@
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
+ SimpleExchangeParam,
10
+ PoolLiquidity,
11
+ Logger,
12
+ NumberAsString,
13
+ DexExchangeParam,
14
+ } from '../../types';
15
+ import { SwapSide, Network } from '../../constants';
16
+ import * as CALLDATA_GAS_COST from '../../calldata-gas-cost';
17
+ import { getDexKeysWithNetwork, getBigIntPow } from '../../utils';
18
+ import { Context, IDex } from '../../dex/idex';
19
+ import { IDexHelper } from '../../dex-helper/idex-helper';
20
+ import { OSwapData, OSwapPool, OSwapPoolState } from './types';
21
+ import {
22
+ SimpleExchange,
23
+ getLocalDeadlineAsFriendlyPlaceholder,
24
+ } from '../simple-exchange';
25
+ import { OSwapConfig, Adapters, OSWAP_GAS_COST } from './config';
26
+ import { OSwapEventPool } from './oswap-pool';
27
+ import OSwapABI from '../../abi/oswap/oswap.abi.json';
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
+ ): bigint {
141
+ const rate =
142
+ from.address.toLowerCase() === pool.token0
143
+ ? state.traderate0
144
+ : state.traderate1;
145
+ return side === SwapSide.SELL
146
+ ? (amount * rate) / getBigIntPow(36)
147
+ : (amount * getBigIntPow(36)) / rate;
148
+ }
149
+
150
+ // Returns true if the pool has enough liquidity for the swap. False otherwise.
151
+ checkLiquidity(
152
+ pool: OSwapPool,
153
+ state: OSwapPoolState,
154
+ from: Token,
155
+ amount: bigint,
156
+ side: SwapSide,
157
+ ): boolean {
158
+ if (side === SwapSide.SELL) {
159
+ const needed = this.calcPrice(pool, state, from, amount, side);
160
+ return from.address.toLowerCase() === pool.token0
161
+ ? needed <= state.balance1
162
+ : needed <= state.balance0;
163
+ }
164
+ // SwapSide.BUY
165
+ return from.address.toLowerCase() === pool.token0
166
+ ? amount <= state.balance1
167
+ : amount <= state.balance0;
168
+ }
169
+
170
+ // Returns pool prices for amounts.
171
+ // If limitPools is defined only pools in limitPools
172
+ // should be used. If limitPools is undefined then
173
+ // any pool can be used.
174
+ async getPricesVolume(
175
+ srcToken: Token,
176
+ destToken: Token,
177
+ amounts: bigint[],
178
+ side: SwapSide,
179
+ blockNumber: number,
180
+ limitPools?: string[],
181
+ ): Promise<null | ExchangePrices<OSwapData>> {
182
+ // Get the pool to use.
183
+ const pool = this.getPoolByTokenPair(srcToken, destToken);
184
+ if (!pool) return null;
185
+
186
+ // Make sure the pool meets the optional limitPools filter.
187
+ if (limitPools && !limitPools.includes(pool.id)) return null;
188
+
189
+ const eventPool = this.eventPools[pool.id];
190
+ if (!eventPool)
191
+ throw new Error(`OSwap pool ${pool.id}: No EventPool found.`);
192
+
193
+ const state = await eventPool.getStateOrGenerate(blockNumber);
194
+
195
+ // Ensure there is enough liquidity in the pool to process all the requested swaps.
196
+ const totalAmount = amounts.reduce(
197
+ (a: bigint, b: bigint) => a + b,
198
+ BigInt(0),
199
+ );
200
+ if (!this.checkLiquidity(pool, state, srcToken, totalAmount, side)) {
201
+ return null;
202
+ }
203
+ // Calculate the prices
204
+ const unitAmount = getBigIntPow(18);
205
+ const unitPrice = this.calcPrice(pool, state, srcToken, unitAmount, side);
206
+ const prices = amounts.map(amount =>
207
+ this.calcPrice(pool, state, srcToken, amount, side),
208
+ );
209
+
210
+ return [
211
+ {
212
+ prices,
213
+ unit: unitPrice,
214
+ data: {
215
+ pool: pool.address,
216
+ path: [srcToken.address, destToken.address],
217
+ },
218
+ exchange: this.dexKey,
219
+ poolIdentifier: pool.id,
220
+ gasCost: OSWAP_GAS_COST,
221
+ poolAddresses: [pool.address],
222
+ },
223
+ ];
224
+ }
225
+
226
+ // Returns estimated gas cost of calldata for this DEX in multiSwap
227
+ getCalldataGasCost(poolPrices: PoolPrices<OSwapData>): number | number[] {
228
+ return (
229
+ CALLDATA_GAS_COST.DEX_OVERHEAD +
230
+ // ParentStruct header
231
+ CALLDATA_GAS_COST.OFFSET_SMALL +
232
+ // ParentStruct -> path[] header
233
+ CALLDATA_GAS_COST.OFFSET_SMALL +
234
+ // ParentStruct -> path length
235
+ CALLDATA_GAS_COST.LENGTH_SMALL +
236
+ // ParentStruct -> path[0]
237
+ CALLDATA_GAS_COST.ADDRESS +
238
+ // ParentStruct -> path[1]
239
+ CALLDATA_GAS_COST.ADDRESS +
240
+ // ParentStruct -> receiver header
241
+ CALLDATA_GAS_COST.OFFSET_SMALL +
242
+ // ParentStruct -> receiver
243
+ CALLDATA_GAS_COST.ADDRESS
244
+ );
245
+ }
246
+
247
+ // Encode params required by the exchange adapter
248
+ // Used for multiSwap, buy & megaSwap
249
+ getAdapterParam(
250
+ srcToken: string,
251
+ destToken: string,
252
+ srcAmount: string,
253
+ destAmount: string,
254
+ data: OSwapData,
255
+ side: SwapSide,
256
+ ): AdapterExchangeParam {
257
+ return {
258
+ targetExchange: data.pool,
259
+ payload: '',
260
+ networkFee: '0',
261
+ };
262
+ }
263
+
264
+ // Encode call data used by simpleSwap like routers
265
+ // Used for simpleSwap & simpleBuy
266
+ getDexParam(
267
+ srcToken: Address,
268
+ destToken: Address,
269
+ srcAmount: NumberAsString,
270
+ destAmount: NumberAsString,
271
+ recipient: Address,
272
+ data: OSwapData,
273
+ side: SwapSide,
274
+ _: Context,
275
+ executorAddress: Address,
276
+ ): DexExchangeParam {
277
+ let method: string;
278
+ let args: any;
279
+
280
+ const deadline = getLocalDeadlineAsFriendlyPlaceholder();
281
+ if (side === SwapSide.SELL) {
282
+ method = 'swapExactTokensForTokens';
283
+ args = [srcAmount, destAmount, data.path, recipient, deadline];
284
+ } else {
285
+ method = 'swapTokensForExactTokens';
286
+ args = [destAmount, srcAmount, data.path, recipient, deadline];
287
+ }
288
+
289
+ const swapData = this.iOSwap.encodeFunctionData(method, args);
290
+
291
+ return {
292
+ needWrapNative: this.needWrapNative,
293
+ dexFuncHasRecipient: true,
294
+ exchangeData: swapData,
295
+ targetExchange: data.pool,
296
+ returnAmountPos: undefined,
297
+ };
298
+ }
299
+
300
+ // This is called once before getTopPoolsForToken is
301
+ // called for multiple tokens. This can be helpful to
302
+ // update common state required for calculating
303
+ // getTopPoolsForToken. It is optional for a DEX
304
+ // to implement this
305
+ async updatePoolState(): Promise<void> {
306
+ return Promise.resolve();
307
+ }
308
+
309
+ // Returns a list of top pools based on liquidity. Max
310
+ // limit number pools should be returned.
311
+ async getTopPoolsForToken(
312
+ tokenAddress: Address,
313
+ limit: number,
314
+ ): Promise<PoolLiquidity[]> {
315
+ // Get the list of pools using the token.
316
+ const pools = this.getPoolsByTokenAddress(tokenAddress);
317
+ if (!pools.length) return [];
318
+
319
+ const results = await Promise.all<PoolLiquidity>(
320
+ pools.map(async pool => {
321
+ // Get the pool's balance and its USD value.
322
+ const eventPool = this.eventPools[pool.id];
323
+ const blockNumber =
324
+ await this.dexHelper.web3Provider.eth.getBlockNumber();
325
+ const state = await eventPool.getStateOrGenerate(blockNumber);
326
+
327
+ const usd0 = await this.dexHelper.getTokenUSDPrice(
328
+ { address: pool.token0, decimals: 18 },
329
+ state.balance0,
330
+ );
331
+ const usd1 = await this.dexHelper.getTokenUSDPrice(
332
+ { address: pool.token1, decimals: 18 },
333
+ state.balance1,
334
+ );
335
+
336
+ // Get the other token in the pair.
337
+ const pairedToken =
338
+ pool.token0 === tokenAddress.toLowerCase()
339
+ ? { address: pool.token1, decimals: 18 }
340
+ : { address: pool.token0, decimals: 18 };
341
+
342
+ return {
343
+ exchange: this.dexKey,
344
+ address: pool.address,
345
+ connectorTokens: [pairedToken],
346
+ liquidityUSD: usd0 + usd1,
347
+ };
348
+ }),
349
+ );
350
+ return results
351
+ .filter(r => r)
352
+ .sort((a, b) => a.liquidityUSD - b.liquidityUSD)
353
+ .slice(0, limit);
354
+ }
355
+
356
+ // This is optional function in case if your implementation has acquired any resources
357
+ // you need to release for graceful shutdown. For example, it may be any interval timer
358
+ releaseResources(): AsyncOrSync<void> {}
359
+ }
@@ -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
+ };
@@ -110,12 +110,12 @@ export class SimpleExchange {
110
110
  spender?: Address,
111
111
  networkFee: NumberAsString = '0',
112
112
  preCalls?: Omit<SimpleExchangeParam, 'networkFee'>,
113
- skipAllowance?: boolean,
114
113
  ): Promise<SimpleExchangeParam> {
115
- const approveParam = await (!skipAllowance
116
- ? this.getApproveSimpleParam(src, spender || swapCallee, srcAmount)
117
- : { callees: [], calldata: [], values: [], networkFee: '0' });
118
-
114
+ const approveParam = await this.getApproveSimpleParam(
115
+ src,
116
+ spender || swapCallee,
117
+ srcAmount,
118
+ );
119
119
  const swapValue = (
120
120
  BigInt(networkFee) + (isETHAddress(src) ? BigInt(srcAmount) : 0n)
121
121
  ).toString();
@@ -29,17 +29,9 @@ function testForNetwork(
29
29
  ContractMethod.simpleSwap,
30
30
  ContractMethod.multiSwap,
31
31
  ContractMethod.megaSwap,
32
- ContractMethod.swapExactAmountIn,
33
- ],
34
- ],
35
- [
36
- SwapSide.BUY,
37
- [
38
- ContractMethod.simpleBuy,
39
- ContractMethod.buy,
40
- ContractMethod.swapExactAmountOut,
41
32
  ],
42
33
  ],
34
+ [SwapSide.BUY, [ContractMethod.simpleBuy, ContractMethod.buy]],
43
35
  ]);
44
36
 
45
37
  describe(`${network}`, () => {
@@ -207,10 +207,6 @@ export class Spark
207
207
  destAmount,
208
208
  swapData,
209
209
  exchange,
210
- undefined,
211
- undefined,
212
- undefined,
213
- isSell && this.isDai(destToken),
214
210
  );
215
211
  }
216
212
 
@@ -268,7 +268,6 @@ export class Executor01BytecodeBuilder extends ExecutorBytecodeBuilder<
268
268
  (!isETHAddress(swap.srcToken) ||
269
269
  (isETHAddress(swap.srcToken) && index !== 0)) &&
270
270
  !curExchangeParam.transferSrcTokenBeforeSwap &&
271
- !curExchangeParam.skipApproval &&
272
271
  curExchangeParam.approveData
273
272
  ) {
274
273
  const approveCallData = this.buildApproveCallData(
@@ -606,7 +606,6 @@ export class Executor02BytecodeBuilder extends ExecutorBytecodeBuilder<
606
606
  if (
607
607
  !isETHAddress(swap.srcToken) &&
608
608
  !curExchangeParam.transferSrcTokenBeforeSwap &&
609
- !curExchangeParam.skipApproval &&
610
609
  curExchangeParam.approveData
611
610
  ) {
612
611
  const approveCallData = this.buildApproveCallData(
@@ -147,7 +147,6 @@ export class Executor03BytecodeBuilder extends ExecutorBytecodeBuilder<
147
147
  if (
148
148
  flags.dexes[index] % 4 !== 1 && // not sendEth
149
149
  !isETHAddress(swap.srcToken) &&
150
- !curExchangeParam.skipApproval &&
151
150
  curExchangeParam.approveData
152
151
  ) {
153
152
  // TODO: as we give approve for MAX_UINT and approve for current targetExchange was given
@@ -102,31 +102,6 @@ describe('Executor01ByteCodeBuilder e2e tests', () => {
102
102
  const network = Network.MAINNET;
103
103
 
104
104
  describe('SimpleSwap', () => {
105
- describe('AngleStakedStableUSD', () => {
106
- const dexKey = 'AngleStakedStableUSD';
107
-
108
- const tokens = Tokens[network];
109
- const holders = Holders[network];
110
- const provider = new StaticJsonRpcProvider(
111
- generateConfig(network).privateHttpProvider,
112
- network,
113
- );
114
-
115
- it('SimpleSwap stUSD -> USDA', async () => {
116
- await testE2E(
117
- tokens['stUSD'],
118
- tokens['USDA'],
119
- holders['stUSD'],
120
- '1000000000000',
121
- SwapSide.SELL,
122
- dexKey,
123
- ContractMethod.simpleSwap,
124
- network,
125
- provider,
126
- );
127
- });
128
- });
129
-
130
105
  describe('UniswapV3', () => {
131
106
  const dexKey = 'UniswapV3';
132
107