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.

620 lines (619 loc) • 27.5 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Payload = void 0; const morpho_ts_1 = require("@morpho-org/morpho-ts"); const viem_1 = require("viem"); const constants_js_1 = require("../constants.js"); const errors_js_1 = require("../errors.js"); const index_js_1 = require("../offers/index.js"); const offerStructInternal_js_1 = require("./offerStructInternal.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. */ var Payload; (function (Payload) { /** * Current Midnight mempool payload wire version. * * @example * ```ts * import { Payload } from "@morpho-org/midnight-sdk"; * * console.log(Payload.CURRENT_VERSION); * ``` */ Payload.CURRENT_VERSION = 1; const VERSION_PREFIX_BYTES = 1; const LENGTH_PREFIX_BYTES = 4; const HEADER_BYTES = VERSION_PREFIX_BYTES + LENGTH_PREFIX_BYTES; /** * 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); * ``` */ Payload.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); * ``` */ Payload.MAX_PAYLOAD_BYTES = 1_000_000; /** * 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); * ``` */ Payload.MAX_COMPRESSED_ITEMS_BYTES = Payload.MAX_PAYLOAD_BYTES - HEADER_BYTES - Payload.MAX_ATTRIBUTION_SUFFIX_BYTES; /** * 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); * ``` */ Payload.MAX_DECOMPRESSED_ITEMS_BYTES = 6_000_000; const ABI_ARRAY_HEAD_BYTES = 64; const ABI_LENGTH_LOW_OFFSET = 60; const MAX_TIMESTAMP_SECONDS = 1000000000000n - 1n; /** * 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); * ``` */ Payload.MAX_PAYLOAD_HEX_LENGTH = "0x".length + Payload.MAX_PAYLOAD_BYTES * 2; /** * 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); * ``` */ Payload.MAX_REQUEST_BODY_BYTES = Payload.MAX_PAYLOAD_HEX_LENGTH + 1_024; const offerStructAbiComponents = [ { name: "market", type: "tuple", components: [ { name: "chainId", type: "uint256" }, { name: "midnight", type: "address" }, { name: "loanToken", type: "address" }, { name: "collateralParams", type: "tuple[]", components: [ { name: "token", type: "address" }, { name: "lltv", type: "uint256" }, { name: "liquidationCursor", type: "uint256" }, { name: "oracle", type: "address" }, ], }, { name: "maturity", type: "uint256" }, { name: "rcfThreshold", type: "uint256" }, { name: "enterGate", type: "address" }, { name: "liquidatorGate", type: "address" }, ], }, { name: "buy", type: "bool" }, { name: "maker", type: "address" }, { name: "start", type: "uint256" }, { name: "expiry", type: "uint256" }, { name: "tick", type: "uint256" }, { name: "group", type: "bytes32" }, { name: "callback", type: "address" }, { name: "callbackData", type: "bytes" }, { name: "receiverIfMakerIsSeller", type: "address" }, { name: "ratifier", type: "address" }, { name: "reduceOnly", type: "bool" }, { name: "maxUnits", type: "uint256" }, { name: "maxAssets", type: "uint256" }, { name: "continuousFeeCap", type: "uint256" }, ]; const itemsAbi = [ { name: "items", type: "tuple[]", components: [ { name: "offer", type: "tuple", components: offerStructAbiComponents }, { name: "ratifierData", type: "bytes" }, ], }, ]; /** * 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); * ``` */ async function encode(items) { assertNonEmptyItemCount(items.length); const payloadItems = items.map((item) => { const offer = index_js_1.OfferUtils.toStruct({ offer: item.offer }); assertApiValidOfferStruct(offer); return { offer, ratifierData: item.ratifierData, }; }); const itemBytes = (0, viem_1.hexToBytes)((0, viem_1.encodeAbiParameters)(itemsAbi, [payloadItems])); const compressed = await compressItemsPayload(itemBytes); const encoded = new Uint8Array(HEADER_BYTES + compressed.length); encoded[0] = Payload.CURRENT_VERSION; new DataView(encoded.buffer, encoded.byteOffset, encoded.byteLength).setUint32(VERSION_PREFIX_BYTES, compressed.length); encoded.set(compressed, HEADER_BYTES); return (0, viem_1.bytesToHex)(encoded); } Payload.encode = encode; /** * 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); * ``` */ async function decode(payload, options) { const { compressed, maxItems } = parseWirePayload(payload, options); return decodeItems(await decompressItemsPayload(compressed), maxItems); } Payload.decode = decode; /** * 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, options) { const { compressed, maxItems } = parseWirePayload(payload, options); assertCompressedItemsLength(compressed); let decoded; try { decoded = options.gunzip(compressed, Payload.MAX_DECOMPRESSED_ITEMS_BYTES); } catch (error) { if (error instanceof errors_js_1.PayloadDecodeError) { throw error; } throw new errors_js_1.PayloadDecodeError("decompression failed", error instanceof Error ? error : undefined); } if (decoded.length > Payload.MAX_DECOMPRESSED_ITEMS_BYTES) { throw new errors_js_1.PayloadDecodeError(`decompressed items exceed ${Payload.MAX_DECOMPRESSED_ITEMS_BYTES} bytes`); } return decodeItems(decoded, maxItems); } Payload.decodeSync = decodeSync; function parseWirePayload(payload, options) { const maxItems = resolveMaxItems(options?.maxItems); if (payload.length > Payload.MAX_PAYLOAD_HEX_LENGTH) { throw new errors_js_1.PayloadDecodeError(`payload hex exceeds ${Payload.MAX_PAYLOAD_HEX_LENGTH} characters`); } const bytes = (0, viem_1.hexToBytes)(payload); if (bytes.length < HEADER_BYTES) { throw new errors_js_1.PayloadDecodeError("payload too short for header"); } const version = bytes[0]; if (version !== (Payload.CURRENT_VERSION & 0xff)) { throw new errors_js_1.PayloadDecodeError(`invalid version: expected ${Payload.CURRENT_VERSION}, got ${version}`); } const compressedLength = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(VERSION_PREFIX_BYTES); const compressedEnd = HEADER_BYTES + compressedLength; if (compressedEnd > bytes.length) { throw new errors_js_1.PayloadDecodeError("payload truncated before declared gzip length"); } const suffixLength = bytes.length - compressedEnd; if (suffixLength > Payload.MAX_ATTRIBUTION_SUFFIX_BYTES) { throw new errors_js_1.PayloadDecodeError(`trailing suffix exceeds ${Payload.MAX_ATTRIBUTION_SUFFIX_BYTES} bytes: got ${suffixLength}`); } return { compressed: bytes.subarray(HEADER_BYTES, compressedEnd), maxItems, }; } function decodeItems(decoded, maxItems) { assertAbiItemCountWithinCallerLimit(decoded, maxItems); const items = decodeItemsBytes(decoded); assertNonEmptyItemCount(items.length); assertCallerItemCountLimit(items.length, maxItems); assertCanonicalItemsBytes(items, decoded); return items; } function decodeItemsBytes(decoded) { let raw; try { [raw] = (0, viem_1.decodeAbiParameters)(itemsAbi, (0, viem_1.bytesToHex)(decoded)); } catch (error) { throw new errors_js_1.PayloadDecodeError("items abi decode failed", error instanceof Error ? error : undefined); } try { return raw.map((entry) => { assertApiValidOfferStruct(entry.offer); return { offer: index_js_1.Offer.from(entry.offer), ratifierData: entry.ratifierData, }; }); } catch (error) { if (error instanceof errors_js_1.PayloadDecodeError) { throw error; } if (error instanceof Error) { throw new errors_js_1.PayloadDecodeError(`invalid offer bytes: ${error.message}`, error); } throw error; } } function assertCanonicalItemsBytes(items, decoded) { const canonical = (0, viem_1.encodeAbiParameters)(itemsAbi, [ items.map((item) => ({ offer: index_js_1.OfferUtils.toStruct({ offer: item.offer }), ratifierData: item.ratifierData, })), ]); if (canonical !== (0, viem_1.bytesToHex)(decoded)) { throw new errors_js_1.PayloadDecodeError("items payload has non-canonical ABI bytes"); } } function assertApiValidOfferStruct(offer) { if ((0, offerStructInternal_js_1.isEmptyOfferStruct)(offer)) { return; } assertCollateralParams(offer); assertSafeTimestamp("market.maturity", offer.market.maturity); assertMaturityAt15Utc(offer.market.maturity); assertSafeTimestamp("start", offer.start); assertSafeTimestamp("expiry", offer.expiry); assertApiValidOfferTimeRange(offer); if (offer.buy && !(0, offerStructInternal_js_1.isZeroAddress)(offer.receiverIfMakerIsSeller)) { throw new errors_js_1.PayloadDecodeError("invalid offer bytes: receiverIfMakerIsSeller must be zero for buy offers"); } if (offer.expiry > offer.market.maturity) { throw new errors_js_1.PayloadDecodeError("invalid offer bytes: expiry must be before or equal to maturity"); } if (offer.tick > constants_js_1.MAX_TICK) { throw new errors_js_1.PayloadDecodeError(`invalid offer bytes: tick exceeds maximum ${constants_js_1.MAX_TICK}`); } if ((offer.maxUnits === 0n) === (offer.maxAssets === 0n)) { throw new errors_js_1.PayloadDecodeError("invalid offer bytes: exactly one of maxUnits and maxAssets must be non-zero"); } if (offer.maxUnits > constants_js_1.MAX_OFFER_CAP) { throw new errors_js_1.PayloadDecodeError(`invalid offer bytes: maxUnits exceeds maximum ${constants_js_1.MAX_OFFER_CAP}`); } if (offer.maxAssets > constants_js_1.MAX_OFFER_CAP) { throw new errors_js_1.PayloadDecodeError(`invalid offer bytes: maxAssets exceeds maximum ${constants_js_1.MAX_OFFER_CAP}`); } if (offer.continuousFeeCap < 0n) { throw new errors_js_1.PayloadDecodeError("invalid offer bytes: continuousFeeCap must be non-negative"); } } function assertApiValidOfferTimeRange(offer) { try { index_js_1.OfferUtils.validateOfferTimeRange(offer); } catch (error) { if (error instanceof errors_js_1.InvalidOfferParameterError) { throw new errors_js_1.PayloadDecodeError(`invalid offer bytes: ${error.message}`, error); } throw error; } } function assertCollateralParams(offer) { const collateralParams = offer.market.collateralParams; if (collateralParams.length === 0) { throw new errors_js_1.PayloadDecodeError("invalid offer bytes: at least one collateral required"); } if (collateralParams.length > Number(constants_js_1.MAX_COLLATERALS)) { throw new errors_js_1.PayloadDecodeError(`invalid offer bytes: market.collateralParams has ${collateralParams.length} collaterals, exceeding the maximum of ${constants_js_1.MAX_COLLATERALS}`); } let previousToken; for (const params of collateralParams) { if (params.lltv < 0n || params.lltv > morpho_ts_1.MathLib.WAD) { throw new errors_js_1.PayloadDecodeError(`invalid offer bytes: collateral lltv must be between 0 and WAD, got ${params.lltv}`); } if (params.liquidationCursor < 0n || params.liquidationCursor >= morpho_ts_1.MathLib.WAD) { throw new errors_js_1.PayloadDecodeError(`invalid offer bytes: collateral liquidationCursor must be between 0 and WAD, exclusive of WAD, got ${params.liquidationCursor}`); } const maxLif = morpho_ts_1.MathLib.mulDivDown(morpho_ts_1.MathLib.WAD, morpho_ts_1.MathLib.WAD, morpho_ts_1.MathLib.WAD - morpho_ts_1.MathLib.mulDivDown(params.liquidationCursor, morpho_ts_1.MathLib.WAD - params.lltv, morpho_ts_1.MathLib.WAD)); if (maxLif > 2n * morpho_ts_1.MathLib.WAD) { throw new errors_js_1.PayloadDecodeError(`invalid offer bytes: computed collateral maxLif exceeds 2 WAD, got ${maxLif}`); } if (params.lltv !== morpho_ts_1.MathLib.WAD && params.lltv * maxLif > 999000000000000000n * morpho_ts_1.MathLib.WAD) { throw new errors_js_1.PayloadDecodeError(`invalid offer bytes: computed collateral maxLif ${maxLif} is too high for lltv ${params.lltv}`); } const token = params.token.toLowerCase(); if ((0, offerStructInternal_js_1.isZeroAddress)(token)) { throw new errors_js_1.PayloadDecodeError("invalid offer bytes: collateral token must be non-zero"); } if (previousToken != null && previousToken >= token) { throw new errors_js_1.PayloadDecodeError("invalid offer bytes: collaterals must be sorted and unique"); } previousToken = token; } } function assertSafeTimestamp(field, value) { if (value > MAX_TIMESTAMP_SECONDS) { throw new errors_js_1.PayloadDecodeError(`invalid offer bytes: ${field} exceeds ${MAX_TIMESTAMP_SECONDS}`); } } function assertMaturityAt15Utc(value) { const date = new Date(Number(value) * 1000); if (date.getUTCHours() !== 15 || date.getUTCMinutes() !== 0 || date.getUTCSeconds() !== 0 || date.getUTCMilliseconds() !== 0) { throw new errors_js_1.PayloadDecodeError("invalid offer bytes: maturity must be at 15:00:00 UTC"); } } function resolveMaxItems(maxItems) { if (maxItems === undefined) { return undefined; } if (!Number.isInteger(maxItems) || maxItems < 1) { throw new errors_js_1.PayloadDecodeError(`maxItems must be a positive integer: got ${maxItems}`); } return maxItems; } function assertNonEmptyItemCount(count) { if (count === 0) { throw new errors_js_1.PayloadDecodeError("items payload is empty"); } } function assertCallerItemCountLimit(count, maxItems) { if (maxItems === undefined) { return; } if (count > maxItems) { throw new errors_js_1.PayloadDecodeError(`items payload exceeds ${maxItems} items`); } } async function compressItemsPayload(payload) { if (payload.length > Payload.MAX_DECOMPRESSED_ITEMS_BYTES) { throw new errors_js_1.PayloadDecodeError(`decompressed items exceed ${Payload.MAX_DECOMPRESSED_ITEMS_BYTES} bytes`); } let compressed; try { const stream = singleChunkStream(payload).pipeThrough(new CompressionStream("gzip")); compressed = new Uint8Array(await new Response(stream).arrayBuffer()); } catch (error) { throw new errors_js_1.PayloadDecodeError("compression failed", error instanceof Error ? error : undefined); } if (compressed.length > Payload.MAX_COMPRESSED_ITEMS_BYTES) { throw new errors_js_1.PayloadDecodeError(`compressed items exceed ${Payload.MAX_COMPRESSED_ITEMS_BYTES} bytes`); } return compressed; } function assertCompressedItemsLength(compressed) { if (compressed.length === 0) { throw new errors_js_1.PayloadDecodeError("decompression failed"); } if (compressed.length > Payload.MAX_COMPRESSED_ITEMS_BYTES) { throw new errors_js_1.PayloadDecodeError(`compressed items exceed ${Payload.MAX_COMPRESSED_ITEMS_BYTES} bytes`); } } async function decompressItemsPayload(compressed) { assertCompressedItemsLength(compressed); const reader = singleChunkStream(compressed) .pipeThrough(new DecompressionStream("gzip")) .getReader(); const chunks = []; let totalLength = 0; try { while (true) { const { done, value } = await reader.read(); if (done) { break; } totalLength += value.length; if (totalLength > Payload.MAX_DECOMPRESSED_ITEMS_BYTES) { await reader.cancel(); throw new errors_js_1.PayloadDecodeError(`decompressed items exceed ${Payload.MAX_DECOMPRESSED_ITEMS_BYTES} bytes`); } chunks.push(value); } } catch (error) { if (error instanceof errors_js_1.PayloadDecodeError) { throw error; } throw new errors_js_1.PayloadDecodeError("decompression failed", error instanceof Error ? error : undefined); } const result = new Uint8Array(totalLength); let offset = 0; for (const chunk of chunks) { result.set(chunk, offset); offset += chunk.length; } return result; } function singleChunkStream(bytes) { return new ReadableStream({ start(controller) { controller.enqueue(new Uint8Array(bytes)); controller.close(); }, }); } function assertAbiItemCountWithinCallerLimit(decoded, maxItems) { if (decoded.length < ABI_ARRAY_HEAD_BYTES) { throw new errors_js_1.PayloadDecodeError("items payload truncated before ABI array head"); } if (maxItems === undefined) { return; } for (let i = 32; i < ABI_LENGTH_LOW_OFFSET; i++) { if (decoded[i] !== 0) { throw new errors_js_1.PayloadDecodeError(`items payload exceeds ${maxItems} items`); } } const length = new DataView(decoded.buffer, decoded.byteOffset, decoded.byteLength).getUint32(ABI_LENGTH_LOW_OFFSET); if (length > maxItems) { throw new errors_js_1.PayloadDecodeError(`items payload exceeds ${maxItems} items`); } } })(Payload || (exports.Payload = Payload = {}));