@morpho-org/blue-sdk 1.0.3 → 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 (158) 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/market/Market.d.ts +159 -0
  42. package/lib/market/Market.js +240 -0
  43. package/lib/market/MarketConfig.d.ts +44 -0
  44. package/lib/market/MarketConfig.js +56 -0
  45. package/lib/market/MarketUtils.d.ts +165 -0
  46. package/lib/market/MarketUtils.js +182 -0
  47. package/lib/market/MarketUtils.test.d.ts +1 -0
  48. package/lib/market/MarketUtils.test.js +19 -0
  49. package/lib/market/index.js +19 -0
  50. package/lib/maths/AdaptiveCurveIrmLib.d.ts +37 -0
  51. package/lib/maths/AdaptiveCurveIrmLib.js +116 -0
  52. package/lib/maths/MathLib.d.ts +94 -0
  53. package/lib/maths/MathLib.js +153 -0
  54. package/lib/maths/MathUtils.d.ts +15 -0
  55. package/lib/maths/MathUtils.js +33 -0
  56. package/lib/maths/SharesMath.d.ts +12 -0
  57. package/lib/maths/SharesMath.js +22 -0
  58. package/lib/maths/index.js +20 -0
  59. package/lib/notifications.d.ts +98 -0
  60. package/lib/notifications.js +52 -0
  61. package/lib/position/Position.d.ts +118 -0
  62. package/lib/position/Position.js +145 -0
  63. package/lib/position/index.js +17 -0
  64. package/lib/signatures/index.d.ts +12 -0
  65. package/lib/signatures/index.js +39 -0
  66. package/lib/signatures/manager.d.ts +10 -0
  67. package/lib/signatures/manager.js +37 -0
  68. package/lib/signatures/permit.d.ts +21 -0
  69. package/lib/signatures/permit.js +101 -0
  70. package/lib/signatures/permit2.d.ts +20 -0
  71. package/lib/signatures/permit2.js +91 -0
  72. package/lib/signatures/types.d.ts +13 -0
  73. package/lib/signatures/types.js +2 -0
  74. package/lib/signatures/utils.d.ts +6 -0
  75. package/lib/signatures/utils.js +44 -0
  76. package/lib/tests/mocks/markets.d.ts +17 -0
  77. package/lib/tests/mocks/markets.js +108 -0
  78. package/lib/token/ERC20Metadata.d.ts +249 -0
  79. package/lib/token/ERC20Metadata.js +81 -0
  80. package/lib/token/Token.d.ts +45 -0
  81. package/lib/token/Token.js +39 -0
  82. package/lib/token/TokenNamespace.d.ts +18 -0
  83. package/lib/token/TokenNamespace.js +55 -0
  84. package/lib/token/WrappedToken.d.ts +42 -0
  85. package/lib/token/WrappedToken.js +87 -0
  86. package/lib/token/index.js +18 -0
  87. package/lib/types.d.ts +29 -0
  88. package/lib/types.js +23 -0
  89. package/lib/user/User.d.ts +20 -0
  90. package/lib/user/User.js +11 -0
  91. package/lib/user/index.js +18 -0
  92. package/lib/user/user.types.d.ts +18 -0
  93. package/lib/user/user.types.js +2 -0
  94. package/lib/vault/Vault.d.ts +167 -0
  95. package/lib/vault/Vault.js +156 -0
  96. package/lib/vault/VaultAllocation.d.ts +38 -0
  97. package/lib/vault/VaultAllocation.js +18 -0
  98. package/lib/vault/VaultConfig.d.ts +23 -0
  99. package/lib/vault/VaultConfig.js +26 -0
  100. package/lib/vault/VaultUtils.d.ts +17 -0
  101. package/lib/vault/VaultUtils.js +17 -0
  102. package/lib/vault/index.js +20 -0
  103. package/package.json +6 -9
  104. package/src/addresses.ts +0 -247
  105. package/src/chain/chain.constants.ts +0 -235
  106. package/src/chain/chain.test.ts +0 -51
  107. package/src/chain/chain.types.ts +0 -42
  108. package/src/chain/chain.utils.ts +0 -44
  109. package/src/constants.ts +0 -18
  110. package/src/errors.ts +0 -75
  111. package/src/ethers/ethers.test.ts +0 -17
  112. package/src/ethers/safeGetAddress.ts +0 -4
  113. package/src/ethers/safeParseUnits.ts +0 -29
  114. package/src/evm.ts +0 -172
  115. package/src/helpers/format/format.test.ts +0 -340
  116. package/src/helpers/format/format.ts +0 -416
  117. package/src/helpers/getChecksumedAddress.ts +0 -15
  118. package/src/helpers/locale.ts +0 -108
  119. package/src/holding/Holding.ts +0 -109
  120. package/src/market/Market.ts +0 -479
  121. package/src/market/MarketConfig.ts +0 -108
  122. package/src/market/MarketUtils.test.ts +0 -25
  123. package/src/market/MarketUtils.ts +0 -467
  124. package/src/maths/AdaptiveCurveIrmLib.ts +0 -143
  125. package/src/maths/MathLib.ts +0 -208
  126. package/src/maths/MathUtils.ts +0 -31
  127. package/src/maths/SharesMath.ts +0 -40
  128. package/src/notifications.ts +0 -167
  129. package/src/position/Position.ts +0 -251
  130. package/src/signatures/index.ts +0 -18
  131. package/src/signatures/manager.ts +0 -50
  132. package/src/signatures/permit.ts +0 -126
  133. package/src/signatures/permit2.ts +0 -120
  134. package/src/signatures/types.ts +0 -18
  135. package/src/signatures/utils.ts +0 -83
  136. package/src/tests/mocks/markets.ts +0 -110
  137. package/src/token/ERC20Metadata.ts +0 -124
  138. package/src/token/Token.ts +0 -83
  139. package/src/token/TokenNamespace.ts +0 -76
  140. package/src/token/WrappedToken.ts +0 -142
  141. package/src/types.ts +0 -37
  142. package/src/user/User.ts +0 -32
  143. package/src/user/user.types.ts +0 -25
  144. package/src/vault/Vault.ts +0 -370
  145. package/src/vault/VaultAllocation.ts +0 -58
  146. package/src/vault/VaultConfig.ts +0 -55
  147. package/src/vault/VaultUtils.ts +0 -47
  148. /package/{src/chain/index.ts → lib/chain/index.d.ts} +0 -0
  149. /package/{src/ethers/index.ts → lib/ethers/index.d.ts} +0 -0
  150. /package/{src/helpers/format/index.ts → lib/helpers/format/index.d.ts} +0 -0
  151. /package/{src/helpers/index.ts → lib/helpers/index.d.ts} +0 -0
  152. /package/{src/holding/index.ts → lib/holding/index.d.ts} +0 -0
  153. /package/{src/market/index.ts → lib/market/index.d.ts} +0 -0
  154. /package/{src/maths/index.ts → lib/maths/index.d.ts} +0 -0
  155. /package/{src/position/index.ts → lib/position/index.d.ts} +0 -0
  156. /package/{src/token/index.ts → lib/token/index.d.ts} +0 -0
  157. /package/{src/user/index.ts → lib/user/index.d.ts} +0 -0
  158. /package/{src/vault/index.ts → lib/vault/index.d.ts} +0 -0
