@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.
502 lines (501 loc) • 23.8 kB
JavaScript
import { BLUE_API_BASE_URL, isHexEqual } from "@morpho-org/morpho-ts";
import { isAddress, isAddressEqual, isHex, maxUint256, zeroAddress, } from "viem";
import { InvalidMidnightApiResponseError, InvalidOfferParameterError, MidnightApiError, } from "../errors.js";
import { MarketUtils } from "../market/index.js";
import { TickLib } from "../math/index.js";
import { OfferUtils } from "../offers/index.js";
import { version } from "../version.js";
import { MempoolPayloadValidationRule, } from "./types.js";
const DEFAULT_MIDNIGHT_API_URL = new URL("/v0/midnight", BLUE_API_BASE_URL);
const MAX_UINT256_DECIMAL_LENGTH = maxUint256.toString().length;
/** @internal Sends one Midnight API request and maps non-2xx responses to SDK errors. */
export async function requestMidnightApi(params) {
const baseUrl = new URL(params.baseUrl ?? DEFAULT_MIDNIGHT_API_URL);
baseUrl.search = "";
baseUrl.hash = "";
if (!baseUrl.pathname.endsWith("/")) {
baseUrl.pathname = `${baseUrl.pathname}/`;
}
const relativePath = params.path.startsWith("/")
? params.path.slice(1)
: params.path;
const url = new URL(relativePath, baseUrl);
url.search = "";
url.hash = "";
if (params.query != null) {
for (const [key, value] of Object.entries(params.query)) {
if (value === undefined) {
continue;
}
if (Array.isArray(value) && value.length === 0) {
continue;
}
if (Array.isArray(value)) {
url.searchParams.set(key, value.map(String).join(","));
}
else {
url.searchParams.set(key, value instanceof Date ? value.toISOString() : String(value));
}
}
}
const headers = new Headers(params.request?.headers);
if (params.body !== undefined) {
headers.set("Content-Type", "application/json");
}
headers.set("sdk-version", version);
const init = {
...params.request,
method: params.method,
headers,
};
init.body =
params.body === undefined ? undefined : JSON.stringify(params.body);
const response = await (params.fetch ?? globalThis.fetch)(url, init);
let json;
let jsonParseError;
try {
json = await response.json();
}
catch (error) {
if (response.ok) {
throw new InvalidMidnightApiResponseError("Midnight API success response did not contain valid JSON.", { cause: error });
}
jsonParseError = error;
json = undefined;
}
if (!response.ok) {
const error = isRecord(json) && isRecord(json.error) ? json.error : undefined;
throw new MidnightApiError({
status: response.status,
code: typeof error?.code === "string" ? error.code : undefined,
message: typeof error?.message === "string" ? error.message : undefined,
details: error != null && "details" in error ? error.details : undefined,
requestId: typeof error?.request_id === "string" ? error.request_id : undefined,
cause: jsonParseError,
});
}
return json;
}
/** @internal Builds a book endpoint path with encoded path segments. */
export function buildBookPath(params) {
const segments = [
"books",
params.marketId,
params.side,
params.suffix,
].filter((segment) => segment !== undefined);
return segments.map(encodeURIComponent).join("/");
}
/**
* @internal Maps a book market API payload to the SDK response shape, rejecting any
* response whose advertised `market_id` cannot be derived from — or does not match —
* its own market params. Recomputing the id with `MarketUtils.toId` (mirroring the
* takeable-offers path) stops a hostile API from pairing a trusted id with foreign
* metadata; every book flows through here, so both bound paths reject the same substitution.
* Collaterals are returned in the protocol's canonical order so their array index matches
* the onchain `collateralIndex`.
*/
function mapBookMarket(book) {
// Validate the response shape before reading its fields.
requireObject(book, "book");
if (typeof book.market_id !== "string") {
throw new InvalidMidnightApiResponseError("Midnight API book market_id is not a string.");
}
let derivedMarketId;
let matchesAdvertisedId;
try {
derivedMarketId = MarketUtils.toId({
chainId: book.chain_id,
midnight: book.midnight,
loanToken: book.loan_token,
collateralParams: book.collaterals.map((collateral) => ({
token: collateral.token,
lltv: collateral.lltv,
liquidationCursor: collateral.liquidation_cursor,
oracle: collateral.oracle,
})),
maturity: book.maturity,
rcfThreshold: book.rcf_threshold,
enterGate: book.enter_gate,
liquidatorGate: book.liquidator_gate,
});
// Comparison stays inside the try so a malformed advertised `market_id`
// (non-hex value) surfaces as a wrapped response error, not a raw TypeError.
matchesAdvertisedId = isHexEqual(derivedMarketId, book.market_id);
}
catch (cause) {
throw new InvalidMidnightApiResponseError(`Midnight API book market_id "${book.market_id}" could not be validated against its market params.`, { cause });
}
if (!matchesAdvertisedId) {
throw new InvalidMidnightApiResponseError(`Midnight API book market_id "${book.market_id}" does not match the id "${derivedMarketId}" derived from its market params.`);
}
return {
marketId: book.market_id,
chainId: book.chain_id,
midnight: book.midnight,
loanToken: book.loan_token,
collaterals: [...book.collaterals]
.sort(MarketUtils.compareCollateralTokens)
.map(mapCollateral),
maturity: book.maturity,
rcfThreshold: book.rcf_threshold,
enterGate: book.enter_gate,
liquidatorGate: book.liquidator_gate,
asks: mapPriceLevels(book.asks, "asks"),
bids: mapPriceLevels(book.bids, "bids"),
};
}
/** @internal Maps a book market, binding its verified id to the requested market. */
export function mapBoundBookMarket(book, requestedMarketId) {
const market = mapBookMarket(book);
if (!isHexEqual(market.marketId, requestedMarketId)) {
throw new InvalidMidnightApiResponseError(`Midnight API book market_id "${market.marketId}" does not match requested market "${requestedMarketId}".`);
}
return market;
}
/** @internal Maps listed book markets, binding each verified id to requested filters when present. */
export function mapBoundBooks(books, context = {}) {
return requireArray(books, "books").map((book) => {
const market = mapBookMarket(book);
if (context.marketIds != null &&
context.marketIds.length > 0 &&
!context.marketIds.some((marketId) => isHexEqual(marketId, market.marketId))) {
throw new InvalidMidnightApiResponseError(`Midnight API book market_id "${market.marketId}" is outside the requested market_ids filter.`);
}
if (context.chainIds != null &&
context.chainIds.length > 0 &&
!context.chainIds.includes(market.chainId)) {
throw new InvalidMidnightApiResponseError(`Midnight API book market_id "${market.marketId}" is outside the requested chain_ids filter.`);
}
if (context.loanTokens != null &&
context.loanTokens.length > 0 &&
!context.loanTokens.some((token) => isAddressEqual(token, market.loanToken))) {
throw new InvalidMidnightApiResponseError(`Midnight API book market_id "${market.marketId}" is outside the requested loan_tokens filter.`);
}
const { collateralTokens } = context;
if (collateralTokens != null &&
collateralTokens.length > 0 &&
!market.collaterals.some((collateral) => collateralTokens.some((token) => isAddressEqual(token, collateral.token)))) {
throw new InvalidMidnightApiResponseError(`Midnight API book market_id "${market.marketId}" is outside the requested collateral_tokens filter.`);
}
if (context.maturities != null &&
context.maturities.length > 0 &&
!context.maturities.includes(market.maturity)) {
throw new InvalidMidnightApiResponseError(`Midnight API book market_id "${market.marketId}" is outside the requested maturities filter.`);
}
return market;
});
}
/** @internal Maps a collateral API payload to the SDK response shape. */
function mapCollateral(collateral) {
return {
token: collateral.token,
lltv: collateral.lltv,
liquidationCursor: collateral.liquidation_cursor,
oracle: collateral.oracle,
};
}
/** @internal Maps a price-level API payload to the SDK response shape. */
function mapPriceLevel(level) {
// Validate the response shape before reading its fields.
requireObject(level, "price level");
if (typeof level.tick !== "number" || !Number.isSafeInteger(level.tick)) {
throw new InvalidMidnightApiResponseError(`Midnight API price level tick (${typeof level.tick}) is not a safe integer.`);
}
const price = requireBigIntString(level.price, "price level price");
const units = requireBigIntString(level.units, "price level units");
const assets = requireBigIntString(level.assets, "price level assets");
if (typeof level.count !== "number" || !Number.isSafeInteger(level.count)) {
throw new InvalidMidnightApiResponseError(`Midnight API price level count (${typeof level.count}) is not a safe integer.`);
}
return {
tick: level.tick,
price,
units,
assets,
count: level.count,
};
}
/** @internal Maps API price levels and sorts them best first: asks by ascending tick, bids by descending tick. */
export function mapPriceLevels(levels, side) {
return requireArray(levels, "price levels")
.map(mapPriceLevel)
.sort((a, b) => (side === "asks" ? a.tick - b.tick : b.tick - a.tick));
}
/**
* @internal Maps a takeable-offer API payload, returning its market collaterals
* in canonical protocol order so the struct validated by the SDK is the one
* ABI-encoded onchain.
*/
function mapTakeableOffer(takeableOffer) {
const offer = takeableOffer.offer;
const expiry = BigInt(requireNonNegativeSafeInteger(offer.expiry, "offer expiry"));
const validUntil = takeableOffer.valid_until;
if (typeof validUntil !== "number" ||
!Number.isSafeInteger(validUntil) ||
validUntil < 0 ||
BigInt(validUntil) > expiry) {
throw new InvalidMidnightApiResponseError("Midnight API takeable offer valid_until must be a non-negative safe integer no greater than offer.expiry.");
}
// The filters after mapping call viem helpers that throw their own errors on non-address values.
for (const [field, value] of [
["maker", offer.maker],
["receiver_if_maker_is_seller", offer.receiver_if_maker_is_seller],
]) {
if (typeof value !== "string" || !isAddress(value, { strict: false })) {
throw new InvalidMidnightApiResponseError(`Midnight API takeable offer ${field} (${typeof value}) is not an address.`);
}
}
if (typeof offer.group !== "string" || !isHex(offer.group)) {
throw new InvalidMidnightApiResponseError(`Midnight API takeable offer group (${typeof offer.group}) is not a hex string.`);
}
for (const [field, value] of [
["buy", offer.buy],
["reduce_only", offer.reduce_only],
]) {
if (typeof value !== "boolean") {
throw new InvalidMidnightApiResponseError(`Midnight API takeable offer ${field} (${typeof value}) is not a boolean.`);
}
}
return {
marketId: takeableOffer.market_id,
units: BigInt(requireBigIntString(takeableOffer.units, "takeable offer units")),
offer: {
market: {
chainId: BigInt(requireNonNegativeSafeInteger(offer.market.chain_id, "offer market chain_id")),
midnight: offer.market.midnight,
loanToken: offer.market.loan_token,
collateralParams: [...offer.market.collaterals]
.sort(MarketUtils.compareCollateralTokens)
.map((collateral) => ({
token: collateral.token,
lltv: BigInt(requireBigIntString(collateral.lltv, "offer collateral lltv")),
liquidationCursor: BigInt(requireBigIntString(collateral.liquidation_cursor, "offer collateral liquidation_cursor")),
oracle: collateral.oracle,
})),
maturity: BigInt(requireNonNegativeSafeInteger(offer.market.maturity, "offer market maturity")),
rcfThreshold: BigInt(requireBigIntString(offer.market.rcf_threshold, "offer market rcf_threshold")),
enterGate: offer.market.enter_gate,
liquidatorGate: offer.market.liquidator_gate,
},
buy: offer.buy,
maker: offer.maker,
start: BigInt(requireNonNegativeSafeInteger(offer.start, "offer start")),
expiry,
tick: TickLib.assertTickInRange(BigInt(offer.tick)),
group: offer.group,
callback: offer.callback,
callbackData: offer.callback_data,
receiverIfMakerIsSeller: offer.receiver_if_maker_is_seller,
ratifier: offer.ratifier,
reduceOnly: offer.reduce_only,
maxUnits: BigInt(requireBigIntString(offer.max_units, "offer max_units")),
maxAssets: BigInt(requireBigIntString(offer.max_assets, "offer max_assets")),
continuousFeeCap: BigInt(requireBigIntString(offer.continuous_fee_cap, "offer continuous_fee_cap")),
},
ratifierData: takeableOffer.ratifier_data,
validUntil: BigInt(validUntil),
};
}
/** @internal Maps, validates offer caps and units, and best-price-sorts API takeable offers. */
export function mapBoundTakeableOffers(takeableOffers, context) {
const mapped = requireArray(takeableOffers, "takeable offers").map((takeableOffer) => {
// Validate the response shape before reading its fields.
requireObject(takeableOffer, "takeable offer");
// Rejects malformed entries before the catch below interpolates their market_id.
if (typeof takeableOffer.market_id !== "string") {
throw new InvalidMidnightApiResponseError("Midnight API takeable offer market_id is not a string.");
}
let take;
let matchesAdvertisedId;
let embeddedMarketId;
try {
take = mapTakeableOffer(takeableOffer);
embeddedMarketId = MarketUtils.toId(take.offer.market);
matchesAdvertisedId = isHexEqual(embeddedMarketId, take.marketId);
}
catch (cause) {
throw new InvalidMidnightApiResponseError(`Midnight API takeable offer market_id "${takeableOffer.market_id}" could not be mapped or validated against its embedded offer market.`, { cause });
}
if (!matchesAdvertisedId) {
throw new InvalidMidnightApiResponseError(`Midnight API takeable offer market_id "${take.marketId}" does not match embedded offer market "${embeddedMarketId}".`);
}
const { maxUnits, maxAssets, buy, maker, receiverIfMakerIsSeller } = take.offer;
if (!isAddress(receiverIfMakerIsSeller)) {
throw new InvalidMidnightApiResponseError(`Midnight API takeable offer receiverIfMakerIsSeller "${receiverIfMakerIsSeller}" is not an address.`);
}
if (!buy && isAddressEqual(receiverIfMakerIsSeller, zeroAddress)) {
throw new InvalidMidnightApiResponseError(`Midnight API sell offer for market_id "${take.marketId}" routes seller proceeds to the zero address. Sell offers must use a non-zero receiverIfMakerIsSeller.`);
}
try {
// Return values unused: called only to enforce the cap-shape and buy-receiver invariants.
OfferUtils.validateOfferCaps({ maxUnits, maxAssets });
OfferUtils.resolveReceiverIfMakerIsSeller({
buy,
maker,
receiverIfMakerIsSeller,
});
}
catch (cause) {
if (!(cause instanceof InvalidOfferParameterError)) {
throw cause;
}
throw new InvalidMidnightApiResponseError(`Midnight API takeable offer for market_id "${take.marketId}" is not executable: ${cause.message}`, { cause });
}
if (maxUnits > 0n && take.units > maxUnits) {
throw new InvalidMidnightApiResponseError(`Midnight API takeable offer for market_id "${take.marketId}" reports units "${take.units}" above offer maxUnits "${maxUnits}".`);
}
if (context.marketId != null &&
!isHexEqual(take.marketId, context.marketId)) {
throw new InvalidMidnightApiResponseError(`Midnight API takeable offer market_id "${take.marketId}" does not match requested market "${context.marketId}".`);
}
if (context.marketIds != null &&
context.marketIds.length > 0 &&
!context.marketIds.some((marketId) => isHexEqual(marketId, take.marketId))) {
throw new InvalidMidnightApiResponseError(`Midnight API takeable offer market_id "${take.marketId}" is outside the requested market_ids filter.`);
}
if (context.side != null) {
const expectedBuy = context.side === "bids";
if (take.offer.buy !== expectedBuy) {
throw new InvalidMidnightApiResponseError(`Midnight API ${context.side} takeable offer returned offer.buy "${take.offer.buy}".`);
}
}
if (context.maker != null &&
!isAddressEqual(take.offer.maker, context.maker)) {
throw new InvalidMidnightApiResponseError(`Midnight API takeable offer maker "${take.offer.maker}" does not match requested maker "${context.maker}".`);
}
if (context.taker != null &&
isAddressEqual(take.offer.maker, context.taker)) {
throw new InvalidMidnightApiResponseError(`Midnight API takeable offer maker "${take.offer.maker}" matches the requested taker "${context.taker}".`);
}
if (context.groups != null && context.groups.length > 0) {
const offerGroup = take.offer.group;
if (!context.groups.some((group) => isHexEqual(group, offerGroup))) {
throw new InvalidMidnightApiResponseError(`Midnight API takeable offer group "${offerGroup}" is outside the requested groups filter.`);
}
}
return take;
});
if (context.side == null) {
return mapped;
}
return [...mapped].sort((a, b) => {
if (a.offer.tick === b.offer.tick) {
return 0;
}
if (context.side === "asks") {
return a.offer.tick < b.offer.tick ? -1 : 1;
}
return a.offer.tick > b.offer.tick ? -1 : 1;
});
}
/** @internal Parses the mempool validation response envelope. */
export function parseValidationResponse(response) {
const parsedResponse = requireRecord(response, "validation response");
const data = requireRecord(parsedResponse.data, "validation response data");
if (!Array.isArray(data.issues)) {
throw new InvalidMidnightApiResponseError('Midnight API validation response is missing "data.issues".');
}
const issues = data.issues.map((issue) => {
const record = requireRecord(issue, "validation issue");
const rule = record.rule;
if (typeof rule !== "string") {
throw new InvalidMidnightApiResponseError('Midnight API validation issue is missing "rule".');
}
const details = record.details;
if (details == null) {
return { rule };
}
if (rule === MempoolPayloadValidationRule.MinOfferAssetsUsd &&
isRecord(details)) {
const loanToken = details.loan_token;
const rawMinAssets = details.min_assets;
if (typeof loanToken === "string" &&
isAddress(loanToken) &&
typeof rawMinAssets === "string" &&
rawMinAssets.length <= MAX_UINT256_DECIMAL_LENGTH &&
/^\d+$/.test(rawMinAssets)) {
const minAssets = BigInt(rawMinAssets);
if (minAssets <= maxUint256) {
return {
rule,
details: {
type: "minOfferAssetsUsd",
loanToken,
minAssets,
},
};
}
}
}
return {
rule,
details: {
type: "unknown",
raw: details,
},
};
});
return {
valid: issues.length === 0,
issues,
};
}
/** @internal Returns `value` when it is a non-null, non-array object. */
export function requireObject(value, context) {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
throw new InvalidMidnightApiResponseError(`Midnight API ${context} is malformed.`);
}
return value;
}
/** @internal Returns a Midnight API response envelope after checking it carries `data`. */
export function requireResponseEnvelope(response, context) {
// Validate the response shape before reading its fields.
requireObject(response, `${context} response`);
if (response.data == null) {
throw new InvalidMidnightApiResponseError(`Midnight API ${context} response is missing "data".`);
}
return response;
}
/** @internal Parses a paginated response cursor, treating a missing cursor as the last page. */
export function parseResponseCursor(cursor, context) {
if (cursor == null) {
return null;
}
if (typeof cursor === "string") {
return cursor;
}
throw new InvalidMidnightApiResponseError(`Midnight API ${context} cursor is malformed.`);
}
/** @internal Returns `value` when it is a decimal string of a uint256. */
export function requireBigIntString(value, context) {
if (typeof value === "string" &&
value.length <= MAX_UINT256_DECIMAL_LENGTH &&
/^\d+$/.test(value) &&
BigInt(value) <= maxUint256) {
return value;
}
throw new InvalidMidnightApiResponseError(`Midnight API ${context} (${typeof value}) is not a decimal uint256 string.`);
}
function requireNonNegativeSafeInteger(value, context) {
if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) {
return value;
}
throw new InvalidMidnightApiResponseError(`Midnight API ${context} (${typeof value}) is not a non-negative safe integer.`);
}
function requireArray(value, context) {
if (Array.isArray(value)) {
return value;
}
throw new InvalidMidnightApiResponseError(`Midnight API ${context} is malformed.`);
}
/** @internal Returns `value` when it is a plain object, else throws `InvalidMidnightApiResponseError`. */
function requireRecord(value, context) {
if (isRecord(value)) {
return value;
}
throw new InvalidMidnightApiResponseError(`Midnight API ${context} is malformed.`);
}
function isRecord(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}