@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.
551 lines (550 loc) • 23.9 kB
JavaScript
import { MathLib } from "@morpho-org/morpho-ts";
import { bytesToHex, decodeAbiParameters, encodeAbiParameters, hexToBytes, } from "viem";
import { MAX_COLLATERALS, MAX_OFFER_CAP, MAX_TICK } from "../constants.js";
import { InvalidOfferParameterError, PayloadDecodeError } from "../errors.js";
import { Offer, OfferUtils, } from "../offers/index.js";
import { isEmptyOfferStruct, isZeroAddress } from "./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.
*/
export 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) {
if (Payload.CURRENT_VERSION > 0xff) {
throw new PayloadDecodeError(`version overflow: ${Payload.CURRENT_VERSION} exceeds 255`);
}
assertNonEmptyItemCount(items.length);
const payloadItems = items.map((item) => {
const offer = OfferUtils.toStruct({ offer: item.offer });
assertApiValidOfferStruct(offer);
return {
offer,
ratifierData: item.ratifierData,
};
});
const itemBytes = hexToBytes(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 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 maxItems = resolveMaxItems(options?.maxItems);
if (payload.length > Payload.MAX_PAYLOAD_HEX_LENGTH) {
throw new PayloadDecodeError(`payload hex exceeds ${Payload.MAX_PAYLOAD_HEX_LENGTH} characters`);
}
const bytes = hexToBytes(payload);
if (bytes.length < HEADER_BYTES) {
throw new PayloadDecodeError("payload too short for header");
}
const version = bytes[0];
if (version !== (Payload.CURRENT_VERSION & 0xff)) {
throw new 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 PayloadDecodeError("payload truncated before declared gzip length");
}
const suffixLength = bytes.length - compressedEnd;
if (suffixLength > Payload.MAX_ATTRIBUTION_SUFFIX_BYTES) {
throw new PayloadDecodeError(`trailing suffix exceeds ${Payload.MAX_ATTRIBUTION_SUFFIX_BYTES} bytes: got ${suffixLength}`);
}
const compressed = bytes.subarray(HEADER_BYTES, compressedEnd);
const decoded = await decompressItemsPayload(compressed);
assertAbiItemCountWithinCallerLimit(decoded, maxItems);
const items = decodeItemsBytes(decoded);
assertNonEmptyItemCount(items.length);
assertCallerItemCountLimit(items.length, maxItems);
assertCanonicalItemsBytes(items, decoded);
return items;
}
Payload.decode = decode;
function decodeItemsBytes(decoded) {
let raw;
try {
[raw] = decodeAbiParameters(itemsAbi, bytesToHex(decoded));
}
catch (error) {
throw new PayloadDecodeError("items abi decode failed", error instanceof Error ? error : undefined);
}
try {
return raw.map((entry) => {
assertApiValidOfferStruct(entry.offer);
return {
offer: Offer.from(entry.offer),
ratifierData: entry.ratifierData,
};
});
}
catch (error) {
if (error instanceof PayloadDecodeError)
throw error;
if (error instanceof Error) {
throw new PayloadDecodeError(`invalid offer bytes: ${error.message}`, error);
}
throw error;
}
}
function assertCanonicalItemsBytes(items, decoded) {
const canonical = encodeAbiParameters(itemsAbi, [
items.map((item) => ({
offer: OfferUtils.toStruct({ offer: item.offer }),
ratifierData: item.ratifierData,
})),
]);
if (canonical !== bytesToHex(decoded)) {
throw new PayloadDecodeError("items payload has non-canonical ABI bytes");
}
}
function assertApiValidOfferStruct(offer) {
if (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 && !isZeroAddress(offer.receiverIfMakerIsSeller)) {
throw new PayloadDecodeError("invalid offer bytes: receiverIfMakerIsSeller must be zero for buy offers");
}
if (offer.expiry > offer.market.maturity) {
throw new PayloadDecodeError("invalid offer bytes: expiry must be before or equal to maturity");
}
if (offer.tick > MAX_TICK) {
throw new PayloadDecodeError(`invalid offer bytes: tick exceeds maximum ${MAX_TICK}`);
}
if ((offer.maxUnits === 0n) === (offer.maxAssets === 0n)) {
throw new PayloadDecodeError("invalid offer bytes: exactly one of maxUnits and maxAssets must be non-zero");
}
if (offer.maxUnits > MAX_OFFER_CAP) {
throw new PayloadDecodeError(`invalid offer bytes: maxUnits exceeds maximum ${MAX_OFFER_CAP}`);
}
if (offer.maxAssets > MAX_OFFER_CAP) {
throw new PayloadDecodeError(`invalid offer bytes: maxAssets exceeds maximum ${MAX_OFFER_CAP}`);
}
if (offer.continuousFeeCap < 0n) {
throw new PayloadDecodeError("invalid offer bytes: continuousFeeCap must be non-negative");
}
}
function assertApiValidOfferTimeRange(offer) {
try {
OfferUtils.validateOfferTimeRange(offer);
}
catch (error) {
if (error instanceof InvalidOfferParameterError) {
throw new PayloadDecodeError(`invalid offer bytes: ${error.message}`, error);
}
throw error;
}
}
function assertCollateralParams(offer) {
const collateralParams = offer.market.collateralParams;
if (collateralParams.length === 0) {
throw new PayloadDecodeError("invalid offer bytes: at least one collateral required");
}
if (collateralParams.length > Number(MAX_COLLATERALS)) {
throw new PayloadDecodeError(`invalid offer bytes: market.collateralParams has ${collateralParams.length} collaterals, exceeding the maximum of ${MAX_COLLATERALS}`);
}
let previousToken;
for (const params of collateralParams) {
if (params.lltv < 0n || params.lltv > MathLib.WAD) {
throw new PayloadDecodeError(`invalid offer bytes: collateral lltv must be between 0 and WAD, got ${params.lltv}`);
}
if (params.liquidationCursor < 0n ||
params.liquidationCursor >= MathLib.WAD) {
throw new PayloadDecodeError(`invalid offer bytes: collateral liquidationCursor must be between 0 and WAD, exclusive of WAD, got ${params.liquidationCursor}`);
}
const maxLif = MathLib.mulDivDown(MathLib.WAD, MathLib.WAD, MathLib.WAD -
MathLib.mulDivDown(params.liquidationCursor, MathLib.WAD - params.lltv, MathLib.WAD));
if (maxLif > 2n * MathLib.WAD) {
throw new PayloadDecodeError(`invalid offer bytes: computed collateral maxLif exceeds 2 WAD, got ${maxLif}`);
}
if (params.lltv !== MathLib.WAD &&
params.lltv * maxLif > 999000000000000000n * MathLib.WAD) {
throw new PayloadDecodeError(`invalid offer bytes: computed collateral maxLif ${maxLif} is too high for lltv ${params.lltv}`);
}
const token = params.token.toLowerCase();
if (isZeroAddress(token)) {
throw new PayloadDecodeError("invalid offer bytes: collateral token must be non-zero");
}
if (previousToken != null && previousToken >= token) {
throw new PayloadDecodeError("invalid offer bytes: collaterals must be sorted and unique");
}
previousToken = token;
}
}
function assertSafeTimestamp(field, value) {
if (value > MAX_TIMESTAMP_SECONDS) {
throw new 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 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 PayloadDecodeError(`maxItems must be a positive integer: got ${maxItems}`);
}
return maxItems;
}
function assertNonEmptyItemCount(count) {
if (count === 0)
throw new PayloadDecodeError("items payload is empty");
}
function assertCallerItemCountLimit(count, maxItems) {
if (maxItems === undefined)
return;
if (count > maxItems) {
throw new PayloadDecodeError(`items payload exceeds ${maxItems} items`);
}
}
async function compressItemsPayload(payload) {
if (payload.length > Payload.MAX_DECOMPRESSED_ITEMS_BYTES) {
throw new 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 PayloadDecodeError("compression failed", error instanceof Error ? error : undefined);
}
if (compressed.length > Payload.MAX_COMPRESSED_ITEMS_BYTES) {
throw new PayloadDecodeError(`compressed items exceed ${Payload.MAX_COMPRESSED_ITEMS_BYTES} bytes`);
}
return compressed;
}
async function decompressItemsPayload(compressed) {
if (compressed.length === 0)
throw new PayloadDecodeError("decompression failed");
if (compressed.length > Payload.MAX_COMPRESSED_ITEMS_BYTES) {
throw new PayloadDecodeError(`compressed items exceed ${Payload.MAX_COMPRESSED_ITEMS_BYTES} bytes`);
}
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 PayloadDecodeError(`decompressed items exceed ${Payload.MAX_DECOMPRESSED_ITEMS_BYTES} bytes`);
}
chunks.push(value);
}
}
catch (error) {
if (error instanceof PayloadDecodeError)
throw error;
throw new 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 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 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 PayloadDecodeError(`items payload exceeds ${maxItems} items`);
}
}
})(Payload || (Payload = {}));