@morpho-org/blue-sdk 1.0.2 → 1.0.4

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 (159) hide show
  1. package/lib/addresses.d.ts +156 -0
  2. package/lib/addresses.js +160 -0
  3. package/lib/chain/chain.constants.d.ts +3 -0
  4. package/lib/chain/chain.constants.js +232 -0
  5. package/lib/chain/chain.test.d.ts +1 -0
  6. package/lib/chain/chain.test.js +37 -0
  7. package/lib/chain/chain.types.d.ts +20 -0
  8. package/lib/chain/chain.types.js +30 -0
  9. package/lib/chain/chain.utils.d.ts +14 -0
  10. package/lib/chain/chain.utils.js +30 -0
  11. package/lib/chain/index.js +18 -0
  12. package/lib/constants.d.ts +8 -0
  13. package/lib/constants.js +13 -0
  14. package/lib/errors.d.ts +37 -0
  15. package/lib/errors.js +71 -0
  16. package/lib/ethers/ethers.test.d.ts +1 -0
  17. package/lib/ethers/ethers.test.js +11 -0
  18. package/lib/ethers/index.js +18 -0
  19. package/lib/ethers/safeGetAddress.d.ts +1 -0
  20. package/lib/ethers/safeGetAddress.js +6 -0
  21. package/lib/ethers/safeParseUnits.d.ts +2 -0
  22. package/lib/ethers/safeParseUnits.js +25 -0
  23. package/lib/evm.d.ts +36 -0
  24. package/lib/evm.js +113 -0
  25. package/lib/helpers/format/format.d.ts +98 -0
  26. package/lib/helpers/format/format.js +301 -0
  27. package/lib/helpers/format/format.test.d.ts +1 -0
  28. package/lib/helpers/format/format.test.js +257 -0
  29. package/lib/helpers/format/index.js +17 -0
  30. package/lib/helpers/getChecksumedAddress.d.ts +7 -0
  31. package/lib/helpers/getChecksumedAddress.js +17 -0
  32. package/lib/helpers/index.js +20 -0
  33. package/{src/helpers/isZeroAddressOrUnset.ts → lib/helpers/isZeroAddressOrUnset.d.ts} +1 -7
  34. package/lib/helpers/isZeroAddressOrUnset.js +14 -0
  35. package/lib/helpers/locale.d.ts +36 -0
  36. package/lib/helpers/locale.js +86 -0
  37. package/lib/holding/Holding.d.ts +60 -0
  38. package/lib/holding/Holding.js +31 -0
  39. package/lib/holding/index.js +17 -0
  40. package/{src/index.ts → lib/index.d.ts} +0 -1
  41. package/lib/index.js +62 -0
  42. package/lib/market/Market.d.ts +159 -0
  43. package/lib/market/Market.js +240 -0
  44. package/lib/market/MarketConfig.d.ts +44 -0
  45. package/lib/market/MarketConfig.js +56 -0
  46. package/lib/market/MarketUtils.d.ts +165 -0
  47. package/lib/market/MarketUtils.js +182 -0
  48. package/lib/market/MarketUtils.test.d.ts +1 -0
  49. package/lib/market/MarketUtils.test.js +19 -0
  50. package/lib/market/index.js +19 -0
  51. package/lib/maths/AdaptiveCurveIrmLib.d.ts +37 -0
  52. package/lib/maths/AdaptiveCurveIrmLib.js +116 -0
  53. package/lib/maths/MathLib.d.ts +94 -0
  54. package/lib/maths/MathLib.js +153 -0
  55. package/lib/maths/MathUtils.d.ts +15 -0
  56. package/lib/maths/MathUtils.js +33 -0
  57. package/lib/maths/SharesMath.d.ts +12 -0
  58. package/lib/maths/SharesMath.js +22 -0
  59. package/lib/maths/index.js +20 -0
  60. package/lib/notifications.d.ts +98 -0
  61. package/lib/notifications.js +52 -0
  62. package/lib/position/Position.d.ts +118 -0
  63. package/lib/position/Position.js +145 -0
  64. package/lib/position/index.js +17 -0
  65. package/lib/signatures/index.d.ts +12 -0
  66. package/lib/signatures/index.js +39 -0
  67. package/lib/signatures/manager.d.ts +10 -0
  68. package/lib/signatures/manager.js +37 -0
  69. package/lib/signatures/permit.d.ts +21 -0
  70. package/lib/signatures/permit.js +101 -0
  71. package/lib/signatures/permit2.d.ts +20 -0
  72. package/lib/signatures/permit2.js +91 -0
  73. package/lib/signatures/types.d.ts +13 -0
  74. package/lib/signatures/types.js +2 -0
  75. package/lib/signatures/utils.d.ts +6 -0
  76. package/lib/signatures/utils.js +44 -0
  77. package/lib/tests/mocks/markets.d.ts +17 -0
  78. package/lib/tests/mocks/markets.js +108 -0
  79. package/lib/token/ERC20Metadata.d.ts +249 -0
  80. package/lib/token/ERC20Metadata.js +81 -0
  81. package/lib/token/Token.d.ts +45 -0
  82. package/lib/token/Token.js +39 -0
  83. package/lib/token/TokenNamespace.d.ts +18 -0
  84. package/lib/token/TokenNamespace.js +55 -0
  85. package/lib/token/WrappedToken.d.ts +42 -0
  86. package/lib/token/WrappedToken.js +87 -0
  87. package/lib/token/index.js +18 -0
  88. package/lib/types.d.ts +29 -0
  89. package/lib/types.js +23 -0
  90. package/lib/user/User.d.ts +20 -0
  91. package/lib/user/User.js +11 -0
  92. package/lib/user/index.js +18 -0
  93. package/lib/user/user.types.d.ts +18 -0
  94. package/lib/user/user.types.js +2 -0
  95. package/lib/vault/Vault.d.ts +167 -0
  96. package/lib/vault/Vault.js +156 -0
  97. package/lib/vault/VaultAllocation.d.ts +38 -0
  98. package/lib/vault/VaultAllocation.js +18 -0
  99. package/lib/vault/VaultConfig.d.ts +23 -0
  100. package/lib/vault/VaultConfig.js +26 -0
  101. package/lib/vault/VaultUtils.d.ts +17 -0
  102. package/lib/vault/VaultUtils.js +17 -0
  103. package/lib/vault/index.js +20 -0
  104. package/package.json +7 -11
  105. package/src/addresses.ts +0 -261
  106. package/src/chain/chain.constants.ts +0 -235
  107. package/src/chain/chain.test.ts +0 -51
  108. package/src/chain/chain.types.ts +0 -42
  109. package/src/chain/chain.utils.ts +0 -44
  110. package/src/constants.ts +0 -18
  111. package/src/errors.ts +0 -75
  112. package/src/ethers/ethers.test.ts +0 -17
  113. package/src/ethers/safeGetAddress.ts +0 -4
  114. package/src/ethers/safeParseUnits.ts +0 -29
  115. package/src/evm.ts +0 -172
  116. package/src/helpers/format/format.test.ts +0 -340
  117. package/src/helpers/format/format.ts +0 -416
  118. package/src/helpers/getChecksumedAddress.ts +0 -15
  119. package/src/helpers/locale.ts +0 -108
  120. package/src/holding/Holding.ts +0 -109
  121. package/src/market/Market.ts +0 -479
  122. package/src/market/MarketConfig.ts +0 -108
  123. package/src/market/MarketUtils.test.ts +0 -25
  124. package/src/market/MarketUtils.ts +0 -467
  125. package/src/maths/AdaptiveCurveIrmLib.ts +0 -143
  126. package/src/maths/MathLib.ts +0 -208
  127. package/src/maths/MathUtils.ts +0 -31
  128. package/src/maths/SharesMath.ts +0 -40
  129. package/src/notifications.ts +0 -167
  130. package/src/position/Position.ts +0 -251
  131. package/src/signatures/index.ts +0 -18
  132. package/src/signatures/manager.ts +0 -50
  133. package/src/signatures/permit.ts +0 -126
  134. package/src/signatures/permit2.ts +0 -120
  135. package/src/signatures/types.ts +0 -18
  136. package/src/signatures/utils.ts +0 -83
  137. package/src/tests/mocks/markets.ts +0 -110
  138. package/src/token/ERC20Metadata.ts +0 -124
  139. package/src/token/Token.ts +0 -83
  140. package/src/token/TokenNamespace.ts +0 -76
  141. package/src/token/WrappedToken.ts +0 -142
  142. package/src/types.ts +0 -37
  143. package/src/user/User.ts +0 -32
  144. package/src/user/user.types.ts +0 -23
  145. package/src/vault/Vault.ts +0 -370
  146. package/src/vault/VaultAllocation.ts +0 -58
  147. package/src/vault/VaultConfig.ts +0 -55
  148. package/src/vault/VaultUtils.ts +0 -47
  149. /package/{src/chain/index.ts → lib/chain/index.d.ts} +0 -0
  150. /package/{src/ethers/index.ts → lib/ethers/index.d.ts} +0 -0
  151. /package/{src/helpers/format/index.ts → lib/helpers/format/index.d.ts} +0 -0
  152. /package/{src/helpers/index.ts → lib/helpers/index.d.ts} +0 -0
  153. /package/{src/holding/index.ts → lib/holding/index.d.ts} +0 -0
  154. /package/{src/market/index.ts → lib/market/index.d.ts} +0 -0
  155. /package/{src/maths/index.ts → lib/maths/index.d.ts} +0 -0
  156. /package/{src/position/index.ts → lib/position/index.d.ts} +0 -0
  157. /package/{src/token/index.ts → lib/token/index.d.ts} +0 -0
  158. /package/{src/user/index.ts → lib/user/index.d.ts} +0 -0
  159. /package/{src/vault/index.ts → lib/vault/index.d.ts} +0 -0
