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.

836 lines (835 loc) • 43 kB
import { assertNonNegative, MathLib } from "@morpho-org/morpho-ts"; import { InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, } from "../errors.js"; import { TakeAmountsLib } from "../math/index.js"; import { Payload } from "../signatures/Payload.js"; import { buildBookPath, mapBoundBookMarket, mapBoundBooks, mapBoundTakeableOffers, mapPriceLevels, parseResponseCursor, parseValidationResponse, requestMidnightApi, requireBigIntString, requireObject, requireResponseEnvelope, } from "./helpers.js"; export { MempoolPayloadValidationRule } from "./types.js"; /** * Midnight API client and stateless helper surface for books and mempool data. * * Static methods use `https://api.morpho.org/v0/midnight` by default and accept * per-call configuration. Instances keep shared `baseUrl`, `fetch`, and request * options for integrations that make repeated calls. * Caller input and successful JSON output shapes are trusted at runtime; * returned TypeScript types model the API contract. * * @example * ```ts * import { MidnightApi } from "@morpho-org/midnight-sdk/api"; * * const direct = await MidnightApi.validateMempoolPayload({ * chainId: 8453, * payload: "0x0100000000", * }); * * const api = new MidnightApi("https://api.morpho.org/v0/midnight"); * const configured = await api.validateMempoolPayload({ * chainId: 8453, * payload: "0x0100000000", * }); * * console.log(direct.valid && configured.valid); * ``` */ export class MidnightApi { config; /** * Creates a Midnight API client with shared request configuration. * * @param config - API base URL or full request configuration. * @param config.baseUrl - Optional Midnight API base URL. * @param config.fetch - Optional fetch implementation used for all instance calls. * @param config.request - Optional fetch options forwarded to all instance calls. * @returns Configured Midnight API client. * @example * ```ts * import { MidnightApi } from "@morpho-org/midnight-sdk/api"; * * const api = new MidnightApi({ * baseUrl: "https://api.morpho.org/v0/midnight", * }); * console.log(api); * ``` */ constructor(config = {}) { this.config = typeof config === "string" || config instanceof URL ? { baseUrl: config } : { ...config }; } /** * Fetches active Midnight books with market metadata and top price levels. * * Reads `GET /books` from the Midnight API. Does not read onchain RPC state. * * @param params.sort - Optional book sort terms. * @param params.maturities - Optional exact maturity timestamp filters in unix seconds. * @param params.collateralTokens - Optional collateral token address filters. * @param params.loanTokens - Optional loan token address filters. * @param params.chainIds - Optional chain id filters. * @param params.marketIds - Optional market id filters. * @param params.limit - Optional maximum number of books to return. * @param params.cursor - Optional opaque pagination cursor from a previous response. * @param params.baseUrl - Optional Midnight API base URL override. * @param params.fetch - Optional fetch implementation override. * @param params.request - Optional fetch options forwarded to this request. * @returns Paginated books mapped to SDK camelCase fields, with each book's price levels sorted best first (asks ascending tick, bids descending tick). * @throws {MidnightApiError} when the API returns a non-2xx response. * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope, cursor or price levels are malformed, when a returned book's `market_id` does not match, or cannot be derived from, its own market params, or when a returned book falls outside the supplied `marketIds`, `chainIds`, `loanTokens`, `collateralTokens`, or `maturities` filters. * @example * ```ts * import { MidnightApi } from "@morpho-org/midnight-sdk/api"; * * const books = await MidnightApi.fetchBooks({ * chainIds: [8453], * limit: 10, * }); * console.log(books.data.length); * ``` */ static async fetchBooks(params = {}) { const input = params; const response = await requestMidnightApi({ ...input, method: "GET", path: "books", query: { sort: input.sort, maturities: input.maturities, collateral_tokens: input.collateralTokens, loan_tokens: input.loanTokens, chain_ids: input.chainIds, ids: input.marketIds, limit: input.limit, cursor: input.cursor, }, }); const envelope = requireResponseEnvelope(response, "books"); return { cursor: parseResponseCursor(envelope.cursor, "books"), data: mapBoundBooks(envelope.data, { marketIds: input.marketIds, chainIds: input.chainIds, loanTokens: input.loanTokens, collateralTokens: input.collateralTokens, maturities: input.maturities, }), }; } /** * Fetches one Midnight book with market metadata and both sides. * * Reads `GET /books/{marketId}` from the Midnight API. Does not read onchain RPC state. * * @param params.marketId - Market id whose book to read. * @param params.depth - Optional maximum levels returned per side. * @param params.baseUrl - Optional Midnight API base URL override. * @param params.fetch - Optional fetch implementation override. * @param params.request - Optional fetch options forwarded to this request. * @returns Book snapshot mapped to SDK camelCase fields, with price levels sorted best first (asks ascending tick, bids descending tick). * @throws {MidnightApiError} when the API returns a non-2xx response. * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope or price levels are malformed, when the returned book's `market_id` does not match, or cannot be derived from, its own market params, or when it differs from the requested `marketId`. * @example * ```ts * import { MidnightApi } from "@morpho-org/midnight-sdk/api"; * * const book = await MidnightApi.fetchBook({ * marketId: "0x12590ae1aee324a005be565f3bcdd16dbf8daf7969b26c181c8b8f467dad9f67", * }); * console.log(book.data.marketId); * ``` */ static async fetchBook(params) { const input = params; const response = await requestMidnightApi({ ...input, method: "GET", path: buildBookPath({ marketId: input.marketId }), query: { depth: input.depth, }, }); return { data: mapBoundBookMarket(requireResponseEnvelope(response, "book").data, input.marketId), }; } /** * Fetches one side of a Midnight book grouped by price level. * * Reads `GET /books/{marketId}/{side}` from the Midnight API. Does not read onchain RPC state. * * @param params.marketId - Market id whose book side to read. * @param params.side - Book side to query. * @param params.depth - Optional maximum levels returned. * @param params.baseUrl - Optional Midnight API base URL override. * @param params.fetch - Optional fetch implementation override. * @param params.request - Optional fetch options forwarded to this request. * @returns Price levels mapped to SDK camelCase fields, sorted best first (asks ascending tick, bids descending tick). * @throws {MidnightApiError} when the API returns a non-2xx response. * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope or price levels are malformed. * @example * ```ts * import { MidnightApi } from "@morpho-org/midnight-sdk/api"; * * const levels = await MidnightApi.fetchBookPriceLevels({ * marketId: "0x12590ae1aee324a005be565f3bcdd16dbf8daf7969b26c181c8b8f467dad9f67", * side: "asks", * }); * console.log(levels.data.length); * ``` */ static async fetchBookPriceLevels(params) { const input = params; const response = await requestMidnightApi({ ...input, method: "GET", path: buildBookPath({ marketId: input.marketId, side: input.side }), query: { depth: input.depth, }, }); return { data: mapPriceLevels(requireResponseEnvelope(response, "price levels").data, input.side), }; } /** * Fetches executable offers for one side of a Midnight book. * * Reads `GET /books/{marketId}/{side}/takeable-offers` from the Midnight API. Does not read onchain RPC state. * * @param params.marketId - Market id whose book side to read. * @param params.side - Book side to query. * @param params.baseUrl - Optional Midnight API base URL override. * @param params.fetch - Optional fetch implementation override. * @param params.request - Optional fetch options forwarded to this request. * @returns ABI-ready take objects mapped from the API response. * @throws {MidnightApiError} when the API returns a non-2xx response. * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope or takeable offers are malformed, when a returned offer cannot be mapped (malformed numeric or hex fields), when its `market_id` does not match, or cannot be derived from, its embedded market, when it falls outside the requested filters, when its `receiverIfMakerIsSeller` is not a well-formed address or is the zero address on a sell offer, when its caps or buy-side receiver are not executable, or when its units exceed its offer `maxUnits`. * @example * ```ts * import { MidnightApi } from "@morpho-org/midnight-sdk/api"; * * const offers = await MidnightApi.fetchBookTakeableOffers({ * marketId: "0x12590ae1aee324a005be565f3bcdd16dbf8daf7969b26c181c8b8f467dad9f67", * side: "bids", * }); * console.log(offers.data.length); * ``` */ static async fetchBookTakeableOffers(params) { const input = params; const response = await requestMidnightApi({ ...input, method: "GET", path: buildBookPath({ marketId: input.marketId, side: input.side, suffix: "takeable-offers", }), }); return { data: mapBoundTakeableOffers(requireResponseEnvelope(response, "takeable offers").data, { marketId: input.marketId, side: input.side, }), }; } /** * Fetches a bundle-ready quote for one side of a Midnight book. * * Reads `GET /books/{marketId}/{side}/quote` from the Midnight API. Does not read onchain RPC state. * * @param params.marketId - Market id whose book side to quote. * @param params.side - Book side to quote. * @param params.assets - Optional maker-side target assets amount. Mutually exclusive with `params.units`. * @param params.units - Optional target unit amount. Mutually exclusive with `params.assets`. * @param params.averageWorstPrice - Optional WAD-scaled average worst price guard. Mutually exclusive with `params.slippage`. * @param params.slippage - Optional slippage percentage used to derive the guard. Mutually exclusive with `params.averageWorstPrice`. * @param params.taker - Account that will execute the take (the `taker` passed to Midnight `take`). * The API leaves out offers made by this account, since Midnight rejects self-takes. * @param params.limit - Optional maximum number of offers the API walks to build the quote (1 to 10,000, API default 10,000). * @param params.settlementFee - Optional current WAD-scaled settlement fee used for local guard validation. Defaults to zero. * @param params.baseUrl - Optional Midnight API base URL override. * @param params.fetch - Optional fetch implementation override. * @param params.request - Optional fetch options forwarded to this request. * @returns Quote and ABI-ready take caps. `averageWorstPrice` equals the caller's guard when provided, * otherwise the API's guard. Offers are returned as the API sends them. An `asks` quote by * `assets` can include a sell offer whose buyer price (offer price plus the market's settlement * fee) exceeds one asset per unit, such as a `MAX_TICK` ask when the fee is positive. The * `MidnightBundlesV2` assets-target buy reverts on such an offer before its per-offer error * handling, so the whole bundle fails. Drop these offers before building an assets-target buy, * or use a `units` target. * @throws {InvalidMidnightApiQuoteTargetError} when the runtime input does not set exactly one of `units` or `assets`. * @throws {NegativeValueError} when `settlementFee` is negative. * @throws {MidnightApiError} when the API returns a non-2xx response. * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope or quote aggregates are malformed, when a returned offer cannot be mapped (malformed numeric or hex fields), when its `market_id` does not match, or cannot be derived from, its embedded market, when it falls outside the requested filters, when an offer's maker matches the requested `taker`, when its `receiverIfMakerIsSeller` is not a well-formed address or is the zero address on a sell offer, when its caps or buy-side receiver are not executable, when its units exceed its offer `maxUnits`, or when the returned offers imply a rounded aggregate settlement price outside the effective average-worst-price guard. * @throws {SettlementFeeExceedsPriceError} when a bid's settlement fee exceeds its offer price. * @example * ```ts * import { MidnightApi } from "@morpho-org/midnight-sdk/api"; * * const quote = await MidnightApi.fetchBookQuote({ * marketId: "0x12590ae1aee324a005be565f3bcdd16dbf8daf7969b26c181c8b8f467dad9f67", * side: "asks", * assets: 1000000000000000000n, * slippage: "0.5", * }); * console.log(quote.data.averageBestPrice); * ``` */ static async fetchBookQuote(params) { const input = params; if ((input.units == null) === (input.assets == null)) throw new InvalidMidnightApiQuoteTargetError(); const settlementFee = BigInt(input.settlementFee ?? 0n); assertNonNegative("settlementFee", settlementFee); const response = await requestMidnightApi({ ...input, method: "GET", path: buildBookPath({ marketId: input.marketId, side: input.side, suffix: "quote", }), query: { average_worst_price: input.averageWorstPrice, slippage: input.slippage, units: input.units, assets: input.assets, taker: input.taker, limit: input.limit, }, }); const data = requireObject(requireResponseEnvelope(response, "quote").data, "quote data"); const averageBestPrice = requireBigIntString(data.average_best_price, "quote average_best_price"); const responseAverageWorstPrice = requireBigIntString(data.average_worst_price, "quote average_worst_price"); const availableAssets = requireBigIntString(data.available_assets, "quote available_assets"); const availableUnits = requireBigIntString(data.available_units, "quote available_units"); const takeableOffers = mapBoundTakeableOffers(data.takeable_offers, { marketId: input.marketId, side: input.side, taker: input.taker, }); const averageWorstPrice = "averageWorstPrice" in input && input.averageWorstPrice != null ? input.averageWorstPrice : "slippage" in input && input.slippage != null ? responseAverageWorstPrice : undefined; const guard = averageWorstPrice == null ? undefined : BigInt(averageWorstPrice); if (guard != null) { let filledUnits = 0n; let filledAssets = 0n; if ("units" in input && input.units != null) { let remainingUnits = BigInt(input.units); for (const take of takeableOffers) { if (remainingUnits === 0n) break; const { buyerPrice, sellerPrice } = TakeAmountsLib.prices({ offer: take.offer, settlementFee, }); const price = input.side === "asks" ? buyerPrice : sellerPrice; const filled = take.units < remainingUnits ? take.units : remainingUnits; filledUnits += filled; filledAssets += MathLib.mulDiv(filled, price, MathLib.WAD, input.side === "asks" ? "Up" : "Down"); remainingUnits -= filled; } } else { let remainingAssets = BigInt(input.assets); for (const take of takeableOffers) { if (remainingAssets === 0n) break; const { buyerPrice, sellerPrice } = TakeAmountsLib.prices({ offer: take.offer, settlementFee, }); const makerPrice = input.side === "asks" ? sellerPrice : buyerPrice; const settlementPrice = input.side === "asks" ? buyerPrice : sellerPrice; const takeMakerAssets = input.side === "asks" ? MathLib.mulDivUp(take.units, makerPrice, MathLib.WAD) : MathLib.mulDivDown(take.units, makerPrice, MathLib.WAD); const fillsEntireTake = takeMakerAssets <= remainingAssets; const filled = fillsEntireTake ? take.units : MathLib.mulDiv(remainingAssets, MathLib.WAD, makerPrice, input.side === "asks" ? "Down" : "Up"); if (filled === 0n) continue; filledUnits += filled; filledAssets += MathLib.mulDiv(filled, settlementPrice, MathLib.WAD, input.side === "asks" ? "Up" : "Down"); remainingAssets = fillsEntireTake ? remainingAssets - takeMakerAssets : 0n; } } if (filledUnits > 0n) { const averagePrice = MathLib.mulDiv(filledAssets, MathLib.WAD, filledUnits, input.side === "asks" ? "Up" : "Down"); const violatesGuard = input.side === "asks" ? averagePrice > guard : averagePrice < guard; if (violatesGuard) { throw new InvalidMidnightApiResponseError(`Midnight API quote takeable offers imply average price "${averagePrice}" outside average_worst_price guard "${guard}".`); } } } return { data: { averageBestPrice, averageWorstPrice: guard?.toString() ?? responseAverageWorstPrice, availableAssets, availableUnits, takeableOffers, }, }; } /** * Fetches one maker's unexpired, unmatured takeable offers. * * Reads `GET /takeable-offers` from the Midnight API. Does not read onchain RPC state. * * @param params.maker - Maker EVM address. * @param params.marketIds - Optional market id filters. * @param params.groups - Optional group id filters. * @param params.limit - Optional maximum number of offers to return. * @param params.cursor - Optional opaque pagination cursor from a previous response. * @param params.baseUrl - Optional Midnight API base URL override. * @param params.fetch - Optional fetch implementation override. * @param params.request - Optional fetch options forwarded to this request. * @returns Paginated ABI-ready take objects mapped from the API response. * @throws {MidnightApiError} when the API returns a non-2xx response. * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope, cursor or takeable offers are malformed, when a returned offer cannot be mapped (malformed numeric or hex fields), when its `market_id` does not match, or cannot be derived from, its embedded market, when it falls outside the requested filters, when its `receiverIfMakerIsSeller` is not a well-formed address or is the zero address on a sell offer, when its caps or buy-side receiver are not executable, or when its units exceed its offer `maxUnits`. * @example * ```ts * import { MidnightApi } from "@morpho-org/midnight-sdk/api"; * * const offers = await MidnightApi.fetchTakeableOffers({ * maker: "0x7b093658BE7f90B63D7c359e8f408e503c2D9401", * }); * console.log(offers.data.length); * ``` */ static async fetchTakeableOffers(params) { const input = params; const response = await requestMidnightApi({ ...input, method: "GET", path: "takeable-offers", query: { maker: input.maker, market_ids: input.marketIds, groups: input.groups, limit: input.limit, cursor: input.cursor, }, }); const envelope = requireResponseEnvelope(response, "takeable offers"); return { cursor: parseResponseCursor(envelope.cursor, "takeable offers"), data: mapBoundTakeableOffers(envelope.data, { maker: input.maker, marketIds: input.marketIds, groups: input.groups, }), }; } /** * Validates an encoded Midnight mempool payload against API policy. * * Use when an integration already has encoded payload bytes and wants API * feedback before publishing those bytes onchain. Normal SDK maker flows can * call `Tree.mempoolValidate` before ratification, or pass ratification * inputs to that helper when validating final payload bytes. * * Sends `POST /mempool/validate` to the Midnight API. Does not read onchain RPC state. * * @param params.chainId - Chain id whose API policy should validate the payload. * @param params.payload - Encoded Midnight mempool payload bytes. * @param params.timestamp - Optional ISO-8601 timestamp or `Date` selecting the API policy snapshot. * @param params.baseUrl - Optional Midnight API base URL override. * @param params.fetch - Optional fetch implementation override. * @param params.request - Optional fetch options forwarded to this request. * @returns API issues and `valid` summary. * @throws {MidnightApiError} when the API returns a non-2xx response. * @throws {InvalidMidnightApiResponseError} when the API returns malformed success JSON. * @example * ```ts * import { MidnightApi } from "@morpho-org/midnight-sdk/api"; * * const validation = await MidnightApi.validateMempoolPayload({ * chainId: 8453, * payload: "0x0100000000", * }); * console.log(validation.valid); * ``` */ static async validateMempoolPayload(params) { const input = params; const response = await requestMidnightApi({ ...input, method: "POST", path: "mempool/validate", query: { timestamp: input.timestamp, }, body: { chain_id: input.chainId, payload: input.payload, }, }); return parseValidationResponse(response); } /** * Encodes SDK-native payload items and validates them against API policy. * * Use when an integration already has payload-ready items but not encoded * payload bytes. Normal SDK maker flows can call `Tree.mempoolValidate` * before ratification, or pass ratification inputs to that helper when * validating final payload bytes. This helper owns the temporary payload * encoding for validation only. * * Encodes `params.items`, then sends `POST /mempool/validate` to the Midnight API. Does not read onchain RPC state. * * @param params.chainId - Chain id whose API policy should validate the payload. * @param params.items - SDK-native payload items to encode before API validation. * @param params.timestamp - Optional ISO-8601 timestamp or `Date` selecting the API policy snapshot. * @param params.baseUrl - Optional Midnight API base URL override. * @param params.fetch - Optional fetch implementation override. * @param params.request - Optional fetch options forwarded to this request. * @returns API issues and `valid` summary. * @throws {PayloadDecodeError} when item encoding fails. * @throws {MidnightApiError} when the API returns a non-2xx response. * @throws {InvalidMidnightApiResponseError} when the API returns malformed success JSON. * @example * ```ts * import { Offer } from "@morpho-org/midnight-sdk"; * import { MidnightApi } from "@morpho-org/midnight-sdk/api"; * import { zeroAddress } from "viem"; * * const offer = Offer.create({ * market: { * chainId: 8453, * midnight: "0x0000000000000000000000000000000000001000", * loanToken: "0x0000000000000000000000000000000000006000", * collateralParams: [ * { * token: "0x0000000000000000000000000000000000007000", * lltv: 770000000000000000n, * liquidationCursor: 250000000000000000n, * oracle: "0x0000000000000000000000000000000000008000", * }, * ], * maturity: 54_000n, * rcfThreshold: 0n, * enterGate: zeroAddress, * liquidatorGate: zeroAddress, * }, * buy: true, * maker: "0x0000000000000000000000000000000000009000", * tick: 5_000n, * expiry: 3_600n, * ratifier: "0x0000000000000000000000000000000000004000", * maxUnits: 100n, * }); * * const validation = await MidnightApi.validateMempoolItems({ * chainId: 8453, * items: [{ offer, ratifierData: "0x" }], * }); * console.log(validation.valid); * ``` */ static async validateMempoolItems(params) { const input = params; const payload = await Payload.encode(input.items); return MidnightApi.validateMempoolPayload({ baseUrl: input.baseUrl, fetch: input.fetch, request: input.request, chainId: input.chainId, timestamp: input.timestamp, payload, }); } /** * Fetches active Midnight books with this client's configuration. * * Reads `GET /books` from the Midnight API using this client's configuration. Does not read onchain RPC state. * * @param params.sort - Optional book sort terms. * @param params.maturities - Optional exact maturity timestamp filters in unix seconds. * @param params.collateralTokens - Optional collateral token address filters. * @param params.loanTokens - Optional loan token address filters. * @param params.chainIds - Optional chain id filters. * @param params.marketIds - Optional market id filters. * @param params.limit - Optional maximum number of books to return. * @param params.cursor - Optional opaque pagination cursor from a previous response. * @returns Paginated books mapped to SDK camelCase fields, with each book's price levels sorted best first (asks ascending tick, bids descending tick). * @throws {MidnightApiError} when the API returns a non-2xx response. * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope, cursor or price levels are malformed, when a returned book's `market_id` does not match, or cannot be derived from, its own market params, or when a returned book falls outside the supplied `marketIds`, `chainIds`, `loanTokens`, `collateralTokens`, or `maturities` filters. * @example * ```ts * import { MidnightApi } from "@morpho-org/midnight-sdk/api"; * * const api = new MidnightApi(); * const books = await api.fetchBooks({ chainIds: [8453], limit: 10 }); * console.log(books.data.length); * ``` */ fetchBooks(params = {}) { return MidnightApi.fetchBooks({ ...this.config, ...params, }); } /** * Fetches one Midnight book with this client's configuration. * * Reads `GET /books/{marketId}` from the Midnight API using this client's configuration. Does not read onchain RPC state. * * @param params.marketId - Market id whose book to read. * @param params.depth - Optional maximum levels returned per side. * @returns Book snapshot mapped to SDK camelCase fields, with price levels sorted best first (asks ascending tick, bids descending tick). * @throws {MidnightApiError} when the API returns a non-2xx response. * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope or price levels are malformed, when the returned book's `market_id` does not match, or cannot be derived from, its own market params, or when it differs from the requested `marketId`. * @example * ```ts * import { MidnightApi } from "@morpho-org/midnight-sdk/api"; * * const api = new MidnightApi(); * const book = await api.fetchBook({ * marketId: "0x12590ae1aee324a005be565f3bcdd16dbf8daf7969b26c181c8b8f467dad9f67", * }); * console.log(book.data.marketId); * ``` */ fetchBook(params) { return MidnightApi.fetchBook({ ...this.config, ...params, }); } /** * Fetches one side of a Midnight book with this client's configuration. * * Reads `GET /books/{marketId}/{side}` from the Midnight API using this client's configuration. Does not read onchain RPC state. * * @param params.marketId - Market id whose book side to read. * @param params.side - Book side to query. * @param params.depth - Optional maximum levels returned. * @returns Price levels mapped to SDK camelCase fields, sorted best first (asks ascending tick, bids descending tick). * @throws {MidnightApiError} when the API returns a non-2xx response. * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope or price levels are malformed. * @example * ```ts * import { MidnightApi } from "@morpho-org/midnight-sdk/api"; * * const api = new MidnightApi(); * const levels = await api.fetchBookPriceLevels({ * marketId: "0x12590ae1aee324a005be565f3bcdd16dbf8daf7969b26c181c8b8f467dad9f67", * side: "asks", * }); * console.log(levels.data.length); * ``` */ fetchBookPriceLevels(params) { return MidnightApi.fetchBookPriceLevels({ ...this.config, ...params, }); } /** * Fetches executable offers for one book side with this client's configuration. * * Reads `GET /books/{marketId}/{side}/takeable-offers` from the Midnight API using this client's configuration. Does not read onchain RPC state. * * @param params.marketId - Market id whose book side to read. * @param params.side - Book side to query. * @returns ABI-ready take objects mapped from the API response. * @throws {MidnightApiError} when the API returns a non-2xx response. * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope or takeable offers are malformed, when a returned offer cannot be mapped (malformed numeric or hex fields), when its `market_id` does not match, or cannot be derived from, its embedded market, when it falls outside the requested filters, when its `receiverIfMakerIsSeller` is not a well-formed address or is the zero address on a sell offer, when its caps or buy-side receiver are not executable, or when its units exceed its offer `maxUnits`. * @example * ```ts * import { MidnightApi } from "@morpho-org/midnight-sdk/api"; * * const api = new MidnightApi(); * const offers = await api.fetchBookTakeableOffers({ * marketId: "0x12590ae1aee324a005be565f3bcdd16dbf8daf7969b26c181c8b8f467dad9f67", * side: "bids", * }); * console.log(offers.data.length); * ``` */ fetchBookTakeableOffers(params) { return MidnightApi.fetchBookTakeableOffers({ ...this.config, ...params, }); } /** * Fetches a bundle-ready quote with this client's configuration. * * Reads `GET /books/{marketId}/{side}/quote` from the Midnight API using this client's configuration. Does not read onchain RPC state. * * @param params.marketId - Market id whose book side to quote. * @param params.side - Book side to quote. * @param params.assets - Optional maker-side target assets amount. Mutually exclusive with `params.units`. * @param params.units - Optional target unit amount. Mutually exclusive with `params.assets`. * @param params.averageWorstPrice - Optional WAD-scaled average worst price guard. Mutually exclusive with `params.slippage`. * @param params.slippage - Optional slippage percentage used to derive the guard. Mutually exclusive with `params.averageWorstPrice`. * @param params.taker - Account that will execute the take (the `taker` passed to Midnight `take`). * The API leaves out offers made by this account, since Midnight rejects self-takes. * @param params.limit - Optional maximum number of offers the API walks to build the quote (1 to 10,000, API default 10,000). * @param params.settlementFee - Optional current WAD-scaled settlement fee used for local guard validation. Defaults to zero. * @returns Quote and ABI-ready take caps. `averageWorstPrice` equals the caller's guard when provided, * otherwise the API's guard. Offers are returned as the API sends them. An `asks` quote by * `assets` can include a sell offer whose buyer price (offer price plus the market's settlement * fee) exceeds one asset per unit, such as a `MAX_TICK` ask when the fee is positive. The * `MidnightBundlesV2` assets-target buy reverts on such an offer before its per-offer error * handling, so the whole bundle fails. Drop these offers before building an assets-target buy, * or use a `units` target. * @throws {InvalidMidnightApiQuoteTargetError} when the runtime input does not set exactly one of `units` or `assets`. * @throws {NegativeValueError} when `settlementFee` is negative. * @throws {MidnightApiError} when the API returns a non-2xx response. * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope or quote aggregates are malformed, when a returned offer cannot be mapped (malformed numeric or hex fields), when its `market_id` does not match, or cannot be derived from, its embedded market, when it falls outside the requested filters, when an offer's maker matches the requested `taker`, when its `receiverIfMakerIsSeller` is not a well-formed address or is the zero address on a sell offer, when its caps or buy-side receiver are not executable, when its units exceed its offer `maxUnits`, or when the returned offers imply a rounded aggregate settlement price outside the effective average-worst-price guard. * @throws {SettlementFeeExceedsPriceError} when a bid's settlement fee exceeds its offer price. * @example * ```ts * import { MidnightApi } from "@morpho-org/midnight-sdk/api"; * * const api = new MidnightApi(); * const quote = await api.fetchBookQuote({ * marketId: "0x12590ae1aee324a005be565f3bcdd16dbf8daf7969b26c181c8b8f467dad9f67", * side: "asks", * units: "1000000000000000000", * }); * console.log(quote.data.takeableOffers.length); * ``` */ fetchBookQuote(params) { return MidnightApi.fetchBookQuote({ ...this.config, ...params, }); } /** * Fetches one maker's takeable offers with this client's configuration. * * Reads `GET /takeable-offers` from the Midnight API using this client's configuration. Does not read onchain RPC state. * * @param params.maker - Maker EVM address. * @param params.marketIds - Optional market id filters. * @param params.groups - Optional group id filters. * @param params.limit - Optional maximum number of offers to return. * @param params.cursor - Optional opaque pagination cursor from a previous response. * @returns Paginated ABI-ready take objects mapped from the API response. * @throws {MidnightApiError} when the API returns a non-2xx response. * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope, cursor or takeable offers are malformed, when a returned offer cannot be mapped (malformed numeric or hex fields), when its `market_id` does not match, or cannot be derived from, its embedded market, when it falls outside the requested filters, when its `receiverIfMakerIsSeller` is not a well-formed address or is the zero address on a sell offer, when its caps or buy-side receiver are not executable, or when its units exceed its offer `maxUnits`. * @example * ```ts * import { MidnightApi } from "@morpho-org/midnight-sdk/api"; * * const api = new MidnightApi(); * const offers = await api.fetchTakeableOffers({ * maker: "0x7b093658BE7f90B63D7c359e8f408e503c2D9401", * }); * console.log(offers.data.length); * ``` */ fetchTakeableOffers(params) { return MidnightApi.fetchTakeableOffers({ ...this.config, ...params, }); } /** * Validates an encoded Midnight mempool payload with this client's configuration. * * Use when an integration already has encoded payload bytes and wants API * feedback before publishing those bytes onchain. Normal SDK maker flows * should call `Tree.mempoolValidate` before ratification instead of * validating again after `Payload.encode`. * * Sends `POST /mempool/validate` to the Midnight API using this client's configuration. Does not read onchain RPC state. * * @param params.chainId - Chain id whose API policy should validate the payload. * @param params.payload - Encoded Midnight mempool payload bytes. * @param params.timestamp - Optional ISO-8601 timestamp or `Date` selecting the API policy snapshot. * @returns API validation result. * @throws {MidnightApiError} when the API returns a non-2xx response. * @throws {InvalidMidnightApiResponseError} when the API returns malformed success JSON. * @example * ```ts * import { MidnightApi } from "@morpho-org/midnight-sdk/api"; * * const api = new MidnightApi(); * const validation = await api.validateMempoolPayload({ chainId: 8453, payload: "0x0100000000" }); * console.log(validation.valid); * ``` */ validateMempoolPayload(params) { return MidnightApi.validateMempoolPayload({ ...this.config, ...params, }); } /** * Validates payload-ready items with this client's configuration. * * Use when an integration already has payload-ready items but not encoded * payload bytes. Normal SDK maker flows can call `Tree.mempoolValidate` * before ratification, or pass ratification inputs to that helper when * validating final payload bytes. * * Encodes `params.items`, then sends `POST /mempool/validate` to the Midnight API using this client's configuration. Does not read onchain RPC state. * * @param params.chainId - Chain id whose API policy should validate the payload. * @param params.items - SDK-native payload items to encode before API validation. * @param params.timestamp - Optional ISO-8601 timestamp or `Date` selecting the API policy snapshot. * @returns API validation result. * @throws {PayloadDecodeError} when item encoding fails. * @throws {MidnightApiError} when the API returns a non-2xx response. * @throws {InvalidMidnightApiResponseError} when the API returns malformed success JSON. * @example * ```ts * import { Offer } from "@morpho-org/midnight-sdk"; * import { MidnightApi } from "@morpho-org/midnight-sdk/api"; * import { zeroAddress } from "viem"; * * const api = new MidnightApi(); * const offer = Offer.create({ * market: { * chainId: 8453, * midnight: "0x0000000000000000000000000000000000001000", * loanToken: "0x0000000000000000000000000000000000006000", * collateralParams: [ * { * token: "0x0000000000000000000000000000000000007000", * lltv: 770000000000000000n, * liquidationCursor: 250000000000000000n, * oracle: "0x0000000000000000000000000000000000008000", * }, * ], * maturity: 54_000n, * rcfThreshold: 0n, * enterGate: zeroAddress, * liquidatorGate: zeroAddress, * }, * buy: true, * maker: "0x0000000000000000000000000000000000009000", * tick: 5_000n, * expiry: 3_600n, * ratifier: "0x0000000000000000000000000000000000004000", * maxUnits: 100n, * }); * const validation = await api.validateMempoolItems({ * chainId: 8453, * items: [{ offer, ratifierData: "0x" }], * }); * console.log(validation.valid); * ``` */ validateMempoolItems(params) { return MidnightApi.validateMempoolItems({ ...this.config, ...params, }); } }