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.

694 lines (693 loc) • 28.9 kB
import { deepFreeze } from "@morpho-org/morpho-ts"; import { concat, keccak256, } from "viem"; import { MidnightApi } from "../api/MidnightApi.js"; import { MAX_TREE_HEIGHT } from "../constants.js"; import { InvalidOfferGroupError, InvalidTreeError, InvalidTreeHeightError, MidnightMempoolValidationError, } from "../errors.js"; import { Offer, OfferUtils, } from "../offers/index.js"; import { assertNonzeroSellReceiver } from "../offers/offerReceiverInternal.js"; import { EcrecoverRatifierUtils, } from "./EcrecoverRatifier.js"; import { Group } from "./Group.js"; import { GroupUtils } from "./GroupUtils.js"; import { EMPTY_OFFER_STRUCT, isEmptyOfferStruct, } from "./offerStructInternal.js"; import { Payload } from "./Payload.js"; import { PriceRatifierV1 } from "./PriceRatifierV1.js"; import { RateRatifierV1 } from "./RateRatifierV1.js"; import { Ratifier } from "./Ratifier.js"; import { SetterRatifierUtils } from "./SetterRatifier.js"; import { Tree } from "./Tree.js"; import { isPowerOfTwo, nextPowerOfTwo, requireTreeItem, } from "./treeMathInternal.js"; function padOfferStructs(offers) { if (isPowerOfTwo(offers.length)) { return [...offers]; } const paddedLength = nextPowerOfTwo(offers.length); return [ ...offers, ...Array.from({ length: paddedLength - offers.length }, () => EMPTY_OFFER_STRUCT), ]; } function assertIndependentStandaloneOffers(entries) { const seen = new Set(); for (const entry of entries) { if (GroupUtils.isGroupInput(entry) || (entry instanceof Offer && !entry.hasExplicitGroup)) { continue; } const group = entry.group?.toLowerCase(); if (group === undefined) { continue; } const key = `${entry.maker.toLowerCase()}:${group}`; if (seen.has(key)) { throw new InvalidOfferGroupError(`Standalone offers from the same maker specify group "${group}". Pass a Group.create result to share a consumption cap.`); } seen.add(key); } } function assertLeafOffers(offers, leafHashes) { const seen = new Set(); for (const [index, offer] of offers.entries()) { if (isEmptyOfferStruct(offer, { allowDefaultGroup: true })) { continue; } // Reject zero sell receivers on actual offers, not protocol padding. assertNonzeroSellReceiver(offer); const leafHash = requireTreeItem(leafHashes, index); if (seen.has(leafHash)) { throw new InvalidTreeError(`Duplicate offer hash "${leafHash}" in tree.`); } seen.add(leafHash); } /* v8 ignore next: buildDescriptor rejects empty struct lists before padding; this protects direct internal misuse. */ if (seen.size === 0) { throw new InvalidTreeError("Tree must not be empty."); } } function buildLayers(leaves) { let level = [...leaves]; const layers = [level]; while (level.length > 1) { const next = []; for (let i = 0; i < level.length; i += 2) { next.push(TreeUtils.hashNode(requireTreeItem(level, i), requireTreeItem(level, i + 1))); } layers.push(next); level = next; } return layers; } function assertProvableLeaves(leaves) { if (!isPowerOfTwo(leaves.length)) { throw new InvalidTreeError(`Tree leaf count "${leaves.length}" is not a power of two.`); } const height = Math.log2(leaves.length); if (height > MAX_TREE_HEIGHT) { throw new InvalidTreeHeightError(height); } return height; } function computeRootFromLeaves(leaves) { const height = assertProvableLeaves(leaves); const layers = buildLayers(leaves); return { root: requireTreeItem(requireTreeItem(layers, height), 0), height }; } /** * Object-compatible tree hashing, root, proof, and verification helpers. * * Use these when you need pure tree hashing, descriptor construction, or proof * verification. In the normal make-side flow, `Tree.create` wraps descriptor * construction; proof helpers accept the built `Tree` so cached leaves/root are * reused. * * @example * ```ts * import { TreeUtils } from "@morpho-org/midnight-sdk"; * * console.log(typeof TreeUtils.buildRoot); * ``` */ export var TreeUtils; (function (TreeUtils) { /** * Normalizes legacy standard tree entries into grouped offers. * * Explicit groups are flattened into their member offers, and every * standalone offer is normalized as a singleton group using the * router-compatible `GroupUtils.hash` group id. Use this when you need the * exact offer list a standard Ecrecover/Setter tree commits to. * * @param entries - Groups or standalone offers in leaf order. * @returns Offers in leaf order with their committed group ids. * @throws {InvalidOfferGroupError} when a group violates group mechanics or standalone offers from one maker repeat an explicit group id. * @throws {InvalidOfferParameterError} when an explicit group contains a sell offer with the zero address as its receiver. * @example * ```ts * import { TreeUtils, type TreeCreateParams } from "@morpho-org/midnight-sdk"; * * function normalize(entries: TreeCreateParams) { * return TreeUtils.normalizeEntries(entries); * } * ``` */ function normalizeEntries(entries) { // Reject shared caps before normalizing standalone offers independently. assertIndependentStandaloneOffers(entries); return entries.flatMap((entry) => GroupUtils.isGroupInput(entry) ? Group.from(entry).offers : [ new Offer({ ...Offer.from(entry), group: GroupUtils.hash([entry]), }), ]); } TreeUtils.normalizeEntries = normalizeEntries; /** * Validates a tree against Midnight mempool API policy. * * This is an API-backed convenience: by default it encodes each tree leaf * with empty `ratifierData`, then sends the temporary payload to the Midnight * API `POST /mempool/validate` endpoint. Pass `ratification` after signing or * Setter root preparation to validate final payload bytes with real * `ratifierData`. Price/Rate V1 tree snapshots are supported directly and * always post the corresponding V1 `ratify` output — there is no empty * ratifier-data shape because the router decodes the leaf fields to identify * each offer. A V1 `ratification` only asserts the matching route. * * @param params.chainId - Chain id whose API policy should validate the tree. * @param params.tree - Raw standard entries, an offer tree, or a route-typed snapshot to validate. Serialized standard snapshots resume without rewriting committed groups. * @param params.apiUrl - Optional Midnight API URL override used for the validation HTTP request. * @param params.timestamp - Optional ISO-8601 timestamp or `Date` selecting the API policy snapshot. * @param params.fetch - Optional fetch implementation override used for the API call. * @param params.request - Optional fetch options forwarded to the API request. * @param params.ratification - Optional route-matching ratification inputs used to validate final payload bytes with real ratifier data. * @returns Successful API validation result with `valid: true`. * @throws {InvalidTreeError} when the tree is empty, all padding, or duplicated, or when `ratification` does not match the tree route. * @throws {InvalidTreeHeightError} when the resulting height is unsupported. * @throws {InvalidOfferGroupError} when raw standalone offers from one maker repeat an explicit group id. * @throws {InvalidOfferParameterError} when raw tree input contains a sell offer with a zero receiver. * @throws {PayloadDecodeError} when validation payload encoding fails. * @throws {MidnightApiError} when the API returns a non-2xx response. * @throws {InvalidMidnightApiResponseError} when the API returns malformed success JSON. * @throws {MidnightMempoolValidationError} when the API returns validation issues. * @example * ```ts * import { Offer, TreeUtils } 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, * }); * await TreeUtils.mempoolValidate({ * chainId: 8453, * tree: [offer], * }); * ``` */ async function mempoolValidate(params) { let items; if (!Array.isArray(params.tree) && "type" in params.tree && (params.tree.type === "priceV1" || params.tree.type === "rateV1")) { const tree = params.tree; if (params.ratification != null && params.ratification.type !== tree.type) { throw new InvalidTreeError("Ratification route does not match the tree route."); } items = tree.type === "priceV1" ? PriceRatifierV1.ratify({ tree }) : RateRatifierV1.ratify({ tree }); } else { // Only standard Ecrecover/Setter inputs remain beyond this point. // Serialized standard snapshots resume through descriptor validation so committed groups are kept. const rawTree = params.tree; const tree = !(rawTree instanceof Tree) && !Array.isArray(rawTree) && "entries" in rawTree && "offers" in rawTree && "leaves" in rawTree && "root" in rawTree && "height" in rawTree ? Tree.fromDescriptor(rawTree) : rawTree; if (params.ratification == null) { if (Array.isArray(tree) || !("paddedOffers" in tree)) { const entries = Array.isArray(tree) ? tree : [tree]; const offers = normalizeEntries(entries); buildDescriptor(entries); items = offers.map((offer) => ({ offer, ratifierData: "0x", })); } else { items = tree.offers.map((offer) => ({ offer, ratifierData: "0x", })); } } else if (params.ratification.type === "ecrecover") { if (params.ratification.signature == null) { items = await EcrecoverRatifierUtils.ratify({ tree, client: params.ratification.client, account: params.ratification.account, }); } else { items = await EcrecoverRatifierUtils.ratify({ tree, signature: params.ratification.signature, account: params.ratification.account, }); } } else if (params.ratification.type === "setter") { items = SetterRatifierUtils.ratify({ tree }); } else { throw new InvalidTreeError("Ratification route does not match the tree route."); } } const payload = await Payload.encode(items); const validation = await MidnightApi.validateMempoolPayload({ baseUrl: params.apiUrl, fetch: params.fetch, request: params.request, chainId: params.chainId, timestamp: params.timestamp, payload, }); if (!validation.valid) { throw new MidnightMempoolValidationError(validation.issues); } return { valid: true, issues: validation.issues }; } TreeUtils.mempoolValidate = mempoolValidate; /** * Computes HashLib node hash from left and right child hashes. * * @param left - Left child hash. * @param right - Right child hash. * @returns Node hash. * @example * ```ts * import { TreeUtils } from "@morpho-org/midnight-sdk"; * * const root = TreeUtils.hashNode( * "0x0000000000000000000000000000000000000000000000000000000000000000", * "0x0000000000000000000000000000000000000000000000000000000000000000", * ); * console.log(root); * ``` */ function hashNode(left, right) { return keccak256(concat([left, right])); } TreeUtils.hashNode = hashNode; function buildDescriptor(entries) { if ("type" in entries) { switch (entries.type) { case "priceV1": { const descriptor = PriceRatifierV1.buildDescriptor(entries.entries); return deepFreeze({ ...descriptor, type: "priceV1", offers: descriptor.entries .slice(0, descriptor.offers.length) .map((entry) => entry.offer), }); } case "rateV1": { const descriptor = RateRatifierV1.buildDescriptor(entries.entries); return deepFreeze({ ...descriptor, type: "rateV1", offers: descriptor.entries .slice(0, descriptor.offers.length) .map((entry) => entry.offer), }); } case "ecrecover": case "setter": { const { tree } = Ratifier.normalizeRatifierTree({ tree: entries.entries, label: entries.type === "ecrecover" ? "Ecrecover" : "Setter", }); return deepFreeze({ type: entries.type, entries: tree.paddedOffers, offers: tree.paddedOffers.slice(0, tree.offers.length), leaves: tree.leaves, root: tree.root, height: tree.height, }); } default: throw new InvalidTreeError("Unsupported tree ratifier route."); } } // Reject shared caps before encoding standalone offers independently. assertIndependentStandaloneOffers(entries); const structs = entries.flatMap((entry) => GroupUtils.isGroupInput(entry) ? GroupUtils.toStructs(entry) : [ OfferUtils.toStruct({ offer: entry, group: GroupUtils.hash([entry]), }), ]); if (structs.length === 0) { throw new InvalidTreeError("Tree must not be empty."); } const offerStructs = padOfferStructs(structs); const leaves = offerStructs.map(OfferUtils.hashStruct); assertLeafOffers(offerStructs, leaves); const { root, height } = computeRootFromLeaves(leaves); return deepFreeze({ offers: offerStructs, leaves, root, height, }); } TreeUtils.buildDescriptor = buildDescriptor; /** * Builds only the tree root. * * Use when only the root is needed, for example to compare a locally built * tree with an approved root. Use `Tree.create` or `buildDescriptor` if later * proof generation is required. * * @param entries - Groups or standalone offers in leaf order. * @returns Merkle root. * @throws {InvalidTreeError} when the offer count is empty, all padding, or duplicated. * @throws {InvalidTreeHeightError} when the padded tree exceeds supported ratifier typehashes. * @throws {InvalidOfferGroupError} when standalone offers from one maker repeat an explicit group id. * @throws {InvalidOfferParameterError} when a sell offer has the zero address as its receiver. * @example * ```ts * import { Offer, TreeUtils } 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 root = TreeUtils.buildRoot([offer]); * console.log(root); * ``` */ function buildRoot(entries) { return buildDescriptor(entries).root; } TreeUtils.buildRoot = buildRoot; /** * Builds a Merkle root from already-hashed leaves. * * Use this leaf-hash-agnostic form when a ratifier's leaves are not plain * offer hashes, for example `RateRatifierV1.hashLeaf` outputs. The leaf * count must be a power of two; pad non-power-of-two lists beforehand. * * @param leaves - Leaf hashes in leaf order; length must be a power of two. * @returns Merkle root and tree height. * @throws {InvalidTreeError} when the leaf count is not a power of two. * @throws {InvalidTreeHeightError} when the tree exceeds supported ratifier typehashes. * @example * ```ts * import { TreeUtils } from "@morpho-org/midnight-sdk"; * import { zeroHash } from "viem"; * * const { root, height } = TreeUtils.buildRootFromLeaves([zeroHash]); * console.log(height); * ``` */ function buildRootFromLeaves(leaves) { return computeRootFromLeaves(leaves); } TreeUtils.buildRootFromLeaves = buildRootFromLeaves; /** * Builds a Merkle proof for one offer. * * Use after tree construction when a custom ratifier needs one proof; the * built-in ratify helpers use {@link TreeUtils.buildProofs} to generate * `ratifierData` in bulk. * * @param params.tree - Tree-like data with the root and leaves that contain the leaf. * @param params.leafIndex - Leaf index to prove. * @returns Proof descriptor. * @throws {InvalidTreeError} when leaf index is out of range or when the leaf count is not a power of two. * @throws {InvalidTreeHeightError} when the tree height (log2 of the leaf count) exceeds 20. * @example * ```ts * import { Offer, Tree, TreeUtils } 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 proof = TreeUtils.buildProof({ * tree: Tree.create([offer]), * leafIndex: 0n, * }); * console.log(proof.proof.length); * ``` */ function buildProof(params) { const leafIndex = BigInt(params.leafIndex); if (leafIndex < 0n || leafIndex >= BigInt(params.tree.leaves.length)) { throw new InvalidTreeError(`Leaf index "${leafIndex}" is outside the tree.`); } // Height is unused; the call only validates the leaf set is provable. assertProvableLeaves(params.tree.leaves); const index = Number(leafIndex); const layers = buildLayers(params.tree.leaves); const proof = layers .slice(0, -1) .map((level, layerIndex) => requireTreeItem(level, (index >> layerIndex) ^ 1)); return deepFreeze({ root: params.tree.root, leafIndex, proof }); } TreeUtils.buildProof = buildProof; /** * Builds Merkle proofs for a range of leaves from one tree-layer pass. * * Use instead of calling {@link TreeUtils.buildProof} per leaf when many * proofs are needed at once, for example inside `ratify` helpers: the * parent layers are computed once instead of once per leaf. Each returned * proof is byte-identical to `buildProof` on the same tree and leaf index. * * @param params.tree - Tree leaves and root to prove against. * @param params.count - Number of leading leaf indices to prove; defaults to `tree.leaves.length`. * @returns Frozen proofs for leaf indices `0` through `count - 1`. * @throws {InvalidTreeError} when `count` is negative, non-integer, or exceeds the leaf count, or when the leaf count is not a power of two. * @throws {InvalidTreeHeightError} when the tree height (log2 of the leaf count) exceeds 20. * @example * ```ts * import { Offer, Tree, TreeUtils } 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 proofs = TreeUtils.buildProofs({ * tree: Tree.create([offer]), * count: 1, * }); * console.log(proofs[0]!.proof.length); * ``` */ function buildProofs(params) { const count = params.count ?? params.tree.leaves.length; if (!Number.isInteger(count) || count < 0 || count > params.tree.leaves.length) { throw new InvalidTreeError(`Proof count "${count}" is outside the tree.`); } // Height is unused; the call only validates the leaf set is provable. assertProvableLeaves(params.tree.leaves); const layers = buildLayers(params.tree.leaves); const siblingLayers = layers.slice(0, -1); return deepFreeze(Array.from({ length: count }, (_, index) => ({ root: params.tree.root, leafIndex: BigInt(index), proof: siblingLayers.map((level, layerIndex) => requireTreeItem(level, (index >> layerIndex) ^ 1)), }))); } TreeUtils.buildProofs = buildProofs; /** * Verifies a local Merkle proof against a root. * * Use on the take-side or in tests to inspect decoded payload or ratifier * data before forwarding it to a transaction builder. Onchain ratifiers still * perform the authoritative verification. * * @param params.offer - Offer whose hash starts proof reconstruction. * @param params.root - Expected Merkle root. * @param params.leafIndex - Leaf index proven by `params.proof`. * @param params.proof - Merkle proof siblings for the leaf. * @returns Whether the proof reconstructs the supplied root. * @example * ```ts * import { Offer, Tree, TreeUtils } 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 tree = Tree.create([offer]); * const proof = tree.proof(0n); * const valid = TreeUtils.verifyProof({ * offer: tree.offers[0]!, * root: proof.root, * leafIndex: proof.leafIndex, * proof: proof.proof, * }); * console.log(valid); * ``` */ function verifyProof(params) { return verifyLeafProof({ leaf: OfferUtils.hash(Offer.from(params.offer)), root: params.root, leafIndex: params.leafIndex, proof: params.proof, }); } TreeUtils.verifyProof = verifyProof; /** * Verifies a local Merkle proof for an already-hashed leaf against a root. * * Use this leaf-hash-agnostic form when a ratifier's leaves are not plain * offer hashes, for example `RateRatifierV1.hashLeaf` outputs. The leaf * index determines each sibling's left/right position, matching * `HashLib.isLeaf` onchain. * * @param params.leaf - Leaf hash that starts proof reconstruction. * @param params.root - Expected Merkle root. * @param params.leafIndex - Leaf index proven by `params.proof`. * @param params.proof - Merkle proof siblings for the leaf. * @returns Whether the proof reconstructs the supplied root. * @example * ```ts * import { TreeUtils } from "@morpho-org/midnight-sdk"; * import { zeroHash } from "viem"; * * const valid = TreeUtils.verifyLeafProof({ * leaf: zeroHash, * root: zeroHash, * leafIndex: 0n, * proof: [], * }); * console.log(valid); * ``` */ function verifyLeafProof(params) { let node = params.leaf; const leafIndex = BigInt(params.leafIndex); if (leafIndex < 0n || leafIndex >> BigInt(params.proof.length) !== 0n) { return false; } let remainingLeafIndex = leafIndex; for (const sibling of params.proof) { node = (remainingLeafIndex & 1n) === 0n ? hashNode(node, sibling) : hashNode(sibling, node); remainingLeafIndex >>= 1n; } return node === params.root; } TreeUtils.verifyLeafProof = verifyLeafProof; })(TreeUtils || (TreeUtils = {}));