@@ -1,208 +0,0 @@
1
- import { BigNumberish, formatUnits, parseUnits, toBigInt } from "ethers";
2
-
3
- import { Time } from "@morpho-org/morpho-ts";
4
-
5
- export type RoundingDirection = "Up" | "Down";
6
-
7
- /**
8
- * Library to manage fixed-point arithmetic.
9
- * This library reproduces the behaviour of the solidity library MathLib
10
- * TODO: add library link
11
- * @category Maths
12
- *
13
- */
14
- export class MathLib {
15
- static WAD = parseUnits("1");
16
- static MAX_UINT_160 = BigInt("0x" + "f".repeat(40));
17
- static MAX_UINT_128 = BigInt("0x" + "f".repeat(32));
18
- static MAX_UINT_48 = BigInt("0x" + "f".repeat(12));
19
-
20
- /**
21
- * Returns the smallest number given as param
22
- * @param x The first number
23
- * @param y The second number
24
- */
25
- static min(x: BigNumberish, y: BigNumberish): bigint {
26
- x = toBigInt(x);
27
- y = toBigInt(y);
28
-
29
- return x <= y ? x : y;
30
- }
31
-
32
- /**
33
- * Returns the greatest number given as param
34
- * @param x The first number
35
- * @param y The second number
36
- */
37
- static max(x: BigNumberish, y: BigNumberish): bigint {
38
- x = toBigInt(x);
39
- y = toBigInt(y);
40
-
41
- return x <= y ? y : x;
42
- }
43
-
44
- /**
45
- * Perform the WAD-based multiplication of 2 numbers, rounded down
46
- * @param x The first number
47
- * @param y The second number
48
- */
49
- static wMulDown(x: BigNumberish, y: BigNumberish): bigint {
50
- x = toBigInt(x);
51
- y = toBigInt(y);
52
-
53
- return MathLib.wMul(x, y, "Down");
54
- }
55
-
56
- /**
57
- * Perform the WAD-based multiplication of 2 numbers, rounded up
58
- * @param x The first number
59
- * @param y The second number
60
- */
61
- static wMulUp(x: BigNumberish, y: BigNumberish): bigint {
62
- x = toBigInt(x);
63
- y = toBigInt(y);
64
-
65
- return MathLib.wMul(x, y, "Up");
66
- }
67
-
68
- /**
69
- * Perform the WAD-based multiplication of 2 numbers with a provided rounding direction
70
- * @param x The first number
71
- * @param y The second number
72
- */
73
- static wMul(x: bigint, y: bigint, rounding: RoundingDirection): bigint {
74
- return MathLib.mulDiv(x, y, MathLib.WAD, rounding);
75
- }
76
-
77
- /**
78
- * Perform the WAD-based division of 2 numbers, rounded down
79
- * @param x The first number
80
- * @param y The second number
81
- */
82
- static wDivDown(x: BigNumberish, y: BigNumberish): bigint {
83
- x = toBigInt(x);
84
- y = toBigInt(y);
85
-
86
- return MathLib.wDiv(x, y, "Down");
87
- }
88
-
89
- /**
90
- * Perform the WAD-based multiplication of 2 numbers, rounded up
91
- * @param x The first number
92
- * @param y The second number
93
- */
94
- static wDivUp(x: BigNumberish, y: BigNumberish): bigint {
95
- x = toBigInt(x);
96
- y = toBigInt(y);
97
-
98
- return MathLib.wDiv(x, y, "Up");
99
- }
100
-
101
- /**
102
- * Perform the WAD-based multiplication of 2 numbers with a provided rounding direction
103
- * @param x The first number
104
- * @param y The second number
105
- */
106
- static wDiv(
107
- x: BigNumberish,
108
- y: BigNumberish,
109
- rounding: RoundingDirection
110
- ): bigint {
111
- return MathLib.mulDiv(x, MathLib.WAD, y, rounding);
112
- }
113
-
114
- /**
115
- * Multiply two numbers and divide by a denominator, rounding down the result
116
- * @param x The first number
117
- * @param y The second number
118
- * @param denominator The denominator
119
- */
120
- static mulDivDown(
121
- x: BigNumberish,
122
- y: BigNumberish,
123
- denominator: BigNumberish
124
- ): bigint {
125
- x = toBigInt(x);
126
- y = toBigInt(y);
127
- denominator = toBigInt(denominator);
128
-
129
- if (denominator === 0n) throw Error("MathLib: DIVISION_BY_ZERO");
130
-
131
- return (x * y) / denominator;
132
- }
133
-
134
- /**
135
- * Multiply two numbers and divide by a denominator, rounding up the result
136
- * @param x The first number
137
- * @param y The second number
138
- * @param denominator The denominator
139
- */
140
- static mulDivUp(
141
- x: BigNumberish,
142
- y: BigNumberish,
143
- denominator: BigNumberish
144
- ): bigint {
145
- x = toBigInt(x);
146
- y = toBigInt(y);
147
- denominator = toBigInt(denominator);
148
-
149
- if (denominator === 0n) throw Error("MathLib: DIVISION_BY_ZERO");
150
-
151
- const roundup = (x * y) % denominator > 0 ? 1n : 0n;
152
-
153
- return (x * y) / denominator + roundup;
154
- }
155
-
156
- static mulDiv(
157
- x: BigNumberish,
158
- y: BigNumberish,
159
- denominator: BigNumberish,
160
- rounding: RoundingDirection
161
- ) {
162
- return MathLib[`mulDiv${rounding}`](x, y, denominator);
163
- }
164
-
165
- /**
166
- * The sum of the first three non-zero terms of a Taylor expansion of e^(nx) - 1,
167
- * to approximate a continuous compound interest rate.
168
- *
169
- * @param x The base of the exponent
170
- * @param n The exponent
171
- */
172
- static wTaylorCompounded(x: BigNumberish, n: BigNumberish) {
173
- x = toBigInt(x);
174
- n = toBigInt(n);
175
-
176
- const firstTerm = x * n;
177
- const secondTerm = MathLib.mulDivDown(
178
- firstTerm,
179
- firstTerm,
180
- 2n * MathLib.WAD
181
- );
182
- const thirdTerm = MathLib.mulDivDown(
183
- secondTerm,
184
- firstTerm,
185
- 3n * MathLib.WAD
186
- );
187
-
188
- return firstTerm + secondTerm + thirdTerm;
189
- }
190
-
191
- /**
192
- * Converts an apr to compounded apy
193
- *
194
- * @param apr The apr to convert (in WAD)
195
- * @param compounding The compounding basis
196
- */
197
- static aprToApy(apr: bigint, compounding: Time.Unit) {
198
- const factor = Time[compounding].from.y(1n);
199
-
200
- const rate = apr / factor;
201
-
202
- return (
203
- parseUnits(
204
- ((+formatUnits(this.WAD + rate)) ** Number(factor)).toFixed(18)
205
- ) - this.WAD
206
- );
207
- }
208
- }
@@ -1,31 +0,0 @@
1
- /**
2
- * Math utilities
3
- * This library reproduces the behaviour of the solidity library MathUtils
4
- * TODO: add library link
5
- * @category Maths
6
- */
7
- export class MathUtils {
8
- static zeroFloorSub(a: bigint, b: bigint): bigint {
9
- return a - b < 0n ? 0n : a - b;
10
- }
11
-
12
- static min(a: bigint, b: bigint): bigint {
13
- return a < b ? a : b;
14
- }
15
- static mins(...args: bigint[]): bigint {
16
- return args.reduce((a, b) => this.min(a, b));
17
- }
18
- static max(a: bigint, b: bigint): bigint {
19
- return a > b ? a : b;
20
- }
21
- static pos(a: bigint): bigint {
22
- return a >= 0n ? a : 0n;
23
- }
24
- static neg(a: bigint): bigint {
25
- return a < 0n ? -a : 0n;
26
- }
27
-
28
- static abs(a: bigint): bigint {
29
- return a >= 0 ? a : -a;
30
- }
31
- }
@@ -1,40 +0,0 @@
1
- import { BigNumberish, toBigInt } from "ethers";
2
-
3
- import { MathLib, RoundingDirection } from "./MathLib";
4
-
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
- export namespace SharesMath {
10
- export const VIRTUAL_SHARES = 1000000n;
11
- export const VIRTUAL_ASSETS = 1n;
12
-
13
- export function toAssets(
14
- shares: BigNumberish,
15
- totalAssets: BigNumberish,
16
- totalShares: BigNumberish,
17
- rounding: RoundingDirection
18
- ) {
19
- return MathLib.mulDiv(
20
- shares,
21
- toBigInt(totalAssets) + VIRTUAL_ASSETS,
22
- toBigInt(totalShares) + VIRTUAL_SHARES,
23
- rounding
24
- );
25
- }
26
-
27
- export function toShares(
28
- assets: BigNumberish,
29
- totalAssets: BigNumberish,
30
- totalShares: BigNumberish,
31
- rounding: RoundingDirection
32
- ) {
33
- return MathLib.mulDiv(
34
- assets,
35
- toBigInt(totalShares) + VIRTUAL_SHARES,
36
- toBigInt(totalAssets) + VIRTUAL_ASSETS,
37
- rounding
38
- );
39
- }
40
- }
@@ -1,167 +0,0 @@
1
- import {
2
- Signature,
3
- TransactionReceipt,
4
- TransactionRequest,
5
- TransactionResponse,
6
- } from "ethers";
7
- import { Observable, Observer, ReplaySubject, lastValueFrom } from "rxjs";
8
-
9
- import { SignatureMessage } from "./signatures/types";
10
-
11
- export enum NotificationStatus {
12
- signing = "signing",
13
- success = "success",
14
- error = "error",
15
- pending = "pending",
16
- }
17
-
18
- export enum NotificationTopic {
19
- tx = "tx",
20
- signature = "signature",
21
- }
22
-
23
- export interface NotificationContext {
24
- [NotificationTopic.tx]: {
25
- [NotificationStatus.signing]: {
26
- tx: TransactionRequest;
27
- };
28
- [NotificationStatus.pending]: {
29
- args: Record<PropertyKey, any>;
30
- tx: TransactionRequest;
31
- response?: TransactionResponse;
32
- };
33
- [NotificationStatus.success]: {
34
- args: Record<PropertyKey, any>;
35
- tx: TransactionRequest;
36
- response?: TransactionResponse;
37
- receipt: TransactionReceipt | null;
38
- };
39
- [NotificationStatus.error]: {
40
- args: Record<PropertyKey, any>;
41
- tx: TransactionRequest;
42
- response?: TransactionResponse;
43
- error: Error;
44
- };
45
- };
46
- [NotificationTopic.signature]: {
47
- [NotificationStatus.signing]: never;
48
- [NotificationStatus.pending]: {
49
- message: SignatureMessage;
50
- args: Record<PropertyKey, any>;
51
- };
52
- [NotificationStatus.success]: {
53
- message: SignatureMessage;
54
- args: Record<PropertyKey, any>;
55
- signature: Signature;
56
- };
57
- [NotificationStatus.error]: {
58
- message: SignatureMessage;
59
- args: Record<PropertyKey, any>;
60
- error: Error;
61
- };
62
- };
63
- }
64
-
65
- export interface NotificationBody<
66
- Topic extends NotificationTopic = NotificationTopic,
67
- Status extends NotificationStatus = NotificationStatus
68
- > {
69
- id: string;
70
- topic: Topic;
71
- status: Status;
72
- }
73
-
74
- export type Notifications = {
75
- [Topic in NotificationTopic]: {
76
- [Status in NotificationStatus]: NotificationBody<Topic, Status> &
77
- (NotificationContext[Topic][Status] extends never
78
- ? unknown
79
- : { context: NotificationContext[Topic][Status] });
80
- };
81
- };
82
-
83
- export type TxNotification =
84
- Notifications[NotificationTopic.tx][NotificationStatus];
85
- export type SignatureNotification =
86
- Notifications[NotificationTopic.signature][NotificationStatus];
87
- export type Notification = Notifications[NotificationTopic][NotificationStatus];
88
-
89
- export type NotificationsWithoutTopic = {
90
- [Topic in NotificationTopic]: {
91
- [Status in NotificationStatus]: Omit<
92
- NotificationBody<Topic, Status>,
93
- "topic"
94
- > &
95
- (NotificationContext[Topic][Status] extends never
96
- ? unknown
97
- : { context: NotificationContext[Topic][Status] });
98
- };
99
- };
100
-
101
- export interface NotificationConsumer<Topic extends NotificationTopic> {
102
- notifications$: Observable<Notifications[Topic][NotificationStatus]>;
103
- wait: (
104
- observerOrNext?:
105
- | Partial<Observer<Notifications[Topic][NotificationStatus]>>
106
- | ((value: Notifications[Topic][NotificationStatus]) => void)
107
- ) => Promise<
108
- Notifications[Topic][NotificationStatus.success | NotificationStatus.error]
109
- >;
110
- }
111
-
112
- /**
113
- * MUST receive a success or error notification at some point to ensure the result promise resolves.
114
- */
115
- export class NotificationProducer<Topic extends NotificationTopic> {
116
- protected readonly _notifications$ = new ReplaySubject<
117
- Notifications[Topic][NotificationStatus]
118
- >(Infinity);
119
- public readonly notifications$ = this._notifications$.asObservable();
120
-
121
- protected readonly _result = lastValueFrom(this._notifications$);
122
-
123
- public readonly consumer: NotificationConsumer<Topic> = {
124
- notifications$: this.notifications$,
125
- wait: this.wait.bind(this),
126
- };
127
-
128
- /**
129
- * Creates a notification producer.
130
- * MUST receive a success or error notification at some point to ensure the result promise resolves.
131
- * @param topic The notification topic to populate each notification with.
132
- */
133
- constructor(public readonly topic: Topic) {}
134
-
135
- public async wait(
136
- observerOrNext?:
137
- | Partial<Observer<Notifications[Topic][NotificationStatus]>>
138
- | ((value: Notifications[Topic][NotificationStatus]) => void)
139
- ) {
140
- const subscription = this.notifications$.subscribe(observerOrNext);
141
-
142
- const notification = (await this._result) as unknown as Promise<
143
- Notifications[Topic][
144
- | NotificationStatus.success
145
- | NotificationStatus.error]
146
- >;
147
-
148
- subscription.unsubscribe();
149
-
150
- return notification;
151
- }
152
-
153
- public next(
154
- notification: NotificationsWithoutTopic[Topic][NotificationStatus]
155
- ) {
156
- this._notifications$.next({
157
- ...notification,
158
- topic: this.topic,
159
- } as unknown as Notifications[Topic][NotificationStatus]);
160
-
161
- if (
162
- notification.status === NotificationStatus.success ||
163
- notification.status === NotificationStatus.error
164
- )
165
- this._notifications$.complete();
166
- }
167
- }
@@ -1,251 +0,0 @@
1
- import { BigNumberish, Provider, toBigInt } from "ethers";
2
- import { MorphoBlue__factory } from "ethers-types";
3
- import { ViewOverrides } from "ethers-types/dist/common";
4
-
5
- import { getChainAddresses } from "../addresses";
6
- import { ChainId, ChainUtils } from "../chain";
7
- import { Market, MarketConfig } from "../market";
8
- import { Address, MarketId } from "../types";
9
-
10
- export interface InputPosition {
11
- user: Address;
12
- marketId: MarketId;
13
- supplyShares: BigNumberish;
14
- borrowShares: BigNumberish;
15
- collateral: BigNumberish;
16
- }
17
-
18
- export class Position implements InputPosition {
19
- static async fetch(
20
- user: Address,
21
- marketId: MarketId,
22
- runner: { provider: Provider },
23
- {
24
- chainId,
25
- overrides = {},
26
- }: { chainId?: ChainId; overrides?: ViewOverrides } = {}
27
- ) {
28
- chainId ??= ChainUtils.parseSupportedChainId(
29
- (await runner.provider.getNetwork()).chainId
30
- );
31
- const { morpho } = getChainAddresses(chainId);
32
-
33
- const { supplyShares, borrowShares, collateral } =
34
- await MorphoBlue__factory.connect(morpho, runner).position(
35
- marketId,
36
- user,
37
- overrides
38
- );
39
-
40
- return new Position({
41
- user,
42
- marketId,
43
- supplyShares,
44
- borrowShares,
45
- collateral,
46
- });
47
- }
48
-
49
- /**
50
- * The user holding this position.
51
- */
52
- public readonly user: Address;
53
-
54
- /**
55
- * The id of the market on which this position is held.
56
- */
57
- public readonly marketId: MarketId;
58
-
59
- /**
60
- * The amount of supply shares held with this position.
61
- */
62
- public supplyShares: bigint;
63
- /**
64
- * The amount of borrow shares held with this position.
65
- */
66
- public borrowShares: bigint;
67
- /**
68
- * The amount of collateral assets held with this position.
69
- */
70
- public collateral: bigint;
71
-
72
- constructor({
73
- user,
74
- marketId,
75
- supplyShares,
76
- borrowShares,
77
- collateral,
78
- }: InputPosition) {
79
- this.user = user;
80
- this.marketId = marketId;
81
- this.supplyShares = toBigInt(supplyShares);
82
- this.borrowShares = toBigInt(borrowShares);
83
- this.collateral = toBigInt(collateral);
84
- }
85
- }
86
-
87
- export interface InputAccrualPosition extends Omit<InputPosition, "marketId"> {}
88
-
89
- export class AccrualPosition extends Position implements InputAccrualPosition {
90
- static async fetchFromId(
91
- user: Address,
92
- marketId: MarketId,
93
- runner: { provider: Provider },
94
- options: { chainId?: ChainId; overrides?: ViewOverrides }
95
- ) {
96
- const [position, market] = await Promise.all([
97
- await Position.fetch(user, marketId, runner, options),
98
- await Market.fetchFromId(marketId, runner, options),
99
- ]);
100
-
101
- return new AccrualPosition(position, market);
102
- }
103
-
104
- static async fetchFromConfig(
105
- user: Address,
106
- config: MarketConfig,
107
- runner: { provider: Provider },
108
- options: { chainId?: ChainId; overrides?: ViewOverrides }
109
- ) {
110
- const [position, market] = await Promise.all([
111
- await Position.fetch(user, config.id, runner, options),
112
- await Market.fetchFromConfig(config, runner, options),
113
- ]);
114
-
115
- return new AccrualPosition(position, market);
116
- }
117
-
118
- /**
119
- * The market on which this position is held.
120
- */
121
- public readonly market: Market;
122
-
123
- constructor(position: InputAccrualPosition, market: Market) {
124
- super({ ...position, marketId: market.id });
125
-
126
- this.market = market;
127
- }
128
-
129
- get supplyAssets() {
130
- return this.market.toSupplyAssets(this.supplyShares);
131
- }
132
-
133
- get borrowAssets() {
134
- return this.market.toBorrowAssets(this.borrowShares);
135
- }
136
-
137
- /**
138
- * The value of this position's collateral quoted in loan assets.
139
- */
140
- get collateralValue() {
141
- return this.market.getCollateralValue(this.collateral);
142
- }
143
-
144
- /**
145
- * The maximum amount of loan assets that can be borrowed against this position's collateral.
146
- */
147
- get maxBorrowAssets() {
148
- return this.market.getMaxBorrowAssets(this.collateral);
149
- }
150
-
151
- /**
152
- * The maximum additional amount of assets that can be borrowed against this position's collateral.
153
- */
154
- get maxBorrowableAssets() {
155
- return this.market.getMaxBorrowableAssets(this);
156
- }
157
-
158
- /**
159
- * The maximum amount of collateral that can be seized in exchange for the outstanding debt.
160
- */
161
- get seizableCollateral() {
162
- return this.market.getSeizableCollateral(this);
163
- }
164
-
165
- /**
166
- * The maximum amount of collateral that can be withdrawn.
167
- */
168
- get withdrawableCollateral() {
169
- return this.market.getWithdrawableCollateral(this);
170
- }
171
-
172
- /**
173
- * Whether this position is healthy.
174
- */
175
- get isHealthy() {
176
- return this.market.isHealthy(this);
177
- }
178
-
179
- /**
180
- * The price of the collateral quoted in loan assets that would allow this position to be liquidated.
181
- */
182
- get liquidationPrice() {
183
- return this.market.getLiquidationPrice(this);
184
- }
185
-
186
- /**
187
- * The variation of the price of the collateral quoted in loan assets that would allow this position to be liquidated,
188
- * relative to the current collateral price (scaled by WAD).
189
- */
190
- get priceVariationToLiquidation() {
191
- return this.market.getPriceVariationToLiquidation(this);
192
- }
193
-
194
- /**
195
- * This position's Loan-To-Value (debt over collateral power, scaled by WAD).
196
- * If the collateral price is 0, LTV is `MaxUint256`.
197
- */
198
- get ltv() {
199
- return this.market.getLtv(this);
200
- }
201
-
202
- /**
203
- * This position's health factor (collateral power over debt, scaled by WAD).
204
- * If the debt is 0, health factor is `MaxUint256`.
205
- */
206
- get healthFactor() {
207
- return this.market.getHealthFactor(this);
208
- }
209
-
210
- /**
211
- * The percentage of this position's borrow power currently used (scaled by WAD).
212
- * If the collateral price is 0, usage is `MaxUint256`.
213
- */
214
- get borrowCapacityUsage() {
215
- return this.market.getBorrowCapacityUsage(this);
216
- }
217
-
218
- get borrowCapacityLimit() {
219
- return this.market.getBorrowCapacityLimit(this.collateral);
220
- }
221
-
222
- get withdrawCapacityLimit() {
223
- return this.market.getWithdrawCapacityLimit(this.supplyShares);
224
- }
225
-
226
- get withdrawCollateralCapacityLimit() {
227
- return this.market.getWithdrawCollateralCapacityLimit(this);
228
- }
229
-
230
- public accrueInterest(timestamp: BigNumberish) {
231
- return new AccrualPosition(this, this.market.accrueInterest(timestamp));
232
- }
233
-
234
- public getRepayCapacityLimit(loanTokenBalance: bigint) {
235
- return this.market.getRepayCapacityLimit(
236
- this.borrowShares,
237
- loanTokenBalance
238
- );
239
- }
240
-
241
- public getMaxCapacities(
242
- loanTokenBalance: bigint,
243
- collateralTokenBalance: bigint
244
- ) {
245
- return this.market.getMaxCapacities(
246
- this,
247
- loanTokenBalance,
248
- collateralTokenBalance
249
- );
250
- }
251
- }
@@ -1,18 +0,0 @@
1
- import * as _Manager from "./manager";
2
- import * as _Permit from "./permit";
3
- import * as _Permit2 from "./permit2";
4
- import {
5
- safeSignTypedData as _safeSignTypedData,
6
- verifySignature as _verifySignature,
7
- getMessage as _getMessage,
8
- } from "./utils";
9
-
10
- export namespace SignatureUtils {
11
- export import Permit = _Permit;
12
- export import Permit2 = _Permit2;
13
- export import Manager = _Manager;
14
-
15
- export const safeSignTypedData = _safeSignTypedData;
16
- export const verifySignature = _verifySignature;
17
- export const getMessage = _getMessage;
18
- }