@@ -0,0 +1,36 @@
1
+ type LocaleSymbols = {
2
+ decimalSymbol: string;
3
+ groupSymbol: string;
4
+ locale: string;
5
+ };
6
+ export type LocaleParts = LocaleSymbols & {
7
+ value: string;
8
+ };
9
+ /**
10
+ * @returns the locale symbols for the given locale defaulting to en-US
11
+ */
12
+ export declare const getLocaleSymbols: (locale: string) => LocaleSymbols;
13
+ /**
14
+ * @returns the effective browser locale
15
+ */
16
+ export declare const getEffectiveLocale: () => string;
17
+ /**
18
+ * @returns the value as a string with the given locale symbols
19
+ * @param numStr the number as a string in the "from" locale (e.g. "1,2345.6" for en-US)
20
+ * @param from the locale the numStr is in (e.g. "en-US")
21
+ * @param to the locale to convert to (e.g. "fr-FR")
22
+ */
23
+ export declare const convertNumStrToLocal: (numStr: string, from: string, to: string) => string;
24
+ /**
25
+ * @returns the value as a string in the effective browser locale
26
+ * @param numStr the number as a string in the effective browser locale (e.g. "1,2345.6" for en-US)
27
+ * @param to the locale to use (e.g. "fr-FR")
28
+ */
29
+ export declare const convertNumStrFromEffectiveTo: (numStr: string, to: string) => string;
30
+ /**
31
+ * @returns the value as a string with the given locale symbols either from the given locale or the effective browser locale
32
+ * @param numStr the number as a string in english format (e.g. "1,2345.6")
33
+ * @param locale optional - the locale to use (e.g. "fr-FR")
34
+ */
35
+ export declare const getEnUSNumberToLocalParts: (numStr: string, locale?: string) => LocaleParts;
36
+ export {};
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getEnUSNumberToLocalParts = exports.convertNumStrFromEffectiveTo = exports.convertNumStrToLocal = exports.getEffectiveLocale = exports.getLocaleSymbols = void 0;
4
+ const _convertEnNumStrToLocale = (numStr, localSymbols) => {
5
+ return numStr
6
+ .replaceAll(",", "#TEMP#")
7
+ .replaceAll(".", localSymbols.decimalSymbol)
8
+ .replaceAll("#TEMP#", localSymbols.groupSymbol);
9
+ };
10
+ /**
11
+ * @returns the locale symbols for the given locale defaulting to en-US
12
+ */
13
+ const getLocaleSymbols = (locale) => {
14
+ let formatter;
15
+ const formatterOptions = {
16
+ useGrouping: true,
17
+ maximumFractionDigits: 1,
18
+ minimumFractionDigits: 1,
19
+ };
20
+ try {
21
+ formatter = new Intl.NumberFormat(locale, formatterOptions);
22
+ }
23
+ catch {
24
+ formatter = new Intl.NumberFormat("en-US", formatterOptions);
25
+ }
26
+ const parts = formatter.formatToParts(12345.6);
27
+ const decimalSymbol = parts.find((part) => part.type === "decimal").value;
28
+ const groupSymbol = parts.find((part) => part.type === "group").value;
29
+ return { decimalSymbol, groupSymbol, locale };
30
+ };
31
+ exports.getLocaleSymbols = getLocaleSymbols;
32
+ /**
33
+ * @returns the effective browser locale
34
+ */
35
+ const getEffectiveLocale = () => {
36
+ if (typeof window !== "undefined") {
37
+ try {
38
+ const locale = navigator?.language || document?.documentElement?.lang || "en-US";
39
+ new Intl.NumberFormat(locale);
40
+ return locale;
41
+ }
42
+ catch (e) {
43
+ return "en-US";
44
+ }
45
+ }
46
+ return "en-US";
47
+ };
48
+ exports.getEffectiveLocale = getEffectiveLocale;
49
+ /**
50
+ * @returns the value as a string with the given locale symbols
51
+ * @param numStr the number as a string in the "from" locale (e.g. "1,2345.6" for en-US)
52
+ * @param from the locale the numStr is in (e.g. "en-US")
53
+ * @param to the locale to convert to (e.g. "fr-FR")
54
+ */
55
+ const convertNumStrToLocal = (numStr, from, to) => {
56
+ const fromSymbols = (0, exports.getLocaleSymbols)(from);
57
+ const toSymbols = (0, exports.getLocaleSymbols)(to);
58
+ return numStr
59
+ .replaceAll(fromSymbols.groupSymbol, "#GROUP#")
60
+ .replaceAll(fromSymbols.decimalSymbol, "#DECIMAL#")
61
+ .replaceAll("#GROUP#", toSymbols.groupSymbol)
62
+ .replaceAll("#DECIMAL#", toSymbols.decimalSymbol);
63
+ };
64
+ exports.convertNumStrToLocal = convertNumStrToLocal;
65
+ /**
66
+ * @returns the value as a string in the effective browser locale
67
+ * @param numStr the number as a string in the effective browser locale (e.g. "1,2345.6" for en-US)
68
+ * @param to the locale to use (e.g. "fr-FR")
69
+ */
70
+ const convertNumStrFromEffectiveTo = (numStr, to) => {
71
+ const from = (0, exports.getEffectiveLocale)();
72
+ return (0, exports.convertNumStrToLocal)(numStr, from, to);
73
+ };
74
+ exports.convertNumStrFromEffectiveTo = convertNumStrFromEffectiveTo;
75
+ /**
76
+ * @returns the value as a string with the given locale symbols either from the given locale or the effective browser locale
77
+ * @param numStr the number as a string in english format (e.g. "1,2345.6")
78
+ * @param locale optional - the locale to use (e.g. "fr-FR")
79
+ */
80
+ const getEnUSNumberToLocalParts = (numStr, locale) => {
81
+ const _locale = locale || (0, exports.getEffectiveLocale)();
82
+ const localSymbols = (0, exports.getLocaleSymbols)(_locale);
83
+ const value = _convertEnNumStrToLocale(numStr, localSymbols);
84
+ return { ...localSymbols, value };
85
+ };
86
+ exports.getEnUSNumberToLocalParts = getEnUSNumberToLocalParts;
@@ -0,0 +1,60 @@
1
+ import { BigNumberish } from "ethers";
2
+ import { Address } from "../types";
3
+ export declare const ERC20_ALLOWANCE_RECIPIENTS: readonly ["morpho", "permit2", "bundler"];
4
+ export declare const PERMIT2_ALLOWANCE_RECIPIENTS: readonly ["morpho", "bundler"];
5
+ export type Erc20AllowanceRecipient = (typeof ERC20_ALLOWANCE_RECIPIENTS)[number];
6
+ export type Permit2AllowanceRecipient = (typeof PERMIT2_ALLOWANCE_RECIPIENTS)[number];
7
+ export interface Permit2Allowance {
8
+ amount: bigint;
9
+ expiration: bigint;
10
+ nonce: bigint;
11
+ }
12
+ export interface InputHolding {
13
+ user: Address;
14
+ token: Address;
15
+ erc20Allowances: {
16
+ [key in Erc20AllowanceRecipient]: BigNumberish;
17
+ };
18
+ permit2Allowances: {
19
+ [key in Permit2AllowanceRecipient]: Permit2Allowance;
20
+ };
21
+ erc2612Nonce?: BigNumberish;
22
+ canTransfer?: boolean;
23
+ balance: BigNumberish;
24
+ }
25
+ export declare class Holding implements InputHolding {
26
+ /**
27
+ * The user of this holding.
28
+ */
29
+ readonly user: Address;
30
+ /**
31
+ * The token in which this holding is denominated.
32
+ */
33
+ readonly token: Address;
34
+ /**
35
+ * The balance of the user for this token.
36
+ */
37
+ balance: bigint;
38
+ /**
39
+ * Whether the user is allowed to transfer this holding's balance.
40
+ */
41
+ canTransfer?: boolean;
42
+ /**
43
+ * ERC20 allowance for this token from the user to the allowance recipient.
44
+ */
45
+ readonly erc20Allowances: {
46
+ [key in Erc20AllowanceRecipient]: bigint;
47
+ };
48
+ /**
49
+ * Permit2 allowance for this token from the user to the allowance recipient.
50
+ */
51
+ readonly permit2Allowances: {
52
+ [key in Permit2AllowanceRecipient]: Permit2Allowance;
53
+ };
54
+ /**
55
+ * ERC-2612 Permit nonce of the user for this token.
56
+ * `undefined` if the token does not support ERC-2612.
57
+ */
58
+ erc2612Nonce?: bigint;
59
+ constructor({ user, token, erc20Allowances, permit2Allowances, balance, erc2612Nonce, canTransfer, }: InputHolding);
60
+ }
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Holding = exports.PERMIT2_ALLOWANCE_RECIPIENTS = exports.ERC20_ALLOWANCE_RECIPIENTS = void 0;
4
+ const ethers_1 = require("ethers");
5
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
+ const addresses_1 = require("../addresses");
7
+ exports.ERC20_ALLOWANCE_RECIPIENTS = [
8
+ "morpho",
9
+ "permit2",
10
+ "bundler",
11
+ ];
12
+ exports.PERMIT2_ALLOWANCE_RECIPIENTS = [
13
+ "morpho",
14
+ "bundler",
15
+ ];
16
+ class Holding {
17
+ constructor({ user, token, erc20Allowances, permit2Allowances, balance, erc2612Nonce, canTransfer = true, }) {
18
+ this.user = user;
19
+ this.token = token;
20
+ this.balance = (0, ethers_1.toBigInt)(balance);
21
+ this.canTransfer = token === addresses_1.NATIVE_ADDRESS || canTransfer;
22
+ this.erc20Allowances = (0, morpho_ts_1.fromEntries)((0, morpho_ts_1.entries)(erc20Allowances).map(([address, allowance]) => [
23
+ address,
24
+ (0, ethers_1.toBigInt)(allowance),
25
+ ]));
26
+ this.permit2Allowances = permit2Allowances;
27
+ if (erc2612Nonce != null)
28
+ this.erc2612Nonce = (0, ethers_1.toBigInt)(erc2612Nonce);
29
+ }
30
+ }
31
+ exports.Holding = Holding;
@@ -0,0 +1,17 @@
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("./Holding"), exports);
@@ -15,7 +15,6 @@ export * from "./position";
15
15
  export * from "./helpers";
