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.

568 lines (567 loc) • 35.5 kB
import type { FetchBookParams, FetchBookPriceLevelsParams, FetchBookQuoteParams, FetchBooksParams, FetchBookTakeableOffersParams, FetchTakeableOffersParams, MempoolPayloadValidationResult, MidnightApiBookPriceLevelsResult, MidnightApiBookResult, MidnightApiBooksResult, MidnightApiBookTakeableOffersResult, MidnightApiClientParams, MidnightApiConstructorConfig, MidnightApiQuoteResult, MidnightApiTakeableOffersResult, ValidateMempoolItemsParams, ValidateMempoolPayloadParams } from "./types.js"; export type { FetchBookParams, FetchBookPriceLevelsParams, FetchBookQuoteParams, FetchBooksParams, FetchBookTakeableOffersParams, FetchTakeableOffersParams, MempoolPayloadValidationIssue, MempoolPayloadValidationIssueDetails, MempoolPayloadValidationResult, MempoolPayloadValidationSuccess, MidnightApiBookMarket, MidnightApiBookPriceLevelsResult, MidnightApiBookResult, MidnightApiBookSide, MidnightApiBookSort, MidnightApiBookSortField, MidnightApiBookSortTerm, MidnightApiBooksResult, MidnightApiBookTakeableOffersResult, MidnightApiClientParams, MidnightApiCollateral, MidnightApiConfig, MidnightApiConstructorConfig, MidnightApiFetch, MidnightApiPriceLevel, MidnightApiQuote, MidnightApiQuoteAssetsTarget, MidnightApiQuoteAverageWorstPriceGuard, MidnightApiQuoteResult, MidnightApiQuoteSlippageGuard, MidnightApiQuoteUnitsTarget, MidnightApiQuoteWithoutGuard, MidnightApiRequestOptions, MidnightApiSlippage, MidnightApiTake, MidnightApiTakeableOffersResult, ValidateMempoolItemsParams, ValidateMempoolPayloadParams, } from "./types.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 declare class MidnightApi { private readonly 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?: MidnightApiConstructorConfig); /** * 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 fetchBooks(params?: FetchBooksParams): Promise<MidnightApiBooksResult>; /** * 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 fetchBook(params: FetchBookParams): Promise<MidnightApiBookResult>; /** * 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 fetchBookPriceLevels(params: FetchBookPriceLevelsParams): Promise<MidnightApiBookPriceLevelsResult>; /** * 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 fetchBookTakeableOffers(params: FetchBookTakeableOffersParams): Promise<MidnightApiBookTakeableOffersResult>; /** * 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 fee-adjusted guard: asks use buyer price including fee, bids use seller price net of fee. Mutually exclusive with `params.slippage`. * @param params.slippage - Optional slippage percentage deriving a raw tick-price (fee-excluded) guard from the API. 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 for absolute guard pricing and bid fee validation in both modes. Slippage guard pricing excludes it. 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 raw tick-price (fee-excluded) guard. `averageBestPrice` is also raw from the API. * 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 positive target in `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 price outside the guard on its raw (slippage) or fee-adjusted (absolute) surface. * @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 fetchBookQuote(params: FetchBookQuoteParams): Promise<MidnightApiQuoteResult>; /** * 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 fetchTakeableOffers(params: FetchTakeableOffersParams): Promise<MidnightApiTakeableOffersResult>; /** * 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 validateMempoolPayload(params: ValidateMempoolPayloadParams): Promise<MempoolPayloadValidationResult>; /** * 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 validateMempoolItems(params: ValidateMempoolItemsParams): Promise<MempoolPayloadValidationResult>; /** * 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?: MidnightApiClientParams<FetchBooksParams>): Promise<MidnightApiBooksResult>; /** * 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: MidnightApiClientParams<FetchBookParams>): Promise<MidnightApiBookResult>; /** * 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: MidnightApiClientParams<FetchBookPriceLevelsParams>): Promise<MidnightApiBookPriceLevelsResult>; /** * 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: MidnightApiClientParams<FetchBookTakeableOffersParams>): Promise<MidnightApiBookTakeableOffersResult>; /** * 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 fee-adjusted guard: asks use buyer price including fee, bids use seller price net of fee. Mutually exclusive with `params.slippage`. * @param params.slippage - Optional slippage percentage deriving a raw tick-price (fee-excluded) guard from the API. 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 for absolute guard pricing and bid fee validation in both modes. Slippage guard pricing excludes it. Defaults to zero. * @returns Quote and ABI-ready take caps. `averageWorstPrice` equals the caller's guard when provided, * otherwise the API's raw tick-price (fee-excluded) guard. `averageBestPrice` is also raw from the API. * 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 positive target in `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 price outside the guard on its raw (slippage) or fee-adjusted (absolute) surface. * @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: MidnightApiClientParams<FetchBookQuoteParams>): Promise<MidnightApiQuoteResult>; /** * 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: MidnightApiClientParams<FetchTakeableOffersParams>): Promise<MidnightApiTakeableOffersResult>; /** * 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: MidnightApiClientParams<ValidateMempoolPayloadParams>): Promise<MempoolPayloadValidationResult>; /** * 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: MidnightApiClientParams<ValidateMempoolItemsParams>): Promise<MempoolPayloadValidationResult>; }