@paraswap/dex-lib 2.16.6 → 2.16.7-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 (85) hide show
  1. package/.idea/aws.xml +17 -0
  2. package/.idea/codeStyles/Project.xml +19 -0
  3. package/.idea/inspectionProfiles/Project_Default.xml +6 -0
  4. package/.idea/modules.xml +1 -1
  5. package/.idea/paraswap-dex-lib.iml +9 -0
  6. package/build/config.js +4 -4
  7. package/build/dex/aave-v3/tokens/arbitrum.json +20 -20
  8. package/build/dex/aave-v3/tokens/avalanche.json +44 -20
  9. package/build/dex/aave-v3/tokens/fantom.json +30 -30
  10. package/build/dex/aave-v3/tokens/optimism.json +18 -18
  11. package/build/dex/aave-v3/tokens/polygon.json +60 -42
  12. package/build/dex/balancer-v2/balancer-v2.d.ts +9 -14
  13. package/build/dex/balancer-v2/balancer-v2.js +21 -19
  14. package/build/dex/balancer-v2/balancer-v2.js.map +1 -1
  15. package/build/dex/balancer-v2/config.d.ts +2 -7
  16. package/build/dex/balancer-v2/config.js +20 -30
  17. package/build/dex/balancer-v2/config.js.map +1 -1
  18. package/build/dex/balancer-v2/pools/balancer-v2-pool.d.ts +25 -0
  19. package/build/dex/balancer-v2/pools/balancer-v2-pool.js +107 -0
  20. package/build/dex/balancer-v2/pools/balancer-v2-pool.js.map +1 -0
  21. package/build/dex/balancer-v2/pools/linear/LinearMath.d.ts +20 -0
  22. package/build/dex/balancer-v2/pools/linear/LinearMath.js +179 -0
  23. package/build/dex/balancer-v2/pools/linear/LinearMath.js.map +1 -0
  24. package/build/dex/balancer-v2/pools/linear/LinearPool.d.ts +50 -0
  25. package/build/dex/balancer-v2/pools/linear/LinearPool.js +458 -0
  26. package/build/dex/balancer-v2/pools/linear/LinearPool.js.map +1 -0
  27. package/build/dex/balancer-v2/pools/phantom-stable/PhantomStableMath.d.ts +10 -0
  28. package/build/dex/balancer-v2/pools/phantom-stable/PhantomStableMath.js +314 -0
  29. package/build/dex/balancer-v2/pools/phantom-stable/PhantomStableMath.js.map +1 -0
  30. package/build/dex/balancer-v2/pools/phantom-stable/PhantomStablePool.d.ts +50 -0
  31. package/build/dex/balancer-v2/pools/phantom-stable/PhantomStablePool.js +367 -0
  32. package/build/dex/balancer-v2/pools/phantom-stable/PhantomStablePool.js.map +1 -0
  33. package/build/dex/balancer-v2/pools/stable/StableMath.d.ts +7 -0
  34. package/build/dex/balancer-v2/pools/stable/StableMath.js +111 -0
  35. package/build/dex/balancer-v2/pools/stable/StableMath.js.map +1 -0
  36. package/build/dex/balancer-v2/pools/stable/StablePool.d.ts +30 -0
  37. package/build/dex/balancer-v2/pools/stable/StablePool.js +129 -0
  38. package/build/dex/balancer-v2/pools/stable/StablePool.js.map +1 -0
  39. package/build/dex/balancer-v2/pools/weighted/WeightedMath.d.ts +6 -0
  40. package/build/dex/balancer-v2/pools/weighted/WeightedMath.js +61 -0
  41. package/build/dex/balancer-v2/pools/weighted/WeightedMath.js.map +1 -0
  42. package/build/dex/balancer-v2/pools/weighted/WeightedPool.d.ts +30 -0
  43. package/build/dex/balancer-v2/pools/weighted/WeightedPool.js +112 -0
  44. package/build/dex/balancer-v2/pools/weighted/WeightedPool.js.map +1 -0
  45. package/build/dex/balancer-v2/types.d.ts +1 -0
  46. package/build/dex/balancer-v2/types.js.map +1 -1
  47. package/build/dex/balancer-v2/utils.d.ts +3 -2
  48. package/build/dex/balancer-v2/utils.js +6 -4
  49. package/build/dex/balancer-v2/utils.js.map +1 -1
  50. package/package.json +1 -1
  51. package/src/config.ts +4 -4
  52. package/src/dex/balancer-v2/balancer-v2-e2e.test.ts +219 -224
  53. package/src/dex/balancer-v2/balancer-v2.ts +45 -48
  54. package/src/dex/balancer-v2/config.ts +23 -35
  55. package/src/dex/balancer-v2/pools/balancer-v2-pool.ts +274 -0
  56. package/src/dex/balancer-v2/{LinearMath.ts → pools/linear/LinearMath.ts} +11 -10
  57. package/src/dex/balancer-v2/{LinearPool.ts → pools/linear/LinearPool.ts} +210 -6
  58. package/src/dex/balancer-v2/{StableMath.ts → pools/phantom-stable/PhantomStableMath.ts} +101 -21
  59. package/src/dex/balancer-v2/{PhantomStablePool.ts → pools/phantom-stable/PhantomStablePool.ts} +167 -12
  60. package/src/dex/balancer-v2/pools/stable/StableMath.ts +204 -0
  61. package/src/dex/balancer-v2/pools/stable/StablePool.ts +221 -0
  62. package/src/dex/balancer-v2/pools/weighted/WeightedMath.ts +84 -0
  63. package/src/dex/balancer-v2/pools/weighted/WeightedPool.ts +189 -0
  64. package/src/dex/balancer-v2/types.ts +1 -0
  65. package/src/dex/balancer-v2/utils.ts +7 -1
  66. package/tests/constants-e2e.ts +10 -5
  67. package/.vscode/launch.json +0 -21
  68. package/build/abi/AugustusRFQRouter.abi.json +0 -1248
  69. package/build/dex/aave-v3/tokens/mainnet.json +0 -44
  70. package/build/dex/balancer-v2/VirtualBoostedPool.d.ts +0 -79
  71. package/build/dex/balancer-v2/VirtualBoostedPool.js +0 -382
  72. package/build/dex/balancer-v2/VirtualBoostedPool.js.map +0 -1
  73. package/build/dex/test-aave-v3/config.d.ts +0 -4
  74. package/build/dex/test-aave-v3/config.js +0 -15
  75. package/build/dex/test-aave-v3/config.js.map +0 -1
  76. package/build/dex/test-aave-v3/test-aave-v3-pool.d.ts +0 -39
  77. package/build/dex/test-aave-v3/test-aave-v3-pool.js +0 -63
  78. package/build/dex/test-aave-v3/test-aave-v3-pool.js.map +0 -1
  79. package/build/dex/test-aave-v3/test-aave-v3.d.ts +0 -37
  80. package/build/dex/test-aave-v3/test-aave-v3.js +0 -126
  81. package/build/dex/test-aave-v3/test-aave-v3.js.map +0 -1
  82. package/build/dex/test-aave-v3/types.d.ts +0 -6
  83. package/build/dex/test-aave-v3/types.js +0 -3
  84. package/build/dex/test-aave-v3/types.js.map +0 -1
  85. package/src/dex/balancer-v2/balancer-v2-pool.ts +0 -744
