@paraswap/dex-lib 2.16.3 → 2.16.4-balancer-v2-buy.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.
Files changed (86) hide show
  1. package/.idea/aws.xml +17 -0
  2. package/.idea/codeStyles/Project.xml +19 -0
  3. package/.idea/codeStyles/codeStyleConfig.xml +5 -0
  4. package/.idea/inspectionProfiles/Project_Default.xml +6 -0
  5. package/.idea/misc.xml +6 -0
  6. package/.idea/modules.xml +8 -0
  7. package/.idea/paraswap-dex-lib.iml +9 -0
  8. package/.idea/vcs.xml +6 -0
  9. package/build/abi/TraderJoeV21Router.json +1489 -0
  10. package/build/config.js +10 -10
  11. package/build/dex/balancer-v2/balancer-v2.d.ts +9 -14
  12. package/build/dex/balancer-v2/balancer-v2.js +19 -16
  13. package/build/dex/balancer-v2/balancer-v2.js.map +1 -1
  14. package/build/dex/balancer-v2/config.d.ts +2 -7
  15. package/build/dex/balancer-v2/config.js +20 -30
  16. package/build/dex/balancer-v2/config.js.map +1 -1
  17. package/build/dex/balancer-v2/pools/balancer-v2-pool.d.ts +25 -0
  18. package/build/dex/balancer-v2/pools/balancer-v2-pool.js +107 -0
  19. package/build/dex/balancer-v2/pools/balancer-v2-pool.js.map +1 -0
  20. package/build/dex/balancer-v2/pools/linear/LinearMath.d.ts +20 -0
  21. package/build/dex/balancer-v2/pools/linear/LinearMath.js +186 -0
  22. package/build/dex/balancer-v2/pools/linear/LinearMath.js.map +1 -0
  23. package/build/dex/balancer-v2/pools/linear/LinearPool.d.ts +51 -0
  24. package/build/dex/balancer-v2/pools/linear/LinearPool.js +477 -0
  25. package/build/dex/balancer-v2/pools/linear/LinearPool.js.map +1 -0
  26. package/build/dex/balancer-v2/pools/phantom-stable/PhantomStableMath.d.ts +10 -0
  27. package/build/dex/balancer-v2/pools/phantom-stable/PhantomStableMath.js +314 -0
  28. package/build/dex/balancer-v2/pools/phantom-stable/PhantomStableMath.js.map +1 -0
  29. package/build/dex/balancer-v2/pools/phantom-stable/PhantomStablePool.d.ts +50 -0
  30. package/build/dex/balancer-v2/pools/phantom-stable/PhantomStablePool.js +367 -0
  31. package/build/dex/balancer-v2/pools/phantom-stable/PhantomStablePool.js.map +1 -0
  32. package/build/dex/balancer-v2/pools/stable/StableMath.d.ts +7 -0
  33. package/build/dex/balancer-v2/pools/stable/StableMath.js +111 -0
  34. package/build/dex/balancer-v2/pools/stable/StableMath.js.map +1 -0
  35. package/build/dex/balancer-v2/pools/stable/StablePool.d.ts +30 -0
  36. package/build/dex/balancer-v2/pools/stable/StablePool.js +129 -0
  37. package/build/dex/balancer-v2/pools/stable/StablePool.js.map +1 -0
  38. package/build/dex/balancer-v2/pools/weighted/WeightedMath.d.ts +6 -0
  39. package/build/dex/balancer-v2/pools/weighted/WeightedMath.js +61 -0
  40. package/build/dex/balancer-v2/pools/weighted/WeightedMath.js.map +1 -0
  41. package/build/dex/balancer-v2/pools/weighted/WeightedPool.d.ts +30 -0
  42. package/build/dex/balancer-v2/pools/weighted/WeightedPool.js +112 -0
  43. package/build/dex/balancer-v2/pools/weighted/WeightedPool.js.map +1 -0
  44. package/build/dex/balancer-v2/types.d.ts +1 -0
  45. package/build/dex/balancer-v2/types.js.map +1 -1
  46. package/build/dex/index.js +2 -0
  47. package/build/dex/index.js.map +1 -1
  48. package/build/dex/trader-joe-v2.1.d.ts +43 -0
  49. package/build/dex/trader-joe-v2.1.js +78 -0
  50. package/build/dex/trader-joe-v2.1.js.map +1 -0
  51. package/package.json +1 -1
  52. package/src/abi/TraderJoeV21Router.json +1489 -0
  53. package/src/config.ts +10 -10
  54. package/src/dex/balancer-v2/balancer-v2-e2e.test.ts +207 -224
  55. package/src/dex/balancer-v2/balancer-v2.ts +41 -29
  56. package/src/dex/balancer-v2/config.ts +23 -35
  57. package/src/dex/balancer-v2/pools/balancer-v2-pool.ts +274 -0
  58. package/src/dex/balancer-v2/{LinearMath.ts → pools/linear/LinearMath.ts} +81 -23
  59. package/src/dex/balancer-v2/{LinearPool.ts → pools/linear/LinearPool.ts} +241 -5
  60. package/src/dex/balancer-v2/{StableMath.ts → pools/phantom-stable/PhantomStableMath.ts} +101 -21
  61. package/src/dex/balancer-v2/{PhantomStablePool.ts → pools/phantom-stable/PhantomStablePool.ts} +165 -11
  62. package/src/dex/balancer-v2/pools/stable/StableMath.ts +204 -0
  63. package/src/dex/balancer-v2/pools/stable/StablePool.ts +221 -0
  64. package/src/dex/balancer-v2/pools/weighted/WeightedMath.ts +84 -0
  65. package/src/dex/balancer-v2/pools/weighted/WeightedPool.ts +189 -0
  66. package/src/dex/balancer-v2/types.ts +1 -0
  67. package/src/dex/index.ts +2 -0
  68. package/src/dex/trader-joe-v2.1.ts +155 -0
  69. package/tests/constants-e2e.ts +9 -4
  70. package/build/abi/DirectSwap.json +0 -970
  71. package/build/dex/test-dex/config.d.ts +0 -4
  72. package/build/dex/test-dex/config.js +0 -15
  73. package/build/dex/test-dex/config.js.map +0 -1
  74. package/build/dex/test-dex/test-dex-pool.d.ts +0 -39
  75. package/build/dex/test-dex/test-dex-pool.js +0 -63
  76. package/build/dex/test-dex/test-dex-pool.js.map +0 -1
  77. package/build/dex/test-dex/test-dex.d.ts +0 -37
  78. package/build/dex/test-dex/test-dex.js +0 -126
  79. package/build/dex/test-dex/test-dex.js.map +0 -1
  80. package/build/dex/test-dex/types.d.ts +0 -6
  81. package/build/dex/test-dex/types.js +0 -3
  82. package/build/dex/test-dex/types.js.map +0 -1
  83. package/build/dex/woo-fi-v2/woo-fi-math.d.ts +0 -16
  84. package/build/dex/woo-fi-v2/woo-fi-math.js +0 -137
  85. package/build/dex/woo-fi-v2/woo-fi-math.js.map +0 -1
  86. package/src/dex/balancer-v2/balancer-v2-pool.ts +0 -744
