@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.
326 lines (325 loc) • 13.3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Tree = void 0;
const morpho_ts_1 = require("@morpho-org/morpho-ts");
const errors_js_1 = require("../errors.js");
const index_js_1 = require("../offers/index.js");
const PriceRatifierV1_js_1 = require("./PriceRatifierV1.js");
const RateRatifierV1_js_1 = require("./RateRatifierV1.js");
const Ratifier_js_1 = require("./Ratifier.js");
const TreeUtils_js_1 = require("./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);
* ```
*/
class Tree {
/** Explicit route, or undefined for a legacy standard tree. */
type;
/** Complete padded leaf commitments for this route. */
entries;
/** Non-padding offers in leaf order. */
offers;
/** ABI-compatible offers in leaf order, including protocol-zero padding. */
paddedOffers;
/** Leaf hashes for the complete padded `entries`. */
leaves;
/** Merkle root. */
root;
/** Tree height. */
height;
constructor(type, descriptor) {
this.type = type;
this.offers = Object.freeze(descriptor.offers.map((offer) => index_js_1.Offer.from(offer)));
this.entries = (0, morpho_ts_1.deepFreeze)(structuredClone(descriptor.entries));
const entries = this.entries;
this.paddedOffers = Object.freeze(entries.map((entry) => ("offer" in entry ? entry.offer : entry)));
this.leaves = Object.freeze([...descriptor.leaves]);
this.root = descriptor.root;
this.height = descriptor.height;
}
static from(tree) {
if (tree instanceof Tree) {
return tree;
}
// Portable snapshots resume through descriptor validation instead of rebuilding.
if (!Array.isArray(tree) &&
"entries" in tree &&
"leaves" in tree &&
"root" in tree) {
return "type" in tree && tree.type != null
? Tree.fromDescriptor(tree)
: Tree.fromDescriptor(tree);
}
if ("type" in tree && tree.type != null) {
return Tree.create(tree);
}
return Tree.create(Array.isArray(tree) ? tree : [tree]);
}
static create(params) {
if ("type" in params) {
const descriptor = TreeUtils_js_1.TreeUtils.buildDescriptor(params);
switch (descriptor.type) {
case "ecrecover":
return new Tree("ecrecover", descriptor);
case "setter":
return new Tree("setter", descriptor);
case "priceV1":
return new Tree("priceV1", descriptor);
case "rateV1":
return new Tree("rateV1", descriptor);
}
}
const offers = TreeUtils_js_1.TreeUtils.normalizeEntries(params);
const descriptor = TreeUtils_js_1.TreeUtils.buildDescriptor(params);
return new Tree(undefined, {
...descriptor,
offers,
entries: descriptor.offers,
});
}
/**
* 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() {
return (0, morpho_ts_1.deepFreeze)({
type: this.type,
entries: [...this.entries],
offers: this.paddedOffers.slice(0, this.offers.length),
leaves: [...this.leaves],
root: this.root,
height: this.height,
});
}
static fromDescriptor(descriptor) {
switch (descriptor.type) {
case "priceV1":
// Validate caller-controlled hashes, offers and padding before constructing an instance.
PriceRatifierV1_js_1.PriceRatifierV1.buildProof({ tree: descriptor, leafIndex: 0n });
return new Tree("priceV1", {
...descriptor,
entries: descriptor.entries.map((entry, index) => ({
allowedTaker: entry.allowedTaker,
offer: index < descriptor.offers.length
? index_js_1.OfferUtils.toStruct({ offer: entry.offer })
: entry.offer,
})),
});
case "rateV1":
// Validate caller-controlled hashes, offers and padding before constructing an instance.
RateRatifierV1_js_1.RateRatifierV1.buildProof({ tree: descriptor, leafIndex: 0n });
return new Tree("rateV1", {
...descriptor,
entries: descriptor.entries.map((entry, index) => ({
rate: entry.rate,
allowedTaker: entry.allowedTaker,
offer: index < descriptor.offers.length
? index_js_1.OfferUtils.toStruct({ offer: entry.offer })
: entry.offer,
})),
});
case "ecrecover":
case "setter":
case undefined: {
// Validate the complete standard offer commitment without reassigning groups.
Ratifier_js_1.Ratifier.normalizeRatifierTree({
tree: { ...descriptor, paddedOffers: descriptor.entries },
label: descriptor.type === "setter" ? "Setter" : "Ecrecover",
});
const normalized = {
...descriptor,
entries: descriptor.entries.map((offer, index) => index < descriptor.offers.length
? index_js_1.OfferUtils.toStruct({ offer })
: offer),
};
if (descriptor.type === "ecrecover") {
return new Tree("ecrecover", normalized);
}
if (descriptor.type === "setter") {
return new Tree("setter", normalized);
}
return new Tree(undefined, normalized);
}
default:
throw new errors_js_1.InvalidTreeError("Unsupported tree ratifier route.");
}
}
/**
* 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,
* });
* ```
*/
async mempoolValidate(params) {
const descriptor = this.toDescriptor();
if (params.ratification != null &&
(this.type == null
? params.ratification.type !== "ecrecover" &&
params.ratification.type !== "setter"
: params.ratification.type !== this.type)) {
throw new errors_js_1.InvalidTreeError("Ratification route does not match the tree route.");
}
if (this.type === "priceV1" || this.type === "rateV1") {
return TreeUtils_js_1.TreeUtils.mempoolValidate({
...params,
tree: descriptor,
});
}
return TreeUtils_js_1.TreeUtils.mempoolValidate({
...params,
ratification: params.ratification,
tree: Tree.fromDescriptor({
...descriptor,
type: undefined,
entries: this.paddedOffers,
}),
});
}
/**
* 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) {
return TreeUtils_js_1.TreeUtils.buildProof({
tree: this,
leafIndex,
});
}
}
exports.Tree = Tree;