UNPKG

@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.

495 lines (494 loc) • 24 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.requestMidnightApi = requestMidnightApi; exports.buildBookPath = buildBookPath; exports.mapBoundBookMarket = mapBoundBookMarket; exports.mapBoundBooks = mapBoundBooks; exports.mapPriceLevels = mapPriceLevels; exports.mapBoundTakeableOffers = mapBoundTakeableOffers; exports.parseValidationResponse = parseValidationResponse; exports.requireObject = requireObject; exports.requireResponseEnvelope = requireResponseEnvelope; exports.parseResponseCursor = parseResponseCursor; exports.requireBigIntString = requireBigIntString; const morpho_ts_1 = require("@morpho-org/morpho-ts"); const viem_1 = require("viem"); const errors_js_1 = require("../errors.js"); const index_js_1 = require("../market/index.js"); const index_js_2 = require("../math/index.js"); const index_js_3 = require("../offers/index.js"); const version_js_1 = require("../version.js"); const types_js_1 = require("./types.js"); const DEFAULT_MIDNIGHT_API_URL = new URL("/v0/midnight", morpho_ts_1.BLUE_API_BASE_URL); const MAX_UINT256_DECIMAL_LENGTH = viem_1.maxUint256.toString().length; /** @internal Sends one Midnight API request and maps non-2xx responses to SDK errors. */ 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; url.searchParams.set(key, Array.isArray(value) ? value.map(String).join(",") : 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_js_1.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 errors_js_1.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 errors_js_1.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. */ 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 errors_js_1.InvalidMidnightApiResponseError("Midnight API book market_id is not a string."); } let derivedMarketId; let matchesAdvertisedId; try { derivedMarketId = index_js_1.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 = (0, morpho_ts_1.isHexEqual)(derivedMarketId, book.market_id); } catch (cause) { throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API book market_id "${book.market_id}" could not be validated against its market params.`, { cause }); } if (!matchesAdvertisedId) { throw new errors_js_1.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(index_js_1.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. */ function mapBoundBookMarket(book, requestedMarketId) { const market = mapBookMarket(book); if (!(0, morpho_ts_1.isHexEqual)(market.marketId, requestedMarketId)) { throw new errors_js_1.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. */ 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) => (0, morpho_ts_1.isHexEqual)(marketId, market.marketId))) { throw new errors_js_1.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 errors_js_1.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) => (0, viem_1.isAddressEqual)(token, market.loanToken))) { throw new errors_js_1.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) => (0, viem_1.isAddressEqual)(token, collateral.token)))) { throw new errors_js_1.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 errors_js_1.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 errors_js_1.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 errors_js_1.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. */ 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 validUntil = takeableOffer.valid_until; if (typeof validUntil !== "number" || !Number.isSafeInteger(validUntil) || validUntil < 0 || BigInt(validUntil) > BigInt(offer.expiry)) { throw new errors_js_1.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" || !(0, viem_1.isAddress)(value, { strict: false })) { throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API takeable offer ${field} (${typeof value}) is not an address.`); } } if (typeof offer.group !== "string" || !(0, viem_1.isHex)(offer.group)) { throw new errors_js_1.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 errors_js_1.InvalidMidnightApiResponseError(`Midnight API takeable offer ${field} (${typeof value}) is not a boolean.`); } } return { marketId: takeableOffer.market_id, units: BigInt(takeableOffer.units), offer: { market: { chainId: BigInt(offer.market.chain_id), midnight: offer.market.midnight, loanToken: offer.market.loan_token, collateralParams: [...offer.market.collaterals] .sort(index_js_1.MarketUtils.compareCollateralTokens) .map((collateral) => ({ token: collateral.token, lltv: BigInt(collateral.lltv), liquidationCursor: BigInt(collateral.liquidation_cursor), oracle: collateral.oracle, })), maturity: BigInt(offer.market.maturity), rcfThreshold: BigInt(offer.market.rcf_threshold), enterGate: offer.market.enter_gate, liquidatorGate: offer.market.liquidator_gate, }, buy: offer.buy, maker: offer.maker, start: BigInt(offer.start), expiry: BigInt(offer.expiry), tick: index_js_2.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(offer.max_units), maxAssets: BigInt(offer.max_assets), continuousFeeCap: BigInt(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. */ 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 errors_js_1.InvalidMidnightApiResponseError("Midnight API takeable offer market_id is not a string."); } let take; let matchesAdvertisedId; let embeddedMarketId; try { take = mapTakeableOffer(takeableOffer); embeddedMarketId = index_js_1.MarketUtils.toId(take.offer.market); matchesAdvertisedId = (0, morpho_ts_1.isHexEqual)(embeddedMarketId, take.marketId); } catch (cause) { throw new errors_js_1.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 errors_js_1.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 (!(0, viem_1.isAddress)(receiverIfMakerIsSeller)) { throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API takeable offer receiverIfMakerIsSeller "${receiverIfMakerIsSeller}" is not an address.`); } if (!buy && (0, viem_1.isAddressEqual)(receiverIfMakerIsSeller, viem_1.zeroAddress)) { throw new errors_js_1.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. index_js_3.OfferUtils.validateOfferCaps({ maxUnits, maxAssets }); index_js_3.OfferUtils.resolveReceiverIfMakerIsSeller({ buy, maker, receiverIfMakerIsSeller, }); } catch (cause) { if (!(cause instanceof errors_js_1.InvalidOfferParameterError)) throw cause; throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API takeable offer for market_id "${take.marketId}" is not executable: ${cause.message}`, { cause }); } if (maxUnits > 0n && take.units > maxUnits) { throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API takeable offer for market_id "${take.marketId}" reports units "${take.units}" above offer maxUnits "${maxUnits}".`); } if (context.marketId != null && !(0, morpho_ts_1.isHexEqual)(take.marketId, context.marketId)) { throw new errors_js_1.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) => (0, morpho_ts_1.isHexEqual)(marketId, take.marketId))) { throw new errors_js_1.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 errors_js_1.InvalidMidnightApiResponseError(`Midnight API ${context.side} takeable offer returned offer.buy "${take.offer.buy}".`); } } if (context.maker != null && !(0, viem_1.isAddressEqual)(take.offer.maker, context.maker)) { throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API takeable offer maker "${take.offer.maker}" does not match requested maker "${context.maker}".`); } if (context.taker != null && (0, viem_1.isAddressEqual)(take.offer.maker, context.taker)) { throw new errors_js_1.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) => (0, morpho_ts_1.isHexEqual)(group, offerGroup))) { throw new errors_js_1.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. */ function parseValidationResponse(response) { const parsedResponse = requireRecord(response, "validation response"); const data = requireRecord(parsedResponse.data, "validation response data"); if (!Array.isArray(data.issues)) { throw new errors_js_1.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 errors_js_1.InvalidMidnightApiResponseError('Midnight API validation issue is missing "rule".'); } const details = record.details; if (details == null) return { rule }; if (rule === types_js_1.MempoolPayloadValidationRule.MinOfferAssetsUsd && isRecord(details)) { const loanToken = details.loan_token; const rawMinAssets = details.min_assets; if (typeof loanToken === "string" && (0, viem_1.isAddress)(loanToken) && typeof rawMinAssets === "string" && rawMinAssets.length <= MAX_UINT256_DECIMAL_LENGTH && /^\d+$/.test(rawMinAssets)) { const minAssets = BigInt(rawMinAssets); if (minAssets <= viem_1.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. */ function requireObject(value, context) { if (typeof value !== "object" || value === null || Array.isArray(value)) { throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API ${context} is malformed.`); } return value; } /** @internal Returns a Midnight API response envelope after checking it carries `data`. */ function requireResponseEnvelope(response, context) { // Validate the response shape before reading its fields. requireObject(response, `${context} response`); if (response.data == null) { throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API ${context} response is missing "data".`); } return response; } /** @internal Parses a paginated response cursor, treating a missing cursor as the last page. */ function parseResponseCursor(cursor, context) { if (cursor == null) return null; if (typeof cursor === "string") return cursor; throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API ${context} cursor is malformed.`); } /** @internal Returns `value` when it is a decimal string of a uint256. */ function requireBigIntString(value, context) { if (typeof value === "string" && value.length <= MAX_UINT256_DECIMAL_LENGTH && /^\d+$/.test(value) && BigInt(value) <= viem_1.maxUint256) { return value; } throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API ${context} (${typeof value}) is not a decimal uint256 string.`); } function requireArray(value, context) { if (Array.isArray(value)) return value; throw new errors_js_1.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 errors_js_1.InvalidMidnightApiResponseError(`Midnight API ${context} is malformed.`); } function isRecord(value) { return typeof value === "object" && value !== null && !Array.isArray(value); }