@paraswap/dex-lib 3.8.5 → 3.8.6-oswap.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.
@@ -0,0 +1,367 @@
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
+ import { extractReturnAmountPosition } from '../../executor/utils';
29
+
30
+ export class OSwap extends SimpleExchange implements IDex<OSwapData> {
31
+ readonly eventPools: { [id: string]: OSwapEventPool } = {};
32
+
33
+ readonly hasConstantPriceLargeAmounts = false;
34
+
35
+ // This may change in the future, but currently OSwap does not support native ETH.
36
+ readonly needWrapNative = true;
37
+
38
+ readonly isFeeOnTransferSupported = false;
39
+
40
+ public static dexKeysWithNetwork: { key: string; networks: Network[] }[] =
41
+ getDexKeysWithNetwork(OSwapConfig);
42
+
43
+ logger: Logger;
44
+
45
+ readonly iOSwap: Interface;
46
+
47
+ readonly pools: [OSwapPool];
48
+
49
+ constructor(
50
+ readonly network: Network,
51
+ readonly dexKey: string,
52
+ readonly dexHelper: IDexHelper,
53
+ protected adapters = Adapters[network] || {},
54
+ ) {
55
+ super(dexHelper, dexKey);
56
+ this.logger = dexHelper.getLogger(dexKey);
57
+ this.iOSwap = new Interface(OSwapABI);
58
+
59
+ this.pools = OSwapConfig[dexKey][network].pools;
60
+
61
+ // Create an OSwapEventPool per pool, to track each pool's state by subscribing to on-chain events.
62
+ for (const pool of this.pools) {
63
+ this.eventPools[pool.id] = new OSwapEventPool(
64
+ dexKey,
65
+ pool,
66
+ network,
67
+ dexHelper,
68
+ this.logger,
69
+ );
70
+ }
71
+ }
72
+
73
+ // Returns the list of contract adapters (name and index)
74
+ // for a buy/sell. Return null if there are no adapters.
75
+ getAdapters(side: SwapSide): { name: string; index: number }[] | null {
76
+ return null;
77
+ }
78
+
79
+ // Returns the pool matching the specified token pair or null if none found.
80
+ // Note: OSwap V1 does not support more than 1 pool per pair.
81
+ getPoolByTokenPair(srcToken: Token, destToken: Token): OSwapPool | null {
82
+ const srcAddress = srcToken.address.toLowerCase();
83
+ const destAddress = destToken.address.toLowerCase();
84
+
85
+ // A pair must have 2 different tokens.
86
+ if (srcAddress === destAddress) return null;
87
+
88
+ for (const pool of this.pools) {
89
+ if (
90
+ (srcAddress === pool.token0 && destAddress === pool.token1) ||
91
+ (srcAddress === pool.token1 && destAddress === pool.token0)
92
+ ) {
93
+ return pool;
94
+ }
95
+ }
96
+ return null;
97
+ }
98
+
99
+ getPoolById(id: string): OSwapPool | null {
100
+ for (const pool of this.pools) {
101
+ if (pool.id === id) return pool;
102
+ }
103
+ return null;
104
+ }
105
+
106
+ // Returns a list of pool using the token.
107
+ getPoolsByTokenAddress(tokenAddress: Address): OSwapPool[] {
108
+ const address = tokenAddress.toLowerCase();
109
+ let pools: OSwapPool[] = [];
110
+ for (const pool of this.pools) {
111
+ if (address === pool.token0 || address === pool.token1) {
112
+ pools.push(pool);
113
+ }
114
+ }
115
+ return pools;
116
+ }
117
+
118
+ // Returns the list of pool identifiers that can be used
119
+ // for a given swap. poolIdentifiers must be unique
120
+ // across DEXes. It is recommended to use
121
+ // ${dexKey}_${poolAddress} as a poolIdentifier
122
+ async getPoolIdentifiers(
123
+ srcToken: Token,
124
+ destToken: Token,
125
+ side: SwapSide,
126
+ blockNumber: number,
127
+ ): Promise<string[]> {
128
+ const pool = this.getPoolByTokenPair(srcToken, destToken);
129
+ return pool ? [pool.id] : [];
130
+ }
131
+
132
+ // Sell: Given "amount" of "from" token, how much of "to" token will be received by the trader.
133
+ // Buy: Given "amount" of "dest" token, how much of "to" token is required from the trader.
134
+ // Note: OSwap traderate is at precision 36.
135
+ calcPrice(
136
+ pool: OSwapPool,
137
+ state: OSwapPoolState,
138
+ from: Token,
139
+ amount: bigint,
140
+ side: SwapSide,
141
+ ): bigint {
142
+ const rate =
143
+ from.address.toLowerCase() === pool.token0
144
+ ? state.traderate0
145
+ : state.traderate1;
146
+ return side === SwapSide.SELL
147
+ ? (amount * rate) / getBigIntPow(36)
148
+ : (amount * getBigIntPow(36)) / rate;
149
+ }
150
+
151
+ // Returns true if the pool has enough liquidity for the swap. False otherwise.
152
+ checkLiquidity(
153
+ pool: OSwapPool,
154
+ state: OSwapPoolState,
155
+ from: Token,
156
+ amount: bigint,
157
+ side: SwapSide,
158
+ ): boolean {
159
+ if (side === SwapSide.SELL) {
160
+ const needed = this.calcPrice(pool, state, from, amount, side);
161
+ return from.address.toLowerCase() === pool.token0
162
+ ? needed <= state.balance1
163
+ : needed <= state.balance0;
164
+ }
165
+ // SwapSide.BUY
166
+ return from.address.toLowerCase() === pool.token0
167
+ ? amount <= state.balance1
168
+ : amount <= state.balance0;
169
+ }
170
+
171
+ // Returns pool prices for amounts.
172
+ // If limitPools is defined only pools in limitPools
173
+ // should be used. If limitPools is undefined then
174
+ // any pool can be used.
175
+ async getPricesVolume(
176
+ srcToken: Token,
177
+ destToken: Token,
178
+ amounts: bigint[],
179
+ side: SwapSide,
180
+ blockNumber: number,
181
+ limitPools?: string[],
182
+ ): Promise<null | ExchangePrices<OSwapData>> {
183
+ // Get the pool to use.
184
+ const pool = this.getPoolByTokenPair(srcToken, destToken);
185
+ if (!pool) return null;
186
+
187
+ // Make sure the pool meets the optional limitPools filter.
188
+ if (limitPools && !limitPools.includes(pool.id)) return null;
189
+
190
+ const eventPool = this.eventPools[pool.id];
191
+ if (!eventPool)
192
+ throw new Error(`OSwap pool ${pool.id}: No EventPool found.`);
193
+
194
+ const state = await eventPool.getStateOrGenerate(blockNumber);
195
+
196
+ // Ensure there is enough liquidity in the pool to process all the requested swaps.
197
+ const totalAmount = amounts.reduce(
198
+ (a: bigint, b: bigint) => a + b,
199
+ BigInt(0),
200
+ );
201
+ if (!this.checkLiquidity(pool, state, srcToken, totalAmount, side)) {
202
+ return null;
203
+ }
204
+ // Calculate the prices
205
+ const unitAmount = getBigIntPow(18);
206
+ const unitPrice = this.calcPrice(pool, state, srcToken, unitAmount, side);
207
+ const prices = amounts.map(amount =>
208
+ this.calcPrice(pool, state, srcToken, amount, side),
209
+ );
210
+
211
+ return [
212
+ {
213
+ prices,
214
+ unit: unitPrice,
215
+ data: {
216
+ pool: pool.address,
217
+ path: [srcToken.address, destToken.address],
218
+ },
219
+ exchange: this.dexKey,
220
+ poolIdentifier: pool.id,
221
+ gasCost: OSWAP_GAS_COST,
222
+ poolAddresses: [pool.address],
223
+ },
224
+ ];
225
+ }
226
+
227
+ // Returns estimated gas cost of calldata for this DEX in multiSwap
228
+ getCalldataGasCost(poolPrices: PoolPrices<OSwapData>): number | number[] {
229
+ return (
230
+ CALLDATA_GAS_COST.DEX_OVERHEAD +
231
+ // ParentStruct header
232
+ CALLDATA_GAS_COST.OFFSET_SMALL +
233
+ // ParentStruct -> path[] header
234
+ CALLDATA_GAS_COST.OFFSET_SMALL +
235
+ // ParentStruct -> path length
236
+ CALLDATA_GAS_COST.LENGTH_SMALL +
237
+ // ParentStruct -> path[0]
238
+ CALLDATA_GAS_COST.ADDRESS +
239
+ // ParentStruct -> path[1]
240
+ CALLDATA_GAS_COST.ADDRESS +
241
+ // ParentStruct -> receiver header
242
+ CALLDATA_GAS_COST.OFFSET_SMALL +
243
+ // ParentStruct -> receiver
244
+ CALLDATA_GAS_COST.ADDRESS
245
+ );
246
+ }
247
+
248
+ // Encode params required by the exchange adapter
249
+ // Used for multiSwap, buy & megaSwap
250
+ getAdapterParam(
251
+ srcToken: string,
252
+ destToken: string,
253
+ srcAmount: string,
254
+ destAmount: string,
255
+ data: OSwapData,
256
+ side: SwapSide,
257
+ ): AdapterExchangeParam {
258
+ return {
259
+ targetExchange: data.pool,
260
+ payload: '',
261
+ networkFee: '0',
262
+ };
263
+ }
264
+
265
+ // Encode call data used by simpleSwap like routers
266
+ // Used for simpleSwap & simpleBuy
267
+ getDexParam(
268
+ srcToken: Address,
269
+ destToken: Address,
270
+ srcAmount: NumberAsString,
271
+ destAmount: NumberAsString,
272
+ recipient: Address,
273
+ data: OSwapData,
274
+ side: SwapSide,
275
+ _: Context,
276
+ executorAddress: Address,
277
+ ): DexExchangeParam {
278
+ let method: string;
279
+ let args: any;
280
+ let returnAmountPos: number | undefined = undefined;
281
+
282
+ const deadline = getLocalDeadlineAsFriendlyPlaceholder();
283
+ if (side === SwapSide.SELL) {
284
+ method = 'swapExactTokensForTokens';
285
+ returnAmountPos = extractReturnAmountPosition(
286
+ this.iOSwap,
287
+ method,
288
+ 'amounts',
289
+ 1,
290
+ );
291
+ args = [srcAmount, destAmount, data.path, recipient, deadline];
292
+ } else {
293
+ method = 'swapTokensForExactTokens';
294
+ args = [destAmount, srcAmount, data.path, recipient, deadline];
295
+ }
296
+
297
+ const swapData = this.iOSwap.encodeFunctionData(method, args);
298
+
299
+ return {
300
+ needWrapNative: this.needWrapNative,
301
+ dexFuncHasRecipient: true,
302
+ exchangeData: swapData,
303
+ targetExchange: data.pool,
304
+ returnAmountPos,
305
+ };
306
+ }
307
+
308
+ // This is called once before getTopPoolsForToken is
309
+ // called for multiple tokens. This can be helpful to
310
+ // update common state required for calculating
311
+ // getTopPoolsForToken. It is optional for a DEX
312
+ // to implement this
313
+ async updatePoolState(): Promise<void> {
314
+ return Promise.resolve();
315
+ }
316
+
317
+ // Returns a list of top pools based on liquidity. Max
318
+ // limit number pools should be returned.
319
+ async getTopPoolsForToken(
320
+ tokenAddress: Address,
321
+ limit: number,
322
+ ): Promise<PoolLiquidity[]> {
323
+ // Get the list of pools using the token.
324
+ const pools = this.getPoolsByTokenAddress(tokenAddress);
325
+ if (!pools.length) return [];
326
+
327
+ const results = await Promise.all<PoolLiquidity>(
328
+ pools.map(async pool => {
329
+ // Get the pool's balance and its USD value.
330
+ const eventPool = this.eventPools[pool.id];
331
+ const blockNumber =
332
+ await this.dexHelper.web3Provider.eth.getBlockNumber();
333
+ const state = await eventPool.getStateOrGenerate(blockNumber);
334
+
335
+ const usd0 = await this.dexHelper.getTokenUSDPrice(
336
+ { address: pool.token0, decimals: 18 },
337
+ state.balance0,
338
+ );
339
+ const usd1 = await this.dexHelper.getTokenUSDPrice(
340
+ { address: pool.token1, decimals: 18 },
341
+ state.balance1,
342
+ );
343
+
344
+ // Get the other token in the pair.
345
+ const pairedToken =
346
+ pool.token0 === tokenAddress.toLowerCase()
347
+ ? { address: pool.token1, decimals: 18 }
348
+ : { address: pool.token0, decimals: 18 };
349
+
350
+ return {
351
+ exchange: this.dexKey,
352
+ address: pool.address,
353
+ connectorTokens: [pairedToken],
354
+ liquidityUSD: usd0 + usd1,
355
+ };
356
+ }),
357
+ );
358
+ return results
359
+ .filter(r => r)
360
+ .sort((a, b) => a.liquidityUSD - b.liquidityUSD)
361
+ .slice(0, limit);
362
+ }
363
+
364
+ // This is optional function in case if your implementation has acquired any resources
365
+ // you need to release for graceful shutdown. For example, it may be any interval timer
366
+ releaseResources(): AsyncOrSync<void> {}
367
+ }
@@ -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
+ };
package/.idea/aws.xml DELETED
@@ -1,17 +0,0 @@
1
- <?xml version="1.0" encoding="UTF-8"?>
2
- <project version="4">
3
- <component name="accountSettings">
4
- <option name="activeProfile" value="profile:default" />
5
- <option name="activeRegion" value="us-east-1" />
6
- <option name="recentlyUsedProfiles">
7
- <list>
8
- <option value="profile:default" />
9
- </list>
10
- </option>
11
- <option name="recentlyUsedRegions">
12
- <list>
13
- <option value="us-east-1" />
14
- </list>
15
- </option>
16
- </component>
17
- </project>
package/.idea/misc.xml DELETED
@@ -1,6 +0,0 @@
1
- <?xml version="1.0" encoding="UTF-8"?>
2
- <project version="4">
3
- <component name="ProjectRootManager">
4
- <output url="file://$PROJECT_DIR$/out" />
5
- </component>
6
- </project>
@@ -1,7 +0,0 @@
1
- <?xml version="1.0" encoding="UTF-8"?>
2
- <project version="4">
3
- <component name="PrettierConfiguration">
4
- <option name="myRunOnSave" value="true" />
5
- <option name="myRunOnReformat" value="true" />
6
- </component>
7
- </project>