@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.
864 lines (863 loc) • 33.8 kB
TypeScript
import { type BigIntish } from "@morpho-org/morpho-ts";
import { type Account, type Address, type Chain, type Client, type Hash, type Transport } from "viem";
import type { MempoolPayloadValidationSuccess, MidnightApiFetch, MidnightApiRequestOptions } from "../api/types.js";
import { type IOffer, Offer, type OfferStruct } from "../offers/index.js";
import { type EcrecoverSignatureInput } from "./EcrecoverRatifier.js";
import { type GroupInput } from "./GroupUtils.js";
import { Tree } from "./Tree.js";
import type { AnyTreeSnapshot, EcrecoverTreeCreateRequest, TreeCreateRequest, TreeSnapshot } from "./treeTypes.js";
/**
* Fully materialized tree descriptor.
*
* Use this shape when a caller needs leaf structs, leaf hashes, root, and
* height without keeping a `Tree` instance, for example before custom signing
* or proof generation.
*
* @example
* ```ts
* import { Offer, TreeUtils, type TreeDescriptor } 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: TreeDescriptor = TreeUtils.buildDescriptor([offer]);
* console.log(tree.root);
* ```
*/
export interface TreeDescriptor {
/** Offer structs in leaf order, including trailing empty padding. */
readonly offers: readonly OfferStruct[];
/** Leaf hashes for the padded tree. */
readonly leaves: readonly Hash[];
/** Merkle root. */
readonly root: Hash;
/** Tree height. */
readonly height: number;
}
/**
* Merkle proof descriptor for one tree leaf.
*
* Ratifier data embeds this information so a taker can prove the offer belongs
* to the maker-approved or maker-signed root.
*
* @example
* ```ts
* import { Offer, Tree, type TreeProof } 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: TreeProof = Tree.create([offer]).proof(0n);
* console.log(proof.leafIndex);
* ```
*/
export interface TreeProof {
/** Merkle root. */
readonly root: Hash;
/** Leaf index in the tree. */
readonly leafIndex: bigint;
/** Sibling hashes from leaf to root. */
readonly proof: readonly Hash[];
}
/**
* Legacy untagged entries accepted by {@link Tree.create}.
*
* @deprecated Use EcrecoverTreeCreateRequest or SetterTreeCreateRequest with an explicit type and entries.
*
* Entries are either explicit groups or standalone offers. Explicit groups are
* flattened, and standalone offers are hashed with their own group ids.
*
* @example
* ```ts
* import { Tree, type TreeCreateParams } from "@morpho-org/midnight-sdk";
* import { Offer } 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 params = [offer] satisfies TreeCreateParams;
* const tree = Tree.create(params);
* console.log(tree.root);
* ```
*/
export type TreeCreateParams = EcrecoverTreeCreateRequest["entries"];
/**
* Plain creation input or class tree accepted by {@link Tree.from}.
*
* Use this only at boundaries that intentionally convert caller input into a
* `Tree`. Ratifier helpers accept {@link RatifierTreeInput} instead, so they
* can reuse an existing `Tree` or normalize raw offer/group input.
*
* @example
* ```ts
* import { Offer, type TreeInput } 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: TreeInput = [offer];
* console.log(tree);
* ```
*/
export type TreeInput = Tree | TreeCreateParams | GroupInput;
/**
* Tree-shaped data required by ratifier helpers.
*
* A `Tree` class instance satisfies this shape and is the optimal input when a
* caller already built one, because the cached offers, leaves, root, and height
* are reused for signatures and proofs. Plain objects with these fields are
* also accepted by ratifier helpers.
*
* @example
* ```ts
* import { Offer, Tree, type TreeLike } 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: TreeLike = Tree.create([offer]);
* console.log(tree.root);
* ```
*/
export interface TreeLike {
/** Non-padding offers in leaf order. */
readonly offers: readonly IOffer[];
/** ABI-compatible offers in leaf order, including protocol-zero padding. */
readonly paddedOffers: readonly OfferStruct[];
/** Leaf hashes for `paddedOffers`. */
readonly leaves: readonly Hash[];
/** Merkle root. */
readonly root: Hash;
/** Tree height. */
readonly height: number;
}
/**
* Tree-like input accepted by ratifier helpers.
*
* Pass a `Tree` or {@link TreeLike} object to reuse cached hashes and proofs.
* Pass raw offer/group input when convenience matters more than avoiding a
* one-time tree materialization.
*
* @example
* ```ts
* import { Offer, type RatifierTreeInput } 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: RatifierTreeInput = [offer];
* console.log(tree);
* ```
*/
export type RatifierTreeInput = TreeLike | TreeInput;
/**
* Optional ratification inputs for {@link Tree.mempoolValidate}.
*
* Omit this when validating offer policy before the maker signs or approves a
* tree. Provide it when validating the final payload shape, including real
* `ratifierData`, after the Ecrecover signature and signer address exist or the
* Setter root is ready for publication. Price/Rate V1 routes always post real
* ratifier data because the router identifies each offer from its decoded
* leaf fields; their `ratification` is only a route assertion.
*
* @example
* ```ts
* import { zeroHash, type Signature } from "viem";
* import type { TreeMempoolValidateRatification } from "@morpho-org/midnight-sdk";
*
* const ratification: TreeMempoolValidateRatification = {
* type: "ecrecover",
* account: "0x0000000000000000000000000000000000009000",
* signature: { v: 27, r: zeroHash, s: zeroHash } satisfies Signature,
* };
* console.log(ratification.type);
* ```
*/
export type TreeMempoolValidateRatification = {
/** Ecrecover ratifier route. */
readonly type: "ecrecover";
/** Viem client whose transport signs typed data built from the tree. */
readonly client: Client<Transport, Chain, Account | undefined>;
/** Account that signs the tree root. */
readonly account: Account | Address;
/** Omit when the SDK should request the signature through `client`. */
readonly signature?: undefined;
} | {
/** Ecrecover ratifier route. */
readonly type: "ecrecover";
/** Precomputed signature for this tree root. */
readonly signature: EcrecoverSignatureInput;
/** Account that produced the signature. It may be the maker or an address authorized by each maker. */
readonly account: Account | Address;
/** Omit when a precomputed signature is supplied. */
readonly client?: undefined;
} | {
/** Setter ratifier route. */
readonly type: "setter";
} | {
/** PriceRatifierV1 route assertion; validation always encodes its ratifier data. */
readonly type: "priceV1";
} | {
/** RateRatifierV1 route assertion; validation always encodes its ratifier data. */
readonly type: "rateV1";
};
/**
* Parameters for {@link Tree.mempoolValidate}.
*
* Use this when an already-created tree should be validated by the Midnight
* API. Standard routes validate the pre-ratification tree with empty
* `ratifierData` by default; pass `ratification` to validate the final
* payload shape with real ratifier data. Price/Rate V1 routes always encode
* real ratifier data (root, leaf index, proof, allowed taker, and the rate for
* RateRatifierV1) because the router identifies each offer by decoding it; their
* `ratification` only asserts the route.
*
* @example
* ```ts
* import { Offer, Tree, type TreeMempoolValidateParams } 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 params = { chainId: 8453 } satisfies TreeMempoolValidateParams;
* await tree.mempoolValidate(params);
* ```
*/
export interface TreeMempoolValidateParams {
/** Chain id whose API policy should validate the tree. */
readonly chainId: number;
/** Midnight API URL used for the validation HTTP request. Defaults to `https://api.morpho.org/v0/midnight`. */
readonly apiUrl?: string | URL;
/** Optional ISO-8601 timestamp or `Date` selecting the API policy snapshot. */
readonly timestamp?: string | Date;
/** Fetch implementation used for the API call. Defaults to the global `fetch`. */
readonly fetch?: MidnightApiFetch;
/** Additional fetch options forwarded to the API request. */
readonly request?: MidnightApiRequestOptions;
/** Optional ratification inputs used to validate final payload bytes with real ratifier data. */
readonly ratification?: TreeMempoolValidateRatification;
}
/**
* 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 declare namespace 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 an explicit group entry violates group mechanics.
* @example
* ```ts
* import { TreeUtils, type TreeCreateParams } from "@morpho-org/midnight-sdk";
*
* function normalize(entries: TreeCreateParams) {
* return TreeUtils.normalizeEntries(entries);
* }
* ```
*/
function normalizeEntries(entries: TreeCreateParams): readonly Offer[];
/**
* 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 - Offer tree or route-typed tree 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 {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],
* });
* ```
*/
function mempoolValidate(params: Pick<TreeMempoolValidateParams, "chainId" | "apiUrl" | "timestamp" | "fetch" | "request"> & {
readonly tree: TreeInput | TreeSnapshot<"ecrecover"> | TreeSnapshot<"setter"> | TreeSnapshot<"priceV1"> | TreeSnapshot<"rateV1">;
readonly ratification?: TreeMempoolValidateRatification;
}): Promise<MempoolPayloadValidationSuccess>;
/**
* 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: Hash, right: Hash): `0x${string}`;
/**
* Builds a tree descriptor and Merkle root. Non-power-of-two batches are
* padded with protocol-zero offers at the highest leaf indices.
*
* Use after `Group.create` or standalone `Offer.create` when you need the
* padded leaves for custom signing, root approval, or proof construction.
* Groups are encoded with their derived shared group id, and standalone
* offers are encoded as singleton groups with the same algorithm.
* `Tree.create` calls this internally and is the simpler API for most
* make-side code.
*
* @param entries - Tagged route and leaf inputs in leaf order.
* @returns Tree descriptor.
* @throws {InvalidTreeError} when the offer count is empty, all padding, or duplicated.
* @throws {InvalidTreeHeightError} when the padded tree exceeds supported ratifier typehashes.
* @throws {InvalidOfferGroupError} for priceV1/rateV1 entries whose explicit groups break `OfferUtils.validateOfferGroup` rules.
* @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, 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 = TreeUtils.buildDescriptor({ type: "ecrecover", entries: [offer] });
* console.log(tree.root);
* ```
*/
function buildDescriptor<R extends TreeCreateRequest>(entries: R): Extract<AnyTreeSnapshot, {
readonly type: R["type"];
}>;
/**
* Builds a descriptor using the legacy standard-offer input.
* @deprecated Pass a TreeCreateRequest with an explicit ratifier type instead.
* @param entries - Untagged offers or groups in leaf order.
* @returns Legacy padded standard-offer descriptor.
* @throws {InvalidTreeError} When entries are empty, all padding, or duplicated.
* @throws {InvalidTreeHeightError} When the tree height is unsupported.
* @example
* ```ts
* import { TreeUtils, type TreeCreateParams } from "@morpho-org/midnight-sdk";
* function legacyDescriptor(entries: TreeCreateParams) {
* return TreeUtils.buildDescriptor(entries);
* }
* ```
*/
function buildDescriptor(entries: TreeCreateParams): TreeDescriptor;
/**
* 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.
* @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: TreeCreateParams): Hash;
/**
* 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: readonly Hash[]): {
readonly root: Hash;
readonly height: number;
};
/**
* 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: {
readonly tree: Pick<TreeLike, "leaves" | "root">;
readonly leafIndex: BigIntish;
}): TreeProof;
/**
* 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: {
readonly tree: Pick<TreeLike, "leaves" | "root">;
readonly count?: number;
}): readonly TreeProof[];
/**
* 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: {
readonly offer: IOffer;
readonly root: Hash;
readonly leafIndex: BigIntish;
readonly proof: readonly Hash[];
}): boolean;
/**
* 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: {
readonly leaf: Hash;
readonly root: Hash;
readonly leafIndex: BigIntish;
readonly proof: readonly Hash[];
}): boolean;
}