16
16
  export * from "./ethers";
17
17
  export * from "./vault";
18
-
19
18
  export * as evm from "./evm";
20
19
  export * as constants from "./constants";
21
20
  export * as errors from "./errors";
@@ -0,0 +1,159 @@
1
+ import { BigNumberish, Provider } from "ethers";
2
+ import { ViewOverrides } from "ethers-types/dist/common";
3
+ import { ChainId } from "../chain";
4
+ import { RoundingDirection } from "../maths";
5
+ import { MarketId } from "../types";
6
+ import { MarketConfig } from "./MarketConfig";
7
+ export declare enum CapacityLimitReason {
8
+ liquidity = "Liquidity",
9
+ balance = "Balance",
10
+ position = "Position",
11
+ collateral = "Collateral",
12
+ cap = "Cap"
13
+ }
14
+ export interface CapacityLimit {
15
+ value: bigint;
16
+ limiter: CapacityLimitReason;
17
+ }
18
+ export interface MaxPositionCapacities {
19
+ supply: CapacityLimit;
20
+ withdraw: CapacityLimit;
21
+ borrow: CapacityLimit;
22
+ repay: CapacityLimit;
23
+ supplyCollateral: CapacityLimit;
24
+ withdrawCollateral: CapacityLimit;
25
+ }
26
+ export interface InputMarket {
27
+ config: MarketConfig;
28
+ totalSupplyAssets: BigNumberish;
29
+ totalBorrowAssets: BigNumberish;
30
+ totalSupplyShares: BigNumberish;
31
+ totalBorrowShares: BigNumberish;
32
+ lastUpdate: BigNumberish;
33
+ fee: BigNumberish;
34
+ price: BigNumberish;
35
+ rateAtTarget?: BigNumberish;
36
+ }
37
+ export declare class Market implements InputMarket {
38
+ static fetchFromId(id: MarketId, runner: {
39
+ provider: Provider;
40
+ }, { chainId, overrides, }?: {
41
+ chainId?: ChainId;
42
+ overrides?: ViewOverrides;
43
+ }): Promise<Market>;
44
+ static fetchFromConfig(config: MarketConfig, runner: {
45
+ provider: Provider;
46
+ }, { chainId, overrides, }?: {
47
+ chainId?: ChainId;
48
+ overrides?: ViewOverrides;
49
+ }): Promise<Market>;
50
+ /**
51
+ * The market's config.
52
+ */
53
+ readonly config: MarketConfig;
54
+ /**
55
+ * The amount of loan assets supplied in total on the market.
56
+ */
57
+ totalSupplyAssets: bigint;
58
+ /**
59
+ * The amount of loan assets supplied in total on the market.
60
+ */
61
+ totalBorrowAssets: bigint;
62
+ /**
63
+ * The amount of loan assets supplied in total on the market.
64
+ */
65
+ totalSupplyShares: bigint;
66
+ /**
67
+ * The amount of loan assets supplied in total on the market.
68
+ */
69
+ totalBorrowShares: bigint;
70
+ /**
71
+ * The block timestamp (in __seconds__) when the interest was last accrued.
72
+ */
73
+ lastUpdate: bigint;
74
+ /**
75
+ * The fee percentage of the market, scaled by WAD.
76
+ */
77
+ fee: bigint;
78
+ /**
79
+ * The price as returned by the market's oracle.
80
+ */
81
+ price: bigint;
82
+ /**
83
+ * If the market uses the Adaptive Curve IRM, the rate at target utilization.
84
+ * Undefined otherwise.
85
+ */
86
+ rateAtTarget?: bigint;
87
+ constructor({ config, totalSupplyAssets, totalBorrowAssets, totalSupplyShares, totalBorrowShares, lastUpdate, fee, price, rateAtTarget, }: InputMarket);
88
+ get id(): MarketId;
89
+ get isIdle(): boolean;
90
+ /**
91
+ * @warning Cannot be used to calculate the liquidity available inside a callback,
92
+ * because the balance of Blue may be lower than the market's liquidity due to assets being transferred out prior to the callback.
93
+ */
94
+ get liquidity(): bigint;
95
+ get utilization(): bigint;
96
+ get apyAtTarget(): bigint | undefined;
97
+ get supplyRate(): bigint;
98
+ get borrowRate(): bigint;
99
+ get supplyApy(): bigint;
100
+ get borrowApy(): bigint;
101
+ accrueInterest(timestamp: BigNumberish): Market;
102
+ getLiquidityToUtilization(utilization: BigNumberish): bigint;
103
+ getCollateralValue(collateral: BigNumberish): bigint;
104
+ getMaxBorrowAssets(collateral: BigNumberish): bigint;
105
+ getMaxBorrowableAssets(position: {
106
+ collateral: BigNumberish;
107
+ borrowShares: BigNumberish;
108
+ }): bigint;
109
+ getLiquidationSeizedAssets(repaidShares: BigNumberish): bigint;
110
+ getLiquidationRepaidShares(seizedAssets: BigNumberish): bigint;
111
+ getSeizableCollateral(position: {
112
+ collateral: BigNumberish;
113
+ borrowShares: BigNumberish;
114
+ }): bigint;
115
+ getWithdrawableCollateral(position: {
116
+ collateral: BigNumberish;
117
+ borrowShares: BigNumberish;
118
+ }): bigint;
119
+ isHealthy(position: {
120
+ collateral: BigNumberish;
121
+ borrowShares: BigNumberish;
122
+ }): boolean;
123
+ getLiquidationPrice(position: {
124
+ collateral: BigNumberish;
125
+ borrowShares: BigNumberish;
126
+ }): bigint | null;
127
+ getPriceVariationToLiquidation(position: {
128
+ collateral: BigNumberish;
129
+ borrowShares: BigNumberish;
130
+ }): bigint | null;
131
+ getHealthFactor(position: {
132
+ collateral: BigNumberish;
133
+ borrowShares: BigNumberish;
134
+ }): bigint | null;
135
+ getLtv(position: {
136
+ collateral: BigNumberish;
137
+ borrowShares: BigNumberish;
138
+ }): bigint | null;
139
+ getBorrowCapacityUsage(position: {
140
+ collateral: BigNumberish;
141
+ borrowShares: BigNumberish;
142
+ }): bigint | null;
143
+ toSupplyAssets(shares: BigNumberish, rounding?: RoundingDirection): bigint;
144
+ toSupplyShares(assets: BigNumberish, rounding?: RoundingDirection): bigint;
145
+ toBorrowAssets(shares: BigNumberish, rounding?: RoundingDirection): bigint;
146
+ toBorrowShares(assets: BigNumberish, rounding?: RoundingDirection): bigint;
147
+ getBorrowCapacityLimit(collateral: bigint): CapacityLimit;
148
+ getRepayCapacityLimit(borrowShares: bigint, loanTokenBalance: bigint): CapacityLimit;
149
+ getWithdrawCapacityLimit(supplyShares: bigint): CapacityLimit;
150
+ getWithdrawCollateralCapacityLimit(position: {
151
+ collateral: bigint;
152
+ borrowShares: bigint;
153
+ }): CapacityLimit;
154
+ getMaxCapacities(position: {
155
+ collateral: bigint;
156
+ supplyShares: bigint;
157
+ borrowShares: bigint;
158
+ }, loanTokenBalance: bigint, collateralTokenBalance: bigint): MaxPositionCapacities;
159
+ }
@@ -0,0 +1,240 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Market = exports.CapacityLimitReason = void 0;
4
+ const ethers_1 = require("ethers");
5
+ const ethers_types_1 = require("ethers-types");
6
+ const addresses_1 = require("../addresses");
7
+ const chain_1 = require("../chain");
8
+ const errors_1 = require("../errors");
9
+ const maths_1 = require("../maths");
10
+ const MarketConfig_1 = require("./MarketConfig");
11
+ const MarketUtils_1 = require("./MarketUtils");
12
+ var CapacityLimitReason;
13
+ (function (CapacityLimitReason) {
14
+ CapacityLimitReason["liquidity"] = "Liquidity";
15
+ CapacityLimitReason["balance"] = "Balance";
16
+ CapacityLimitReason["position"] = "Position";
17
+ CapacityLimitReason["collateral"] = "Collateral";
18
+ CapacityLimitReason["cap"] = "Cap";
19
+ })(CapacityLimitReason || (exports.CapacityLimitReason = CapacityLimitReason = {}));
20
+ class Market {
21
+ static async fetchFromId(id, runner, { chainId, overrides = {}, } = {}) {
22
+ chainId ?? (chainId = chain_1.ChainUtils.parseSupportedChainId((await runner.provider.getNetwork()).chainId));
23
+ const config = await MarketConfig_1.MarketConfig.fetch(id, runner, chainId);
24
+ return Market.fetchFromConfig(config, runner, { chainId, overrides });
25
+ }
26
+ static async fetchFromConfig(config, runner, { chainId, overrides = {}, } = {}) {
27
+ chainId ?? (chainId = chain_1.ChainUtils.parseSupportedChainId((await runner.provider.getNetwork()).chainId));
28
+ const { morpho, adaptiveCurveIrm } = (0, addresses_1.getChainAddresses)(chainId);
29
+ const [{ totalSupplyAssets, totalSupplyShares, totalBorrowShares, totalBorrowAssets, lastUpdate, fee, }, price, rateAtTarget,] = await Promise.all([
30
+ ethers_types_1.MorphoBlue__factory.connect(morpho, runner).market(config.id, overrides),
31
+ config.oracle !== ethers_1.ZeroAddress
32
+ ? ethers_types_1.BlueOracle__factory.connect(config.oracle, runner).price(overrides)
33
+ : 0n,
34
+ config.irm === adaptiveCurveIrm
35
+ ? await ethers_types_1.AdaptiveCurveIrm__factory.connect(config.irm, runner).rateAtTarget(config.id, overrides)
36
+ : undefined,
37
+ ]);
38
+ return new Market({
39
+ config,
40
+ totalSupplyAssets,
41
+ totalBorrowAssets,
42
+ totalSupplyShares,
43
+ totalBorrowShares,
44
+ lastUpdate,
45
+ fee,
46
+ price,
47
+ rateAtTarget,
48
+ });
49
+ }
50
+ constructor({ config, totalSupplyAssets, totalBorrowAssets, totalSupplyShares, totalBorrowShares, lastUpdate, fee, price, rateAtTarget, }) {
51
+ this.config = config;
52
+ this.totalSupplyAssets = (0, ethers_1.toBigInt)(totalSupplyAssets);
53
+ this.totalBorrowAssets = (0, ethers_1.toBigInt)(totalBorrowAssets);
54
+ this.totalSupplyShares = (0, ethers_1.toBigInt)(totalSupplyShares);
55
+ this.totalBorrowShares = (0, ethers_1.toBigInt)(totalBorrowShares);
56
+ this.lastUpdate = (0, ethers_1.toBigInt)(lastUpdate);
57
+ this.fee = (0, ethers_1.toBigInt)(fee);
58
+ this.price = (0, ethers_1.toBigInt)(price);
59
+ if (rateAtTarget != null)
60
+ this.rateAtTarget = (0, ethers_1.toBigInt)(rateAtTarget);
61
+ }
62
+ get id() {
63
+ return this.config.id;
64
+ }
65
+ get isIdle() {
66
+ return this.config.collateralToken === ethers_1.ZeroAddress;
67
+ }
68
+ /**
69
+ * @warning Cannot be used to calculate the liquidity available inside a callback,
70
+ * because the balance of Blue may be lower than the market's liquidity due to assets being transferred out prior to the callback.
71
+ */
72
+ get liquidity() {
73
+ return this.totalSupplyAssets - this.totalBorrowAssets;
74
+ }
75
+ get utilization() {
76
+ return MarketUtils_1.MarketUtils.getUtilization(this);
77
+ }
78
+ get apyAtTarget() {
79
+ if (this.rateAtTarget == null)
80
+ return;
81
+ return MarketUtils_1.MarketUtils.getApy(this.rateAtTarget);
82
+ }
83
+ get supplyRate() {
84
+ return MarketUtils_1.MarketUtils.getSupplyRate(this.borrowRate, this);
85
+ }
86
+ get borrowRate() {
87
+ if (this.rateAtTarget == null)
88
+ return 0n;
89
+ return maths_1.AdaptiveCurveIrmLib.getBorrowRate(this.utilization, this.rateAtTarget, 0n).avgBorrowRate;
90
+ }
91
+ get supplyApy() {
92
+ return MarketUtils_1.MarketUtils.getApy(this.supplyRate);
93
+ }
94
+ get borrowApy() {
95
+ return MarketUtils_1.MarketUtils.getApy(this.borrowRate);
96
+ }
97
+ accrueInterest(timestamp) {
98
+ timestamp = (0, ethers_1.toBigInt)(timestamp);
99
+ const elapsed = timestamp - this.lastUpdate;
100
+ if (elapsed < 0n)
101
+ throw new errors_1.InvalidInterestAccrualError(this.id, timestamp, this.lastUpdate);
102
+ let borrowRate = 0n;
103
+ let { rateAtTarget } = this;
104
+ if (this.rateAtTarget != null) {
105
+ const { avgBorrowRate, endRateAtTarget } = maths_1.AdaptiveCurveIrmLib.getBorrowRate(this.utilization, this.rateAtTarget, elapsed);
106
+ borrowRate = avgBorrowRate;
107
+ rateAtTarget = endRateAtTarget;
108
+ }
109
+ const { interest, feeShares } = MarketUtils_1.MarketUtils.getAccruedInterest(borrowRate, this, elapsed);
110
+ return new Market({
111
+ ...this,
112
+ totalSupplyAssets: this.totalSupplyAssets + interest,
113
+ totalBorrowAssets: this.totalBorrowAssets + interest,
114
+ totalSupplyShares: this.totalSupplyShares + feeShares,
115
+ lastUpdate: timestamp,
116
+ rateAtTarget,
117
+ });
118
+ }
119
+ getLiquidityToUtilization(utilization) {
120
+ return MarketUtils_1.MarketUtils.getLiquidityToUtilization(this, utilization);
121
+ }
122
+ getCollateralValue(collateral) {
123
+ return MarketUtils_1.MarketUtils.getCollateralValue(collateral, this);
124
+ }
125
+ getMaxBorrowAssets(collateral) {
126
+ return MarketUtils_1.MarketUtils.getMaxBorrowAssets(collateral, this, this.config);
127
+ }
128
+ getMaxBorrowableAssets(position) {
129
+ return MarketUtils_1.MarketUtils.getMaxBorrowableAssets(position, this, this.config);
130
+ }
131
+ getLiquidationSeizedAssets(repaidShares) {
132
+ return MarketUtils_1.MarketUtils.getLiquidationSeizedAssets(repaidShares, this, this.config);
133
+ }
134
+ getLiquidationRepaidShares(seizedAssets) {
135
+ return MarketUtils_1.MarketUtils.getLiquidationRepaidShares(seizedAssets, this, this.config);
136
+ }
137
+ getSeizableCollateral(position) {
138
+ return MarketUtils_1.MarketUtils.getSeizableCollateral(position, this, this.config);
139
+ }
140
+ getWithdrawableCollateral(position) {
141
+ return MarketUtils_1.MarketUtils.getWithdrawableCollateral(position, this, this.config);
142
+ }
143
+ isHealthy(position) {
144
+ return MarketUtils_1.MarketUtils.isHealthy(position, this, this.config);
145
+ }
146
+ getLiquidationPrice(position) {
147
+ return MarketUtils_1.MarketUtils.getLiquidationPrice(position, this, this.config);
148
+ }
149
+ getPriceVariationToLiquidation(position) {
150
+ return MarketUtils_1.MarketUtils.getPriceVariationToLiquidation(position, this, this.config);
151
+ }
152
+ getHealthFactor(position) {
153
+ return MarketUtils_1.MarketUtils.getHealthFactor(position, this, this.config);
154
+ }
155
+ getLtv(position) {
156
+ return MarketUtils_1.MarketUtils.getLtv(position, this);
157
+ }
158
+ getBorrowCapacityUsage(position) {
159
+ return MarketUtils_1.MarketUtils.getBorrowCapacityUsage(position, this, this.config);
160
+ }
161
+ toSupplyAssets(shares, rounding) {
162
+ return MarketUtils_1.MarketUtils.toSupplyAssets(shares, this, rounding);
163
+ }
164
+ toSupplyShares(assets, rounding) {
165
+ return MarketUtils_1.MarketUtils.toSupplyShares(assets, this, rounding);
166
+ }
167
+ toBorrowAssets(shares, rounding) {
168
+ return MarketUtils_1.MarketUtils.toBorrowAssets(shares, this, rounding);
169
+ }
170
+ toBorrowShares(assets, rounding) {
171
+ return MarketUtils_1.MarketUtils.toBorrowShares(assets, this, rounding);
172
+ }
173
+ getBorrowCapacityLimit(collateral) {
174
+ const maxBorrowableAssets = this.getMaxBorrowAssets(collateral);
175
+ const { liquidity } = this;
176
+ if (maxBorrowableAssets > liquidity)
177
+ return {
178
+ value: liquidity,
179
+ limiter: CapacityLimitReason.liquidity,
180
+ };
181
+ return {
182
+ value: maxBorrowableAssets,
183
+ limiter: CapacityLimitReason.collateral,
184
+ };
185
+ }
186
+ getRepayCapacityLimit(borrowShares, loanTokenBalance) {
187
+ const borrowAssets = this.toBorrowAssets(borrowShares);
188
+ if (borrowAssets > loanTokenBalance)
189
+ return {
190
+ value: loanTokenBalance,
191
+ limiter: CapacityLimitReason.balance,
192
+ };
193
+ return {
194
+ value: borrowAssets,
195
+ limiter: CapacityLimitReason.position,
196
+ };
197
+ }
198
+ getWithdrawCapacityLimit(supplyShares) {
199
+ const supplyAssets = this.toSupplyAssets(supplyShares);
200
+ const { liquidity } = this;
201
+ if (supplyAssets > liquidity)
202
+ return {
203
+ value: liquidity,
204
+ limiter: CapacityLimitReason.liquidity,
205
+ };
206
+ return {
207
+ value: supplyAssets,
208
+ limiter: CapacityLimitReason.position,
209
+ };
210
+ }
211
+ getWithdrawCollateralCapacityLimit(position) {
212
+ const withdrawableCollateral = this.getWithdrawableCollateral(position);
213
+ if (position.collateral > withdrawableCollateral)
214
+ return {
215
+ value: withdrawableCollateral,
216
+ limiter: CapacityLimitReason.collateral,
217
+ };
218
+ return {
219
+ value: position.collateral,
220
+ limiter: CapacityLimitReason.position,
221
+ };
222
+ }
223
+ getMaxCapacities(position, loanTokenBalance, collateralTokenBalance) {
224
+ return {
225
+ supply: {
226
+ value: loanTokenBalance,
227
+ limiter: CapacityLimitReason.balance,
228
+ },
229
+ withdraw: this.getWithdrawCapacityLimit(position.supplyShares),
230
+ borrow: this.getBorrowCapacityLimit(position.collateral),
231
+ repay: this.getRepayCapacityLimit(position.borrowShares, loanTokenBalance),
232
+ supplyCollateral: {
233
+ value: collateralTokenBalance,
234
+ limiter: CapacityLimitReason.balance,
235
+ },
236
+ withdrawCollateral: this.getWithdrawCollateralCapacityLimit(position),
237
+ };
238
+ }
239
+ }
240
+ exports.Market = Market;
@@ -0,0 +1,44 @@
1
+ import { Provider } from "ethers";
2
+ import { MarketParamsStruct } from "ethers-types/dist/protocols/morpho/blue/MorphoBlue";
3
+ import { ChainId } from "../chain";
4
+ import { Address, MarketId } from "../types";
5
+ export interface MarketParams extends MarketParamsStruct {
6
+ loanToken: Address;
7
+ collateralToken: Address;
8
+ oracle: Address;
9
+ irm: Address;
10
+ }
11
+ export declare class MarketConfig implements MarketParams {
12
+ private static readonly _CACHE;
13
+ static get(id: MarketId): MarketConfig;
14
+ static fetch(id: MarketId, runner: {
15
+ provider: Provider;
16
+ }, chainId?: ChainId): Promise<MarketConfig>;
17
+ static idle(token: Address): MarketConfig;
18
+ /**
19
+ * The market's collateral token address.
20
+ */
21
+ readonly collateralToken: Address;
22
+ /**
23
+ * The market's loan token address.
24
+ */
25
+ readonly loanToken: Address;
26
+ /**
27
+ * The market's oracle address.
28
+ */
29
+ readonly oracle: Address;
30
+ /**
31
+ * The market's interest rate model address.
32
+ */
33
+ readonly irm: Address;
34
+ /**
35
+ * The market's liquidation Loan-To-Value (scaled by WAD).
36
+ */
37
+ readonly lltv: bigint;
38
+ constructor({ collateralToken, loanToken, oracle, irm, lltv }: MarketParams);
39
+ /**
40
+ * The market's hex-encoded id, defined as the hash of the market's params.
41
+ */
42
+ get id(): MarketId;
43
+ get liquidationIncentiveFactor(): bigint;
44
+ }