@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.
340 lines (339 loc) • 15.4 kB
TypeScript
import { type BigIntish } from "@morpho-org/morpho-ts";
import type { Hash } from "viem";
import type { MempoolPayloadValidationSuccess } from "../api/types.js";
import { Offer, type OfferStruct } from "../offers/index.js";
import { type TreeCreateParams, type TreeInput, type TreeProof } from "./TreeUtils.js";
import type { AnyTree, AnyTreeSnapshot, RatifierKind, TreeCreateRequest, TreeEntry, TreeSnapshot, TypedTreeMempoolValidateParams } from "./treeTypes.js";
export type { RatifierTreeInput, TreeCreateParams, TreeDescriptor, TreeInput, TreeLike, TreeMempoolValidateParams, TreeMempoolValidateRatification, TreeProof, } from "./TreeUtils.js";
/**
* Maker-side Merkle tree used by Midnight ratifiers.
*
* Build a tree after offers have been created and related offers have been
* grouped. The tree root is what Ecrecover makers sign, Setter makers approve,
* and payload items later prove with per-leaf ratifier data. Price/Rate V1
* trees carry their additional leaf commitments and use onchain root approval.
*
* @example
* ```ts
* import { Offer, Tree } 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({ type: "ecrecover", entries: [offer] });
* console.log(tree.root);
* ```
*/
export declare class Tree<K extends RatifierKind | undefined = undefined> {
/** Explicit route, or undefined for a legacy standard tree. */
readonly type: K;
/** Complete padded leaf commitments for this route. */
readonly entries: readonly TreeEntry<K>[];
/** Non-padding offers in leaf order. */
readonly offers: readonly Offer[];
/** ABI-compatible offers in leaf order, including protocol-zero padding. */
readonly paddedOffers: readonly OfferStruct[];
/** Leaf hashes for the complete padded `entries`. */
readonly leaves: readonly Hash[];
/** Merkle root. */
readonly root: Hash;
/** Tree height. */
readonly height: number;
private constructor();
/**
* Returns a tree instance from class or plain input.
*
* Use at boundaries that accept either a prebuilt tree or raw group/offer
* inputs, such as API validation helpers. Existing `Tree` instances are
* returned as-is.
*
* @param tree - Tree class or creation input.
* @returns Tree instance.
* @throws {InvalidTreeError} when the tree is empty, all padding, or duplicated.
* @throws {InvalidTreeHeightError} when the resulting height is unsupported.
* @throws {InvalidOfferGroupError} when standalone standard offers from one maker repeat an explicit group id, or V1 groups violate group mechanics.
* @throws {InvalidOfferParameterError} when creating a tree from a sell offer with the zero address as its receiver.
* @throws {InvalidRateRatifierV1RateError} when a Rate leaf has a negative rate.
* @throws {InvalidRateRatifierV1TickError} when a Rate leaf offer tick is below `RateRatifierV1.MIN_TICK`.
* @example
* ```ts
* import { Offer, Tree } 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.from({ type: "ecrecover", entries: [offer] });
* console.log(tree.root);
* ```
*/
static from<T extends AnyTree | AnyTreeSnapshot | TreeCreateRequest>(tree: T): Extract<AnyTree, {
readonly type: T["type"];
}>;
/**
* Resolves an untagged standard tree or legacy creation input.
* @deprecated Pass a tagged TreeCreateRequest or a route-typed Tree instead.
* @param tree - Legacy tree, offer, group, or array of entries.
* @returns Untagged standard tree.
* @throws {InvalidTreeError} When entries are empty, all padding, or duplicated.
* @throws {InvalidTreeHeightError} When the tree height is unsupported.
* @throws {InvalidOfferGroupError} When standalone offers from one maker repeat an explicit group id.
* @example
* ```ts
* import { Tree, type TreeInput } from "@morpho-org/midnight-sdk";
* function legacyTree(input: TreeInput) { return Tree.from(input); }
* ```
*/
static from(tree: TreeInput): Tree;
/**
* Creates a route-typed tree from standard offer/groups or Price/Rate leaf inputs.
*
* Use after `Offer.create` and optional `Group.create`, before
* `Tree.mempoolValidate`, `EcrecoverRatifier.ratify`, or
* `SetterRatifier.ratify`. Ecrecover and Setter trees flatten groups and
* normalize standalone offers as singleton groups. For these routes, pass
* a `Group.create` result as one entry when offers should share a
* consumption cap.
*
* @param params.type - Ratifier route selecting the leaf commitment format.
* @param params.entries - Standard offer/groups or route-specific leaves in leaf order.
* @returns A tree whose entries and validation options are inferred from the route.
* @throws {InvalidTreeError} when the tree is empty, all padding, or duplicated.
* @throws {InvalidTreeHeightError} when the resulting height is unsupported.
* @throws {InvalidOfferGroupError} when standalone standard offers from one maker repeat an explicit group id, or V1 groups violate group mechanics.
* @throws {InvalidOfferParameterError} when a sell offer has the zero address as its receiver.
* @throws {InvalidRateRatifierV1RateError} when a Rate leaf has a negative rate.
* @throws {InvalidRateRatifierV1TickError} when a Rate leaf offer tick is below `RateRatifierV1.MIN_TICK`.
* @example
* ```ts
* import { Offer, Tree } 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({ type: "ecrecover", entries: [offer] });
* console.log(tree.height);
* ```
*/
static create<R extends TreeCreateRequest>(params: R): Extract<AnyTree, {
readonly type: R["type"];
}>;
/**
* Creates a legacy tree compatible with Ecrecover and Setter.
* @deprecated Pass `{ type, entries }` to select a ratifier explicitly.
* @param params - Standard offer/group inputs.
* @returns Untagged standard tree.
* @throws {InvalidOfferParameterError} when a sell offer has the zero address as its receiver.
* @throws {InvalidTreeError} when the tree is empty, all padding, or duplicated.
* @throws {InvalidTreeHeightError} when the resulting height is unsupported.
* @throws {InvalidOfferGroupError} when standalone offers from one maker repeat an explicit group id.
* @example
* ```ts
* import { Tree, type IOffer } from "@morpho-org/midnight-sdk";
* function legacyTree(offers: readonly IOffer[]) { return Tree.create(offers); }
* ```
*/
static create(params: TreeCreateParams): Tree;
/**
* Exports plain normalized data for transport; does not claim root authorization.
* @returns Descriptor with the same route and padded commitments.
* @example
* ```ts
* import { Tree, type IOffer } from "@morpho-org/midnight-sdk";
* function prepare(offers: readonly IOffer[]) {
* return Tree.create({ type: "setter", entries: offers }).toDescriptor();
* }
* ```
*/
toDescriptor(): TreeSnapshot<K>;
/**
* Validates portable data before constructing a tree. Hashes and padding are checked again.
* @param descriptor - Tagged descriptor, or legacy untagged snapshot.
* @returns A new tree with the descriptor's route.
* @throws {InvalidTreeError} When entries, offers, padding, hashes or root disagree.
* @throws {InvalidTreeHeightError} When height is unsupported.
* @throws {InvalidRateRatifierV1TickError} when a rateV1 snapshot entry's offer tick is below `RateRatifierV1.MIN_TICK`.
* @example
* ```ts
* import { Tree, type TreeSnapshot } from "@morpho-org/midnight-sdk";
* function resume(snapshot: TreeSnapshot<"rateV1">) {
* return Tree.fromDescriptor(snapshot); // Tree<"rateV1">
* }
* ```
*/
static fromDescriptor<D extends AnyTreeSnapshot>(descriptor: D): Extract<AnyTree, {
readonly type: D["type"];
}>;
static fromDescriptor(descriptor: TreeSnapshot<undefined>): Tree;
/**
* Validates this 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 routes always post their real ratifier data
* because the router decodes it to identify each offer; their
* `ratification` only asserts the route.
*
* @param params.chainId - Chain id whose API policy should validate this tree.
* @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 authorization inputs; Price/Rate routes require their root to have been approved onchain.
* @returns Successful API validation result with `valid: true`.
* @throws {InvalidTreeError} when the ratification route differs from the tree route.
* @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, Tree } 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 Tree.create({ type: "ecrecover", entries: [offer] }).mempoolValidate({
* chainId: 8453,
* });
* ```
*/
mempoolValidate(params: TypedTreeMempoolValidateParams<K>): Promise<MempoolPayloadValidationSuccess>;
/**
* Builds a Merkle proof for one leaf.
*
* Ratifier utilities call this when building per-offer `ratifierData`. Use it
* directly only for custom ratifiers or local proof inspection.
*
* @param leafIndex - Leaf index to prove.
* @returns Tree proof.
* @throws {InvalidTreeError} when the leaf index is out of range.
* @example
* ```ts
* import { Offer, Tree } 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 = Tree.create([offer]).proof(0n);
* console.log(proof.root);
* ```
*/
proof(leafIndex: BigIntish): TreeProof;
}