@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.
527 lines (526 loc) • 22.4 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PriceRatifierV1Utils = exports.PriceRatifierV1 = void 0;
const morpho_ts_1 = require("@morpho-org/morpho-ts");
const viem_1 = require("viem");
const abis_js_1 = require("../abis.js");
const constants_js_1 = require("../constants.js");
const errors_js_1 = require("../errors.js");
const index_js_1 = require("../market/index.js");
const index_js_2 = require("../offers/index.js");
const GroupUtils_js_1 = require("./GroupUtils.js");
const offerStructInternal_js_1 = require("./offerStructInternal.js");
const ratifierV1Internal_js_1 = require("./ratifierV1Internal.js");
const TreeUtils_js_1 = require("./TreeUtils.js");
const priceRatifierV1DataAbi = [
{ name: "root", type: "bytes32" },
{ name: "leafIndex", type: "uint256" },
{ name: "proof", type: "bytes32[]" },
{ name: "allowedTaker", type: "address" },
];
const priceRatifierV1LeafHashParams = [
{ name: "typehash", type: "bytes32" },
{ name: "marketHash", type: "bytes32" },
{ name: "buy", type: "bool" },
{ name: "maker", type: "address" },
{ name: "start", type: "uint256" },
{ name: "expiry", type: "uint256" },
{ name: "tick", type: "uint256" },
{ name: "allowedTaker", type: "address" },
{ name: "group", type: "bytes32" },
{ name: "callback", type: "address" },
{ name: "callbackDataHash", type: "bytes32" },
{ name: "receiverIfMakerIsSeller", type: "address" },
{ name: "ratifier", type: "address" },
{ name: "reduceOnly", type: "bool" },
{ name: "maxUnits", type: "uint128" },
{ name: "maxAssets", type: "uint128" },
{ name: "continuousFeeCap", type: "uint256" },
];
const isPaddingEntry = (entry) => (0, offerStructInternal_js_1.isEmptyOfferStruct)(entry.offer) && (0, offerStructInternal_js_1.isZeroAddress)(entry.allowedTaker);
/**
* PriceRatifierV1-specific pure utilities.
*
* Use this route when makers ratify a Merkle root of price-bounded offers
* onchain. The make-side sequence is: create offers with the PriceRatifierV1
* address, build the tree descriptor, ratify the root onchain (directly or
* through `setIsRootRatified`), then call `ratify` and pass the returned items
* to `Payload.encode`.
*
* @example
* ```ts
* import { PriceRatifierV1 } from "@morpho-org/midnight-sdk";
*
* console.log(typeof PriceRatifierV1.ratify);
* ```
*/
var PriceRatifierV1;
(function (PriceRatifierV1) {
/**
* Computes the PriceRatifierV1 EIP-712 leaf hash for one leaf struct.
*
* This is the SDK port of `HashLib.hashPriceRatifierV1Offer`: the offer's
* `tick` is kept and `allowedTaker` is appended after it.
*
* @param leaf - ABI-compatible leaf to hash.
* @returns Leaf hash used in the ratified Merkle tree.
* @example
* ```ts
* import { PriceRatifierV1, type OfferStruct } from "@morpho-org/midnight-sdk";
* import { zeroAddress } from "viem";
*
* function hash(offer: OfferStruct) {
* return PriceRatifierV1.hashLeaf({
* offer,
* allowedTaker: zeroAddress,
* });
* }
* ```
*/
function hashLeaf(leaf) {
const { offer } = leaf;
return (0, viem_1.keccak256)((0, viem_1.encodeAbiParameters)(priceRatifierV1LeafHashParams, [
constants_js_1.PRICE_RATIFIER_V1_OFFER_TYPEHASH,
index_js_1.MarketUtils.hash(offer.market),
offer.buy,
offer.maker,
offer.start,
offer.expiry,
offer.tick,
leaf.allowedTaker,
offer.group,
offer.callback,
(0, viem_1.keccak256)(offer.callbackData),
offer.receiverIfMakerIsSeller,
offer.ratifier,
offer.reduceOnly,
offer.maxUnits,
offer.maxAssets,
offer.continuousFeeCap,
]));
}
PriceRatifierV1.hashLeaf = hashLeaf;
/**
* Zero-group member hash of one leaf, as consumed by `GroupUtils.hashMembers`.
*
* This is what the router recomputes for its `group_identity` check: the
* PriceRatifierV1 leaf hash with `group = 0`, so the id also commits to
* `allowedTaker`.
*
* @param leaf - Price-committed offer leaf.
* @returns Zero-group PriceRatifierV1 leaf hash.
* @example
* ```ts
* import { Offer, PriceRatifierV1 } 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: "0x000000000000000000000000000000000000a111",
* maxUnits: 100n,
* });
*
* console.log(PriceRatifierV1.memberHash({ offer }));
* ```
*/
function memberHash(leaf) {
return hashLeaf({
offer: index_js_2.OfferUtils.toStruct({ offer: leaf.offer, group: viem_1.zeroHash }),
allowedTaker: leaf.allowedTaker ?? viem_1.zeroAddress,
});
}
PriceRatifierV1.memberHash = memberHash;
/**
* Content-addressed consumption group id for PriceRatifierV1 leaves.
*
* Mirrors `GroupUtils.hash` with the PriceRatifierV1 {@link memberHash}, so
* it matches the router-derived group. Use it to share one group across
* several leaves; single leaves get this id by default in
* {@link buildDescriptor}. Leaves sharing a group must satisfy the same
* constraints as `Group.create` (one maker, side, and cap mode/value); this
* helper only derives the id and does not check them.
*
* @param leaves - Leaves sharing one consumption group.
* @returns Content-addressed group id.
* @throws {InvalidOfferGroupError} when `leaves` is empty.
* @example
* ```ts
* import { Offer, PriceRatifierV1 } 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: "0x000000000000000000000000000000000000a111",
* maxUnits: 100n,
* });
* const leaves = [{ offer }, { offer: Offer.from({ ...offer, tick: 5_004n }) }];
*
* const group = PriceRatifierV1.groupId(leaves);
* const grouped = leaves.map((leaf) => ({
* ...leaf,
* offer: Offer.from({ ...leaf.offer, group }),
* }));
* ```
*/
function groupId(leaves) {
return GroupUtils_js_1.GroupUtils.hashMembers(Array.from(leaves, memberHash));
}
PriceRatifierV1.groupId = groupId;
/**
* Builds a PriceRatifierV1 tree descriptor from leaf input.
*
* Non-power-of-two leaf lists are padded with protocol-zero leaves at the
* highest leaf indices. A group matching the generic content id of all
* leaves sharing it (for example from `OfferUtils.toStruct` or
* `Group.create`) is re-derived with {@link groupId}; other explicit groups
* are committed as-is. Every explicit group is first checked with
* {@link OfferUtils.validateOfferGroup}. An omitted `group` defaults to the leaf's
* content-addressed singleton {@link groupId}, which commits to
* `allowedTaker` like the router does.
*
* @param leaves - Price-bounded offer leaves in leaf order.
* @returns PriceRatifierV1 tree descriptor.
* @throws {InvalidOfferGroupError} when an explicitly grouped offer breaks `OfferUtils.validateOfferGroup` rules (members differ in maker, side, loan token, chain, Midnight contract or cap mode/value, an offer has an invalid cap, or a buy offer sets `receiverIfMakerIsSeller`).
* @throws {InvalidTreeError} when the leaf list is empty, contains duplicate leaf hashes, or mixes ratifier addresses.
* @throws {InvalidTreeHeightError} when the padded tree exceeds supported ratifier typehashes.
* @example
* ```ts
* import { PriceRatifierV1, type IOffer } from "@morpho-org/midnight-sdk";
*
* function build(offer: IOffer) {
* return PriceRatifierV1.buildDescriptor([{ offer }]);
* }
* ```
*/
function buildDescriptor(leaves) {
const normalized = leaves.map((leaf) => ({
offer: index_js_2.Offer.from(leaf.offer),
allowedTaker: leaf.allowedTaker ?? viem_1.zeroAddress,
}));
const assignedOffers = (0, ratifierV1Internal_js_1.assignRatifierV1Groups)(normalized, groupId);
const offers = [];
const structs = normalized.map(({ allowedTaker }, index) => {
const offer = assignedOffers[index];
offers.push(offer);
return { offer: index_js_2.OfferUtils.toStruct({ offer }), allowedTaker };
});
const descriptor = (0, ratifierV1Internal_js_1.buildRatifierV1Descriptor)({
entries: structs,
padding: { offer: offerStructInternal_js_1.EMPTY_OFFER_STRUCT, allowedTaker: viem_1.zeroAddress },
hashLeaf,
ratifierOf: (leafStruct) => leafStruct.offer.ratifier,
label: "PriceRatifierV1",
});
return Object.freeze({
entries: (0, morpho_ts_1.deepFreeze)(descriptor.entries),
leaves: (0, morpho_ts_1.deepFreeze)(descriptor.leaves),
root: descriptor.root,
height: descriptor.height,
offers: Object.freeze([...offers]),
});
}
PriceRatifierV1.buildDescriptor = buildDescriptor;
const treeHelpers = {
buildDescriptor,
hashLeaf,
isPadding: isPaddingEntry,
ratifierOf: (leafStruct) => leafStruct.offer.ratifier,
label: "PriceRatifierV1",
type: "priceV1",
};
/**
* Builds a Merkle proof for one PriceRatifierV1 leaf.
*
* @param params.tree - PriceRatifierV1 tree descriptor or raw leaf input.
* @param params.leafIndex - Leaf index to prove.
* @returns Proof descriptor.
* @throws {InvalidOfferGroupError} when an explicitly grouped offer breaks `OfferUtils.validateOfferGroup` rules (members differ in maker, side, loan token, chain, Midnight contract or cap mode/value, an offer has an invalid cap, or a buy offer sets `receiverIfMakerIsSeller`). For raw leaf input only.
* @throws {InvalidTreeError} when the tree is invalid or the leaf index is out of range.
* @throws {InvalidTreeHeightError} when the tree exceeds the supported height.
* @example
* ```ts
* import { PriceRatifierV1, type IOffer } from "@morpho-org/midnight-sdk";
*
* function build(offer: IOffer) {
* return PriceRatifierV1.buildProof({
* tree: PriceRatifierV1.buildDescriptor([{ offer }]),
* leafIndex: 0n,
* });
* }
* ```
*/
function buildProof(params) {
const tree = (0, ratifierV1Internal_js_1.resolveRatifierV1Tree)(params.tree, treeHelpers);
return TreeUtils_js_1.TreeUtils.buildProof({ tree, leafIndex: params.leafIndex });
}
PriceRatifierV1.buildProof = buildProof;
/**
* Encodes PriceRatifierV1 ratifier data.
*
* Use only when you already have a root, proof, and allowed taker. Most
* maker flows call `ratifierData` for one leaf or `ratify` for every leaf
* in the ratified tree.
*
* @param params.root - Merkle root ratified by the maker's PriceRatifierV1.
* @param params.leafIndex - Leaf index proven by `params.proof`.
* @param params.proof - Merkle proof siblings for the leaf.
* @param params.allowedTaker - Taker restriction carried by the leaf.
* @returns ABI-encoded ratifier data.
* @example
* ```ts
* import { PriceRatifierV1 } from "@morpho-org/midnight-sdk";
* import { zeroAddress, zeroHash } from "viem";
*
* const data = PriceRatifierV1.encodeRatifierData({
* root: zeroHash,
* leafIndex: 0n,
* proof: [],
* allowedTaker: zeroAddress,
* });
* console.log(data);
* ```
*/
function encodeRatifierData(params) {
return (0, viem_1.encodeAbiParameters)(priceRatifierV1DataAbi, [
params.root,
BigInt(params.leafIndex),
params.proof,
params.allowedTaker,
]);
}
PriceRatifierV1.encodeRatifierData = encodeRatifierData;
/**
* Decodes PriceRatifierV1 ratifier data.
*
* Use on the take-side or in tests after `Payload.decode` to inspect the
* proof and allowed taker attached to a published offer.
*
* @param data - ABI-encoded ratifier data.
* @returns Decoded PriceRatifierV1 ratifier data.
* @example
* ```ts
* import { PriceRatifierV1 } from "@morpho-org/midnight-sdk";
* import { zeroAddress, zeroHash } from "viem";
*
* const decoded = PriceRatifierV1.decodeRatifierData(
* PriceRatifierV1.encodeRatifierData({
* root: zeroHash,
* leafIndex: 0n,
* proof: [],
* allowedTaker: zeroAddress,
* }),
* );
* console.log(decoded.allowedTaker);
* ```
*/
function decodeRatifierData(data) {
const [root, leafIndex, proof, allowedTaker] = (0, viem_1.decodeAbiParameters)(priceRatifierV1DataAbi, data);
return (0, morpho_ts_1.deepFreeze)({ root, leafIndex, proof: [...proof], allowedTaker });
}
PriceRatifierV1.decodeRatifierData = decodeRatifierData;
/**
* Verifies that PriceRatifierV1 ratifier data proves one payload offer
* belongs to its root.
*
* This helper intentionally does not check the onchain
* `PriceRatifierV1.ratification` state. Consumers can query that value at
* their own block context after local proof verification.
*
* @param params.offer - Offer carried by the payload item.
* @param params.ratifierData - ABI-encoded PriceRatifierV1 ratifier data.
* @param params.taker - Optional taker to check against the leaf's allowed taker.
* @returns Decoded PriceRatifierV1 ratifier data after proof verification.
* @throws {InvalidTreeError} when the proof does not include `offer` in `root`.
* @throws {RatifierV1TakerNotAllowedError} when `taker` is not the leaf's allowed taker.
* @example
* ```ts
* import { PriceRatifierV1, type IOffer } from "@morpho-org/midnight-sdk";
* import type { Hex } from "viem";
*
* function check(offer: IOffer, ratifierData: Hex) {
* return PriceRatifierV1.verifyRatifierData({ offer, ratifierData });
* }
* ```
*/
function verifyRatifierData(params) {
const decoded = decodeRatifierData(params.ratifierData);
const leaf = hashLeaf({
offer: index_js_2.OfferUtils.toStruct({ offer: index_js_2.Offer.from(params.offer) }),
allowedTaker: decoded.allowedTaker,
});
if (!TreeUtils_js_1.TreeUtils.verifyLeafProof({
leaf,
root: decoded.root,
leafIndex: decoded.leafIndex,
proof: decoded.proof,
})) {
throw new errors_js_1.InvalidTreeError("Ratifier data proof does not include offer.");
}
(0, ratifierV1Internal_js_1.assertRatifierV1Taker)({
taker: params.taker,
allowedTaker: decoded.allowedTaker,
});
return decoded;
}
PriceRatifierV1.verifyRatifierData = verifyRatifierData;
/**
* Builds one ratifier-data value for a tree leaf.
*
* Use after root ratification when a caller needs data for one offer leaf.
* Use `ratify` to produce payload-ready items for the whole tree.
*
* @param params.tree - PriceRatifierV1 tree descriptor or raw leaf input.
* @param params.leafIndex - Leaf index to prove.
* @returns ABI-encoded PriceRatifierV1 data.
* @throws {InvalidOfferGroupError} when an explicitly grouped offer breaks `OfferUtils.validateOfferGroup` rules (members differ in maker, side, loan token, chain, Midnight contract or cap mode/value, an offer has an invalid cap, or a buy offer sets `receiverIfMakerIsSeller`). For raw leaf input only.
* @throws {InvalidTreeError} when the tree is invalid, the leaf index is outside the tree, or the tree contains multiple ratifiers.
* @throws {InvalidTreeHeightError} when the tree exceeds the supported height.
* @example
* ```ts
* import { PriceRatifierV1, type IOffer } from "@morpho-org/midnight-sdk";
*
* function build(offer: IOffer) {
* return PriceRatifierV1.ratifierData({
* tree: [{ offer }],
* leafIndex: 0n,
* });
* }
* ```
*/
function ratifierData(params) {
const tree = (0, ratifierV1Internal_js_1.resolveRatifierV1Tree)(params.tree, treeHelpers);
const proof = TreeUtils_js_1.TreeUtils.buildProof({ tree, leafIndex: params.leafIndex });
const entry = tree.entries[Number(proof.leafIndex)];
return encodeRatifierData({
root: proof.root,
leafIndex: proof.leafIndex,
proof: proof.proof,
allowedTaker: entry.allowedTaker,
});
}
PriceRatifierV1.ratifierData = ratifierData;
/**
* Returns payload-ready items after a PriceRatifierV1 root has been ratified.
*
* Use after the root ratification transaction has been submitted for every
* maker in the tree. The returned items can be passed directly to
* `Payload.encode`. All offers in the tree must use one ratifier address;
* build separate trees per ratifier.
*
* @param params.tree - PriceRatifierV1 tree descriptor or raw leaf input whose root has already been ratified onchain.
* @returns Items containing each non-padding offer and its ratifier data.
* @throws {InvalidOfferGroupError} when an explicitly grouped offer breaks `OfferUtils.validateOfferGroup` rules (members differ in maker, side, loan token, chain, Midnight contract or cap mode/value, an offer has an invalid cap, or a buy offer sets `receiverIfMakerIsSeller`). For raw leaf input only.
* @throws {InvalidTreeError} when the tree is invalid or contains multiple ratifiers.
* @throws {InvalidTreeHeightError} when the tree exceeds the supported height.
* @example
* ```ts
* import { PriceRatifierV1, type IOffer } from "@morpho-org/midnight-sdk";
*
* function build(offer: IOffer) {
* return PriceRatifierV1.ratify({
* tree: [{ offer }],
* });
* }
* ```
*/
function ratify(params) {
const tree = (0, ratifierV1Internal_js_1.resolveRatifierV1Tree)(params.tree, treeHelpers);
const proofs = TreeUtils_js_1.TreeUtils.buildProofs({
tree,
count: tree.offers.length,
});
return tree.offers.map((offer, leafIndex) => {
const entry = tree.entries[leafIndex];
const proof = proofs[leafIndex];
return {
offer,
ratifierData: encodeRatifierData({
root: proof.root,
leafIndex: proof.leafIndex,
proof: proof.proof,
allowedTaker: entry.allowedTaker,
}),
};
});
}
PriceRatifierV1.ratify = ratify;
/**
* Encodes a `setIsRootRatified` call to a PriceRatifierV1 contract.
*
* Onchain, the caller must be the maker or an address authorized by the
* maker on the Midnight instance. The returned descriptor is neutral and
* never signs or submits anything.
*
* @param params.ratifier - PriceRatifierV1 contract address.
* @param params.maker - Maker whose ratification entry is updated.
* @param params.root - Merkle root to ratify or unratify.
* @param params.isRatified - New ratification flag for the root.
* @returns Neutral call descriptor.
* @throws {InvalidRatifierV1AddressError} when the ratifier address is the zero address.
* @example
* ```ts
* import { PriceRatifierV1 } from "@morpho-org/midnight-sdk";
* import { zeroAddress, zeroHash } from "viem";
*
* const call = PriceRatifierV1.encodeSetIsRootRatified({
* ratifier: "0x0000000000000000000000000000000000000001",
* maker: zeroAddress,
* root: zeroHash,
* isRatified: true,
* });
* console.log(call.to);
* ```
*/
function encodeSetIsRootRatified(params) {
(0, ratifierV1Internal_js_1.assertRatifierV1Address)(params.ratifier);
return (0, morpho_ts_1.deepFreeze)({
to: params.ratifier,
data: (0, viem_1.encodeFunctionData)({
abi: abis_js_1.priceRatifierV1Abi,
functionName: "setIsRootRatified",
args: [params.maker, params.root, params.isRatified],
}),
});
}
PriceRatifierV1.encodeSetIsRootRatified = encodeSetIsRootRatified;
})(PriceRatifierV1 || (exports.PriceRatifierV1Utils = exports.PriceRatifierV1 = PriceRatifierV1 = {}));