@@ -1,744 +0,0 @@
1
- import { Interface } from '@ethersproject/abi';
2
- import { BigNumber } from '@ethersproject/bignumber';
3
- import { MathSol } from './balancer-v2-math';
4
- import { SwapSide } from '../../constants';
5
- import { callData, SubgraphPoolBase, PoolState, TokenState } from './types';
6
- import { getTokenScalingFactor, decodeThrowError } from './utils';
7
- import WeightedPoolABI from '../../abi/balancer-v2/weighted-pool.json';
8
- import StablePoolABI from '../../abi/balancer-v2/stable-pool.json';
9
- import MetaStablePoolABI from '../../abi/balancer-v2/meta-stable-pool.json';
10
- import { BI_POWS } from '../../bigint-constants';
11
- import { assert } from 'ts-essentials';
12
-
13
- const _require = (b: boolean, message: string) => {
14
- if (!b) throw new Error(message);
15
- };
16
-
17
- export class BasePool {
18
- _subtractSwapFeeAmount(amount: bigint, _swapFeePercentage: bigint): bigint {
19
- // This returns amount - fee amount, so we round up (favoring a higher fee amount).
20
- const feeAmount = MathSol.mulUpFixed(amount, _swapFeePercentage);
21
- return amount - feeAmount;
22
- }
23
-
24
- // These methods use fixed versions to match SC scaling
25
- _upscaleArray(amounts: bigint[], scalingFactors: bigint[]): bigint[] {
26
- return amounts.map((a, i) => MathSol.mulUpFixed(a, scalingFactors[i]));
27
- }
28
-
29
- _upscale(amount: bigint, scalingFactor: bigint): bigint {
30
- return MathSol.mulUpFixed(amount, scalingFactor);
31
- }
32
-
33
- _downscaleDown(amount: bigint, scalingFactor: bigint): bigint {
34
- return MathSol.divDownFixed(amount, scalingFactor);
35
- }
36
-
37
- _nullifyIfMaxAmountExceeded(amountToTrade: bigint, swapMax: bigint): bigint {
38
- return swapMax >= amountToTrade ? amountToTrade : 0n;
39
- }
40
- }
41
-
42
- type WeightedPoolPairData = {
43
- tokenInBalance: bigint;
44
- tokenOutBalance: bigint;
45
- tokenInScalingFactor: bigint;
46
- tokenOutScalingFactor: bigint;
47
- tokenInWeight: bigint;
48
- tokenOutWeight: bigint;
49
- swapFee: bigint;
50
- };
51
-
52
- type StablePoolPairData = {
53
- balances: bigint[];
54
- indexIn: number;
55
- indexOut: number;
56
- scalingFactors: bigint[];
57
- swapFee: bigint;
58
- amp: bigint;
59
- };
60
-
61
- abstract class BaseGeneralPool extends BasePool {
62
- // Swap Hooks
63
-
64
- // Modification: this is inspired from the function onSwap which is in the original contract
65
- onSell(amounts: bigint[], poolPairData: StablePoolPairData): bigint[] {
66
- // _validateIndexes(indexIn, indexOut, _getTotalTokens());
67
- // uint256[] memory scalingFactors = _scalingFactors();
68
- return this._swapGivenIn(
69
- amounts,
70
- poolPairData.balances,
71
- poolPairData.indexIn,
72
- poolPairData.indexOut,
73
- poolPairData.scalingFactors,
74
- poolPairData.swapFee,
75
- poolPairData.amp,
76
- );
77
- }
78
-
79
- _swapGivenIn(
80
- tokenAmountsIn: bigint[],
81
- balances: bigint[],
82
- indexIn: number,
83
- indexOut: number,
84
- scalingFactors: bigint[],
85
- _swapFeePercentage: bigint,
86
- _amplificationParameter: bigint,
87
- ): bigint[] {
88
- // Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis.
89
- const tokenAmountsInWithFee = tokenAmountsIn.map(a =>
90
- this._subtractSwapFeeAmount(a, _swapFeePercentage),
91
- );
92
-
93
- const balancesUpscaled = this._upscaleArray(balances, scalingFactors);
94
- const tokenAmountsInScaled = tokenAmountsInWithFee.map(a =>
95
- this._upscale(a, scalingFactors[indexIn]),
96
- );
97
-
98
- const amountsOut = this._onSwapGivenIn(
99
- tokenAmountsInScaled,
100
- balancesUpscaled,
101
- indexIn,
102
- indexOut,
103
- _amplificationParameter,
104
- );
105
-
106
- // amountOut tokens are exiting the Pool, so we round down.
107
- return amountsOut.map(a =>
108
- this._downscaleDown(a, scalingFactors[indexOut]),
109
- );
110
- }
111
-
112
- /*
113
- * @dev Called when a swap with the Pool occurs, where the amount of tokens entering the Pool is known.
114
- *
115
- * Returns the amount of tokens that will be taken from the Pool in return.
116
- *
117
- * All amounts inside `swapRequest` and `balances` are upscaled. The swap fee has already been deducted from
118
- * `swapRequest.amount`.
119
- *
120
- * The return value is also considered upscaled, and will be downscaled (rounding down) before returning it to the
121
- * Vault.
122
- */
123
- abstract _onSwapGivenIn(
124
- tokenAmountsIn: bigint[],
125
- balances: bigint[],
126
- indexIn: number,
127
- indexOut: number,
128
- _amplificationParameter: bigint,
129
- ): bigint[];
130
- }
131
-
132
- abstract class BaseMinimalSwapInfoPool extends BasePool {
133
- // Swap Hooks
134
-
135
- // Modification: this is inspired from the function onSwap which is in the original contract
136
- onSell(
137
- tokenAmountsIn: bigint[],
138
- poolPairData: WeightedPoolPairData,
139
- ): bigint[] {
140
- // uint256 _scalingFactorTokenIn = _scalingFactor(request.tokenIn);
141
- // uint256 _scalingFactorTokenOut = _scalingFactor(request.tokenOut);
142
-
143
- // Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis.
144
- const tokenAmountsInWithFee = tokenAmountsIn.map(a =>
145
- this._subtractSwapFeeAmount(a, poolPairData.swapFee),
146
- );
147
-
148
- // All token amounts are upscaled.
149
- const balanceTokenIn = this._upscale(
150
- poolPairData.tokenInBalance,
151
- poolPairData.tokenInScalingFactor,
152
- );
153
- const balanceTokenOut = this._upscale(
154
- poolPairData.tokenOutBalance,
155
- poolPairData.tokenOutScalingFactor,
156
- );
157
- const tokenAmountsInScaled = tokenAmountsInWithFee.map(a =>
158
- this._upscale(a, poolPairData.tokenInScalingFactor),
159
- );
160
-
161
- const amountsOut = this._onSwapGivenIn(
162
- tokenAmountsInScaled,
163
- balanceTokenIn,
164
- balanceTokenOut,
165
- poolPairData.tokenInWeight,
166
- poolPairData.tokenOutWeight,
167
- );
168
-
169
- // amountOut tokens are exiting the Pool, so we round down.
170
- return amountsOut.map(a =>
171
- this._downscaleDown(a, poolPairData.tokenOutScalingFactor),
172
- );
173
- }
174
-
175
- abstract _onSwapGivenIn(
176
- tokenAmountsIn: bigint[],
177
- currentBalanceTokenIn: bigint,
178
- currentBalanceTokenOut: bigint,
179
- _weightIn: bigint,
180
- _weightOut: bigint,
181
- ): bigint[];
182
- }
183
-
184
- class StableMath {
185
- static _AMP_PRECISION = BI_POWS[3];
186
-
187
- static _calculateInvariant(
188
- amplificationParameter: bigint,
189
- balances: bigint[],
190
- roundUp: boolean,
191
- ): bigint {
192
- /**********************************************************************************************
193
- // invariant //
194
- // D = invariant D^(n+1) //
195
- // A = amplification coefficient A n^n S + D = A D n^n + ----------- //
196
- // S = sum of balances n^n P //
197
- // P = product of balances //
198
- // n = number of tokens //
199
- *********x************************************************************************************/
200
-
201
- // We support rounding up or down.
202
-
203
- let sum = 0n;
204
- const numTokens = balances.length;
205
- for (let i = 0; i < numTokens; i++) {
206
- sum = sum + balances[i];
207
- }
208
- if (sum == 0n) {
209
- return 0n;
210
- }
211
-
212
- let prevInvariant = 0n;
213
- let invariant = sum;
214
- const ampTimesTotal = amplificationParameter * BigInt(numTokens);
215
-
216
- for (let i = 0; i < 255; i++) {
217
- let P_D = balances[0] * BigInt(numTokens);
218
- for (let j = 1; j < numTokens; j++) {
219
- P_D = MathSol.div(
220
- MathSol.mul(MathSol.mul(P_D, balances[j]), BigInt(numTokens)),
221
- invariant,
222
- roundUp,
223
- );
224
- }
225
- prevInvariant = invariant;
226
- invariant = MathSol.div(
227
- MathSol.mul(MathSol.mul(BigInt(numTokens), invariant), invariant) +
228
- MathSol.div(
229
- MathSol.mul(MathSol.mul(ampTimesTotal, sum), P_D),
230
- this._AMP_PRECISION,
231
- roundUp,
232
- ),
233
- MathSol.mul(BigInt(numTokens + 1), invariant) +
234
- // No need to use checked arithmetic for the amp precision, the amp is guaranteed to be at least 1
235
- MathSol.div(
236
- MathSol.mul(ampTimesTotal - this._AMP_PRECISION, P_D),
237
- this._AMP_PRECISION,
238
- !roundUp,
239
- ),
240
- roundUp,
241
- );
242
-
243
- if (invariant > prevInvariant) {
244
- if (invariant - prevInvariant <= 1) {
245
- return invariant;
246
- }
247
- } else if (prevInvariant - invariant <= 1) {
248
- return invariant;
249
- }
250
- }
251
-
252
- throw new Error('Errors.STABLE_INVARIANT_DIDNT_CONVERGE');
253
- }
254
-
255
- static _calcOutGivenIn(
256
- amplificationParameter: bigint,
257
- balances: bigint[],
258
- tokenIndexIn: number,
259
- tokenIndexOut: number,
260
- tokenAmountsIn: bigint[],
261
- ): bigint[] {
262
- /**************************************************************************************************************
263
- // outGivenIn token x for y - polynomial equation to solve //
264
- // ay = amount out to calculate //
265
- // by = balance token out //
266
- // y = by - ay (finalBalanceOut) //
267
- // D = invariant D D^(n+1) //
268
- // A = amplification coefficient y^2 + ( S - ---------- - D) * y - ------------- = 0 //
269
- // n = number of tokens (A * n^n) A * n^2n * P //
270
- // S = sum of final balances but y //
271
- // P = product of final balances but y //
272
- **************************************************************************************************************/
273
-
274
- // Amount out, so we round down overall.
275
-
276
- // Given that we need to have a greater final balance out, the invariant needs to be rounded up
277
- const invariant = this._calculateInvariant(
278
- amplificationParameter,
279
- balances,
280
- true,
281
- );
282
-
283
- const initBalance = balances[tokenIndexIn];
284
- // Modification: The original code was implemented for a single tokenAmountsIn
285
- return tokenAmountsIn.map(a => {
286
- balances[tokenIndexIn] = initBalance + a;
287
-
288
- const finalBalanceOut =
289
- this._getTokenBalanceGivenInvariantAndAllOtherBalances(
290
- amplificationParameter,
291
- balances,
292
- invariant,
293
- tokenIndexOut,
294
- );
295
-
296
- // No need to use checked arithmetic since `tokenAmountIn` was actually added to the same balance right before
297
- // calling `_getTokenBalanceGivenInvariantAndAllOtherBalances` which doesn't alter the balances array.
298
- // balances[tokenIndexIn] = balances[tokenIndexIn] - tokenAmountIn;
299
- return balances[tokenIndexOut] - finalBalanceOut - 1n;
300
- });
301
- }
302
-
303
- static _getTokenBalanceGivenInvariantAndAllOtherBalances(
304
- amplificationParameter: bigint,
305
- balances: bigint[],
306
- invariant: bigint,
307
- tokenIndex: number,
308
- ): bigint {
309
- // Rounds result up overall
310
-
311
- const ampTimesTotal = amplificationParameter * BigInt(balances.length);
312
- let sum = balances[0];
313
- let P_D = balances[0] * BigInt(balances.length);
314
- for (let j = 1; j < balances.length; j++) {
315
- P_D = MathSol.divDown(
316
- MathSol.mul(MathSol.mul(P_D, balances[j]), BigInt(balances.length)),
317
- invariant,
318
- );
319
- sum = sum + balances[j];
320
- }
321
- // No need to use safe math, based on the loop above `sum` is greater than or equal to `balances[tokenIndex]`
322
- sum = sum - balances[tokenIndex];
323
-
324
- const inv2 = MathSol.mul(invariant, invariant);
325
- // We remove the balance fromm c by multiplying it
326
- const c = MathSol.mul(
327
- MathSol.mul(
328
- MathSol.divUp(inv2, MathSol.mul(ampTimesTotal, P_D)),
329
- this._AMP_PRECISION,
330
- ),
331
- balances[tokenIndex],
332
- );
333
- const b =
334
- sum +
335
- MathSol.mul(
336
- MathSol.divDown(invariant, ampTimesTotal),
337
- this._AMP_PRECISION,
338
- );
339
-
340
- // We iterate to find the balance
341
- let prevTokenBalance = 0n;
342
- // We multiply the first iteration outside the loop with the invariant to set the value of the
343
- // initial approximation.
344
- let tokenBalance = MathSol.divUp(inv2 + c, invariant + b);
345
-
346
- for (let i = 0; i < 255; i++) {
347
- prevTokenBalance = tokenBalance;
348
-
349
- tokenBalance = MathSol.divUp(
350
- MathSol.mul(tokenBalance, tokenBalance) + c,
351
- MathSol.mul(tokenBalance, 2n) + b - invariant,
352
- );
353
-
354
- if (tokenBalance > prevTokenBalance) {
355
- if (tokenBalance - prevTokenBalance <= 1) {
356
- return tokenBalance;
357
- }
358
- } else if (prevTokenBalance - tokenBalance <= 1) {
359
- return tokenBalance;
360
- }
361
- }
362
-
363
- throw new Error('Errors.STABLE_GET_BALANCE_DIDNT_CONVERGE');
364
- }
365
- }
366
-
367
- export class StablePool extends BaseGeneralPool {
368
- vaultAddress: string;
369
- vaultInterface: Interface;
370
- poolInterface: Interface;
371
- metaPoolInterface: Interface;
372
-
373
- constructor(vaultAddress: string, vaultInterface: Interface) {
374
- super();
375
- this.vaultAddress = vaultAddress;
376
- this.vaultInterface = vaultInterface;
377
- this.poolInterface = new Interface(StablePoolABI);
378
- this.metaPoolInterface = new Interface(MetaStablePoolABI);
379
- }
380
-
381
- _onSwapGivenIn(
382
- tokenAmountsIn: bigint[],
383
- balances: bigint[],
384
- indexIn: number,
385
- indexOut: number,
386
- _amplificationParameter: bigint,
387
- ): bigint[] {
388
- return StableMath._calcOutGivenIn(
389
- _amplificationParameter,
390
- balances,
391
- indexIn,
392
- indexOut,
393
- tokenAmountsIn,
394
- );
395
- }
396
-
397
- /*
398
- Helper function to parse pool data into params for onSell function.
399
- */
400
- parsePoolPairData(
401
- pool: SubgraphPoolBase,
402
- poolState: PoolState,
403
- tokenIn: string,
404
- tokenOut: string,
405
- ): StablePoolPairData {
406
- let indexIn = 0,
407
- indexOut = 0;
408
- const scalingFactors: bigint[] = [];
409
- const balances = poolState.orderedTokens.map((tokenAddress, i) => {
410
- const t = pool.tokensMap[tokenAddress.toLowerCase()];
411
- if (t.address.toLowerCase() === tokenIn.toLowerCase()) indexIn = i;
412
- if (t.address.toLowerCase() === tokenOut.toLowerCase()) indexOut = i;
413
- if (pool.poolType === 'MetaStable')
414
- scalingFactors.push(
415
- poolState.tokens[t.address.toLowerCase()].scalingFactor || 0n,
416
- );
417
- else scalingFactors.push(getTokenScalingFactor(t.decimals));
418
- return poolState.tokens[t.address.toLowerCase()].balance;
419
- });
420
-
421
- const poolPairData: StablePoolPairData = {
422
- balances,
423
- indexIn,
424
- indexOut,
425
- scalingFactors,
426
- swapFee: poolState.swapFee,
427
- amp: poolState.amp ? poolState.amp : 0n,
428
- };
429
- return poolPairData;
430
- }
431
-
432
- /*
433
- Helper function to construct onchain multicall data for StablePool.
434
- */
435
- getOnChainCalls(pool: SubgraphPoolBase): callData[] {
436
- const poolCallData: callData[] = [
437
- {
438
- target: this.vaultAddress,
439
- callData: this.vaultInterface.encodeFunctionData('getPoolTokens', [
440
- pool.id,
441
- ]),
442
- },
443
- {
444
- target: pool.address,
445
- callData: this.poolInterface.encodeFunctionData('getSwapFeePercentage'),
446
- },
447
- {
448
- target: pool.address,
449
- callData: this.poolInterface.encodeFunctionData(
450
- 'getAmplificationParameter',
451
- ),
452
- },
453
- ];
454
- if (pool.poolType === 'MetaStable') {
455
- poolCallData.push({
456
- target: pool.address,
457
- callData:
458
- this.metaPoolInterface.encodeFunctionData('getScalingFactors'),
459
- });
460
- }
461
- return poolCallData;
462
- }
463
-
464
- /*
465
- Helper function to decodes multicall data for a Stable Pool.
466
- data must contain returnData
467
- startIndex is where to start in returnData. Allows this decode function to be called along with other pool types.
468
- */
469
- decodeOnChainCalls(
470
- pool: SubgraphPoolBase,
471
- data: { success: boolean; returnData: any }[],
472
- startIndex: number,
473
- ): [{ [address: string]: PoolState }, number] {
474
- const pools = {} as { [address: string]: PoolState };
475
-
476
- const poolTokens = decodeThrowError(
477
- this.vaultInterface,
478
- 'getPoolTokens',
479
- data[startIndex++],
480
- pool.address,
481
- );
482
- const swapFee = decodeThrowError(
483
- this.poolInterface,
484
- 'getSwapFeePercentage',
485
- data[startIndex++],
486
- pool.address,
487
- )[0];
488
- const amp = decodeThrowError(
489
- this.poolInterface,
490
- 'getAmplificationParameter',
491
- data[startIndex++],
492
- pool.address,
493
- );
494
- let scalingFactors: BigNumber[] | undefined;
495
- if (pool.poolType === 'MetaStable') {
496
- scalingFactors = decodeThrowError(
497
- this.metaPoolInterface,
498
- 'getScalingFactors',
499
- data[startIndex++],
500
- pool.address,
501
- )[0];
502
- }
503
-
504
- const poolState: PoolState = {
505
- swapFee: BigInt(swapFee.toString()),
506
- tokens: poolTokens.tokens.reduce(
507
- (ptAcc: { [address: string]: TokenState }, pt: string, j: number) => {
508
- const tokenState: TokenState = {
509
- balance: BigInt(poolTokens.balances[j].toString()),
510
- };
511
-
512
- if (scalingFactors)
513
- tokenState.scalingFactor = BigInt(scalingFactors[j].toString());
514
-
515
- ptAcc[pt.toLowerCase()] = tokenState;
516
- return ptAcc;
517
- },
518
- {},
519
- ),
520
- orderedTokens: poolTokens.tokens,
521
- };
522
-
523
- if (amp) {
524
- poolState.amp = BigInt(amp.value.toString());
525
- }
526
-
527
- pools[pool.address] = poolState;
528
-
529
- return [pools, startIndex];
530
- }
531
-
532
- /*
533
- For stable pools there is no Swap limit. As an approx - use almost the total balance of token out as we can add any amount of tokenIn and expect some back.
534
- */
535
- getSwapMaxAmount(poolPairData: StablePoolPairData, side: SwapSide): bigint {
536
- return (
537
- (this._upscale(
538
- poolPairData.balances[poolPairData.indexOut],
539
- poolPairData.scalingFactors[poolPairData.indexOut],
540
- ) *
541
- 99n) /
542
- 100n
543
- );
544
- }
545
- }
546
-
547
- export class WeightedMath {
548
- static _MAX_IN_RATIO = 300000000000000000n;
549
- static _MAX_OUT_RATIO = 300000000000000000n;
550
- // Computes how many tokens can be taken out of a pool if `amountIn` are sent, given the
551
- // current balances and weights.
552
- static _calcOutGivenIn(
553
- balanceIn: bigint,
554
- weightIn: bigint,
555
- balanceOut: bigint,
556
- weightOut: bigint,
557
- amountsIn: bigint[],
558
- ): bigint[] {
559
- /**********************************************************************************************
560
- // outGivenIn //
561
- // aO = amountOut //
562
- // bO = balanceOut //
563
- // bI = balanceIn / / bI \ (wI / wO) \ //
564
- // aI = amountIn aO = bO * | 1 - | -------------------------- | ^ | //
565
- // wI = weightIn \ \ ( bI + aI ) / / //
566
- // wO = weightOut //
567
- **********************************************************************************************/
568
-
569
- // Amount out, so we round down overall.
570
-
571
- // The multiplication rounds down, and the subtrahend (power) rounds up (so the base rounds up too).
572
- // Because bI / (bI + aI) <= 1, the exponent rounds down.
573
-
574
- // Cannot exceed maximum in ratio
575
-
576
- const exponent = MathSol.divDownFixed(weightIn, weightOut);
577
- return amountsIn.map(amountIn => {
578
- _require(
579
- amountIn <= MathSol.mulDownFixed(balanceIn, this._MAX_IN_RATIO),
580
- 'Errors.MAX_IN_RATIO',
581
- );
582
- const denominator = balanceIn + amountIn;
583
- const base = MathSol.divUpFixed(balanceIn, denominator);
584
- const power = MathSol.powUpFixed(base, exponent);
585
-
586
- return MathSol.mulDownFixed(balanceOut, MathSol.complementFixed(power));
587
- });
588
- }
589
- }
590
-
591
- export class WeightedPool extends BaseMinimalSwapInfoPool {
592
- vaultAddress: string;
593
- vaultInterface: Interface;
594
- poolInterface: Interface;
595
-
596
- constructor(vaultAddress: string, vaultInterface: Interface) {
597
- super();
598
- this.vaultAddress = vaultAddress;
599
- this.vaultInterface = vaultInterface;
600
- this.poolInterface = new Interface(WeightedPoolABI);
601
- }
602
-
603
- _onSwapGivenIn(
604
- tokenAmountsIn: bigint[],
605
- currentBalanceTokenIn: bigint,
606
- currentBalanceTokenOut: bigint,
607
- _weightIn: bigint,
608
- _weightOut: bigint,
609
- ): bigint[] {
610
- return WeightedMath._calcOutGivenIn(
611
- currentBalanceTokenIn,
612
- _weightIn,
613
- currentBalanceTokenOut,
614
- _weightOut,
615
- tokenAmountsIn,
616
- );
617
- }
618
-
619
- /*
620
- Helper function to parse pool data into params for onSell function.
621
- */
622
- parsePoolPairData(
623
- pool: SubgraphPoolBase,
624
- poolState: PoolState,
625
- tokenIn: string,
626
- tokenOut: string,
627
- ): WeightedPoolPairData {
628
- const inAddress = tokenIn.toLowerCase();
629
- const outAddress = tokenOut.toLowerCase();
630
-
631
- const tIn = pool.tokens.find(t => t.address.toLowerCase() === inAddress);
632
- const tOut = pool.tokens.find(t => t.address.toLowerCase() === outAddress);
633
-
634
- if (!tIn || !tOut) return {} as WeightedPoolPairData;
635
-
636
- const tokenInBalance = poolState.tokens[inAddress].balance;
637
- const tokenOutBalance = poolState.tokens[outAddress].balance;
638
- const tokenInWeight = poolState.tokens[inAddress].weight || 0n;
639
- const tokenOutWeight = poolState.tokens[outAddress].weight || 0n;
640
- const tokenInScalingFactor = getTokenScalingFactor(tIn.decimals);
641
- const tokenOutScalingFactor = getTokenScalingFactor(tOut.decimals);
642
-
643
- const poolPairData: WeightedPoolPairData = {
644
- tokenInBalance,
645
- tokenOutBalance,
646
- tokenInScalingFactor,
647
- tokenOutScalingFactor,
648
- tokenInWeight,
649
- tokenOutWeight,
650
- swapFee: poolState.swapFee,
651
- };
652
- return poolPairData;
653
- }
654
-
655
- /*
656
- Helper function to construct onchain multicall data for WeightedPool (also 'LiquidityBootstrapping' and 'Investment' pool types).
657
- */
658
- getOnChainCalls(pool: SubgraphPoolBase): callData[] {
659
- return [
660
- {
661
- target: this.vaultAddress,
662
- callData: this.vaultInterface.encodeFunctionData('getPoolTokens', [
663
- pool.id,
664
- ]),
665
- },
666
- {
667
- target: pool.address,
668
- callData: this.poolInterface.encodeFunctionData('getSwapFeePercentage'),
669
- },
670
- {
671
- target: pool.address,
672
- callData: this.poolInterface.encodeFunctionData('getNormalizedWeights'),
673
- },
674
- ];
675
- }
676
-
677
- /*
678
- Helper function to decodes multicall data for a Weighted Pool.
679
- data must contain returnData
680
- startIndex is where to start in returnData. Allows this decode function to be called along with other pool types.
681
- */
682
- decodeOnChainCalls(
683
- pool: SubgraphPoolBase,
684
- data: { success: boolean; returnData: any }[],
685
- startIndex: number,
686
- ): [{ [address: string]: PoolState }, number] {
687
- const pools = {} as { [address: string]: PoolState };
688
-
689
- const poolTokens = decodeThrowError(
690
- this.vaultInterface,
691
- 'getPoolTokens',
692
- data[startIndex++],
693
- pool.address,
694
- );
695
- const swapFee = decodeThrowError(
696
- this.poolInterface,
697
- 'getSwapFeePercentage',
698
- data[startIndex++],
699
- pool.address,
700
- )[0];
701
- const normalisedWeights = decodeThrowError(
702
- this.poolInterface,
703
- 'getNormalizedWeights',
704
- data[startIndex++],
705
- pool.address,
706
- )[0];
707
-
708
- const poolState: PoolState = {
709
- swapFee: BigInt(swapFee.toString()),
710
- tokens: poolTokens.tokens.reduce(
711
- (ptAcc: { [address: string]: TokenState }, pt: string, j: number) => {
712
- const tokenState: TokenState = {
713
- balance: BigInt(poolTokens.balances[j].toString()),
714
- };
715
-
716
- if (normalisedWeights)
717
- tokenState.weight = BigInt(normalisedWeights[j].toString());
718
-
719
- ptAcc[pt.toLowerCase()] = tokenState;
720
- return ptAcc;
721
- },
722
- {},
723
- ),
724
- orderedTokens: poolTokens.tokens,
725
- };
726
-
727
- pools[pool.address] = poolState;
728
-
729
- return [pools, startIndex];
730
- }
731
-
732
- /*
733
- For weighted pools there is a Swap limit of 30%: amounts swapped may not be larger than this percentage of total balance.
734
- */
735
- getSwapMaxAmount(poolPairData: WeightedPoolPairData, side: SwapSide): bigint {
736
- return (
737
- ((side === SwapSide.SELL
738
- ? poolPairData.tokenInBalance
739
- : poolPairData.tokenOutBalance) *
740
- 3n) /
741
- 10n
742
- );
743
- }
744
- }