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.

317 lines (316 loc) • 12.4 kB
import { type Hex } from "viem"; import { type IOffer } from "../offers/index.js"; /** * Midnight mempool payload codec namespace. * * Use `Payload.encode` to turn ratified offer items into wire bytes for mempool * publication or raw payload API validation, and `Payload.decode` to inspect * published maker offers, ratifier data, or attribution-tagged payloads. */ export declare namespace Payload { /** * One mempool payload item: a maker-side `Offer` together with the opaque * `ratifierData` blob a taker hands to `Midnight.take(..., ratifierData)`. * * `ratifierData` is owned by the ratifier scheme the maker used (e.g. * `EcrecoverRatifier.ratifierData`). The payload codec treats it as * opaque bytes — simulators that only need to forward `ratifierData` can * stay completely ratifier-agnostic. * * Build items with `EcrecoverRatifier.ratify` or * `SetterRatifier.ratify` after the tree is signed or approved, then pass * the items to `Payload.encode` for publication. * * @example * ```ts * import { Offer, type Payload } from "@morpho-org/midnight-sdk"; * 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 item: Payload.Item = { * offer, * ratifierData: "0x", * }; * console.log(item.ratifierData); * ``` */ type Item = { /** Maker-side offer carried by the payload. */ readonly offer: IOffer; /** Opaque ratifier data passed to `Midnight.take`. */ readonly ratifierData: Hex; }; /** * Current Midnight mempool payload wire version. * * @example * ```ts * import { Payload } from "@morpho-org/midnight-sdk"; * * console.log(Payload.CURRENT_VERSION); * ``` */ const CURRENT_VERSION = 1; /** * Upper bound on opaque bytes appended after the gzip stream (e.g. an app * attribution tag). The suffix is meant to be small, so `decode` rejects a * larger one: this keeps the `MAX_PAYLOAD_BYTES` ceiling meaningful for the * whole input. Without it a tiny declared `gzipLen` could smuggle an * arbitrarily large suffix past validation and into the indexer while still * forcing the API to receive and hex-decode the whole blob. * * @example * ```ts * import { Payload } from "@morpho-org/midnight-sdk"; * * console.log(Payload.MAX_ATTRIBUTION_SUFFIX_BYTES); * ``` */ const MAX_ATTRIBUTION_SUFFIX_BYTES = 256; /** * Largest fully framed wire payload, in bytes, matching the router/onchain * mempool cap. * * @example * ```ts * import { Payload } from "@morpho-org/midnight-sdk"; * * console.log(Payload.MAX_PAYLOAD_BYTES); * ``` */ const MAX_PAYLOAD_BYTES = 1000000; /** * Maximum gzip-compressed item bytes accepted by the payload codec. * * The budget reserves room for the fixed header and the largest accepted * attribution suffix so the full wire payload never exceeds * {@link MAX_PAYLOAD_BYTES}. * * @example * ```ts * import { Payload } from "@morpho-org/midnight-sdk"; * * console.log(Payload.MAX_COMPRESSED_ITEMS_BYTES); * ``` */ const MAX_COMPRESSED_ITEMS_BYTES: number; /** * Maximum ABI-decoded item bytes accepted by the payload codec. * * @example * ```ts * import { Payload } from "@morpho-org/midnight-sdk"; * * console.log(Payload.MAX_DECOMPRESSED_ITEMS_BYTES); * ``` */ const MAX_DECOMPRESSED_ITEMS_BYTES = 6000000; /** * Largest `0x`-prefixed hex string that can encode a wire payload. * * @example * ```ts * import { Payload } from "@morpho-org/midnight-sdk"; * * console.log(Payload.MAX_PAYLOAD_HEX_LENGTH); * ``` */ const MAX_PAYLOAD_HEX_LENGTH: number; /** * Largest inbound HTTP request body, in bytes, accepted by the API and * gatekeeper APIs. * * @example * ```ts * import { Payload } from "@morpho-org/midnight-sdk"; * * console.log(Payload.MAX_REQUEST_BODY_BYTES); * ``` */ const MAX_REQUEST_BODY_BYTES: number; /** * Optional decode bounds. * * @example * ```ts * import type { Payload } from "@morpho-org/midnight-sdk"; * * const options: Payload.DecodeOptions = { maxItems: 16 }; * console.log(options.maxItems); * ``` */ type DecodeOptions = { /** Optional caller-provided item cap. */ readonly maxItems?: number; }; /** * ABI-encode `items` as `(Offer, bytes ratifierData)[]` and gzip the result, * then emit the wire payload `version || uint32(gzipLen) || gzip(...)`. The * single-byte version prefix lets future formats coexist on the wire; the * 4-byte big-endian length delimits the gzip stream so `decode` finds its end * without scanning. That delimiter is what lets a publisher append a small * opaque suffix (e.g. an attribution tag) after the gzip stream — `decode` * ignores up to `MAX_ATTRIBUTION_SUFFIX_BYTES` bytes past `gzipLen` and rejects * a larger suffix. Item order is preserved verbatim and is the order a consumer * sees on decode. * * Use after ratifier utilities have produced payload-ready items and before an * onchain mempool submission. Normal SDK maker flows should validate the tree * with `Tree.mempoolValidate` before ratification; use * `MidnightApi.validateMempoolPayload` only when validating already encoded * payload bytes. * * @param items - Per-leaf items in the order the maker committed to. Must * contain at least one item and fit within payload byte-size limits. * @returns The encoded payload as a `Hex` string, ready to include in onchain * mempool submission calldata. * @throws {PayloadDecodeError} when the item list is empty, encoding or compression * exceeds SDK byte-size limits, or a non-empty offer fails payload validation * for collateral requirements, maturity timing, expiry range, tick bounds, or * `maxUnits`/`maxAssets` cap shape. * @example * ```ts * import { Offer, Payload } from "@morpho-org/midnight-sdk"; * 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 encoded = await Payload.encode([{ offer, ratifierData: "0x" }]); * console.log(encoded); * ``` */ function encode(items: readonly Item[]): Promise<Hex>; /** * Parse a wire payload back into its `(offer, ratifierData)` items. The version * byte is validated against `CURRENT_VERSION` and not surfaced — any payload * that decodes successfully is on the current wire format. The 4-byte length * prefix bounds the gzip stream; up to `MAX_ATTRIBUTION_SUFFIX_BYTES` bytes * after it (e.g. an attribution suffix appended by the publishing app) are * ignored, so a tagged payload decodes identically to an untagged one. A larger * trailing suffix is rejected so an oversized blob cannot ride a small payload * past validation and into the indexer. * * Use on the take-side, in indexers, or in diagnostics when you need to inspect * the offer structs and ratifier data that a maker published. * * @param payload - Hex payload bytes to decode. * @param options - Optional decode bounds. * @returns The decoded items in encoded order. * @throws {PayloadDecodeError} when the payload is malformed or exceeds protocol limits. * @example * ```ts * import { Offer, Payload } from "@morpho-org/midnight-sdk"; * 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 encoded = await Payload.encode([{ offer, ratifierData: "0x" }]); * const items = await Payload.decode(encoded); * console.log(items.length); * ``` */ function decode(payload: Hex, options?: DecodeOptions): Promise<Item[]>; /** * Synchronous {@link decode} for callers that cannot await, such as offline * calldata verifiers. Applies the same wire, size, item and canonical-ABI * checks as `decode`, but delegates gzip decompression to `options.gunzip` * because the platform's built-in `DecompressionStream` is asynchronous. * * @param payload - Hex payload bytes to decode. * @param options - Synchronous gzip decompressor and optional decode bounds. * @param options.gunzip - Decompresses one complete gzip stream. It receives * `MAX_DECOMPRESSED_ITEMS_BYTES` as `maxBytes` and should stop and throw once * output exceeds it, so a small payload cannot expand without bound. * @param options.maxItems - Optional caller-provided item cap. * @returns The decoded items in encoded order. * @throws {PayloadDecodeError} when the payload is malformed, exceeds protocol * limits, or `gunzip` throws. * @example * ```ts * import { Payload } from "@morpho-org/midnight-sdk"; * import { gunzipSync } from "node:zlib"; * import type { Hex } from "viem"; * * function decodeMakerPayload(payload: Hex) { * return Payload.decodeSync(payload, { * gunzip: (compressed, maxBytes) => * gunzipSync(compressed, { maxOutputLength: maxBytes }), * }); * } * // decodeMakerPayload(payload) returns the payload's (offer, ratifierData) items. * ``` */ function decodeSync(payload: Hex, options: DecodeOptions & { readonly gunzip: (compressed: Uint8Array, maxBytes: number) => Uint8Array; }): Item[]; }