@@ -1,5 +1,5 @@
1
- import { BI_POWS } from '../../bigint-constants';
2
- import { MathSol } from './balancer-v2-math';
1
+ import { BI_POWS } from '../../../../bigint-constants';
2
+ import { MathSol } from '../../balancer-v2-math';
3
3
 
4
4
  const AMP_PRECISION = BI_POWS[3];
5
5
 
@@ -9,15 +9,15 @@ export function _calculateInvariant(
9
9
  roundUp: boolean,
10
10
  ): bigint {
11
11
  /**********************************************************************************************
12
- // invariant //
13
- // D = invariant D^(n+1) //
14
- // A = amplification coefficient A n^n S + D = A D n^n + ----------- //
15
- // S = sum of balances n^n P //
16
- // P = product of balances //
17
- // n = number of tokens //
18
- *********x************************************************************************************/
12
+ // invariant //
13
+ // D = invariant D^(n+1) //
14
+ // A = amplification coefficient A n^n S + D = A D n^n + ----------- //
15
+ // S = sum of balances n^n P //
16
+ // P = product of balances //
17
+ // n = number of tokens //
18
+ *********x************************************************************************************/
19
19
 
20
- // We support rounding up or down.
20
+ // We support rounding up or down.
21
21
 
22
22
  let sum = 0n;
23
23
  const numTokens = balances.length;
@@ -44,18 +44,18 @@ export function _calculateInvariant(
44
44
  prevInvariant = invariant;
45
45
  invariant = MathSol.div(
46
46
  MathSol.mul(MathSol.mul(BigInt(numTokens), invariant), invariant) +
47
- MathSol.div(
48
- MathSol.mul(MathSol.mul(ampTimesTotal, sum), P_D),
49
- AMP_PRECISION,
50
- roundUp,
51
- ),
47
+ MathSol.div(
48
+ MathSol.mul(MathSol.mul(ampTimesTotal, sum), P_D),
49
+ AMP_PRECISION,
50
+ roundUp,
51
+ ),
52
52
  MathSol.mul(BigInt(numTokens + 1), invariant) +
53
- // No need to use checked arithmetic for the amp precision, the amp is guaranteed to be at least 1
54
- MathSol.div(
55
- MathSol.mul(ampTimesTotal - AMP_PRECISION, P_D),
56
- AMP_PRECISION,
57
- !roundUp,
58
- ),
53
+ // No need to use checked arithmetic for the amp precision, the amp is guaranteed to be at least 1
54
+ MathSol.div(
55
+ MathSol.mul(ampTimesTotal - AMP_PRECISION, P_D),
56
+ AMP_PRECISION,
57
+ !roundUp,
58
+ ),
59
59
  roundUp,
60
60
  );
61
61
 
@@ -81,6 +81,17 @@ export function _calcOutGivenIn(
81
81
  amountIn: bigint,
82
82
  invariant?: bigint,
83
83
  ): bigint {
84
+ /**************************************************************************************************************
85
+ // outGivenIn token x for y - polynomial equation to solve //
86
+ // ay = amount out to calculate //
87
+ // by = balance token out //
88
+ // y = by - ay (finalBalanceOut) //
89
+ // D = invariant D D^(n+1) //
90
+ // A = amplification coefficient y^2 + ( S - ---------- - D) * y - ------------- = 0 //
91
+ // n = number of tokens (A * n^n) A * n^2n * P //
92
+ // S = sum of final balances but y //
93
+ // P = product of final balances but y //
94
+ **************************************************************************************************************/
84
95
  balances = [...balances];
85
96
  // Given that we need to have a greater final balance out, the invariant needs to be rounded up
86
97
  if (!invariant) invariant = _calculateInvariant(amp, balances, true);
@@ -105,6 +116,19 @@ export function _calcInGivenOut(
105
116
  fee: bigint,
106
117
  invariant?: bigint,
107
118
  ): bigint {
119
+ /**************************************************************************************************************
120
+ // inGivenOut token x for y - polynomial equation to solve //
121
+ // ax = amount in to calculate //
122
+ // bx = balance token in //
123
+ // x = bx + ax (finalBalanceIn) //
124
+ // D = invariant D D^(n+1) //
125
+ // A = amplification coefficient x^2 + ( S - ---------- - D) * x - ------------- = 0 //
126
+ // n = number of tokens (A * n^n) A * n^2n * P //
127
+ // S = sum of final balances but x //
128
+ // P = product of final balances but x //
129
+ **************************************************************************************************************/
130
+
131
+ // Given that we need to have a greater final balance in, the invariant needs to be rounded up
108
132
  balances = [...balances];
109
133
  if (!invariant) invariant = _calculateInvariant(amp, balances, true);
110
134
  balances[tokenIndexOut] = MathSol.sub(balances[tokenIndexOut], amountOut);
@@ -120,6 +144,7 @@ export function _calcInGivenOut(
120
144
  MathSol.sub(finalBalanceIn, balances[tokenIndexIn]),
121
145
  1n,
122
146
  );
147
+
123
148
  amountIn = addFee(amountIn, fee);
124
149
  return amountIn;
125
150
  }
@@ -195,6 +220,61 @@ export function _calcBptOutGivenExactTokensIn(
195
220
  }
196
221
  }
197
222
 
223
+ export function _calcTokenInGivenExactBptOut(
224
+ amp: bigint,
225
+ balances: bigint[],
226
+ tokenIndexIn: number,
227
+ bptAmountOut: bigint,
228
+ bptTotalSupply: bigint,
229
+ fee: bigint,
230
+ invariant?: bigint,
231
+ ): bigint {
232
+ if (!invariant) invariant = _calculateInvariant(amp, balances, true);
233
+
234
+ const newInvariant = MathSol.mulUpFixed(
235
+ MathSol.divUpFixed(
236
+ MathSol.add(bptTotalSupply, bptAmountOut),
237
+ bptTotalSupply
238
+ ),
239
+ invariant
240
+ );
241
+
242
+ const newBalanceTokenIndex =
243
+ _getTokenBalanceGivenInvariantAndAllOtherBalances(
244
+ amp,
245
+ balances,
246
+ newInvariant,
247
+ tokenIndexIn
248
+ );
249
+ const amountInWithoutFee = MathSol.sub(
250
+ newBalanceTokenIndex,
251
+ balances[tokenIndexIn]
252
+ );
253
+
254
+ let sumBalances = BigInt(0);
255
+ for (let i = 0; i < balances.length; i++) {
256
+ sumBalances = MathSol.add(sumBalances, balances[i]);
257
+ }
258
+
259
+ // We can now compute how much extra balance is being deposited
260
+ // and used in virtual swaps, and charge swap fees accordingly.
261
+ const currentWeight = MathSol.divDownFixed(
262
+ balances[tokenIndexIn],
263
+ sumBalances
264
+ );
265
+ const taxablePercentage = MathSol.complementFixed(currentWeight);
266
+ const taxableAmount = MathSol.mulUpFixed(
267
+ amountInWithoutFee,
268
+ taxablePercentage
269
+ );
270
+ const nonTaxableAmount = MathSol.sub(amountInWithoutFee, taxableAmount);
271
+
272
+ return MathSol.add(
273
+ nonTaxableAmount,
274
+ MathSol.divUpFixed(taxableAmount, MathSol.sub(MathSol.ONE, fee))
275
+ );
276
+ }
277
+
198
278
  /*
199
279
  Flow of calculations:
200
280
  amountsTokenOut -> amountsOutProportional ->
@@ -1,12 +1,12 @@
1
1
  import { Interface } from '@ethersproject/abi';
2
2
  import { BigNumber } from '@ethersproject/bignumber';
3
- import { BasePool } from './balancer-v2-pool';
4
- import { isSameAddress, decodeThrowError } from './utils';
5
- import * as StableMath from './StableMath';
6
- import { SubgraphPoolBase, PoolState, callData, TokenState } from './types';
7
- import { SwapSide } from '../../constants';
8
- import MetaStablePoolABI from '../../abi/balancer-v2/meta-stable-pool.json';
9
- import ComposableStablePoolABI from '../../abi/balancer-v2/ComposableStable.json';
3
+ import { BasePool } from '../balancer-v2-pool';
4
+ import { isSameAddress, decodeThrowError } from '../../utils';
5
+ import * as PhantomStableMath from './PhantomStableMath';
6
+ import { SubgraphPoolBase, PoolState, callData } from '../../types';
7
+ import { SwapSide } from '../../../../constants';
8
+ import MetaStablePoolABI from '../../../../abi/balancer-v2/meta-stable-pool.json';
9
+ import ComposableStablePoolABI from '../../../../abi/balancer-v2/ComposableStable.json';
10
10
  import { keyBy } from 'lodash';
11
11
 
12
12
  enum PairTypes {
@@ -84,6 +84,21 @@ export class PhantomStablePool extends BasePool {
84
84
  );
85
85
  }
86
86
 
87
+ onBuy(amounts: bigint[], poolPairData: PhantomStablePoolPairData): bigint[] {
88
+ return this._swapGivenOut(
89
+ amounts,
90
+ poolPairData.tokens,
91
+ poolPairData.balances,
92
+ poolPairData.indexIn,
93
+ poolPairData.indexOut,
94
+ poolPairData.bptIndex,
95
+ poolPairData.scalingFactors,
96
+ poolPairData.swapFee,
97
+ poolPairData.amp,
98
+ poolPairData.actualSupply,
99
+ );
100
+ }
101
+
87
102
  // StablePool's `_onSwapGivenIn` and `_onSwapGivenOut` handlers are meant to process swaps between Pool tokens.
88
103
  // Since one of the Pool's tokens is the preminted BPT, we need to a) handle swaps where that tokens is involved
89
104
  // separately (as they are effectively single-token joins or exits), and b) remove BPT from the balances array when
@@ -98,7 +113,7 @@ export class PhantomStablePool extends BasePool {
98
113
  indexIn: number;
99
114
  indexOut: number;
100
115
  } {
101
- if (bptIndex != -1) {
116
+ if (bptIndex !== -1) {
102
117
  balances.splice(bptIndex, 1);
103
118
  if (bptIndex < tokenIndexIn) tokenIndexIn -= 1;
104
119
  if (bptIndex < tokenIndexOut) tokenIndexOut -= 1;
@@ -110,6 +125,64 @@ export class PhantomStablePool extends BasePool {
110
125
  };
111
126
  }
112
127
 
128
+ _swapGivenOut(
129
+ tokenAmountsOut: bigint[],
130
+ tokens: string[],
131
+ balances: bigint[],
132
+ indexIn: number,
133
+ indexOut: number,
134
+ bptIndex: number,
135
+ scalingFactors: bigint[],
136
+ swapFeePercentage: bigint,
137
+ amplificationParameter: bigint,
138
+ actualSupply: bigint | undefined,
139
+ ) {
140
+ // Phantom pools allow trading between token and pool BPT
141
+ let pairType: PairTypes;
142
+ if (isSameAddress(tokens[indexIn], tokens[bptIndex])) {
143
+ pairType = PairTypes.BptToToken;
144
+ } else if (isSameAddress(tokens[indexOut], tokens[bptIndex])) {
145
+ pairType = PairTypes.TokenToBpt;
146
+ } else {
147
+ pairType = PairTypes.TokenToToken;
148
+ }
149
+
150
+ const balancesUpscaled = this._upscaleArray(balances, scalingFactors);
151
+ const tokenAmountsOutScaled = tokenAmountsOut.map(a =>
152
+ this._upscale(a, scalingFactors[indexOut]),
153
+ );
154
+
155
+ let bptSupply: bigint;
156
+ if (actualSupply) bptSupply = actualSupply;
157
+ // VirtualBPTSupply must be used for the maths
158
+ else bptSupply = this.MAX_TOKEN_BALANCE.sub(balances[bptIndex]).toBigInt();
159
+
160
+ const droppedBpt = this.removeBPT(
161
+ balancesUpscaled,
162
+ indexIn,
163
+ indexOut,
164
+ bptIndex,
165
+ );
166
+
167
+ const amountsIn = this._onSwapGivenOut(
168
+ tokenAmountsOutScaled,
169
+ droppedBpt.balances,
170
+ droppedBpt.indexIn,
171
+ droppedBpt.indexOut,
172
+ amplificationParameter,
173
+ bptSupply,
174
+ pairType,
175
+ );
176
+
177
+ const amountsInDownscaled = amountsIn.map(a =>
178
+ this._downscaleUp(a, scalingFactors[indexIn]),
179
+ );
180
+
181
+ return amountsInDownscaled.map(a =>
182
+ this._addFeeAmount(a, swapFeePercentage),
183
+ );
184
+ }
185
+
113
186
  _swapGivenIn(
114
187
  tokenAmountsIn: bigint[],
115
188
  tokens: string[],
@@ -136,6 +209,7 @@ export class PhantomStablePool extends BasePool {
136
209
  const tokenAmountsInWithFee = tokenAmountsIn.map(a =>
137
210
  this._subtractSwapFeeAmount(a, swapFeePercentage),
138
211
  );
212
+
139
213
  const balancesUpscaled = this._upscaleArray(balances, scalingFactors);
140
214
  const tokenAmountsInScaled = tokenAmountsInWithFee.map(a =>
141
215
  this._upscale(a, scalingFactors[indexIn]),
@@ -169,6 +243,87 @@ export class PhantomStablePool extends BasePool {
169
243
  );
170
244
  }
171
245
 
246
+ _onSwapGivenOut(
247
+ tokenAmountsOut: bigint[],
248
+ balances: bigint[],
249
+ indexIn: number,
250
+ indexOut: number,
251
+ _amplificationParameter: bigint,
252
+ virtualBptSupply: bigint,
253
+ pairType: PairTypes,
254
+ ) {
255
+ const invariant = PhantomStableMath._calculateInvariant(
256
+ _amplificationParameter,
257
+ balances,
258
+ true,
259
+ );
260
+
261
+ const amountsIn: bigint[] = [];
262
+
263
+ if (pairType === PairTypes.TokenToBpt) {
264
+ tokenAmountsOut.forEach(amountOut => {
265
+ let amt: bigint;
266
+ try {
267
+ const amountsInBigInt = Array(balances.length).fill(0n);
268
+ amountsInBigInt[indexIn] = amountOut;
269
+
270
+ amt = PhantomStableMath._calcTokenInGivenExactBptOut(
271
+ _amplificationParameter,
272
+ balances,
273
+ indexIn,
274
+ amountOut,
275
+ virtualBptSupply,
276
+ 0n,
277
+ invariant,
278
+ );
279
+ } catch (err) {
280
+ amt = 0n;
281
+ }
282
+ amountsIn.push(amt);
283
+ });
284
+ } else if (pairType === PairTypes.BptToToken) {
285
+
286
+ tokenAmountsOut.forEach(amountOut => {
287
+ let amt: bigint;
288
+ try {
289
+ const amountsOutBigInt = Array(balances.length).fill(0n);
290
+ amountsOutBigInt[indexOut] = amountOut;
291
+
292
+ amt = PhantomStableMath._calcBptInGivenExactTokensOut(
293
+ _amplificationParameter,
294
+ balances,
295
+ amountsOutBigInt,
296
+ virtualBptSupply,
297
+ 0n,
298
+ invariant,
299
+ );
300
+ } catch (err) {
301
+ amt = 0n;
302
+ }
303
+ amountsIn.push(amt);
304
+ });
305
+ } else {
306
+ tokenAmountsOut.forEach(amountOut => {
307
+ let amt: bigint;
308
+ try {
309
+ amt = PhantomStableMath._calcInGivenOut(
310
+ _amplificationParameter,
311
+ balances,
312
+ indexIn,
313
+ indexOut,
314
+ amountOut,
315
+ 0n,
316
+ invariant,
317
+ );
318
+ } catch (err) {
319
+ amt = 0n;
320
+ }
321
+ amountsIn.push(amt);
322
+ });
323
+ }
324
+ return amountsIn;
325
+ }
326
+
172
327
  /*
173
328
  Called when a swap with the Pool occurs, where the amount of tokens entering the Pool is known.
174
329
  All amounts are upscaled.
@@ -184,7 +339,7 @@ export class PhantomStablePool extends BasePool {
184
339
  virtualBptSupply: bigint,
185
340
  pairType: PairTypes,
186
341
  ): bigint[] {
187
- const invariant = StableMath._calculateInvariant(
342
+ const invariant = PhantomStableMath._calculateInvariant(
188
343
  _amplificationParameter,
189
344
  balances,
190
345
  true,
@@ -199,7 +354,7 @@ export class PhantomStablePool extends BasePool {
199
354
  const amountsInBigInt = Array(balances.length).fill(0n);
200
355
  amountsInBigInt[indexIn] = amountIn;
201
356
 
202
- amt = StableMath._calcBptOutGivenExactTokensIn(
357
+ amt = PhantomStableMath._calcBptOutGivenExactTokensIn(
203
358
  _amplificationParameter,
204
359
  balances,
205
360
  amountsInBigInt,
@@ -215,7 +370,7 @@ export class PhantomStablePool extends BasePool {
215
370
  tokenAmountsIn.forEach(amountIn => {
216
371
  let amt: bigint;
217
372
  try {
218
- amt = StableMath._calcTokenOutGivenExactBptIn(
373
+ amt = PhantomStableMath._calcTokenOutGivenExactBptIn(
219
374
  _amplificationParameter,
220
375
  balances,
221
376
  indexOut,
@@ -232,7 +387,7 @@ export class PhantomStablePool extends BasePool {
232
387
  tokenAmountsIn.forEach(amountIn => {
233
388
  let amt: bigint;
234
389
  try {
235
- amt = StableMath._calcOutGivenIn(
390
+ amt = PhantomStableMath._calcOutGivenIn(
236
391
  _amplificationParameter,
237
392
  balances,
238
393
  indexIn,
@@ -0,0 +1,204 @@
1
+ import { BI_POWS } from '../../../../bigint-constants';
2
+ import { MathSol } from '../../balancer-v2-math';
3
+
4
+ export class StableMath {
5
+ static _AMP_PRECISION = BI_POWS[3];
6
+
7
+ static _calculateInvariant(
8
+ amplificationParameter: bigint,
9
+ balances: bigint[],
10
+ roundUp: boolean,
11
+ ): bigint {
12
+ /**********************************************************************************************
13
+ // invariant //
14
+ // D = invariant D^(n+1) //
15
+ // A = amplification coefficient A n^n S + D = A D n^n + ----------- //
16
+ // S = sum of balances n^n P //
17
+ // P = product of balances //
18
+ // n = number of tokens //
19
+ *********x************************************************************************************/
20
+
21
+ // We support rounding up or down.
22
+ let sum = 0n;
23
+ const numTokens = balances.length;
24
+ for (let i = 0; i < numTokens; i++) {
25
+ sum = sum + balances[i];
26
+ }
27
+ if (sum == 0n) {
28
+ return 0n;
29
+ }
30
+
31
+ let prevInvariant = 0n;
32
+ let invariant = sum;
33
+ const ampTimesTotal = amplificationParameter * BigInt(numTokens);
34
+
35
+ for (let i = 0; i < 255; i++) {
36
+ let P_D = balances[0] * BigInt(numTokens);
37
+ for (let j = 1; j < numTokens; j++) {
38
+ P_D = MathSol.div(
39
+ MathSol.mul(MathSol.mul(P_D, balances[j]), BigInt(numTokens)),
40
+ invariant,
41
+ roundUp,
42
+ );
43
+ }
44
+ prevInvariant = invariant;
45
+ invariant = MathSol.div(
46
+ MathSol.mul(MathSol.mul(BigInt(numTokens), invariant), invariant) +
47
+ MathSol.div(
48
+ MathSol.mul(MathSol.mul(ampTimesTotal, sum), P_D),
49
+ this._AMP_PRECISION,
50
+ roundUp,
51
+ ),
52
+ MathSol.mul(BigInt(numTokens + 1), invariant) +
53
+ // No need to use checked arithmetic for the amp precision, the amp is guaranteed to be at least 1
54
+ MathSol.div(
55
+ MathSol.mul(ampTimesTotal - this._AMP_PRECISION, P_D),
56
+ this._AMP_PRECISION,
57
+ !roundUp,
58
+ ),
59
+ roundUp,
60
+ );
61
+
62
+ if (invariant > prevInvariant) {
63
+ if (invariant - prevInvariant <= 1) {
64
+ return invariant;
65
+ }
66
+ } else if (prevInvariant - invariant <= 1) {
67
+ return invariant;
68
+ }
69
+ }
70
+
71
+ throw new Error('Errors.STABLE_INVARIANT_DIDNT_CONVERGE');
72
+ }
73
+
74
+
75
+ static _calcInGivenOut(
76
+ amplificationParameter: bigint,
77
+ balances: bigint[],
78
+ tokenIndexIn: number,
79
+ tokenIndexOut: number,
80
+ tokenAmountsOut: bigint[],
81
+ ): bigint[] {
82
+ const invariant = this._calculateInvariant(
83
+ amplificationParameter,
84
+ balances,
85
+ false,
86
+ );
87
+
88
+ return tokenAmountsOut.map(a => {
89
+ balances[tokenIndexOut] = MathSol.sub(balances[tokenIndexOut], a);
90
+
91
+ const finalBalanceIn =
92
+ this._getTokenBalanceGivenInvariantAndAllOtherBalances(
93
+ amplificationParameter,
94
+ balances,
95
+ invariant,
96
+ tokenIndexIn,
97
+ );
98
+
99
+ return MathSol.add(
100
+ MathSol.sub(finalBalanceIn, balances[tokenIndexIn]),
101
+ 1n,
102
+ );
103
+ });
104
+ };
105
+
106
+ static _calcOutGivenIn(
107
+ amplificationParameter: bigint,
108
+ balances: bigint[],
109
+ tokenIndexIn: number,
110
+ tokenIndexOut: number,
111
+ tokenAmountsIn: bigint[],
112
+ ): bigint[] {
113
+ // Amount out, so we round down overall.
114
+
115
+ // Given that we need to have a greater final balance out, the invariant needs to be rounded up
116
+ const invariant = this._calculateInvariant(
117
+ amplificationParameter,
118
+ balances,
119
+ true,
120
+ );
121
+
122
+ const initBalance = balances[tokenIndexIn];
123
+ // Modification: The original code was implemented for a single tokenAmountsIn
124
+ return tokenAmountsIn.map(a => {
125
+ balances[tokenIndexIn] = initBalance + a;
126
+
127
+ const finalBalanceOut =
128
+ this._getTokenBalanceGivenInvariantAndAllOtherBalances(
129
+ amplificationParameter,
130
+ balances,
131
+ invariant,
132
+ tokenIndexOut,
133
+ );
134
+
135
+ // No need to use checked arithmetic since `tokenAmountIn` was actually added to the same balance right before
136
+ // calling `_getTokenBalanceGivenInvariantAndAllOtherBalances` which doesn't alter the balances array.
137
+ // balances[tokenIndexIn] = balances[tokenIndexIn] - tokenAmountIn;
138
+ return balances[tokenIndexOut] - finalBalanceOut - 1n;
139
+ });
140
+ }
141
+
142
+ static _getTokenBalanceGivenInvariantAndAllOtherBalances(
143
+ amplificationParameter: bigint,
144
+ balances: bigint[],
145
+ invariant: bigint,
146
+ tokenIndex: number,
147
+ ): bigint {
148
+ // Rounds result up overall
149
+
150
+ const ampTimesTotal = amplificationParameter * BigInt(balances.length);
151
+ let sum = balances[0];
152
+ let P_D = balances[0] * BigInt(balances.length);
153
+ for (let j = 1; j < balances.length; j++) {
154
+ P_D = MathSol.divDown(
155
+ MathSol.mul(MathSol.mul(P_D, balances[j]), BigInt(balances.length)),
156
+ invariant,
157
+ );
158
+ sum = sum + balances[j];
159
+ }
160
+ // No need to use safe math, based on the loop above `sum` is greater than or equal to `balances[tokenIndex]`
161
+ sum = sum - balances[tokenIndex];
162
+
163
+ const inv2 = MathSol.mul(invariant, invariant);
164
+ // We remove the balance fromm c by multiplying it
165
+ const c = MathSol.mul(
166
+ MathSol.mul(
167
+ MathSol.divUp(inv2, MathSol.mul(ampTimesTotal, P_D)),
168
+ this._AMP_PRECISION,
169
+ ),
170
+ balances[tokenIndex],
171
+ );
172
+ const b =
173
+ sum +
174
+ MathSol.mul(
175
+ MathSol.divDown(invariant, ampTimesTotal),
176
+ this._AMP_PRECISION,
177
+ );
178
+
179
+ // We iterate to find the balance
180
+ let prevTokenBalance = 0n;
181
+ // We multiply the first iteration outside the loop with the invariant to set the value of the
182
+ // initial approximation.
183
+ let tokenBalance = MathSol.divUp(inv2 + c, invariant + b);
184
+
185
+ for (let i = 0; i < 255; i++) {
186
+ prevTokenBalance = tokenBalance;
187
+
188
+ tokenBalance = MathSol.divUp(
189
+ MathSol.mul(tokenBalance, tokenBalance) + c,
190
+ MathSol.mul(tokenBalance, 2n) + b - invariant,
191
+ );
192
+
193
+ if (tokenBalance > prevTokenBalance) {
194
+ if (tokenBalance - prevTokenBalance <= 1) {
195
+ return tokenBalance;
196
+ }
197
+ } else if (prevTokenBalance - tokenBalance <= 1) {
198
+ return tokenBalance;
199
+ }
200
+ }
201
+
202
+ throw new Error('Errors.STABLE_GET_BALANCE_DIDNT_CONVERGE');
203
+ }
204
+ }