@paraswap/dex-lib 3.10.0 → 3.10.2
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.
- package/build/abi/fluid-dex/dexFactory.abi.json +506 -0
- package/build/abi/fluid-dex/fluid-dex.abi.json +922 -0
- package/build/abi/fluid-dex/liquidityUserModule.abi.json +145 -0
- package/build/abi/fluid-dex/resolver.abi.json +999 -0
- package/build/dex/fluid-dex/config.d.ts +4 -0
- package/build/dex/fluid-dex/config.js +20 -0
- package/build/dex/fluid-dex/config.js.map +1 -0
- package/build/dex/fluid-dex/fluid-dex-factory.d.ts +49 -0
- package/build/dex/fluid-dex/fluid-dex-factory.js +104 -0
- package/build/dex/fluid-dex/fluid-dex-factory.js.map +1 -0
- package/build/dex/fluid-dex/fluid-dex-pool.d.ts +47 -0
- package/build/dex/fluid-dex/fluid-dex-pool.js +119 -0
- package/build/dex/fluid-dex/fluid-dex-pool.js.map +1 -0
- package/build/dex/fluid-dex/fluid-dex.d.ts +127 -0
- package/build/dex/fluid-dex/fluid-dex.js +502 -0
- package/build/dex/fluid-dex/fluid-dex.js.map +1 -0
- package/build/dex/fluid-dex/types.d.ts +52 -0
- package/build/dex/fluid-dex/types.js +3 -0
- package/build/dex/fluid-dex/types.js.map +1 -0
- package/build/dex/fluid-dex/utils.d.ts +2 -0
- package/build/dex/fluid-dex/utils.js +18 -0
- package/build/dex/fluid-dex/utils.js.map +1 -0
- package/build/dex/index.js +2 -0
- package/build/dex/index.js.map +1 -1
- package/build/dex/paraswap-limit-orders/paraswap-limit-orders.js +1 -1
- package/build/dex/paraswap-limit-orders/paraswap-limit-orders.js.map +1 -1
- package/package.json +1 -1
- package/src/abi/fluid-dex/dexFactory.abi.json +506 -0
- package/src/abi/fluid-dex/fluid-dex.abi.json +922 -0
- package/src/abi/fluid-dex/liquidityUserModule.abi.json +145 -0
- package/src/abi/fluid-dex/resolver.abi.json +999 -0
- package/src/dex/fluid-dex/config.ts +20 -0
- package/src/dex/fluid-dex/fluid-dex-e2e.test.ts +153 -0
- package/src/dex/fluid-dex/fluid-dex-events.test.ts +293 -0
- package/src/dex/fluid-dex/fluid-dex-factory.ts +143 -0
- package/src/dex/fluid-dex/fluid-dex-integration.test.ts +299 -0
- package/src/dex/fluid-dex/fluid-dex-pool.ts +178 -0
- package/src/dex/fluid-dex/fluid-dex.ts +790 -0
- package/src/dex/fluid-dex/types.ts +62 -0
- package/src/dex/fluid-dex/utils.ts +15 -0
- package/src/dex/index.ts +2 -0
- package/src/dex/paraswap-limit-orders/paraswap-limit-orders.ts +1 -1
- package/tests/constants-e2e.ts +2 -2
|
@@ -0,0 +1,790 @@
|
|
|
1
|
+
import { BytesLike } from 'ethers/lib/utils';
|
|
2
|
+
import { Interface } from '@ethersproject/abi';
|
|
3
|
+
import {
|
|
4
|
+
Token,
|
|
5
|
+
Address,
|
|
6
|
+
ExchangePrices,
|
|
7
|
+
PoolPrices,
|
|
8
|
+
AdapterExchangeParam,
|
|
9
|
+
PoolLiquidity,
|
|
10
|
+
DexExchangeParam,
|
|
11
|
+
Logger,
|
|
12
|
+
} from '../../types';
|
|
13
|
+
import { SwapSide, Network } from '../../constants';
|
|
14
|
+
import * as CALLDATA_GAS_COST from '../../calldata-gas-cost';
|
|
15
|
+
import { Context, IDex } from '../../dex/idex';
|
|
16
|
+
import { IDexHelper } from '../../dex-helper/idex-helper';
|
|
17
|
+
import {
|
|
18
|
+
CollateralReserves,
|
|
19
|
+
DebtReserves,
|
|
20
|
+
FluidDexData,
|
|
21
|
+
FluidDexPool,
|
|
22
|
+
FluidDexPoolState,
|
|
23
|
+
Pool,
|
|
24
|
+
} from './types';
|
|
25
|
+
import { SimpleExchange } from '../simple-exchange';
|
|
26
|
+
import FluidDexPoolABI from '../../abi/fluid-dex/fluid-dex.abi.json';
|
|
27
|
+
import { FluidDexConfig, FLUID_DEX_GAS_COST } from './config';
|
|
28
|
+
import { FluidDexEventPool } from './fluid-dex-pool';
|
|
29
|
+
import { FluidDexFactory } from './fluid-dex-factory';
|
|
30
|
+
import { getDexKeysWithNetwork, getBigIntPow } from '../../utils';
|
|
31
|
+
import { extractReturnAmountPosition } from '../../executor/utils';
|
|
32
|
+
import { MultiResult } from '../../lib/multi-wrapper';
|
|
33
|
+
import { generalDecoder } from '../../lib/decoders';
|
|
34
|
+
import { BigNumber } from 'ethers';
|
|
35
|
+
import { sqrt } from './utils';
|
|
36
|
+
|
|
37
|
+
export class FluidDex extends SimpleExchange implements IDex<FluidDexData> {
|
|
38
|
+
eventPools: { [id: string]: FluidDexEventPool } = {};
|
|
39
|
+
readonly hasConstantPriceLargeAmounts = false;
|
|
40
|
+
readonly needWrapNative = false;
|
|
41
|
+
readonly isFeeOnTransferSupported = false;
|
|
42
|
+
public static dexKeysWithNetwork: { key: string; networks: Network[] }[] =
|
|
43
|
+
getDexKeysWithNetwork(FluidDexConfig);
|
|
44
|
+
|
|
45
|
+
logger: Logger;
|
|
46
|
+
|
|
47
|
+
pools: FluidDexPool[] = [];
|
|
48
|
+
|
|
49
|
+
readonly factory: FluidDexFactory;
|
|
50
|
+
|
|
51
|
+
readonly fluidDexPoolIface: Interface;
|
|
52
|
+
|
|
53
|
+
FEE_100_PERCENT = BigInt(1000000);
|
|
54
|
+
|
|
55
|
+
constructor(
|
|
56
|
+
readonly network: Network,
|
|
57
|
+
readonly dexKey: string,
|
|
58
|
+
readonly dexHelper: IDexHelper,
|
|
59
|
+
) {
|
|
60
|
+
super(dexHelper, dexKey);
|
|
61
|
+
this.logger = dexHelper.getLogger(dexKey);
|
|
62
|
+
this.factory = new FluidDexFactory(
|
|
63
|
+
'FluidDex',
|
|
64
|
+
FluidDexConfig['FluidDex'][network].commonAddresses,
|
|
65
|
+
network,
|
|
66
|
+
dexHelper,
|
|
67
|
+
this.logger,
|
|
68
|
+
);
|
|
69
|
+
this.fluidDexPoolIface = new Interface(FluidDexPoolABI);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
private async fetchFluidDexPools(
|
|
73
|
+
blockNumber: number,
|
|
74
|
+
): Promise<FluidDexPool[]> {
|
|
75
|
+
const poolsFromResolver = await this.factory.getStateOrGenerate(
|
|
76
|
+
blockNumber,
|
|
77
|
+
false,
|
|
78
|
+
);
|
|
79
|
+
return poolsFromResolver.map(pool => ({
|
|
80
|
+
id: `FluidDex_${pool.address.toLowerCase()}`,
|
|
81
|
+
address: pool.address.toLowerCase(),
|
|
82
|
+
token0: pool.token0.toLowerCase(),
|
|
83
|
+
token1: pool.token1.toLowerCase(),
|
|
84
|
+
}));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Initialize pricing is called once in the start of
|
|
88
|
+
// pricing service. It is intended to setup the integration
|
|
89
|
+
// for pricing requests. It is optional for a DEX to
|
|
90
|
+
// implement this function
|
|
91
|
+
async initializePricing(blockNumber: number) {
|
|
92
|
+
await this.factory.initialize(blockNumber);
|
|
93
|
+
this.pools = await this.fetchFluidDexPools(blockNumber);
|
|
94
|
+
|
|
95
|
+
for (const pool of this.pools) {
|
|
96
|
+
if (!this.eventPools[pool.id]) {
|
|
97
|
+
this.eventPools[pool.id] = new FluidDexEventPool(
|
|
98
|
+
'FluidDex',
|
|
99
|
+
pool.address,
|
|
100
|
+
this.factory.commonAddresses,
|
|
101
|
+
this.network,
|
|
102
|
+
this.dexHelper,
|
|
103
|
+
this.logger,
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
await Promise.all(
|
|
109
|
+
Object.values(this.eventPools).map(async eventPool => {
|
|
110
|
+
return eventPool.initialize(blockNumber);
|
|
111
|
+
}),
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
getAdapters(side: SwapSide) {
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
decodePools = (result: MultiResult<BytesLike> | BytesLike): Pool[] => {
|
|
120
|
+
return generalDecoder(
|
|
121
|
+
result,
|
|
122
|
+
['tuple(address pool, address token0, address token1)[]'],
|
|
123
|
+
undefined,
|
|
124
|
+
decoded => {
|
|
125
|
+
return decoded.map((decodedPool: any) => ({
|
|
126
|
+
address: decodedPool[0][0].toLowerCase(),
|
|
127
|
+
token0: decodedPool[0][1].toLowerCase(),
|
|
128
|
+
token1: decodedPool[0][2].toLowerCase(),
|
|
129
|
+
}));
|
|
130
|
+
},
|
|
131
|
+
);
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
// Returns list of pool identifiers that can be used
|
|
135
|
+
// for a given swap. poolIdentifiers must be unique
|
|
136
|
+
// across DEXes. It is recommended to use
|
|
137
|
+
// ${dexKey}_${poolAddress} as a poolIdentifier
|
|
138
|
+
async getPoolIdentifiers(
|
|
139
|
+
srcToken: Token,
|
|
140
|
+
destToken: Token,
|
|
141
|
+
side: SwapSide,
|
|
142
|
+
blockNumber: number,
|
|
143
|
+
): Promise<string[]> {
|
|
144
|
+
if (side === SwapSide.BUY) return [];
|
|
145
|
+
|
|
146
|
+
const pool = await this.getPoolByTokenPair(
|
|
147
|
+
srcToken.address,
|
|
148
|
+
destToken.address,
|
|
149
|
+
);
|
|
150
|
+
return pool ? [pool.id] : [];
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async getPoolByTokenPair(
|
|
154
|
+
srcToken: Address,
|
|
155
|
+
destToken: Address,
|
|
156
|
+
): Promise<FluidDexPool | null> {
|
|
157
|
+
const srcAddress = srcToken.toLowerCase();
|
|
158
|
+
const destAddress = destToken.toLowerCase();
|
|
159
|
+
|
|
160
|
+
// A pair must have 2 different tokens.
|
|
161
|
+
if (srcAddress === destAddress) return null;
|
|
162
|
+
|
|
163
|
+
for (const pool of this.pools) {
|
|
164
|
+
if (
|
|
165
|
+
(srcAddress === pool.token0 && destAddress === pool.token1) ||
|
|
166
|
+
(srcAddress === pool.token1 && destAddress === pool.token0)
|
|
167
|
+
) {
|
|
168
|
+
return pool;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// Returns pool prices for amounts.
|
|
175
|
+
// If limitPools is defined only pools in limitPools
|
|
176
|
+
// should be used. If limitPools is undefined then
|
|
177
|
+
// any pools can be used.
|
|
178
|
+
async getPricesVolume(
|
|
179
|
+
srcToken: Token,
|
|
180
|
+
destToken: Token,
|
|
181
|
+
amounts: bigint[],
|
|
182
|
+
side: SwapSide,
|
|
183
|
+
blockNumber: number,
|
|
184
|
+
limitPools?: string[],
|
|
185
|
+
): Promise<null | ExchangePrices<FluidDexData>> {
|
|
186
|
+
try {
|
|
187
|
+
if (srcToken.address.toLowerCase() === destToken.address.toLowerCase())
|
|
188
|
+
return null;
|
|
189
|
+
|
|
190
|
+
if (side === SwapSide.BUY) return null;
|
|
191
|
+
// Get the pool to use.
|
|
192
|
+
const pool = await this.getPoolByTokenPair(
|
|
193
|
+
srcToken.address,
|
|
194
|
+
destToken.address,
|
|
195
|
+
);
|
|
196
|
+
if (!pool) return null;
|
|
197
|
+
|
|
198
|
+
// Make sure the pool meets the optional limitPools filter.
|
|
199
|
+
if (limitPools && !limitPools.includes(pool.id)) return null;
|
|
200
|
+
|
|
201
|
+
const eventPool = this.eventPools[pool.id];
|
|
202
|
+
|
|
203
|
+
if (!eventPool) {
|
|
204
|
+
this.logger.error(`fluid-dex pool ${pool.id}: No EventPool found.`);
|
|
205
|
+
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const state = await eventPool.getState(blockNumber);
|
|
210
|
+
if (!state) return null;
|
|
211
|
+
|
|
212
|
+
const prices = amounts.map(amount => {
|
|
213
|
+
return this.swapIn(
|
|
214
|
+
srcToken.address.toLowerCase() === pool.token0.toLowerCase(),
|
|
215
|
+
amount,
|
|
216
|
+
state.collateralReserves,
|
|
217
|
+
state.debtReserves,
|
|
218
|
+
srcToken.decimals,
|
|
219
|
+
destToken.decimals,
|
|
220
|
+
BigInt(state.fee),
|
|
221
|
+
);
|
|
222
|
+
});
|
|
223
|
+
return [
|
|
224
|
+
{
|
|
225
|
+
prices: prices,
|
|
226
|
+
unit: getBigIntPow(
|
|
227
|
+
(side === SwapSide.SELL ? destToken : srcToken).decimals,
|
|
228
|
+
),
|
|
229
|
+
data: {
|
|
230
|
+
colReserves: state.collateralReserves,
|
|
231
|
+
debtReserves: state.debtReserves,
|
|
232
|
+
exchange: this.dexKey,
|
|
233
|
+
},
|
|
234
|
+
exchange: this.dexKey,
|
|
235
|
+
poolIdentifier: pool.id,
|
|
236
|
+
gasCost: FLUID_DEX_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<FluidDexData>): number | number[] {
|
|
254
|
+
return CALLDATA_GAS_COST.DEX_NO_PAYLOAD;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// Encode params required by the exchange adapter
|
|
258
|
+
// V5: Used for multiSwap, buy & megaSwap
|
|
259
|
+
// V6: Not used, can be left blank
|
|
260
|
+
// Hint: abiCoder.encodeParameter() could be useful
|
|
261
|
+
getAdapterParam(
|
|
262
|
+
srcToken: string,
|
|
263
|
+
destToken: string,
|
|
264
|
+
srcAmount: string,
|
|
265
|
+
destAmount: string,
|
|
266
|
+
data: FluidDexData,
|
|
267
|
+
side: SwapSide,
|
|
268
|
+
): AdapterExchangeParam {
|
|
269
|
+
if (side === SwapSide.BUY) throw new Error(`Buy not supported`);
|
|
270
|
+
const { exchange } = data;
|
|
271
|
+
|
|
272
|
+
// Encode here the payload for adapter
|
|
273
|
+
const payload = '';
|
|
274
|
+
|
|
275
|
+
return {
|
|
276
|
+
targetExchange: exchange,
|
|
277
|
+
payload,
|
|
278
|
+
networkFee: '0',
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// Returns list of top pools based on liquidity. Max
|
|
283
|
+
// limit number pools should be returned.
|
|
284
|
+
async getTopPoolsForToken(
|
|
285
|
+
tokenAddress: Address,
|
|
286
|
+
limit: number,
|
|
287
|
+
): Promise<PoolLiquidity[]> {
|
|
288
|
+
//@TODO
|
|
289
|
+
return [];
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
async getDexParam(
|
|
293
|
+
srcToken: Address,
|
|
294
|
+
destToken: Address,
|
|
295
|
+
srcAmount: string,
|
|
296
|
+
destAmount: string,
|
|
297
|
+
recipient: Address,
|
|
298
|
+
data: FluidDexData,
|
|
299
|
+
side: SwapSide,
|
|
300
|
+
context: Context,
|
|
301
|
+
executorAddress: Address,
|
|
302
|
+
): Promise<DexExchangeParam> {
|
|
303
|
+
if (side === SwapSide.BUY) throw new Error(`Buy not supported`);
|
|
304
|
+
|
|
305
|
+
let args: any;
|
|
306
|
+
let returnAmountPos: number | undefined;
|
|
307
|
+
|
|
308
|
+
const method = 'swapIn';
|
|
309
|
+
|
|
310
|
+
returnAmountPos = extractReturnAmountPosition(
|
|
311
|
+
this.fluidDexPoolIface,
|
|
312
|
+
method,
|
|
313
|
+
'amountOut_',
|
|
314
|
+
1,
|
|
315
|
+
);
|
|
316
|
+
|
|
317
|
+
const pool = await this.getPoolByTokenPair(srcToken, destToken);
|
|
318
|
+
|
|
319
|
+
if (pool!.token0.toLowerCase() !== srcToken.toLowerCase()) {
|
|
320
|
+
args = [false, BigInt(srcAmount), BigInt(destAmount), recipient];
|
|
321
|
+
} else {
|
|
322
|
+
args = [true, BigInt(srcAmount), BigInt(destAmount), recipient];
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const swapData = this.fluidDexPoolIface.encodeFunctionData(method, args);
|
|
326
|
+
|
|
327
|
+
return {
|
|
328
|
+
needWrapNative: this.needWrapNative,
|
|
329
|
+
dexFuncHasRecipient: true,
|
|
330
|
+
exchangeData: swapData,
|
|
331
|
+
targetExchange: pool!.address,
|
|
332
|
+
returnAmountPos,
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Calculates the output amount for a given input amount in a swap operation.
|
|
338
|
+
* @param swap0To1 - Direction of the swap. True if swapping token0 for token1, false otherwise.
|
|
339
|
+
* @param amountIn - The amount of input token to be swapped (as a BigInt).
|
|
340
|
+
* @param colReserves - The reserves of the collateral pool.
|
|
341
|
+
* @param debtReserves - The reserves of the debt pool.
|
|
342
|
+
* @param inDecimals - The number of decimals for the input token.
|
|
343
|
+
* @param outDecimals - The number of decimals for the output token.
|
|
344
|
+
* @returns The calculated output amount (as a BigInt).
|
|
345
|
+
*/
|
|
346
|
+
private swapIn(
|
|
347
|
+
swap0To1: boolean,
|
|
348
|
+
amountIn: bigint,
|
|
349
|
+
colReserves: CollateralReserves,
|
|
350
|
+
debtReserves: DebtReserves,
|
|
351
|
+
inDecimals: number,
|
|
352
|
+
outDecimals: number,
|
|
353
|
+
fee: bigint,
|
|
354
|
+
): bigint {
|
|
355
|
+
if (amountIn === 0n) {
|
|
356
|
+
return 0n; // Return 0 if input amount is 0
|
|
357
|
+
}
|
|
358
|
+
if (
|
|
359
|
+
colReserves.token0RealReserves + debtReserves.token0RealReserves == 0n &&
|
|
360
|
+
colReserves.token1RealReserves + debtReserves.token1RealReserves == 0n
|
|
361
|
+
) {
|
|
362
|
+
return 0n;
|
|
363
|
+
}
|
|
364
|
+
const amountInAdjusted =
|
|
365
|
+
(amountIn * BigInt(10 ** 12)) / BigInt(10 ** inDecimals);
|
|
366
|
+
|
|
367
|
+
const amountOut = this.swapInAdjusted(
|
|
368
|
+
swap0To1,
|
|
369
|
+
amountInAdjusted, // Convert back to number for internal calculations
|
|
370
|
+
colReserves,
|
|
371
|
+
debtReserves,
|
|
372
|
+
fee,
|
|
373
|
+
);
|
|
374
|
+
const result = (amountOut * BigInt(10 ** outDecimals)) / BigInt(10 ** 12);
|
|
375
|
+
return result;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Calculates the output amount for a given input amount in a swap operation.
|
|
380
|
+
* @param swap0To1 - Direction of the swap. True if swapping token0 for token1, false otherwise.
|
|
381
|
+
* @param amountToSwap - The amount of input token to be swapped.
|
|
382
|
+
* @param colReserves - The reserves of the collateral pool.
|
|
383
|
+
* @param debtReserves - The reserves of the debt pool.
|
|
384
|
+
* @returns The calculated output amount.
|
|
385
|
+
*/
|
|
386
|
+
private swapInAdjusted(
|
|
387
|
+
swap0To1: boolean,
|
|
388
|
+
amountToSwap: bigint,
|
|
389
|
+
colReserves: CollateralReserves,
|
|
390
|
+
debtReserves: DebtReserves,
|
|
391
|
+
fee: bigint,
|
|
392
|
+
): bigint {
|
|
393
|
+
const {
|
|
394
|
+
token0RealReserves,
|
|
395
|
+
token1RealReserves,
|
|
396
|
+
token0ImaginaryReserves,
|
|
397
|
+
token1ImaginaryReserves,
|
|
398
|
+
} = colReserves;
|
|
399
|
+
|
|
400
|
+
const {
|
|
401
|
+
token0RealReserves: debtToken0RealReserves,
|
|
402
|
+
token1RealReserves: debtToken1RealReserves,
|
|
403
|
+
token0ImaginaryReserves: debtToken0ImaginaryReserves,
|
|
404
|
+
token1ImaginaryReserves: debtToken1ImaginaryReserves,
|
|
405
|
+
} = debtReserves;
|
|
406
|
+
|
|
407
|
+
// Check if all reserves of collateral pool are greater than 0
|
|
408
|
+
const colPoolEnabled =
|
|
409
|
+
token0RealReserves > BigInt(0) &&
|
|
410
|
+
token1RealReserves > BigInt(0) &&
|
|
411
|
+
token0ImaginaryReserves > BigInt(0) &&
|
|
412
|
+
token1ImaginaryReserves > BigInt(0);
|
|
413
|
+
|
|
414
|
+
// Check if all reserves of debt pool are greater than 0
|
|
415
|
+
const debtPoolEnabled =
|
|
416
|
+
debtToken0RealReserves > BigInt(0) &&
|
|
417
|
+
debtToken1RealReserves > BigInt(0) &&
|
|
418
|
+
debtToken0ImaginaryReserves > BigInt(0) &&
|
|
419
|
+
debtToken1ImaginaryReserves > BigInt(0);
|
|
420
|
+
|
|
421
|
+
let colReserveIn: bigint,
|
|
422
|
+
colReserveOut: bigint,
|
|
423
|
+
debtReserveIn: bigint,
|
|
424
|
+
debtReserveOut: bigint;
|
|
425
|
+
let colIReserveIn: bigint,
|
|
426
|
+
colIReserveOut: bigint,
|
|
427
|
+
debtIReserveIn: bigint,
|
|
428
|
+
debtIReserveOut: bigint;
|
|
429
|
+
|
|
430
|
+
if (swap0To1) {
|
|
431
|
+
colReserveIn = token0RealReserves;
|
|
432
|
+
colReserveOut = token1RealReserves;
|
|
433
|
+
colIReserveIn = token0ImaginaryReserves;
|
|
434
|
+
colIReserveOut = token1ImaginaryReserves;
|
|
435
|
+
debtReserveIn = debtToken0RealReserves;
|
|
436
|
+
debtReserveOut = debtToken1RealReserves;
|
|
437
|
+
debtIReserveIn = debtToken0ImaginaryReserves;
|
|
438
|
+
debtIReserveOut = debtToken1ImaginaryReserves;
|
|
439
|
+
} else {
|
|
440
|
+
colReserveIn = token1RealReserves;
|
|
441
|
+
colReserveOut = token0RealReserves;
|
|
442
|
+
colIReserveIn = token1ImaginaryReserves;
|
|
443
|
+
colIReserveOut = token0ImaginaryReserves;
|
|
444
|
+
debtReserveIn = debtToken1RealReserves;
|
|
445
|
+
debtReserveOut = debtToken0RealReserves;
|
|
446
|
+
debtIReserveIn = debtToken1ImaginaryReserves;
|
|
447
|
+
debtIReserveOut = debtToken0ImaginaryReserves;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
let a: bigint;
|
|
451
|
+
if (colPoolEnabled && debtPoolEnabled) {
|
|
452
|
+
a = this.swapRoutingIn(
|
|
453
|
+
amountToSwap,
|
|
454
|
+
colIReserveOut,
|
|
455
|
+
colIReserveIn,
|
|
456
|
+
debtIReserveOut,
|
|
457
|
+
debtIReserveIn,
|
|
458
|
+
);
|
|
459
|
+
} else if (debtPoolEnabled) {
|
|
460
|
+
a = BigInt(-1); // Route from debt pool
|
|
461
|
+
} else if (colPoolEnabled) {
|
|
462
|
+
a = amountToSwap + BigInt(1); // Route from collateral pool
|
|
463
|
+
} else {
|
|
464
|
+
throw new Error('No pools are enabled');
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
let amountOutCollateral = BigInt(0);
|
|
468
|
+
let amountOutDebt = BigInt(0);
|
|
469
|
+
|
|
470
|
+
if (a <= BigInt(0)) {
|
|
471
|
+
// Entire trade routes through debt pool
|
|
472
|
+
amountOutDebt = this.getAmountOut(
|
|
473
|
+
this.applyFee(amountToSwap, fee),
|
|
474
|
+
debtIReserveIn,
|
|
475
|
+
debtIReserveOut,
|
|
476
|
+
);
|
|
477
|
+
} else if (a >= amountToSwap) {
|
|
478
|
+
// Entire trade routes through collateral pool
|
|
479
|
+
amountOutCollateral = this.getAmountOut(
|
|
480
|
+
this.applyFee(amountToSwap, fee),
|
|
481
|
+
colIReserveIn,
|
|
482
|
+
colIReserveOut,
|
|
483
|
+
);
|
|
484
|
+
} else {
|
|
485
|
+
// Trade routes through both pools
|
|
486
|
+
amountOutCollateral = this.getAmountOut(
|
|
487
|
+
this.applyFee(a, fee),
|
|
488
|
+
colIReserveIn,
|
|
489
|
+
colIReserveOut,
|
|
490
|
+
);
|
|
491
|
+
amountOutDebt = this.getAmountOut(
|
|
492
|
+
this.applyFee(amountToSwap - a, fee),
|
|
493
|
+
debtIReserveIn,
|
|
494
|
+
debtIReserveOut,
|
|
495
|
+
);
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
if (amountOutDebt > debtReserveOut) {
|
|
499
|
+
return 0n;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
if (amountOutCollateral > colReserveOut) {
|
|
503
|
+
return 0n;
|
|
504
|
+
}
|
|
505
|
+
const totalAmountOut = amountOutCollateral + amountOutDebt;
|
|
506
|
+
|
|
507
|
+
return totalAmountOut;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
applyFee(amount: bigint, fee: bigint): bigint {
|
|
511
|
+
return (amount * (this.FEE_100_PERCENT - fee)) / this.FEE_100_PERCENT;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* Given an input amount of asset and pair reserves, returns the maximum output amount of the other asset.
|
|
516
|
+
* @param amountIn - The amount of input asset.
|
|
517
|
+
* @param iReserveIn - Imaginary token reserve with input amount.
|
|
518
|
+
* @param iReserveOut - Imaginary token reserve of output amount.
|
|
519
|
+
* @returns The maximum output amount of the other asset.
|
|
520
|
+
*/
|
|
521
|
+
private getAmountOut(
|
|
522
|
+
amountIn: bigint,
|
|
523
|
+
iReserveIn: bigint,
|
|
524
|
+
iReserveOut: bigint,
|
|
525
|
+
): bigint {
|
|
526
|
+
// Both numerator and denominator are scaled to 1e6 to factor in fee scaling.
|
|
527
|
+
const numerator = amountIn * iReserveOut;
|
|
528
|
+
const denominator = iReserveIn + amountIn;
|
|
529
|
+
|
|
530
|
+
// Using the swap formula: (AmountIn * iReserveY) / (iReserveX + AmountIn)
|
|
531
|
+
// We use division with rounding down, which is the default for bigint division
|
|
532
|
+
|
|
533
|
+
return numerator / denominator;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/**
|
|
537
|
+
* Given an output amount of asset and pair reserves, returns the input amount of the other asset
|
|
538
|
+
* @param amountOut - Desired output amount of the asset.
|
|
539
|
+
* @param iReserveIn - Imaginary token reserve of input amount.
|
|
540
|
+
* @param iReserveOut - Imaginary token reserve of output amount.
|
|
541
|
+
* @returns The input amount of the other asset.
|
|
542
|
+
*/
|
|
543
|
+
private getAmountIn(
|
|
544
|
+
amountOut: bigint,
|
|
545
|
+
iReserveIn: bigint,
|
|
546
|
+
iReserveOut: bigint,
|
|
547
|
+
): bigint {
|
|
548
|
+
// Both numerator and denominator are scaled to 1e6 to factor in fee scaling.
|
|
549
|
+
const numerator = amountOut * iReserveIn;
|
|
550
|
+
const denominator = iReserveOut - amountOut;
|
|
551
|
+
|
|
552
|
+
// Using the swap formula: (AmountOut * iReserveX) / (iReserveY - AmountOut)
|
|
553
|
+
return numerator / denominator;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/**
|
|
557
|
+
* Calculates how much of a swap should go through the collateral pool for output amount.
|
|
558
|
+
* @param t - Total amount out.
|
|
559
|
+
* @param x - Imaginary reserves of token in of collateral.
|
|
560
|
+
* @param y - Imaginary reserves of token out of collateral.
|
|
561
|
+
* @param x2 - Imaginary reserves of token in of debt.
|
|
562
|
+
* @param y2 - Imaginary reserves of token out of debt.
|
|
563
|
+
* @returns How much swap should go through collateral pool. Remaining will go from debt.
|
|
564
|
+
* @note If a < 0 then entire trade route through debt pool and debt pool arbitrage with col pool.
|
|
565
|
+
* @note If a > t then entire trade route through col pool and col pool arbitrage with debt pool.
|
|
566
|
+
* @note If a > 0 & a < t then swap will route through both pools.
|
|
567
|
+
*/
|
|
568
|
+
private swapRoutingOut(
|
|
569
|
+
t: bigint,
|
|
570
|
+
x: bigint,
|
|
571
|
+
y: bigint,
|
|
572
|
+
x2: bigint,
|
|
573
|
+
y2: bigint,
|
|
574
|
+
): bigint {
|
|
575
|
+
// Adding 1e18 precision
|
|
576
|
+
const xyRoot = BigInt(
|
|
577
|
+
Math.floor(Math.sqrt(Number(x * y * BigInt(10n ** 18n)))),
|
|
578
|
+
);
|
|
579
|
+
const x2y2Root = BigInt(
|
|
580
|
+
Math.floor(Math.sqrt(Number(x2 * y2 * BigInt(10n ** 18n)))),
|
|
581
|
+
);
|
|
582
|
+
|
|
583
|
+
// 1e18 precision gets cancelled out in division
|
|
584
|
+
const numerator = t * xyRoot + y * x2y2Root - y2 * xyRoot;
|
|
585
|
+
const denominator = xyRoot + x2y2Root;
|
|
586
|
+
|
|
587
|
+
// Use integer division (rounds down)
|
|
588
|
+
const a = numerator / denominator;
|
|
589
|
+
|
|
590
|
+
return a;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
/**
|
|
594
|
+
* Calculates how much of a swap should go through the collateral pool.
|
|
595
|
+
* @param t - Total amount in.
|
|
596
|
+
* @param x - Imaginary reserves of token out of collateral.
|
|
597
|
+
* @param y - Imaginary reserves of token in of collateral.
|
|
598
|
+
* @param x2 - Imaginary reserves of token out of debt.
|
|
599
|
+
* @param y2 - Imaginary reserves of token in of debt.
|
|
600
|
+
* @returns How much swap should go through collateral pool. Remaining will go from debt.
|
|
601
|
+
* @note If a < 0 then entire trade route through debt pool and debt pool arbitrage with col pool.
|
|
602
|
+
* @note If a > t then entire trade route through col pool and col pool arbitrage with debt pool.
|
|
603
|
+
* @note If a > 0 & a < t then swap will route through both pools.
|
|
604
|
+
*/
|
|
605
|
+
private swapRoutingIn(
|
|
606
|
+
t: bigint,
|
|
607
|
+
x: bigint,
|
|
608
|
+
y: bigint,
|
|
609
|
+
x2: bigint,
|
|
610
|
+
y2: bigint,
|
|
611
|
+
): bigint {
|
|
612
|
+
// Adding 1e18 precision
|
|
613
|
+
|
|
614
|
+
const xyRoot = sqrt(BigNumber.from(x).mul(y).mul(BigInt(1e18))).toBigInt();
|
|
615
|
+
const x2y2Root = sqrt(
|
|
616
|
+
BigNumber.from(x2).mul(y2).mul(BigInt(1e18)),
|
|
617
|
+
).toBigInt();
|
|
618
|
+
|
|
619
|
+
// Calculating 'a' using the given formula
|
|
620
|
+
const a = (y2 * xyRoot + t * xyRoot - y * x2y2Root) / (xyRoot + x2y2Root);
|
|
621
|
+
return a;
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/**
|
|
625
|
+
* Calculates the input amount for a given output amount in a swap operation.
|
|
626
|
+
* @param {boolean} swap0to1 - Direction of the swap. True if swapping token0 for token1, false otherwise.
|
|
627
|
+
* @param {bigint} amountOut - The amount of output token to be swapped.
|
|
628
|
+
* @param {Reserves} colReserves - The reserves of the collateral pool.
|
|
629
|
+
* @param {Reserves} debtReserves - The reserves of the debt pool.
|
|
630
|
+
* @param {number} inDecimals - The number of decimals for the input token.
|
|
631
|
+
* @param {number} outDecimals - The number of decimals for the output token.
|
|
632
|
+
* @param {number} fee - The fee for the swap. 1e4 = 1%
|
|
633
|
+
* @returns {bigint} amountIn - The calculated input amount required for the swap.
|
|
634
|
+
*/
|
|
635
|
+
private swapOut(
|
|
636
|
+
swap0to1: boolean,
|
|
637
|
+
amountOut: bigint,
|
|
638
|
+
colReserves: CollateralReserves,
|
|
639
|
+
debtReserves: DebtReserves,
|
|
640
|
+
inDecimals: number,
|
|
641
|
+
outDecimals: number,
|
|
642
|
+
fee: bigint,
|
|
643
|
+
): bigint {
|
|
644
|
+
const amountOutAdjusted =
|
|
645
|
+
(amountOut * BigInt(10 ** 12)) / BigInt(10 ** outDecimals);
|
|
646
|
+
const amountIn = this.swapOutAdjusted(
|
|
647
|
+
swap0to1,
|
|
648
|
+
amountOutAdjusted,
|
|
649
|
+
colReserves,
|
|
650
|
+
debtReserves,
|
|
651
|
+
);
|
|
652
|
+
|
|
653
|
+
const FEE_100_PERCENT = BigInt(1e6); // Assuming this constant is defined elsewhere
|
|
654
|
+
|
|
655
|
+
const result =
|
|
656
|
+
((amountIn * FEE_100_PERCENT) / (FEE_100_PERCENT - fee)) *
|
|
657
|
+
BigInt(10 ** (inDecimals - 12));
|
|
658
|
+
|
|
659
|
+
return result;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/**
|
|
663
|
+
* Calculates the input amount for a given output amount in a swap operation.
|
|
664
|
+
* @param {boolean} swap0to1 - Direction of the swap. True if swapping token0 for token1, false otherwise.
|
|
665
|
+
* @param {bigint} amountOut - The amount of output token to be swapped.
|
|
666
|
+
* @param {CollateralReserves} colReserves - The reserves of the collateral pool.
|
|
667
|
+
* @param {DebtReserves} debtReserves - The reserves of the debt pool.
|
|
668
|
+
* @returns {bigint} The calculated input amount required for the swap.
|
|
669
|
+
*/
|
|
670
|
+
private swapOutAdjusted(
|
|
671
|
+
swap0to1: boolean,
|
|
672
|
+
amountOut: bigint,
|
|
673
|
+
colReserves: CollateralReserves,
|
|
674
|
+
debtReserves: DebtReserves,
|
|
675
|
+
): bigint {
|
|
676
|
+
const {
|
|
677
|
+
token0RealReserves,
|
|
678
|
+
token1RealReserves,
|
|
679
|
+
token0ImaginaryReserves,
|
|
680
|
+
token1ImaginaryReserves,
|
|
681
|
+
} = colReserves;
|
|
682
|
+
|
|
683
|
+
const {
|
|
684
|
+
token0RealReserves: debtToken0RealReserves,
|
|
685
|
+
token1RealReserves: debtToken1RealReserves,
|
|
686
|
+
token0ImaginaryReserves: debtToken0ImaginaryReserves,
|
|
687
|
+
token1ImaginaryReserves: debtToken1ImaginaryReserves,
|
|
688
|
+
} = debtReserves;
|
|
689
|
+
|
|
690
|
+
// Check if all reserves of collateral pool are greater than 0
|
|
691
|
+
const colPoolEnabled =
|
|
692
|
+
token0RealReserves > 0n &&
|
|
693
|
+
token1RealReserves > 0n &&
|
|
694
|
+
token0ImaginaryReserves > 0n &&
|
|
695
|
+
token1ImaginaryReserves > 0n;
|
|
696
|
+
|
|
697
|
+
// Check if all reserves of debt pool are greater than 0
|
|
698
|
+
const debtPoolEnabled =
|
|
699
|
+
debtToken0RealReserves > 0n &&
|
|
700
|
+
debtToken1RealReserves > 0n &&
|
|
701
|
+
debtToken0ImaginaryReserves > 0n &&
|
|
702
|
+
debtToken1ImaginaryReserves > 0n;
|
|
703
|
+
|
|
704
|
+
let colReserveIn: bigint,
|
|
705
|
+
colReserveOut: bigint,
|
|
706
|
+
debtReserveIn: bigint,
|
|
707
|
+
debtReserveOut: bigint;
|
|
708
|
+
let colIReserveIn: bigint,
|
|
709
|
+
colIReserveOut: bigint,
|
|
710
|
+
debtIReserveIn: bigint,
|
|
711
|
+
debtIReserveOut: bigint;
|
|
712
|
+
|
|
713
|
+
if (swap0to1) {
|
|
714
|
+
colReserveIn = token0RealReserves;
|
|
715
|
+
colReserveOut = token1RealReserves;
|
|
716
|
+
colIReserveIn = token0ImaginaryReserves;
|
|
717
|
+
colIReserveOut = token1ImaginaryReserves;
|
|
718
|
+
debtReserveIn = debtToken0RealReserves;
|
|
719
|
+
debtReserveOut = debtToken1RealReserves;
|
|
720
|
+
debtIReserveIn = debtToken0ImaginaryReserves;
|
|
721
|
+
debtIReserveOut = debtToken1ImaginaryReserves;
|
|
722
|
+
} else {
|
|
723
|
+
colReserveIn = token1RealReserves;
|
|
724
|
+
colReserveOut = token0RealReserves;
|
|
725
|
+
colIReserveIn = token1ImaginaryReserves;
|
|
726
|
+
colIReserveOut = token0ImaginaryReserves;
|
|
727
|
+
debtReserveIn = debtToken1RealReserves;
|
|
728
|
+
debtReserveOut = debtToken0RealReserves;
|
|
729
|
+
debtIReserveIn = debtToken1ImaginaryReserves;
|
|
730
|
+
debtIReserveOut = debtToken0ImaginaryReserves;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
let a: bigint;
|
|
734
|
+
if (colPoolEnabled && debtPoolEnabled) {
|
|
735
|
+
a = this.swapRoutingOut(
|
|
736
|
+
amountOut,
|
|
737
|
+
colIReserveIn,
|
|
738
|
+
colIReserveOut,
|
|
739
|
+
debtIReserveIn,
|
|
740
|
+
debtIReserveOut,
|
|
741
|
+
);
|
|
742
|
+
} else if (debtPoolEnabled) {
|
|
743
|
+
a = -1n; // Route from debt pool
|
|
744
|
+
} else if (colPoolEnabled) {
|
|
745
|
+
a = amountOut + 1n; // Route from collateral pool
|
|
746
|
+
} else {
|
|
747
|
+
throw new Error('No pools are enabled');
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
let amountInCollateral = 0n;
|
|
751
|
+
let amountInDebt = 0n;
|
|
752
|
+
|
|
753
|
+
if (a <= 0n) {
|
|
754
|
+
// Entire trade routes through debt pool
|
|
755
|
+
amountInDebt = this.getAmountIn(
|
|
756
|
+
amountOut,
|
|
757
|
+
debtIReserveIn,
|
|
758
|
+
debtIReserveOut,
|
|
759
|
+
);
|
|
760
|
+
if (amountOut > debtReserveOut) {
|
|
761
|
+
return 2n ** 64n - 1n; // BigInt max value
|
|
762
|
+
}
|
|
763
|
+
} else if (a >= amountOut) {
|
|
764
|
+
// Entire trade routes through collateral pool
|
|
765
|
+
amountInCollateral = this.getAmountIn(
|
|
766
|
+
amountOut,
|
|
767
|
+
colIReserveIn,
|
|
768
|
+
colIReserveOut,
|
|
769
|
+
);
|
|
770
|
+
if (amountOut > colReserveOut) {
|
|
771
|
+
return 2n ** 64n - 1n; // BigInt max value
|
|
772
|
+
}
|
|
773
|
+
} else {
|
|
774
|
+
// Trade routes through both pools
|
|
775
|
+
amountInCollateral = this.getAmountIn(a, colIReserveIn, colIReserveOut);
|
|
776
|
+
amountInDebt = this.getAmountIn(
|
|
777
|
+
amountOut - a,
|
|
778
|
+
debtIReserveIn,
|
|
779
|
+
debtIReserveOut,
|
|
780
|
+
);
|
|
781
|
+
if (amountOut - a > debtReserveOut || a > debtReserveOut) {
|
|
782
|
+
return 2n ** 64n - 1n; // BigInt max value
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
const totalAmountIn = amountInCollateral + amountInDebt;
|
|
787
|
+
|
|
788
|
+
return totalAmountIn;
|
|
789
|
+
}
|
|
790
|
+
}
|