@morpho-org/midnight-sdk
Version:
Viem-based package for Morpho Midnight that exports protocol utilities, fetch helpers, and Midnight API utilities under a dedicated API subpath.
380 lines (379 loc) • 15.3 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MarketUtils = void 0;
const morpho_ts_1 = require("@morpho-org/morpho-ts");
const viem_1 = require("viem");
const constants_js_1 = require("../constants.js");
const errors_js_1 = require("../errors.js");
const Market_js_1 = require("./Market.js");
const SSTORE2_PREFIX = "0x600b380380600b5f395ff3";
const collateralParamsHashParams = [
{ name: "typehash", type: "bytes32" },
{ name: "token", type: "address" },
{ name: "lltv", type: "uint256" },
{ name: "liquidationCursor", type: "uint256" },
{ name: "oracle", type: "address" },
];
const marketHashParams = [
{ name: "typehash", type: "bytes32" },
{ name: "chainId", type: "uint256" },
{ name: "midnight", type: "address" },
{ name: "loanToken", type: "address" },
{ name: "collateralParamsHash", type: "bytes32" },
{ name: "maturity", type: "uint256" },
{ name: "rcfThreshold", type: "uint256" },
{ name: "enterGate", type: "address" },
{ name: "liquidatorGate", type: "address" },
];
const marketParamsAbiParameter = {
type: "tuple",
components: [
{ name: "chainId", type: "uint256" },
{ name: "midnight", type: "address" },
{ name: "loanToken", type: "address" },
{
name: "collateralParams",
type: "tuple[]",
components: [
{ name: "token", type: "address" },
{ name: "lltv", type: "uint256" },
{ name: "liquidationCursor", type: "uint256" },
{ name: "oracle", type: "address" },
],
},
{ name: "maturity", type: "uint256" },
{ name: "rcfThreshold", type: "uint256" },
{ name: "enterGate", type: "address" },
{ name: "liquidatorGate", type: "address" },
],
};
/**
* Domain helpers for Midnight markets.
*
* @example
* ```ts
* import { MarketUtils } from "@morpho-org/midnight-sdk";
*
* console.log(typeof MarketUtils.hash);
* ```
*/
var MarketUtils;
(function (MarketUtils) {
/**
* @internal Orders collaterals by token address, case-insensitively, matching the protocol's
* canonical `collateralIndex` order used by `MarketParams` and `MarketUtils.hash`.
*
* @param a - First collateral.
* @param b - Second collateral.
* @returns Negative when `a` sorts before `b`, positive when after, `0` when tokens are equal.
*/
function compareCollateralTokens(a, b) {
const tokenA = a.token.toLowerCase();
const tokenB = b.token.toLowerCase();
if (tokenA === tokenB)
return 0;
return tokenA < tokenB ? -1 : 1;
}
MarketUtils.compareCollateralTokens = compareCollateralTokens;
/**
* Converts collateral params from a plain input or ABI tuple.
*
* @param params.token - Collateral token address.
* @param params.lltv - WAD-scaled liquidation loan-to-value.
* @param params.liquidationCursor - WAD-scaled liquidation cursor.
* @param params.oracle - Oracle address used to price this collateral.
* @returns Collateral params with bigint fields.
* @example
* ```ts
* import { MarketUtils } from "@morpho-org/midnight-sdk";
*
* const collateral = MarketUtils.toCollateralParams({
* token: "0x0000000000000000000000000000000000000001",
* lltv: 770000000000000000n,
* liquidationCursor: 250000000000000000n,
* oracle: "0x0000000000000000000000000000000000000002",
* });
* console.log(collateral.liquidationCursor);
* ```
*/
function toCollateralParams(params) {
let lltv;
let liquidationCursor;
try {
lltv = BigInt(params.lltv);
liquidationCursor = BigInt(params.liquidationCursor);
}
catch (cause) {
throw new errors_js_1.InvalidMarketParameterError({
parameter: "collateralParams",
value: params,
instruction: "Provide bigint-compatible lltv and liquidationCursor values.",
cause,
});
}
return {
token: params.token,
lltv,
liquidationCursor,
oracle: params.oracle,
};
}
MarketUtils.toCollateralParams = toCollateralParams;
/**
* Converts market params into the tuple object expected by viem ABI encoders.
*
* @param market - Market params or hydrated market.
* @returns ABI-compatible market params.
* @example
* ```ts
* import { MarketUtils } from "@morpho-org/midnight-sdk";
*
* const struct = MarketUtils.toStruct({
* chainId: 8453,
* midnight: "0x0000000000000000000000000000000000001000",
* loanToken: "0x0000000000000000000000000000000000006000",
* collateralParams: [
* {
* token: "0x0000000000000000000000000000000000007000",
* lltv: 770000000000000000n,
* liquidationCursor: 250000000000000000n,
* oracle: "0x0000000000000000000000000000000000008000",
* },
* ],
* maturity: 54_000n,
* rcfThreshold: 0n,
* enterGate: "0x0000000000000000000000000000000000000000",
* liquidatorGate: "0x0000000000000000000000000000000000000000",
* });
* console.log(struct.maturity);
* ```
*/
function toStruct(market) {
const params = Market_js_1.MarketParams.from(market);
return {
chainId: params.chainId,
midnight: params.midnight,
loanToken: params.loanToken,
collateralParams: params.collateralParams.map((collateral) => ({
token: collateral.token,
lltv: collateral.lltv,
liquidationCursor: collateral.liquidationCursor,
oracle: collateral.oracle,
})),
maturity: params.maturity,
rcfThreshold: params.rcfThreshold,
enterGate: params.enterGate,
liquidatorGate: params.liquidatorGate,
};
}
MarketUtils.toStruct = toStruct;
/**
* Returns configured collateral by index.
*
* @param market - Market params or hydrated market.
* @param index - Collateral index to look up.
* @returns Collateral entry for the configured index.
* @throws {UnknownCollateralIndexError} when the index is not configured.
* @example
* ```ts
* import { MarketUtils } from "@morpho-org/midnight-sdk";
*
* const collateral = MarketUtils.getCollateralByIndex({
* chainId: 8453,
* midnight: "0x0000000000000000000000000000000000001000",
* loanToken: "0x0000000000000000000000000000000000000001",
* collateralParams: [
* {
* token: "0x0000000000000000000000000000000000000002",
* lltv: 770000000000000000n,
* liquidationCursor: 250000000000000000n,
* oracle: "0x0000000000000000000000000000000000000003",
* },
* ],
* maturity: 1n,
* rcfThreshold: 0n,
* enterGate: "0x0000000000000000000000000000000000000000",
* liquidatorGate: "0x0000000000000000000000000000000000000000",
* }, 0n);
* console.log(collateral.token);
* ```
*/
function getCollateralByIndex(market, index) {
const normalizedIndex = BigInt(index);
const params = Market_js_1.MarketParams.from(market);
const collateral = normalizedIndex >= 0n &&
normalizedIndex <= BigInt(Number.MAX_SAFE_INTEGER)
? params.collateralParams[Number(normalizedIndex)]
: undefined;
if (collateral == null) {
throw new errors_js_1.UnknownCollateralIndexError({
market: toId(params),
collateralIndex: normalizedIndex,
});
}
return collateral;
}
MarketUtils.getCollateralByIndex = getCollateralByIndex;
/**
* Returns the liquidation incentive factor for an LLTV and liquidation cursor.
*
* @param input - WAD-scaled LLTV or collateral params carrying an LLTV.
* @param cursor - WAD-scaled liquidation cursor.
* @returns WAD-scaled liquidation incentive factor.
* @example
* ```ts
* import { MarketUtils } from "@morpho-org/midnight-sdk";
*
* const liquidationIncentiveFactor = MarketUtils.getLiquidationIncentiveFactor(
* 770000000000000000n,
* 250000000000000000n,
* );
* console.log(liquidationIncentiveFactor);
* ```
*/
function getLiquidationIncentiveFactor(input, cursor) {
const lltv = typeof input === "object" ? input.lltv : input;
const cursorValue = BigInt(cursor);
const denominator = morpho_ts_1.MathLib.WAD -
morpho_ts_1.MathLib.mulDiv(cursorValue, morpho_ts_1.MathLib.WAD - BigInt(lltv), morpho_ts_1.MathLib.WAD, "Down");
return morpho_ts_1.MathLib.mulDiv(morpho_ts_1.MathLib.WAD, morpho_ts_1.MathLib.WAD, denominator, "Down");
}
MarketUtils.getLiquidationIncentiveFactor = getLiquidationIncentiveFactor;
/**
* Computes the Midnight settlement fee from market cbp buckets and time to maturity.
*
* This mirrors Midnight `settlementFee`: cbp buckets are scaled by {@link CBP},
* values are linearly interpolated between {@link SETTLEMENT_FEE_BREAKPOINTS},
* and any time to maturity at or above 360 days uses the last bucket.
*
* @param params.settlementFeeCbps - Seven settlement-fee centibip buckets from the market state.
* @param params.timeToMaturity - Seconds until market maturity.
* @returns WAD-scaled settlement fee.
* @throws {NegativeValueError} when `timeToMaturity` is negative.
* @example
* ```ts
* import { MarketUtils } from "@morpho-org/midnight-sdk";
*
* const fee = MarketUtils.getSettlementFee({
* settlementFeeCbps: [1, 2, 3, 4, 5, 6, 7],
* timeToMaturity: 12n * 60n * 60n,
* });
* console.log(fee);
* ```
*/
function getSettlementFee(params) {
const timeToMaturity = BigInt(params.timeToMaturity);
(0, morpho_ts_1.assertNonNegative)("timeToMaturity", timeToMaturity);
const lastIndex = constants_js_1.SETTLEMENT_FEE_BREAKPOINTS.length - 1;
const lastBreakpoint = constants_js_1.SETTLEMENT_FEE_BREAKPOINTS[lastIndex];
if (timeToMaturity >= lastBreakpoint) {
return BigInt(params.settlementFeeCbps[lastIndex]) * constants_js_1.CBP;
}
const upperIndex = constants_js_1.SETTLEMENT_FEE_BREAKPOINTS.findIndex((breakpoint) => timeToMaturity < breakpoint);
const lowerIndex = upperIndex - 1;
const start = constants_js_1.SETTLEMENT_FEE_BREAKPOINTS[lowerIndex];
const end = constants_js_1.SETTLEMENT_FEE_BREAKPOINTS[upperIndex];
const feeLower = BigInt(params.settlementFeeCbps[lowerIndex]) * constants_js_1.CBP;
const feeUpper = BigInt(params.settlementFeeCbps[upperIndex]) * constants_js_1.CBP;
return ((feeLower * (end - timeToMaturity) +
feeUpper * (timeToMaturity - start)) /
(end - start));
}
MarketUtils.getSettlementFee = getSettlementFee;
/**
* Computes the HashLib market params struct hash.
*
* Hashing canonicalizes non-empty collateral params by token order and
* preserves the protocol-zero empty market used for tree padding. It does
* not validate every market creation rule. Use {@link MarketParams} when
* constructing user-facing market params.
*
* @param market - Market to hash.
* @returns EIP-712 market struct hash.
* @example
* ```ts
* import { MarketUtils } from "@morpho-org/midnight-sdk";
*
* const hash = MarketUtils.hash({
* chainId: 8453,
* midnight: "0x0000000000000000000000000000000000001000",
* loanToken: "0x0000000000000000000000000000000000000001",
* collateralParams: [
* {
* token: "0x0000000000000000000000000000000000000002",
* lltv: 770000000000000000n,
* liquidationCursor: 250000000000000000n,
* oracle: "0x0000000000000000000000000000000000000003",
* },
* ],
* maturity: 1n,
* rcfThreshold: 0n,
* enterGate: "0x0000000000000000000000000000000000000000",
* liquidatorGate: "0x0000000000000000000000000000000000000000",
* });
* console.log(hash);
* ```
*/
function hash(market) {
const marketParams = "params" in market ? market.params : market;
const collateralParams = marketParams.collateralParams.length === 0
? marketParams.collateralParams
: [...marketParams.collateralParams].sort(compareCollateralTokens);
const collateralParamHashes = collateralParams.map((params) => (0, viem_1.keccak256)((0, viem_1.encodeAbiParameters)(collateralParamsHashParams, [
constants_js_1.COLLATERAL_PARAMS_TYPEHASH,
params.token,
BigInt(params.lltv),
BigInt(params.liquidationCursor),
params.oracle,
])));
const collateralParamsHash = (0, viem_1.keccak256)((0, viem_1.concat)(collateralParamHashes));
return (0, viem_1.keccak256)((0, viem_1.encodeAbiParameters)(marketHashParams, [
constants_js_1.MARKET_TYPEHASH,
BigInt(marketParams.chainId),
marketParams.midnight,
marketParams.loanToken,
collateralParamsHash,
BigInt(marketParams.maturity),
BigInt(marketParams.rcfThreshold),
marketParams.enterGate,
marketParams.liquidatorGate,
]));
}
MarketUtils.hash = hash;
/**
* Computes the Midnight id for a market using `IdLib.toId`.
*
* @param market - Market to hash.
* @returns Market id.
* @example
* ```ts
* import { MarketUtils } from "@morpho-org/midnight-sdk";
*
* const id = MarketUtils.toId({
* chainId: 8453,
* midnight: "0x0000000000000000000000000000000000001000",
* loanToken: "0x0000000000000000000000000000000000000001",
* collateralParams: [
* {
* token: "0x0000000000000000000000000000000000000002",
* lltv: 770000000000000000n,
* liquidationCursor: 250000000000000000n,
* oracle: "0x0000000000000000000000000000000000000003",
* },
* ],
* maturity: 1n,
* rcfThreshold: 0n,
* enterGate: "0x0000000000000000000000000000000000000000",
* liquidatorGate: "0x0000000000000000000000000000000000000000",
* });
* console.log(id);
* ```
*/
function toId(market) {
const marketParams = Market_js_1.MarketParams.from(market);
const encodedMarket = (0, viem_1.encodeAbiParameters)([marketParamsAbiParameter], [toStruct(marketParams)]);
const creationHash = (0, viem_1.keccak256)((0, viem_1.concat)([SSTORE2_PREFIX, encodedMarket]));
return (0, viem_1.keccak256)((0, viem_1.encodePacked)(["uint8", "address", "uint256", "bytes32"], [255, marketParams.midnight, 0n, creationHash]));
}
MarketUtils.toId = toId;
})(MarketUtils || (exports.MarketUtils = MarketUtils = {}));