@morpho-org/blue-sdk 1.0.0-integ-650.0

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/README.md +106 -0
  2. package/lib/addresses.d.ts +113 -0
  3. package/lib/addresses.js +162 -0
  4. package/lib/chain.d.ts +29 -0
  5. package/lib/chain.js +289 -0
  6. package/lib/chain.test.d.ts +1 -0
  7. package/lib/chain.test.js +21 -0
  8. package/lib/constants.d.ts +29 -0
  9. package/lib/constants.js +33 -0
  10. package/lib/errors.d.ts +58 -0
  11. package/lib/errors.js +119 -0
  12. package/lib/helpers/format/format.d.ts +122 -0
  13. package/lib/helpers/format/format.js +286 -0
  14. package/lib/helpers/format/format.test.d.ts +1 -0
  15. package/lib/helpers/format/format.test.js +255 -0
  16. package/lib/helpers/format/index.d.ts +1 -0
  17. package/lib/helpers/format/index.js +17 -0
  18. package/lib/helpers/index.d.ts +2 -0
  19. package/lib/helpers/index.js +18 -0
  20. package/lib/helpers/locale.d.ts +46 -0
  21. package/lib/helpers/locale.js +96 -0
  22. package/lib/holding/AssetBalances.d.ts +48 -0
  23. package/lib/holding/AssetBalances.js +42 -0
  24. package/lib/holding/Holding.d.ts +59 -0
  25. package/lib/holding/Holding.js +59 -0
  26. package/lib/holding/index.d.ts +2 -0
  27. package/lib/holding/index.js +18 -0
  28. package/lib/index.d.ts +25 -0
  29. package/lib/index.js +54 -0
  30. package/lib/market/Market.d.ts +329 -0
  31. package/lib/market/Market.js +460 -0
  32. package/lib/market/MarketConfig.d.ts +52 -0
  33. package/lib/market/MarketConfig.js +76 -0
  34. package/lib/market/MarketUtils.d.ts +232 -0
  35. package/lib/market/MarketUtils.js +263 -0
  36. package/lib/market/MarketUtils.test.d.ts +1 -0
  37. package/lib/market/MarketUtils.test.js +38 -0
  38. package/lib/market/index.d.ts +3 -0
  39. package/lib/market/index.js +19 -0
  40. package/lib/maths/AdaptiveCurveIrmLib.d.ts +39 -0
  41. package/lib/maths/AdaptiveCurveIrmLib.js +134 -0
  42. package/lib/maths/MathLib.d.ts +114 -0
  43. package/lib/maths/MathLib.js +175 -0
  44. package/lib/maths/SharesMath.d.ts +12 -0
  45. package/lib/maths/SharesMath.js +21 -0
  46. package/lib/maths/index.d.ts +3 -0
  47. package/lib/maths/index.js +19 -0
  48. package/lib/position/Position.d.ts +126 -0
  49. package/lib/position/Position.js +203 -0
  50. package/lib/position/index.d.ts +1 -0
  51. package/lib/position/index.js +17 -0
  52. package/lib/tests/mocks/markets.d.ts +19 -0
  53. package/lib/tests/mocks/markets.js +121 -0
  54. package/lib/token/ConstantWrappedToken.d.ts +18 -0
  55. package/lib/token/ConstantWrappedToken.js +36 -0
  56. package/lib/token/ExchangeRateWrappedToken.d.ts +11 -0
  57. package/lib/token/ExchangeRateWrappedToken.js +21 -0
  58. package/lib/token/Token.d.ts +46 -0
  59. package/lib/token/Token.js +64 -0
  60. package/lib/token/VaultToken.d.ts +14 -0
  61. package/lib/token/VaultToken.js +23 -0
  62. package/lib/token/WrappedToken.d.ts +17 -0
  63. package/lib/token/WrappedToken.js +33 -0
  64. package/lib/token/index.d.ts +5 -0
  65. package/lib/token/index.js +21 -0
  66. package/lib/types.d.ts +30 -0
  67. package/lib/types.js +22 -0
  68. package/lib/user/User.d.ts +20 -0
  69. package/lib/user/User.js +23 -0
  70. package/lib/user/index.d.ts +1 -0
  71. package/lib/user/index.js +17 -0
  72. package/lib/vault/Vault.d.ts +166 -0
  73. package/lib/vault/Vault.js +234 -0
  74. package/lib/vault/VaultConfig.d.ts +22 -0
  75. package/lib/vault/VaultConfig.js +32 -0
  76. package/lib/vault/VaultMarketAllocation.d.ts +20 -0
  77. package/lib/vault/VaultMarketAllocation.js +30 -0
  78. package/lib/vault/VaultMarketConfig.d.ts +43 -0
  79. package/lib/vault/VaultMarketConfig.js +43 -0
  80. package/lib/vault/VaultMarketPublicAllocatorConfig.d.ts +29 -0
  81. package/lib/vault/VaultMarketPublicAllocatorConfig.js +28 -0
  82. package/lib/vault/VaultUtils.d.ts +18 -0
  83. package/lib/vault/VaultUtils.js +20 -0
  84. package/lib/vault/index.d.ts +6 -0
  85. package/lib/vault/index.js +22 -0
  86. package/package.json +53 -0
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AdaptiveCurveIrmLib = void 0;
4
+ const constants_1 = require("../constants");
5
+ const MathLib_1 = require("./MathLib");
6
+ /**
7
+ * JS implementation of {@link https://github.com/morpho-org/morpho-blue-irm/blob/main/src/libraries/adaptive-curve/ExpLib.sol ExpLib} used by the Adaptive Curve IRM.
8
+ */
9
+ var AdaptiveCurveIrmLib;
10
+ (function (AdaptiveCurveIrmLib) {
11
+ AdaptiveCurveIrmLib.CURVE_STEEPNESS = 4000000000000000000n;
12
+ AdaptiveCurveIrmLib.TARGET_UTILIZATION = 900000000000000000n;
13
+ AdaptiveCurveIrmLib.INITIAL_RATE_AT_TARGET = 40000000000000000n / constants_1.SECONDS_PER_YEAR;
14
+ AdaptiveCurveIrmLib.ADJUSTMENT_SPEED = 50000000000000000000n / constants_1.SECONDS_PER_YEAR;
15
+ AdaptiveCurveIrmLib.MIN_RATE_AT_TARGET = 1000000000000000n / constants_1.SECONDS_PER_YEAR;
16
+ AdaptiveCurveIrmLib.MAX_RATE_AT_TARGET = 2000000000000000000n / constants_1.SECONDS_PER_YEAR;
17
+ /**
18
+ * ln(2), scaled by WAD.
19
+ */
20
+ AdaptiveCurveIrmLib.LN_2_INT = 693147180559945309n;
21
+ /**
22
+ * ln(1e-18), scaled by WAD.
23
+ */
24
+ AdaptiveCurveIrmLib.LN_WEI_INT = -41446531673892822312n;
25
+ /**
26
+ * Above this bound, `wExp` is clipped to avoid overflowing when multiplied with 1 ether.
27
+ * This upper bound corresponds to: ln(type(int256).max / 1e36) (scaled by WAD, floored).
28
+ */
29
+ AdaptiveCurveIrmLib.WEXP_UPPER_BOUND = 93859467695000404319n;
30
+ /**
31
+ * The value of wExp(`WEXP_UPPER_BOUND`).
32
+ */
33
+ AdaptiveCurveIrmLib.WEXP_UPPER_VALUE = 57716089161558943949701069502944508345128422502756744429568n;
34
+ /**
35
+ * Returns an approximation of exp(x) used by the Adaptive Curve IRM.
36
+ * @param x
37
+ */
38
+ function wExp(x) {
39
+ x = BigInt(x);
40
+ // If x < ln(1e-18) then exp(x) < 1e-18 so it is rounded to zero.
41
+ if (x < AdaptiveCurveIrmLib.LN_WEI_INT)
42
+ return 0n;
43
+ // `wExp` is clipped to avoid overflowing when multiplied with 1 ether.
44
+ if (x >= AdaptiveCurveIrmLib.WEXP_UPPER_BOUND)
45
+ return AdaptiveCurveIrmLib.WEXP_UPPER_VALUE;
46
+ // Decompose x as x = q * ln(2) + r with q an integer and -ln(2)/2 <= r <= ln(2)/2.
47
+ // q = x / ln(2) rounded half toward zero.
48
+ const roundingAdjustment = x < 0n ? -(AdaptiveCurveIrmLib.LN_2_INT / 2n) : AdaptiveCurveIrmLib.LN_2_INT / 2n;
49
+ const q = (x + roundingAdjustment) / AdaptiveCurveIrmLib.LN_2_INT;
50
+ const r = x - q * AdaptiveCurveIrmLib.LN_2_INT;
51
+ // Compute e^r with a 2nd-order Taylor polynomial.
52
+ const expR = MathLib_1.MathLib.WAD + r + (r * r) / MathLib_1.MathLib.WAD / 2n;
53
+ // Return e^x = 2^q * e^r.
54
+ if (q === 0n)
55
+ return expR << q;
56
+ return expR >> -q;
57
+ }
58
+ AdaptiveCurveIrmLib.wExp = wExp;
59
+ function getBorrowRate(startUtilization, startRateAtTarget, elapsed) {
60
+ startUtilization = BigInt(startUtilization);
61
+ startRateAtTarget = BigInt(startRateAtTarget);
62
+ elapsed = BigInt(elapsed);
63
+ const errNormFactor = startUtilization > AdaptiveCurveIrmLib.TARGET_UTILIZATION
64
+ ? MathLib_1.MathLib.WAD - AdaptiveCurveIrmLib.TARGET_UTILIZATION
65
+ : AdaptiveCurveIrmLib.TARGET_UTILIZATION;
66
+ const err = MathLib_1.MathLib.wDivDown(startUtilization - AdaptiveCurveIrmLib.TARGET_UTILIZATION, errNormFactor);
67
+ let avgRateAtTarget;
68
+ let endRateAtTarget;
69
+ if (startRateAtTarget === 0n) {
70
+ // First interaction.
71
+ avgRateAtTarget = AdaptiveCurveIrmLib.INITIAL_RATE_AT_TARGET;
72
+ endRateAtTarget = AdaptiveCurveIrmLib.INITIAL_RATE_AT_TARGET;
73
+ }
74
+ else {
75
+ // The speed is assumed constant between two updates, but it is in fact not constant because of interest.
76
+ // So the rate is always underestimated.
77
+ const speed = MathLib_1.MathLib.wMulDown(AdaptiveCurveIrmLib.ADJUSTMENT_SPEED, err);
78
+ const linearAdaptation = speed * elapsed;
79
+ if (linearAdaptation === 0n) {
80
+ // If linearAdaptation == 0, avgRateAtTarget = endRateAtTarget = startRateAtTarget;
81
+ avgRateAtTarget = startRateAtTarget;
82
+ endRateAtTarget = startRateAtTarget;
83
+ }
84
+ else {
85
+ // Non negative because MIN_RATE_AT_TARGET > 0.
86
+ const _newRateAtTarget = (linearAdaptation) => MathLib_1.MathLib.min(MathLib_1.MathLib.max(MathLib_1.MathLib.wMulDown(startRateAtTarget, wExp(linearAdaptation)), AdaptiveCurveIrmLib.MIN_RATE_AT_TARGET), AdaptiveCurveIrmLib.MAX_RATE_AT_TARGET);
87
+ // Formula of the average rate that should be returned to Morpho Blue:
88
+ // avg = 1/T * ∫_0^T curve(startRateAtTarget*exp(speed*x), err) dx
89
+ // The integral is approximated with the trapezoidal rule:
90
+ // avg ~= 1/T * Σ_i=1^N [curve(f((i-1) * T/N), err) + curve(f(i * T/N), err)] / 2 * T/N
91
+ // Where f(x) = startRateAtTarget*exp(speed*x)
92
+ // avg ~= Σ_i=1^N [curve(f((i-1) * T/N), err) + curve(f(i * T/N), err)] / (2 * N)
93
+ // As curve is linear in its first argument:
94
+ // avg ~= curve([Σ_i=1^N [f((i-1) * T/N) + f(i * T/N)] / (2 * N), err)
95
+ // avg ~= curve([(f(0) + f(T))/2 + Σ_i=1^(N-1) f(i * T/N)] / N, err)
96
+ // avg ~= curve([(startRateAtTarget + endRateAtTarget)/2 + Σ_i=1^(N-1) f(i * T/N)] / N, err)
97
+ // With N = 2:
98
+ // avg ~= curve([(startRateAtTarget + endRateAtTarget)/2 + startRateAtTarget*exp(speed*T/2)] / 2, err)
99
+ // avg ~= curve([startRateAtTarget + endRateAtTarget + 2*startRateAtTarget*exp(speed*T/2)] / 4, err)
100
+ endRateAtTarget = _newRateAtTarget(linearAdaptation);
101
+ avgRateAtTarget =
102
+ (startRateAtTarget +
103
+ endRateAtTarget +
104
+ 2n * _newRateAtTarget(linearAdaptation / 2n)) /
105
+ 4n;
106
+ }
107
+ }
108
+ // Non negative because 1 - 1/C >= 0, C - 1 >= 0.
109
+ const coeff = err < 0
110
+ ? MathLib_1.MathLib.WAD - MathLib_1.MathLib.wDivDown(MathLib_1.MathLib.WAD, AdaptiveCurveIrmLib.CURVE_STEEPNESS)
111
+ : AdaptiveCurveIrmLib.CURVE_STEEPNESS - MathLib_1.MathLib.WAD;
112
+ // Non negative if avgRateAtTarget >= 0 because if err < 0, coeff <= 1.
113
+ return {
114
+ avgBorrowRate: MathLib_1.MathLib.wMulDown(MathLib_1.MathLib.wMulDown(coeff, err) + MathLib_1.MathLib.WAD, avgRateAtTarget),
115
+ endRateAtTarget,
116
+ };
117
+ }
118
+ AdaptiveCurveIrmLib.getBorrowRate = getBorrowRate;
119
+ function getUtilizationAtBorrowRate(borrowRate, rateAtTarget) {
120
+ borrowRate = BigInt(borrowRate);
121
+ rateAtTarget = BigInt(rateAtTarget);
122
+ if (borrowRate >= rateAtTarget) {
123
+ const maxBorrowRate = MathLib_1.MathLib.wMulDown(rateAtTarget, AdaptiveCurveIrmLib.CURVE_STEEPNESS);
124
+ const diffToMaxBorrowRate = maxBorrowRate - rateAtTarget;
125
+ if (diffToMaxBorrowRate === 0n)
126
+ return MathLib_1.MathLib.WAD;
127
+ return MathLib_1.MathLib.min(MathLib_1.MathLib.WAD, AdaptiveCurveIrmLib.TARGET_UTILIZATION +
128
+ MathLib_1.MathLib.mulDivDown(MathLib_1.MathLib.WAD - AdaptiveCurveIrmLib.TARGET_UTILIZATION, borrowRate - rateAtTarget, diffToMaxBorrowRate));
129
+ }
130
+ const minBorrowRate = MathLib_1.MathLib.wDivDown(rateAtTarget, AdaptiveCurveIrmLib.CURVE_STEEPNESS);
131
+ return MathLib_1.MathLib.max(0n, MathLib_1.MathLib.mulDivDown(AdaptiveCurveIrmLib.TARGET_UTILIZATION, borrowRate - minBorrowRate, rateAtTarget - minBorrowRate));
132
+ }
133
+ AdaptiveCurveIrmLib.getUtilizationAtBorrowRate = getUtilizationAtBorrowRate;
134
+ })(AdaptiveCurveIrmLib || (exports.AdaptiveCurveIrmLib = AdaptiveCurveIrmLib = {}));
@@ -0,0 +1,114 @@
1
+ import { Time } from "@morpho-org/morpho-ts";
2
+ import { BigIntish } from "../types";
3
+ export type RoundingDirection = "Up" | "Down";
4
+ /**
5
+ * Library to manage fixed-point arithmetic.
6
+ * This library reproduces the behaviour of the solidity library MathLib
7
+ * TODO: add library link
8
+ * @category Maths
9
+ *
10
+ */
11
+ export declare class MathLib {
12
+ static WAD: bigint;
13
+ static MAX_UINT_256: bigint;
14
+ static MAX_UINT_160: bigint;
15
+ static MAX_UINT_128: bigint;
16
+ static MAX_UINT_48: bigint;
17
+ static maxUint(nBits: number): bigint;
18
+ /**
19
+ * Returns the absolute value of a number
20
+ * @param a The number
21
+ */
22
+ static abs(a: BigIntish): bigint;
23
+ /**
24
+ * Returns the smallest number given as param
25
+ * @param x The first number
26
+ * @param y The second number
27
+ */
28
+ static min(...xs: BigIntish[]): bigint;
29
+ /**
30
+ * Returns the greatest number given as param
31
+ * @param x The first number
32
+ * @param y The second number
33
+ */
34
+ static max(...xs: BigIntish[]): bigint;
35
+ /**
36
+ * Returns the subtraction of b from a, floored to zero if negative
37
+ * @param x The first number
38
+ * @param y The second number
39
+ */
40
+ static zeroFloorSub(x: BigIntish, y: BigIntish): bigint;
41
+ /**
42
+ * Perform the WAD-based multiplication of 2 numbers, rounded down
43
+ * @param x The first number
44
+ * @param y The second number
45
+ */
46
+ static wMulDown(x: BigIntish, y: BigIntish): bigint;
47
+ /**
48
+ * Perform the WAD-based multiplication of 2 numbers, rounded up
49
+ * @param x The first number
50
+ * @param y The second number
51
+ */
52
+ static wMulUp(x: BigIntish, y: BigIntish): bigint;
53
+ /**
54
+ * Perform the WAD-based multiplication of 2 numbers with a provided rounding direction
55
+ * @param x The first number
56
+ * @param y The second number
57
+ */
58
+ static wMul(x: BigIntish, y: BigIntish, rounding: RoundingDirection): bigint;
59
+ /**
60
+ * Perform the WAD-based division of 2 numbers, rounded down
61
+ * @param x The first number
62
+ * @param y The second number
63
+ */
64
+ static wDivDown(x: BigIntish, y: BigIntish): bigint;
65
+ /**
66
+ * Perform the WAD-based multiplication of 2 numbers, rounded up
67
+ * @param x The first number
68
+ * @param y The second number
69
+ */
70
+ static wDivUp(x: BigIntish, y: BigIntish): bigint;
71
+ /**
72
+ * Perform the WAD-based multiplication of 2 numbers with a provided rounding direction
73
+ * @param x The first number
74
+ * @param y The second number
75
+ */
76
+ static wDiv(x: BigIntish, y: BigIntish, rounding: RoundingDirection): bigint;
77
+ /**
78
+ * Multiply two numbers and divide by a denominator, rounding down the result
79
+ * @param x The first number
80
+ * @param y The second number
81
+ * @param denominator The denominator
82
+ */
83
+ static mulDivDown(x: BigIntish, y: BigIntish, denominator: BigIntish): bigint;
84
+ /**
85
+ * Multiply two numbers and divide by a denominator, rounding up the result
86
+ * @param x The first number
87
+ * @param y The second number
88
+ * @param denominator The denominator
89
+ */
90
+ static mulDivUp(x: BigIntish, y: BigIntish, denominator: BigIntish): bigint;
91
+ static mulDiv(x: BigIntish, y: BigIntish, denominator: BigIntish, rounding: RoundingDirection): bigint;
92
+ /**
93
+ * The sum of the first three non-zero terms of a Taylor expansion of e^(nx) - 1,
94
+ * to approximate a continuous compound interest rate.
95
+ *
96
+ * @param x The base of the exponent
97
+ * @param n The exponent
98
+ */
99
+ static wTaylorCompounded(x: BigIntish, n: BigIntish): bigint;
100
+ /**
101
+ * Converts an rate to compounded apy
102
+ *
103
+ * @param rate The rate to convert (in WAD)
104
+ * @param period The compounding basis
105
+ */
106
+ static rateToApy(rate: BigIntish, period: Time.PeriodLike): number;
107
+ /**
108
+ * Converts an apr to compounded apy
109
+ *
110
+ * @param apr The apr to convert (in WAD)
111
+ * @param compounding The compounding basis
112
+ */
113
+ static aprToApy(apr: BigIntish, compounding: Time.PeriodLike): number;
114
+ }
@@ -0,0 +1,175 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MathLib = void 0;
4
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
5
+ const helpers_1 = require("../helpers");
6
+ /**
7
+ * Library to manage fixed-point arithmetic.
8
+ * This library reproduces the behaviour of the solidity library MathLib
9
+ * TODO: add library link
10
+ * @category Maths
11
+ *
12
+ */
13
+ class MathLib {
14
+ static WAD = 1000000000000000000n;
15
+ static MAX_UINT_256 = MathLib.maxUint(256);
16
+ static MAX_UINT_160 = MathLib.maxUint(160);
17
+ static MAX_UINT_128 = MathLib.maxUint(128);
18
+ static MAX_UINT_48 = MathLib.maxUint(48);
19
+ static maxUint(nBits) {
20
+ if (nBits % 4 !== 0)
21
+ throw new Error(`Invalid number of bits: ${nBits}`);
22
+ return BigInt("0x" + "f".repeat(nBits / 4));
23
+ }
24
+ /**
25
+ * Returns the absolute value of a number
26
+ * @param a The number
27
+ */
28
+ static abs(a) {
29
+ a = BigInt(a);
30
+ return a >= 0 ? a : -a;
31
+ }
32
+ /**
33
+ * Returns the smallest number given as param
34
+ * @param x The first number
35
+ * @param y The second number
36
+ */
37
+ static min(...xs) {
38
+ return xs.map(BigInt).reduce((x, y) => (x <= y ? x : y));
39
+ }
40
+ /**
41
+ * Returns the greatest number given as param
42
+ * @param x The first number
43
+ * @param y The second number
44
+ */
45
+ static max(...xs) {
46
+ return xs.map(BigInt).reduce((x, y) => (x <= y ? y : x));
47
+ }
48
+ /**
49
+ * Returns the subtraction of b from a, floored to zero if negative
50
+ * @param x The first number
51
+ * @param y The second number
52
+ */
53
+ static zeroFloorSub(x, y) {
54
+ x = BigInt(x);
55
+ y = BigInt(y);
56
+ return x <= y ? 0n : x - y;
57
+ }
58
+ /**
59
+ * Perform the WAD-based multiplication of 2 numbers, rounded down
60
+ * @param x The first number
61
+ * @param y The second number
62
+ */
63
+ static wMulDown(x, y) {
64
+ return MathLib.wMul(x, y, "Down");
65
+ }
66
+ /**
67
+ * Perform the WAD-based multiplication of 2 numbers, rounded up
68
+ * @param x The first number
69
+ * @param y The second number
70
+ */
71
+ static wMulUp(x, y) {
72
+ return MathLib.wMul(x, y, "Up");
73
+ }
74
+ /**
75
+ * Perform the WAD-based multiplication of 2 numbers with a provided rounding direction
76
+ * @param x The first number
77
+ * @param y The second number
78
+ */
79
+ static wMul(x, y, rounding) {
80
+ return MathLib.mulDiv(x, y, MathLib.WAD, rounding);
81
+ }
82
+ /**
83
+ * Perform the WAD-based division of 2 numbers, rounded down
84
+ * @param x The first number
85
+ * @param y The second number
86
+ */
87
+ static wDivDown(x, y) {
88
+ return MathLib.wDiv(x, y, "Down");
89
+ }
90
+ /**
91
+ * Perform the WAD-based multiplication of 2 numbers, rounded up
92
+ * @param x The first number
93
+ * @param y The second number
94
+ */
95
+ static wDivUp(x, y) {
96
+ return MathLib.wDiv(x, y, "Up");
97
+ }
98
+ /**
99
+ * Perform the WAD-based multiplication of 2 numbers with a provided rounding direction
100
+ * @param x The first number
101
+ * @param y The second number
102
+ */
103
+ static wDiv(x, y, rounding) {
104
+ return MathLib.mulDiv(x, MathLib.WAD, y, rounding);
105
+ }
106
+ /**
107
+ * Multiply two numbers and divide by a denominator, rounding down the result
108
+ * @param x The first number
109
+ * @param y The second number
110
+ * @param denominator The denominator
111
+ */
112
+ static mulDivDown(x, y, denominator) {
113
+ x = BigInt(x);
114
+ y = BigInt(y);
115
+ denominator = BigInt(denominator);
116
+ if (denominator === 0n)
117
+ throw Error("MathLib: DIVISION_BY_ZERO");
118
+ return (x * y) / denominator;
119
+ }
120
+ /**
121
+ * Multiply two numbers and divide by a denominator, rounding up the result
122
+ * @param x The first number
123
+ * @param y The second number
124
+ * @param denominator The denominator
125
+ */
126
+ static mulDivUp(x, y, denominator) {
127
+ x = BigInt(x);
128
+ y = BigInt(y);
129
+ denominator = BigInt(denominator);
130
+ if (denominator === 0n)
131
+ throw Error("MathLib: DIVISION_BY_ZERO");
132
+ const roundup = (x * y) % denominator > 0 ? 1n : 0n;
133
+ return (x * y) / denominator + roundup;
134
+ }
135
+ static mulDiv(x, y, denominator, rounding) {
136
+ return MathLib[`mulDiv${rounding}`](x, y, denominator);
137
+ }
138
+ /**
139
+ * The sum of the first three non-zero terms of a Taylor expansion of e^(nx) - 1,
140
+ * to approximate a continuous compound interest rate.
141
+ *
142
+ * @param x The base of the exponent
143
+ * @param n The exponent
144
+ */
145
+ static wTaylorCompounded(x, n) {
146
+ const firstTerm = BigInt(x) * BigInt(n);
147
+ const secondTerm = MathLib.mulDivDown(firstTerm, firstTerm, 2n * MathLib.WAD);
148
+ const thirdTerm = MathLib.mulDivDown(secondTerm, firstTerm, 3n * MathLib.WAD);
149
+ return firstTerm + secondTerm + thirdTerm;
150
+ }
151
+ /**
152
+ * Converts an rate to compounded apy
153
+ *
154
+ * @param rate The rate to convert (in WAD)
155
+ * @param period The compounding basis
156
+ */
157
+ static rateToApy(rate, period) {
158
+ const { unit, duration } = morpho_ts_1.Time.toPeriod(period);
159
+ const factor = morpho_ts_1.Time[unit].from.y(1) / duration;
160
+ return ((1 + Number(helpers_1.format.number.locale("en").of(BigInt(rate), 18))) ** factor -
161
+ 1);
162
+ }
163
+ /**
164
+ * Converts an apr to compounded apy
165
+ *
166
+ * @param apr The apr to convert (in WAD)
167
+ * @param compounding The compounding basis
168
+ */
169
+ static aprToApy(apr, compounding) {
170
+ const { unit, duration } = morpho_ts_1.Time.toPeriod(compounding);
171
+ const rate = (BigInt(apr) * BigInt(duration)) / morpho_ts_1.Time[unit].from.y(1n);
172
+ return this.rateToApy(rate, compounding);
173
+ }
174
+ }
175
+ exports.MathLib = MathLib;
@@ -0,0 +1,12 @@
1
+ import { BigIntish } from "../types";
2
+ import { RoundingDirection } from "./MathLib";
3
+ /**
4
+ * JS implementation of {@link https://github.com/morpho-org/morpho-blue/blob/main/src/libraries/SharesMathLib.sol SharesMathLib} used by Morpho Blue
5
+ * & MetaMorpho (via {@link https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/ERC4626.sol ERC4626}).
6
+ */
7
+ export declare namespace SharesMath {
8
+ const VIRTUAL_SHARES = 1000000n;
9
+ const VIRTUAL_ASSETS = 1n;
10
+ function toAssets(shares: BigIntish, totalAssets: BigIntish, totalShares: BigIntish, rounding: RoundingDirection): bigint;
11
+ function toShares(assets: BigIntish, totalAssets: BigIntish, totalShares: BigIntish, rounding: RoundingDirection): bigint;
12
+ }
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SharesMath = void 0;
4
+ const MathLib_1 = require("./MathLib");
5
+ /**
6
+ * JS implementation of {@link https://github.com/morpho-org/morpho-blue/blob/main/src/libraries/SharesMathLib.sol SharesMathLib} used by Morpho Blue
7
+ * & MetaMorpho (via {@link https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/ERC4626.sol ERC4626}).
8
+ */
9
+ var SharesMath;
10
+ (function (SharesMath) {
11
+ SharesMath.VIRTUAL_SHARES = 1000000n;
12
+ SharesMath.VIRTUAL_ASSETS = 1n;
13
+ function toAssets(shares, totalAssets, totalShares, rounding) {
14
+ return MathLib_1.MathLib.mulDiv(shares, BigInt(totalAssets) + SharesMath.VIRTUAL_ASSETS, BigInt(totalShares) + SharesMath.VIRTUAL_SHARES, rounding);
15
+ }
16
+ SharesMath.toAssets = toAssets;
17
+ function toShares(assets, totalAssets, totalShares, rounding) {
18
+ return MathLib_1.MathLib.mulDiv(assets, BigInt(totalShares) + SharesMath.VIRTUAL_SHARES, BigInt(totalAssets) + SharesMath.VIRTUAL_ASSETS, rounding);
19
+ }
20
+ SharesMath.toShares = toShares;
21
+ })(SharesMath || (exports.SharesMath = SharesMath = {}));
@@ -0,0 +1,3 @@
1
+ export * from "./MathLib";
2
+ export * from "./SharesMath";
3
+ export * from "./AdaptiveCurveIrmLib";
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./MathLib"), exports);
18
+ __exportStar(require("./SharesMath"), exports);
19
+ __exportStar(require("./AdaptiveCurveIrmLib"), exports);
@@ -0,0 +1,126 @@
1
+ import { Market, MaxBorrowOptions, MaxWithdrawCollateralOptions } from "../market";
2
+ import { Address, BigIntish, MarketId } from "../types";
3
+ export interface InputPosition {
4
+ user: Address;
5
+ marketId: MarketId;
6
+ supplyShares: bigint;
7
+ borrowShares: bigint;
8
+ collateral: bigint;
9
+ }
10
+ export declare class Position implements InputPosition {
11
+ /**
12
+ * The user holding this position.
13
+ */
14
+ readonly user: Address;
15
+ /**
16
+ * The id of the market on which this position is held.
17
+ */
18
+ readonly marketId: MarketId;
19
+ /**
20
+ * The amount of supply shares held with this position.
21
+ */
22
+ supplyShares: bigint;
23
+ /**
24
+ * The amount of borrow shares held with this position.
25
+ */
26
+ borrowShares: bigint;
27
+ /**
28
+ * The amount of collateral assets held with this position.
29
+ */
30
+ collateral: bigint;
31
+ constructor({ user, marketId, supplyShares, borrowShares, collateral, }: InputPosition);
32
+ }
33
+ export interface InputAccrualPosition extends Omit<InputPosition, "marketId"> {
34
+ }
35
+ export declare class AccrualPosition extends Position implements InputAccrualPosition {
36
+ /**
37
+ * The market on which this position is held.
38
+ */
39
+ readonly market: Market;
40
+ constructor(position: InputAccrualPosition, market: Market);
41
+ get supplyAssets(): bigint;
42
+ get borrowAssets(): bigint;
43
+ /**
44
+ * The value of this position's collateral quoted in loan assets.
45
+ */
46
+ get collateralValue(): bigint;
47
+ /**
48
+ * The maximum amount of loan assets that can be borrowed against this position's collateral.
49
+ */
50
+ get maxBorrowAssets(): bigint;
51
+ /**
52
+ * The maximum additional amount of assets that can be borrowed against this position's collateral.
53
+ */
54
+ get maxBorrowableAssets(): bigint;
55
+ /**
56
+ * The maximum amount of collateral that can be seized in exchange for the outstanding debt.
57
+ */
58
+ get seizableCollateral(): bigint;
59
+ /**
60
+ * The maximum amount of collateral that can be withdrawn.
61
+ */
62
+ get withdrawableCollateral(): bigint;
63
+ /**
64
+ * Whether this position is healthy.
65
+ */
66
+ get isHealthy(): boolean;
67
+ /**
68
+ * The price of the collateral quoted in loan assets that would allow this position to be liquidated.
69
+ */
70
+ get liquidationPrice(): bigint | null;
71
+ /**
72
+ * The variation of the price of the collateral quoted in loan assets that would allow this position to be liquidated,
73
+ * relative to the current collateral price (scaled by WAD).
74
+ */
75
+ get priceVariationToLiquidation(): bigint | null;
76
+ /**
77
+ * This position's Loan-To-Value (debt over collateral power, scaled by WAD).
78
+ * If the collateral price is 0, LTV is `MaxUint256`.
79
+ */
80
+ get ltv(): bigint | null;
81
+ /**
82
+ * This position's health factor (collateral power over debt, scaled by WAD).
83
+ * If the debt is 0, health factor is `MaxUint256`.
84
+ */
85
+ get healthFactor(): bigint | null;
86
+ /**
87
+ * The percentage of this position's borrow power currently used (scaled by WAD).
88
+ * If the collateral price is 0, usage is `MaxUint256`.
89
+ */
90
+ get borrowCapacityUsage(): bigint | null;
91
+ get borrowCapacityLimit(): import("../market").CapacityLimit;
92
+ get withdrawCapacityLimit(): import("../market").CapacityLimit;
93
+ get withdrawCollateralCapacityLimit(): import("../market").CapacityLimit;
94
+ /**
95
+ * Returns a new position derived from this position, whose interest has been accrued up to the given timestamp.
96
+ * @param timestamp The timestamp at which to accrue interest. Must be greater than or equal to the market's `lastUpdate`.
97
+ */
98
+ accrueInterest(timestamp?: BigIntish): AccrualPosition;
99
+ supply(assets: bigint, shares: bigint, timestamp?: BigIntish): {
100
+ position: AccrualPosition;
101
+ assets: bigint;
102
+ shares: bigint;
103
+ };
104
+ withdraw(assets: bigint, shares: bigint, timestamp?: BigIntish): {
105
+ position: AccrualPosition;
106
+ assets: bigint;
107
+ shares: bigint;
108
+ };
109
+ supplyCollateral(assets: bigint): AccrualPosition;
110
+ withdrawCollateral(assets: bigint, timestamp?: BigIntish): AccrualPosition;
111
+ borrow(assets: bigint, shares: bigint, timestamp?: BigIntish): {
112
+ position: AccrualPosition;
113
+ assets: bigint;
114
+ shares: bigint;
115
+ };
116
+ repay(assets: bigint, shares: bigint, timestamp?: BigIntish): {
117
+ position: AccrualPosition;
118
+ assets: bigint;
119
+ shares: bigint;
120
+ };
121
+ getRepayCapacityLimit(loanTokenBalance: bigint): import("../market").CapacityLimit;
122
+ getMaxCapacities(loanTokenBalance: bigint, collateralTokenBalance: bigint, options?: {
123
+ borrow?: MaxBorrowOptions;
124
+ withdrawCollateral?: MaxWithdrawCollateralOptions;
125
+ }): import("../market").MaxPositionCapacities;
126
+ }