-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathAsMaths.sol
More file actions
1279 lines (1162 loc) · 42.2 KB
/
AsMaths.sol
File metadata and controls
1279 lines (1162 loc) · 42.2 KB
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
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import "./AsCast.sol";
/**
* _ _ _
* __ _ ___| |_ _ __ ___ | | __ _| |__
* / ` / __| _| '__/ \| |/ ` | ' \
* | O \__ \ |_| | | O | | O | O |
* \__,_|___/.__|_| \___/|_|\__,_|_.__/ ©️ 2024
*
* @title AsMaths Library
* @author Astrolab DAO - Astrolab's Maths library inspired by many (oz, abdk, prb, uniswap...)
*/
library AsMaths {
using AsCast for uint256;
using AsCast for int256;
/*═══════════════════════════════════════════════════════════════╗
║ TYPES ║
╚═══════════════════════════════════════════════════════════════*/
/**
* @notice Enumeration for rounding modes
* @dev Four rounding modes: Floor, Ceil, Trunc, Expand
*/
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/*═══════════════════════════════════════════════════════════════╗
║ ERRORS ║
╚═══════════════════════════════════════════════════════════════*/
error MathOverflowedMulDiv(); // overflow during multiplication or division
/*═══════════════════════════════════════════════════════════════╗
║ CONSTANTS ║
╚═══════════════════════════════════════════════════════════════*/
// Constants
uint256 internal constant WAD = 1e18; // 18 decimal fixed-point number
uint256 internal constant RAY = 1e27; // 27 decimal fixed-point number
uint256 internal constant BP_BASIS = 100_00; // 50% == 5_000 == 5e3
uint256 internal constant PRECISION_BP_BASIS = BP_BASIS ** 2; // 50% == 50_000_000 == 5e7
uint256 internal constant SEC_PER_YEAR = 31_556_952; // 365.2425 days, more precise than 365 days const
uint256 internal constant MAX_UINT256 = type(uint256).max;
/*═══════════════════════════════════════════════════════════════╗
║ VIEWS ║
╚═══════════════════════════════════════════════════════════════*/
/*═══════════════════════════════════════════════════════════════╗
║ LOGIC ║
╚═══════════════════════════════════════════════════════════════*/
/**
* @notice Subtracts a certain proportion from a given amount
* @param amount Initial amount
* @param basisPoints Proportion to subtract
* @return Result of subtracting the proportion
*/
function subBp(
uint256 amount,
uint256 basisPoints
) internal pure returns (uint256) {
unchecked {
return mulDiv(amount, BP_BASIS - basisPoints, BP_BASIS);
}
}
/**
* @notice Adds a certain proportion to a given amount
* @param amount Initial amount
* @param basisPoints Proportion to add
* @return Result of adding the proportion
*/
function addBp(
uint256 amount,
uint256 basisPoints
) internal pure returns (uint256) {
unchecked {
return mulDiv(amount, BP_BASIS + basisPoints, BP_BASIS);
}
}
/**
* @notice Calculates the proportion of a given amount
* @param amount Initial amount
* @param basisPoints Proportion to calculate
* @return Calculated proportion of the amount /BP_BASIS
*/
function bp(
uint256 amount,
uint256 basisPoints
) internal pure returns (uint256) {
unchecked {
return mulDiv(amount, basisPoints, BP_BASIS);
}
}
/**
* @notice Calculates the proportion of a given amount (inverted)
* @param amount Initial amount
* @param basisPoints Proportion to calculate
* @return Calculated proportion of the amount /BP_BASIS
*/
function revBp(
uint256 amount,
uint256 basisPoints
) internal pure returns (uint256) {
unchecked {
return mulDiv(amount, basisPoints, BP_BASIS - basisPoints);
}
}
/**
* @notice Calculates the precise proportion of a given amount
* @param amount Initial amount
* @param basisPoints Proportion to calculate
* @return Calculated proportion of the amount /PRECISION_BP_BASIS
*/
function precisionBp(
uint256 amount,
uint256 basisPoints
) internal pure returns (uint256) {
unchecked {
return mulDiv(amount, basisPoints, PRECISION_BP_BASIS);
}
}
/**
* @notice Calculates the reverse of adding a certain proportion to a given amount
* @param amount Initial amount
* @param basisPoints Proportion to reverse add
* @return Result of reverse adding the proportion
*/
function revAddBp(
uint256 amount,
uint256 basisPoints
) internal pure returns (uint256) {
unchecked {
return mulDiv(amount, BP_BASIS, BP_BASIS - basisPoints);
}
}
/**
* @notice Calculates the reverse of subtracting a certain proportion from a given amount
* @param amount Initial amount
* @param basisPoints Proportion to reverse subtract
* @return Result of reverse subtracting the proportion
*/
function revSubBp(
uint256 amount,
uint256 basisPoints
) internal pure returns (uint256) {
unchecked {
return mulDiv(amount, BP_BASIS, BP_BASIS + basisPoints);
}
}
/**
* @notice Checks if a value is within a range
* @param value Value to check
* @param _min Minimum value
* @param _max Maximum value
* @return Boolean indicating if the value is within the range
*/
function within(uint256 value, uint256 _min, uint256 _max) internal pure returns (bool) {
unchecked {
return value >= _min && value <= _max;
}
}
function within(uint32 value, uint32 _min, uint32 _max) internal pure returns (bool) {
unchecked {
return value >= _min && value <= _max;
}
}
function within(uint64 value, uint64 _min, uint64 _max) internal pure returns (bool) {
unchecked {
return value >= _min && value <= _max;
}
}
function within(int256 value, int256 _min, int256 _max) internal pure returns (bool) {
unchecked {
return value >= _min && value <= _max;
}
}
function within32(uint32 value, uint256 _min, uint256 _max) internal pure returns (bool) {
unchecked {
return uint256(value) >= _min && uint256(value) <= _max;
}
}
function within64(uint64 value, uint256 _min, uint256 _max) internal pure returns (bool) {
unchecked {
return uint256(value) >= _min && uint256(value) <= _max;
}
}
/**
* @notice Checks if the difference between two values is within a specified range
* @param a First value
* @param b Second value
* @param val Allowable difference
* @return Boolean indicating if the difference is within the specified range
*/
function diffWithin(
uint256 a,
uint256 b,
uint256 val
) internal pure returns (bool) {
return diff(a, b) <= val;
}
/**
* @notice Checks if the difference between two values is within 1
* @param a First value
* @param b Second value
* @return Boolean indicating if the difference is within 1
*/
function diffWithin1(uint256 a, uint256 b) internal pure returns (bool) {
return diffWithin(a, b, 1);
}
/**
* @notice Calculates the absolute difference between two values
* @param a First value
* @param b Second value
* @return Absolute difference between the two values
*/
function diff(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
return a > b ? a - b : b - a;
}
}
/**
* @notice Subtracts a value from another with a minimum of 0
* @param a Initial value
* @param b Value to subtract
* @return Result of subtracting the value, with a minimum of 0
*/
function subMax0(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
return a >= b ? a - b : 0;
}
}
/**
* @notice Subtracts one integer from another with a requirement that the result is non-negative
* @param a Initial integer
* @param b Integer to subtract
* @return Result of subtracting the integer, with a requirement that the result is non-negative
*/
function subNoNeg(int256 a, int256 b) internal pure returns (int256) {
if (a < b) revert AsCast.ValueOutOfCastRange();
unchecked {
return a - b; // no unchecked since if b is very negative, a - b might overflow
}
}
/**
* @notice Multiplies two unsigned integers and round down to the nearest whole number
* @dev Uses unchecked to handle potential overflow situations
* @param a First unsigned integer
* @param b Second unsigned integer
* @return Result of multiplying and rounding down
*/
function mulDown(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
unchecked {
return product / 1e18;
}
}
/**
* @notice Multiplies two signed integers and round down to the nearest whole number
* @dev Uses unchecked to handle potential overflow situations
* @param a First signed integer
* @param b Second signed integer
* @return Result of multiplying and rounding down
*/
function mulDown(int256 a, int256 b) internal pure returns (int256) {
int256 product = a * b;
unchecked {
return product / 1e18;
}
}
/**
* @notice Divides one unsigned integer by another and round down to the nearest whole number
* @dev Uses unchecked to handle potential overflow situations
* @param a Numerator
* @param b Denominator
* @return Result of dividing and rounding down
*/
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 aInflated = a * 1e18;
unchecked {
return aInflated / b;
}
}
/**
* @notice Divides one signed integer by another and round down to the nearest whole number
* @dev Uses unchecked to handle potential overflow situations
* @param a Numerator
* @param b Denominator
* @return Result of dividing and rounding down
*/
function divDown(int256 a, int256 b) internal pure returns (int256) {
int256 aInflated = a * 1e18;
unchecked {
return aInflated / b;
}
}
/**
* @notice Divides one unsigned integer by another and round up to the nearest whole number
* @dev Uses unchecked to handle potential overflow situations
* @param a Numerator
* @param b Denominator
* @return Result of dividing and rounding up
*/
function rawDivUp(uint256 a, uint256 b) internal pure returns (uint256) {
return (a + b - 1) / b;
}
/**
* @notice Gets the absolute value of a signed integer
* @param x Input signed integer
* @return Absolute value of the input
*/
function abs(int256 x) internal pure returns (uint256) {
return
x == type(int256).min
? uint256(type(int256).max) + 1
: uint256(x > 0 ? x : -x);
}
/**
* @notice Negates a signed integer
* @param x Input signed integer
* @return Negated value of the input
*/
function neg(int256 x) internal pure returns (int256) {
return x * -1;
}
/**
* @notice Negates an unsigned integer
* @param x Input unsigned integer
* @return Negated value of the input as a signed integer
*/
function neg(uint256 x) internal pure returns (int256) {
return x.toInt256() * -1;
}
function max(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? x : y;
}
function max(int256 x, int256 y) internal pure returns (int256) {
return x > y ? x : y;
}
function min(uint256 x, uint256 y) internal pure returns (uint256) {
return x < y ? x : y;
}
function min(int256 x, int256 y) internal pure returns (int256) {
return x < y ? x : y;
}
/**
* @notice Checks if two unsigned integers are approximately equal within a specified tolerance
* @dev Uses `mulDown` for the comparison to handle precision loss
* @param a First unsigned integer
* @param b Second unsigned integer
* @param eps Maximum allowable difference between `a` and `b`
* @return Boolean indicating whether the two values are approximately equal
*/
function approxEq(
uint256 a,
uint256 b,
uint256 eps
) internal pure returns (bool) {
return mulDown(b, WAD - eps) <= a && a <= mulDown(b, WAD + eps);
}
/**
* @notice Checks if one unsigned integer is approximately greater than another within a specified tolerance
* @dev Uses `mulDown` for the comparison to handle precision loss
* @param a First unsigned integer
* @param b Second unsigned integer
* @param eps Maximum allowable difference between `a` and `b`
* @return Boolean indicating whether `a` is approximately greater than `b`
*/
function approxGt(
uint256 a,
uint256 b,
uint256 eps
) internal pure returns (bool) {
return a >= b && a <= mulDown(b, WAD + eps);
}
/**
* @notice Checks if one unsigned integer is approximately less than another within a specified tolerance
* @dev Uses `mulDown` for the comparison to handle precision loss
* @param a First unsigned integer
* @param b Second unsigned integer
* @param eps Maximum allowable difference between `a` and `b`
* @return Boolean indicating whether `a` is approximately less than `b`
*/
function approxLt(
uint256 a,
uint256 b,
uint256 eps
) internal pure returns (bool) {
return a <= b && a >= mulDown(b, WAD - eps);
}
/**
* @notice Attempts to add two unsigned integers with overflow protection
* @dev Uses unchecked to handle potential overflow situations
* @param a First unsigned integer
* @param b Second unsigned integer
* @return Tuple with a boolean indicating success and the result of the addition
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) {
// overflow occurred
return (false, 0);
}
return (true, c);
}
}
/**
* @notice Attempts to subtract one unsigned integer from another with overflow protection
* @dev Uses unchecked to handle potential overflow situations
* @param a First unsigned integer
* @param b Second unsigned integer
* @return Tuple with a boolean indicating success and the result of the subtraction
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) {
// underflow occurred
return (false, 0);
}
return (true, a - b);
}
}
/**
* @notice Attempts to multiply two unsigned integers with overflow protection
* @dev Uses unchecked to handle potential overflow situations
* @param a First unsigned integer
* @param b Second unsigned integer
* @return Tuple with a boolean indicating success and the result of the multiplication
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested
// see: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return (true, 0);
}
uint256 c = a * b;
if (c / a != b) {
// overflow occurred
return (false, 0);
}
return (true, c);
}
}
/**
* @notice Returnss the division of two unsigned integers, with a division by zero flag
* @param a Numerator
* @param b Denominator
* @return Tuple with a boolean indicating success and the result of the division
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @notice Returns the remainder of dividing two unsigned integers, with a division by zero flag
* @param a Numerator
* @param b Denominator
* @return Tuple with a boolean indicating success and the result of the remainder
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @notice Returns the average of two numbers. Result is rounded towards zero
* @param a First number
* @param b Second number
* @return Average of the two numbers
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow
return (a & b) + (a ^ b) / 2;
}
/**
* @notice Returns the ceiling of the division of two numbers
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero
* @param a Numerator
* @param b Denominator
* @return Ceiling of the division
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// guarantee the same behavior as in a regular Solidity division
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license
* @param x Numerator
* @param y Numerator
* @param denominator Denominator
* @return result Result of floor(x * y / denominator)
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y
// compute the product mod 2^256 and mod 2^256 - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result
// the result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0
uint256 prod0 = x * y; // least significant 256 bits of the product
uint256 prod1; // most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
// solidity will revert if denominator == 0, unlike the div opcode on its own
// the surrounding unchecked block does not change this fact
// see https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic
return prod0 / denominator;
}
// make sure the result is less than 2^256, also prevents denominator == 0
require(denominator > prod1);
// 512 by 256 division
// make division exact by subtracting the remainder from [prod1 prod0]
uint256 remainder;
assembly {
// compute remainder using mulmod
remainder := mulmod(x, y, denominator)
// subtract 256 bit number from 512 bit number
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// factor powers of two out of denominator and compute the largest power of two divisor of denominator
// always >= 1. See https://cs.stackexchange.com/q/138556/92363
uint256 twos = denominator & (0 - denominator);
assembly {
// divide denominator by twos
denominator := div(denominator, twos)
// divide [prod1 prod0] by twos
prod0 := div(prod0, twos)
// flip twos such that it is 2^256 / twos, if twos is zero, then it becomes one
twos := add(div(sub(0, twos), twos), 1)
}
// shift in bits from prod1 into prod0
prod0 |= prod1 * twos;
// invert denominator mod 2^256, now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256, compute the inverse by starting with a seed that is correct for
// four bits, that is, denominator * inv = 1 mod 2^4
uint256 inverse = (3 * denominator) ^ 2;
// use the Newton-Raphson iteration to improve the precision, thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// because the division is now exact we can divide by multiplying with the modular inverse of denominator
// this will give us the correct result modulo 2^256
// since the preconditions guarantee that the outcome is less than 2^256, this is the final result
// we don't need to compute the high bits of the result and prod1
// is no longer required
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction
* @param x Numerator
* @param y Numerator
* @param denominator Denominator
* @param rounding Rounding direction
* @return Result of x * y / denominator with the specified rounding
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator,
Rounding rounding
) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @notice Calculates x * y / denominator with full precision, rounded up
* @param x Numerator
* @param y Numerator
* @param denominator Denominator
* @return Result of x * y / denominator rounded up
*/
function mulDivRoundUp(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256) {
return mulDiv(x, y, denominator, Rounding.Ceil);
}
/**
* @notice Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero
* @param a Input value
* @return Square root of the input value
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// for our first guess, we get the biggest power of 2 which is smaller than the square root of the target
//
// we know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`
// this value can be written `msb(a)=2**k` with `k=log2(a)`
// this can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit
uint256 result = 1 << (log2(a) >> 1);
// at this point `result` is an estimation with one bit of precision
// we know the true value is a uint128, since it is the square root of a uint256
// newton's method converges quadratically (precision doubles at every iteration)
// we thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction
* @param a Input value
* @param rounding Rounding direction
* @return Square root of the input value with the specified rounding
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return
result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @notice Returns the cube root of a number. If the number is not a perfect cube, the value is rounded
* towards zero
* @param a Input value
* @return s Cube root of the input value
*/
function cbrt(uint256 a) internal pure returns (uint256 s) {
/// @solidity memory-safe-assembly
assembly {
let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, a))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, a))))
r := or(r, shl(5, lt(0xffffffff, shr(r, a))))
r := or(r, shl(4, lt(0xffff, shr(r, a))))
r := or(r, shl(3, lt(0xff, shr(r, a))))
s := div(shl(div(r, 3), shl(lt(0xf, shr(r, a)), 0xf)), xor(7, mod(r, 3)))
s := div(add(add(div(a, mul(s, s)), s), s), 3)
s := div(add(add(div(a, mul(s, s)), s), s), 3)
s := div(add(add(div(a, mul(s, s)), s), s), 3)
s := div(add(add(div(a, mul(s, s)), s), s), 3)
s := div(add(add(div(a, mul(s, s)), s), s), 3)
s := div(add(add(div(a, mul(s, s)), s), s), 3)
s := div(add(add(div(a, mul(s, s)), s), s), 3)
s := sub(s, lt(div(a, mul(s, s)), s))
}
}
/**
* @notice Returns the log in base 2 of a positive value rounded towards zero
* Returns 0 if given 0
* @param value Input value
* @return Log in base 2 of the input value
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @notice Returns the log in base 2, following the selected rounding direction, of a positive value
* Returns 0 if given 0
* @param value Input value
* @param rounding Rounding direction
* @return Log in base 2 of the input value with the specified rounding
*/
function log2(
uint256 value,
Rounding rounding
) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return
result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @notice Returns the log in base 10 of a positive value rounded towards zero
* Returns 0 if given 0
* @param value Input value
* @return Log in base 10 of the input value
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @notice Returns the log in base 10, following the selected rounding direction, of a positive value
* Returns 0 if given 0
* @param value Input value
* @param rounding Rounding direction
* @return Log in base 10 of the input value with the specified rounding
*/
function log10(
uint256 value,
Rounding rounding
) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return
result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @notice Returns the log in base 256 of a positive value rounded towards zero
* Returns 0 if given 0
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string
* @param value Input value
* @return Log in base 256 of the input value
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @notice Returns the log in base 256, following the selected rounding direction, of a positive value
* Returns 0 if given 0
* @param value Input value
* @param rounding Rounding direction
* @return Log in base 256 of the input value with the specified rounding
*/
function log256(
uint256 value,
Rounding rounding
) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return
result +
(unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
function toWad32(uint32 bps) internal pure returns (uint256) {
unchecked {
return uint256(bps) * WAD / BP_BASIS;
}
}
function toWad(uint256 bps) internal pure returns (uint256) {
unchecked {
return bps * WAD / BP_BASIS;
}
}
function toBps(uint256 wad) internal pure returns (uint256) {
unchecked {
return wad * BP_BASIS / WAD;
}
}
function rayToBps(uint256 ray) internal pure returns (uint256) {
unchecked {
return ray * BP_BASIS / RAY;
}
}
function bpsToRay(uint256 bps) internal pure returns (uint256) {
unchecked {
return bps * RAY / BP_BASIS;
}
}
/**
* @notice Equivalent to `x` to the power of `y` denominated in `WAD` with `x` in `WAD`
* because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`
* Note: This function is an approximation
*/
function powWad(int256 x, int256 y) internal pure returns (int256) {
if (y == 0) return int256(WAD);
if (x == 0) return 0;
if (x == int256(WAD) || y == int256(WAD)) return x;
unchecked {
bool isNegative = x < 0 && y % 2 * int256(WAD) == int256(WAD);
x = x < 0 ? -x : x;
x = expWad((lnWad(x) * y) / int256(WAD)); // reuse x to store result
return isNegative ? -x : x;
}
}
/**
* @notice Returns `exp(x)`, denominated in `WAD`
* Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
* Note: This function is an approximation. Monotonically increasing
*/
function expWad(int256 x) internal pure returns (int256 r) {
unchecked {
// When the result is less than 0.5 we return zero
// This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`
if (x <= -41446531673892822313) return r;
/// @solidity memory-safe-assembly
assembly {
// When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
// an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`
if iszero(slt(x, 135305999368893231589)) {
mstore(0x00, 0xa37bfec9) // `ExpOverflow()`
revert(0x1c, 0x04)
}
}
// `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
// for more intermediate precision and a binary basis. This base conversion