-
Notifications
You must be signed in to change notification settings - Fork 136
/
stableMathBigInt.ts
812 lines (747 loc) · 26.6 KB
/
stableMathBigInt.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
/*
Swap outcome and "spot price after swap" formulas for weighted, stable and linear pools.
Amounts are represented using bigint type. Swap outcomes formulas should
match exactly those from smart contracts.
Test cases are found in poolsMathWeighted.spec.ts, poolsMathStable.spec.ts poolsMathLinear.spec.ts.
It is necessary to review whether to use MathSol operations or native +,-,\*,/ case by case. MathSol operations are able to reproduce overflows while native operations produce a much more readable code. For instance, for "spot price after swap" native operations
are preferred since in this case there are not smart contract analogs, amount limits are assumed to have been checked elsewhere, and some formulas get complicated, specially for stable pools.
*/
import { MathSol, BZERO } from '../../utils/basicOperations';
const AMP_PRECISION = BigInt(1e3);
function _calculateInvariant(amp: bigint, balances: bigint[]): bigint {
/**********************************************************************************************
// invariant //
// D = invariant D^(n+1) //
// A = amplification coefficient A n^n S + D = A D n^n + ----------- //
// S = sum of balances n^n P //
// P = product of balances //
// n = number of tokens //
*********x************************************************************************************/
// Always round down, to match Vyper's arithmetic (which always truncates).
let sum = BZERO;
const numTokens = balances.length;
for (let i = 0; i < numTokens; i++) {
sum = sum + balances[i];
}
if (sum == BZERO) {
return BZERO;
}
let prevInvariant = BZERO;
let invariant = sum;
const ampTimesTotal = amp * BigInt(numTokens);
for (let i = 0; i < 255; i++) {
let D_P = invariant;
for (let j = 0; j < numTokens; j++) {
// (D_P * invariant) / (balances[j] * numTokens)
D_P = MathSol.divDown(
MathSol.mul(D_P, invariant),
MathSol.mul(balances[j], BigInt(numTokens))
);
}
prevInvariant = invariant;
invariant = MathSol.divDown(
MathSol.mul(
// (ampTimesTotal * sum) / AMP_PRECISION + D_P * numTokens
MathSol.divDown(
MathSol.mul(ampTimesTotal, sum),
AMP_PRECISION
) + MathSol.mul(D_P, BigInt(numTokens)),
invariant
),
// ((ampTimesTotal - _AMP_PRECISION) * invariant) / _AMP_PRECISION + (numTokens + 1) * D_P
MathSol.divDown(
MathSol.mul(ampTimesTotal - AMP_PRECISION, invariant),
AMP_PRECISION
) + MathSol.mul(BigInt(numTokens + 1), D_P)
);
if (invariant > prevInvariant) {
if (invariant - prevInvariant <= 1) {
return invariant;
}
} else if (prevInvariant - invariant <= 1) {
return invariant;
}
}
throw new Error('Errors.STABLE_INVARIANT_DIDNT_CONVERGE');
}
// PairType = 'token->token'
// SwapType = 'swapExactIn'
export function _calcOutGivenIn(
amp: bigint,
balances: bigint[],
tokenIndexIn: number,
tokenIndexOut: number,
amountIn: bigint,
fee: bigint
): bigint {
amountIn = subtractFee(amountIn, fee);
const invariant = _calculateInvariant(amp, balances);
const initBalance = balances[tokenIndexIn];
balances[tokenIndexIn] = initBalance + amountIn;
const finalBalanceOut = _getTokenBalanceGivenInvariantAndAllOtherBalances(
amp,
balances,
invariant,
tokenIndexOut
);
return balances[tokenIndexOut] - finalBalanceOut - BigInt(1);
}
export function _calcInGivenOut(
amp: bigint,
balances: bigint[],
tokenIndexIn: number,
tokenIndexOut: number,
amountOut: bigint,
fee: bigint
): bigint {
const invariant = _calculateInvariant(amp, balances);
balances[tokenIndexOut] = MathSol.sub(balances[tokenIndexOut], amountOut);
const finalBalanceIn = _getTokenBalanceGivenInvariantAndAllOtherBalances(
amp,
balances,
invariant,
tokenIndexIn
);
let amountIn = MathSol.add(
MathSol.sub(finalBalanceIn, balances[tokenIndexIn]),
BigInt(1)
);
amountIn = addFee(amountIn, fee);
return amountIn;
}
export function _calcBptOutGivenExactTokensIn(
amp: bigint,
balances: bigint[],
amountsIn: bigint[],
bptTotalSupply: bigint,
swapFeePercentage: bigint
): bigint {
// BPT out, so we round down overall.
// First loop calculates the sum of all token balances, which will be used to calculate
// the current weights of each token, relative to this sum
let sumBalances = BigInt(0);
for (let i = 0; i < balances.length; i++) {
sumBalances = sumBalances + balances[i];
}
// Calculate the weighted balance ratio without considering fees
const balanceRatiosWithFee: bigint[] = new Array(amountsIn.length);
// The weighted sum of token balance ratios with fee
let invariantRatioWithFees = BigInt(0);
for (let i = 0; i < balances.length; i++) {
const currentWeight = MathSol.divDownFixed(balances[i], sumBalances);
balanceRatiosWithFee[i] = MathSol.divDownFixed(
balances[i] + amountsIn[i],
balances[i]
);
invariantRatioWithFees =
invariantRatioWithFees +
MathSol.mulDownFixed(balanceRatiosWithFee[i], currentWeight);
}
// Second loop calculates new amounts in, taking into account the fee on the percentage excess
const newBalances: bigint[] = new Array(balances.length);
for (let i = 0; i < balances.length; i++) {
let amountInWithoutFee: bigint;
// Check if the balance ratio is greater than the ideal ratio to charge fees or not
if (balanceRatiosWithFee[i] > invariantRatioWithFees) {
const nonTaxableAmount = MathSol.mulDownFixed(
balances[i],
invariantRatioWithFees - MathSol.ONE
);
const taxableAmount = amountsIn[i] - nonTaxableAmount;
// No need to use checked arithmetic for the swap fee, it is guaranteed to be lower than 50%
amountInWithoutFee =
nonTaxableAmount +
MathSol.mulDownFixed(
taxableAmount,
MathSol.ONE - swapFeePercentage
);
} else {
amountInWithoutFee = amountsIn[i];
}
newBalances[i] = balances[i] + amountInWithoutFee;
}
// Get current and new invariants, taking swap fees into account
const currentInvariant = _calculateInvariant(amp, balances);
const newInvariant = _calculateInvariant(amp, newBalances);
const invariantRatio = MathSol.divDownFixed(newInvariant, currentInvariant);
// If the invariant didn't increase for any reason, we simply don't mint BPT
if (invariantRatio > MathSol.ONE) {
return MathSol.mulDownFixed(
bptTotalSupply,
invariantRatio - MathSol.ONE
);
} else {
return BigInt(0);
}
}
export function _calcTokenInGivenExactBptOut(
amp: bigint,
balances: bigint[],
tokenIndexIn: number,
bptAmountOut: bigint,
bptTotalSupply: bigint,
fee: bigint
): bigint {
// Token in, so we round up overall.
const currentInvariant = _calculateInvariant(amp, balances);
const newInvariant = MathSol.mulUpFixed(
MathSol.divUpFixed(
MathSol.add(bptTotalSupply, bptAmountOut),
bptTotalSupply
),
currentInvariant
);
// Calculate amount in without fee.
const newBalanceTokenIndex =
_getTokenBalanceGivenInvariantAndAllOtherBalances(
amp,
balances,
newInvariant,
tokenIndexIn
);
const amountInWithoutFee = MathSol.sub(
newBalanceTokenIndex,
balances[tokenIndexIn]
);
// First calculate the sum of all token balances, which will be used to calculate
// the current weight of each token
let sumBalances = BigInt(0);
for (let i = 0; i < balances.length; i++) {
sumBalances = MathSol.add(sumBalances, balances[i]);
}
// We can now compute how much extra balance is being deposited
// and used in virtual swaps, and charge swap fees accordingly.
const currentWeight = MathSol.divDownFixed(
balances[tokenIndexIn],
sumBalances
);
const taxablePercentage = MathSol.complementFixed(currentWeight);
const taxableAmount = MathSol.mulUpFixed(
amountInWithoutFee,
taxablePercentage
);
const nonTaxableAmount = MathSol.sub(amountInWithoutFee, taxableAmount);
return MathSol.add(
nonTaxableAmount,
MathSol.divUpFixed(taxableAmount, MathSol.sub(MathSol.ONE, fee))
);
}
/*
Flow of calculations:
amountsTokenOut -> amountsOutProportional ->
amountOutPercentageExcess -> amountOutBeforeFee -> newInvariant -> amountBPTIn
*/
export function _calcBptInGivenExactTokensOut(
amp: bigint,
balances: bigint[],
amountsOut: bigint[],
bptTotalSupply: bigint,
swapFeePercentage: bigint
): bigint {
// BPT in, so we round up overall.
// First loop calculates the sum of all token balances, which will be used to calculate
// the current weights of each token relative to this sum
let sumBalances = BigInt(0);
for (let i = 0; i < balances.length; i++) {
sumBalances = sumBalances + balances[i];
}
// Calculate the weighted balance ratio without considering fees
const balanceRatiosWithoutFee: bigint[] = new Array(amountsOut.length);
let invariantRatioWithoutFees = BigInt(0);
for (let i = 0; i < balances.length; i++) {
const currentWeight = MathSol.divUpFixed(balances[i], sumBalances);
balanceRatiosWithoutFee[i] = MathSol.divUpFixed(
balances[i] - amountsOut[i],
balances[i]
);
invariantRatioWithoutFees =
invariantRatioWithoutFees +
MathSol.mulUpFixed(balanceRatiosWithoutFee[i], currentWeight);
}
// Second loop calculates new amounts in, taking into account the fee on the percentage excess
const newBalances: bigint[] = new Array(balances.length);
for (let i = 0; i < balances.length; i++) {
// Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it to
// 'token out'. This results in slightly larger price impact.
let amountOutWithFee: bigint;
if (invariantRatioWithoutFees > balanceRatiosWithoutFee[i]) {
const nonTaxableAmount = MathSol.mulDownFixed(
balances[i],
MathSol.complementFixed(invariantRatioWithoutFees)
);
const taxableAmount = amountsOut[i] - nonTaxableAmount;
// No need to use checked arithmetic for the swap fee, it is guaranteed to be lower than 50%
amountOutWithFee =
nonTaxableAmount +
MathSol.divUpFixed(
taxableAmount,
MathSol.ONE - swapFeePercentage
);
} else {
amountOutWithFee = amountsOut[i];
}
newBalances[i] = balances[i] - amountOutWithFee;
}
// Get current and new invariants, taking into account swap fees
const currentInvariant = _calculateInvariant(amp, balances);
const newInvariant = _calculateInvariant(amp, newBalances);
const invariantRatio = MathSol.divDownFixed(newInvariant, currentInvariant);
// return amountBPTIn
return MathSol.mulUpFixed(
bptTotalSupply,
MathSol.complementFixed(invariantRatio)
);
}
export function _calcTokenOutGivenExactBptIn(
amp: bigint,
balances: bigint[],
tokenIndex: number,
bptAmountIn: bigint,
bptTotalSupply: bigint,
swapFeePercentage: bigint
): bigint {
// Token out, so we round down overall.
const currentInvariant = _calculateInvariant(amp, balances);
const newInvariant = MathSol.mulUpFixed(
MathSol.divUpFixed(bptTotalSupply - bptAmountIn, bptTotalSupply),
currentInvariant
);
// Calculate amount out without fee
const newBalanceTokenIndex =
_getTokenBalanceGivenInvariantAndAllOtherBalances(
amp,
balances,
newInvariant,
tokenIndex
);
const amountOutWithoutFee = balances[tokenIndex] - newBalanceTokenIndex;
// First calculate the sum of all token balances, which will be used to calculate
// the current weight of each token
let sumBalances = BigInt(0);
for (let i = 0; i < balances.length; i++) {
sumBalances = sumBalances + balances[i];
}
// We can now compute how much excess balance is being withdrawn as a result of the virtual swaps, which result
// in swap fees.
const currentWeight = MathSol.divDownFixed(
balances[tokenIndex],
sumBalances
);
const taxablePercentage = MathSol.complementFixed(currentWeight);
// Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it
// to 'token out'. This results in slightly larger price impact. Fees are rounded up.
const taxableAmount = MathSol.mulUpFixed(
amountOutWithoutFee,
taxablePercentage
);
const nonTaxableAmount = amountOutWithoutFee - taxableAmount;
// No need to use checked arithmetic for the swap fee, it is guaranteed to be lower than 50%
return (
nonTaxableAmount +
MathSol.mulDownFixed(taxableAmount, MathSol.ONE - swapFeePercentage)
);
}
export function _calcTokensOutGivenExactBptIn(
balances: bigint[],
bptAmountIn: bigint,
bptTotalSupply: bigint
): bigint[] {
/**********************************************************************************************
// exactBPTInForTokensOut //
// (per token) //
// aO = tokenAmountOut / bptIn \ //
// b = tokenBalance a0 = b * | --------------------- | //
// bptIn = bptAmountIn \ bptTotalSupply / //
// bpt = bptTotalSupply //
**********************************************************************************************/
// Since we're computing an amount out, we round down overall. This means rounding down on both the
// multiplication and division.
const bptRatio = MathSol.divDownFixed(bptAmountIn, bptTotalSupply);
const amountsOut: bigint[] = new Array(balances.length);
for (let i = 0; i < balances.length; i++) {
amountsOut[i] = MathSol.mulDownFixed(balances[i], bptRatio);
}
return amountsOut;
}
function _getTokenBalanceGivenInvariantAndAllOtherBalances(
amp: bigint,
balances: bigint[],
invariant: bigint,
tokenIndex: number
): bigint {
// Rounds result up overall
const ampTimesTotal = amp * BigInt(balances.length);
let sum = balances[0];
let P_D = balances[0] * BigInt(balances.length);
for (let j = 1; j < balances.length; j++) {
P_D = MathSol.divDown(
MathSol.mul(MathSol.mul(P_D, balances[j]), BigInt(balances.length)),
invariant
);
sum = sum + balances[j];
}
// No need to use safe math, based on the loop above `sum` is greater than or equal to `balances[tokenIndex]`
sum = sum - balances[tokenIndex];
const inv2 = MathSol.mul(invariant, invariant);
// We remove the balance fromm c by multiplying it
const c = MathSol.mul(
MathSol.mul(
MathSol.divUp(inv2, MathSol.mul(ampTimesTotal, P_D)),
AMP_PRECISION
),
balances[tokenIndex]
);
const b =
sum +
MathSol.mul(MathSol.divDown(invariant, ampTimesTotal), AMP_PRECISION);
// We iterate to find the balance
let prevTokenBalance = BZERO;
// We multiply the first iteration outside the loop with the invariant to set the value of the
// initial approximation.
let tokenBalance = MathSol.divUp(inv2 + c, invariant + b);
for (let i = 0; i < 255; i++) {
prevTokenBalance = tokenBalance;
tokenBalance = MathSol.divUp(
MathSol.mul(tokenBalance, tokenBalance) + c,
MathSol.mul(tokenBalance, BigInt(2)) + b - invariant
);
if (tokenBalance > prevTokenBalance) {
if (tokenBalance - prevTokenBalance <= 1) {
return tokenBalance;
}
} else if (prevTokenBalance - tokenBalance <= 1) {
return tokenBalance;
}
}
throw new Error('Errors.STABLE_GET_BALANCE_DIDNT_CONVERGE');
}
function subtractFee(amount: bigint, fee: bigint): bigint {
const feeAmount = MathSol.mulUpFixed(amount, fee);
return amount - feeAmount;
}
function addFee(amount: bigint, fee: bigint): bigint {
return MathSol.divUpFixed(amount, MathSol.complementFixed(fee));
}
/////////
/// SpotPriceAfterSwap
/////////
// PairType = 'token->token'
// SwapType = 'swapExactIn'
export function _spotPriceAfterSwapExactTokenInForTokenOut(
amp: bigint,
balances: bigint[],
tokenIndexIn: number,
tokenIndexOut: number,
amountIn: bigint,
fee: bigint
): bigint {
const feeComplement = MathSol.complementFixed(fee);
const balancesCopy = [...balances];
balances[tokenIndexIn] = MathSol.add(
balances[tokenIndexIn],
MathSol.mulUpFixed(amountIn, feeComplement)
);
balances[tokenIndexOut] = MathSol.sub(
balances[tokenIndexOut],
_calcOutGivenIn(
amp,
balancesCopy,
tokenIndexIn,
tokenIndexOut,
amountIn,
fee
)
);
let ans = _poolDerivatives(
amp,
balances,
tokenIndexIn,
tokenIndexOut,
true,
false
);
ans = MathSol.divDownFixed(
MathSol.ONE,
MathSol.mulDownFixed(ans, feeComplement)
);
return ans;
}
// PairType = 'token->token'
// SwapType = 'swapExactOut'
export function _spotPriceAfterSwapTokenInForExactTokenOut(
amp: bigint,
balances: bigint[],
tokenIndexIn: number,
tokenIndexOut: number,
amountOut: bigint,
fee: bigint
): bigint {
const balancesCopy = [...balances];
const _in = _calcInGivenOut(
amp,
balancesCopy,
tokenIndexIn,
tokenIndexOut,
amountOut,
fee
);
balances[tokenIndexIn] = balances[tokenIndexIn] + _in;
balances[tokenIndexOut] = MathSol.sub(balances[tokenIndexOut], amountOut);
let ans = _poolDerivatives(
amp,
balances,
tokenIndexIn,
tokenIndexOut,
true,
true
);
const feeComplement = MathSol.complementFixed(fee);
ans = MathSol.divUpFixed(
MathSol.ONE,
MathSol.mulUpFixed(ans, feeComplement)
);
return ans;
}
// PairType = 'token->BPT'
// SwapType = 'swapExactIn'
export function _spotPriceAfterSwapExactTokenInForBPTOut(
amp: bigint,
balances: bigint[],
tokenIndexIn: number,
bptTotalSupply: bigint,
amountIn: bigint
// assuming zero fee
): bigint {
balances[tokenIndexIn] = balances[tokenIndexIn] + amountIn;
// working
const amountsIn = balances.map((_value, index) =>
index == tokenIndexIn ? amountIn : BigInt(0)
);
const finalBPTSupply =
bptTotalSupply +
_calcBptOutGivenExactTokensIn(
amp,
balances,
amountsIn,
bptTotalSupply,
BigInt(0)
);
let ans = _poolDerivativesBPT(
amp,
balances,
finalBPTSupply,
tokenIndexIn,
true,
true,
false
);
ans = MathSol.divUpFixed(MathSol.ONE, ans);
return ans;
}
// PairType = 'token->BPT'
// SwapType = 'swapExactOut'
export function _spotPriceAfterSwapTokenInForExactBPTOut(
amp: bigint,
balances: bigint[],
tokenIndexIn: number,
bptTotalSupply: bigint,
amountOut: bigint
// assuming zero fee
): bigint {
const balancesCopy = [...balances];
const _in = _calcTokenInGivenExactBptOut(
amp,
balancesCopy,
tokenIndexIn,
amountOut,
bptTotalSupply,
BigInt(0)
);
balances[tokenIndexIn] = balances[tokenIndexIn] + _in;
let ans = _poolDerivativesBPT(
amp,
balances,
bptTotalSupply + amountOut,
tokenIndexIn,
true,
true,
true
);
ans = MathSol.divUpFixed(MathSol.ONE, ans); // ONE.div(ans.times(feeFactor));
return ans;
}
// PairType = 'BPT->token'
// SwapType = 'swapExactIn'
export function _spotPriceAfterSwapExactBPTInForTokenOut(
amp: bigint,
balances: bigint[],
tokenIndexOut: number,
bptTotalSupply: bigint,
amountIn: bigint
// assuming zero fee
): bigint {
// balances copy not necessary?
const _out = _calcTokenOutGivenExactBptIn(
amp,
balances,
tokenIndexOut,
amountIn,
bptTotalSupply,
BigInt(0)
);
balances[tokenIndexOut] = balances[tokenIndexOut] - _out;
const bptTotalSupplyAfter = MathSol.sub(bptTotalSupply, amountIn);
const ans = _poolDerivativesBPT(
amp,
balances,
bptTotalSupplyAfter,
tokenIndexOut,
true,
false,
false
);
return ans;
}
// PairType = 'BPT->token'
// SwapType = 'swapExactOut'
export function _spotPriceAfterSwapBPTInForExactTokenOut(
amp: bigint,
balances: bigint[],
tokenIndexOut: number,
bptTotalSupply: bigint,
amountOut: bigint
): bigint {
balances[tokenIndexOut] = MathSol.sub(balances[tokenIndexOut], amountOut);
const amountsOut = balances.map((_value, index) =>
index == tokenIndexOut ? amountOut : BigInt(0)
);
const bptTotalSupplyAfter =
bptTotalSupply -
_calcBptInGivenExactTokensOut(
amp,
balances,
amountsOut,
bptTotalSupply,
BigInt(0)
);
const ans = _poolDerivativesBPT(
amp,
balances,
bptTotalSupplyAfter,
tokenIndexOut,
true,
false,
true
);
return ans;
}
export function _poolDerivatives(
amp: bigint,
balances: bigint[],
tokenIndexIn: number,
tokenIndexOut: number,
is_first_derivative: boolean,
wrt_out: boolean
): bigint {
const totalCoins = balances.length;
const D = _calculateInvariant(amp, balances);
let S = BigInt(0);
for (let i = 0; i < totalCoins; i++) {
if (i != tokenIndexIn && i != tokenIndexOut) {
S += balances[i];
}
}
const x = balances[tokenIndexIn];
const y = balances[tokenIndexOut];
const a = amp * BigInt(totalCoins);
const b = a * (S - D) + D * AMP_PRECISION;
const twoaxy = BigInt(2) * a * x * y;
const partial_x = twoaxy + a * y * y + b * y;
const partial_y = twoaxy + a * x * x + b * x;
let ans: bigint;
if (is_first_derivative) {
ans = MathSol.divUpFixed(partial_x, partial_y);
} else {
// Untested case:
const partial_xx = BigInt(2) * a * y;
const partial_yy = BigInt(2) * a * x;
const partial_xy = partial_xx + partial_yy + b; // AMP_PRECISION missing
const numerator =
BigInt(2) * partial_x * partial_y * partial_xy -
partial_xx * partial_y * partial_y +
partial_yy * partial_x * partial_x;
const denominator = partial_x * partial_x * partial_y;
ans = MathSol.divUpFixed(numerator, denominator); // change the order to directly use integer operations
if (wrt_out) {
ans = MathSol.mulUpFixed(
MathSol.mulUpFixed(ans, partial_y),
partial_x
);
}
}
return ans;
}
export function _poolDerivativesBPT(
amp: bigint,
balances: bigint[],
bptSupply: bigint,
tokenIndexIn: number,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
is_first_derivative: boolean,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
is_BPT_out: boolean,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
wrt_out: boolean
): bigint {
const totalCoins = balances.length;
const D = _calculateInvariant(amp, balances);
let S = BigInt(0);
let D_P = D / BigInt(totalCoins);
for (let i = 0; i < totalCoins; i++) {
if (i != tokenIndexIn) {
S = S + balances[i];
D_P = (D_P * D) / (BigInt(totalCoins) * balances[i]);
}
}
const x = balances[tokenIndexIn];
const alpha = amp * BigInt(totalCoins);
const beta = alpha * S; // units = 10 ** 21
const gamma = BigInt(AMP_PRECISION) - alpha;
const partial_x = BigInt(2) * alpha * x + beta + gamma * D;
const minus_partial_D =
D_P * BigInt(totalCoins + 1) * AMP_PRECISION - gamma * x;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const partial_D = -minus_partial_D;
const ans = MathSol.divUpFixed(
(partial_x * bptSupply) / minus_partial_D,
D
);
/*
if (is_first_derivative) {
ans = MathSol.divUpFixed((partial_x * bptSupply) / minus_partial_D, D);
} else {
let partial_xx = bnum(2).times(alpha);
let partial_xD = gamma;
let n_times_nplusone = totalCoins * (totalCoins + 1);
let partial_DD = bnum(0).minus( D_P.times(n_times_nplusone).div(D) );
if (is_BPT_out) {
let term1 = partial_xx.times(partial_D).div( partial_x.pow(2) );
let term2 = bnum(2).times(partial_xD).div(partial_x);
let term3 = partial_DD.div(partial_D);
ans = (term1.minus(term2).plus(term3)).times(D).div(bptSupply)
if (wrt_out) {
let D_prime = bnum(0).minus( partial_x.div(partial_D) );
ans = ans.div( D_prime ).times(D).div(bptSupply);
}
} else {
ans = bnum(2).times(partial_xD).div(partial_D).minus(
partial_DD.times(partial_x).div(partial_D.pow(2)) ).minus(
partial_xx.div(partial_x) );
if (wrt_out) {
ans = ans.times(partial_x).div(minus_partial_D).times(bptSupply).div(D);
}
}
}
*/
return ans;
}