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.

200 lines (199 loc) • 8.69 kB
import { isAddressEqual, zeroAddress } from "viem"; import { MAX_TREE_HEIGHT } from "../constants.js"; import { InvalidRatifierV1AddressError, InvalidTreeError, InvalidTreeHeightError, RatifierV1TakerNotAllowedError, } from "../errors.js"; import { Offer, OfferUtils, } from "../offers/index.js"; import { GroupUtils } from "./GroupUtils.js"; import { isZeroAddress } from "./offerStructInternal.js"; import { TreeUtils } from "./TreeUtils.js"; import { isPowerOfTwo, nextPowerOfTwo } from "./treeMathInternal.js"; /** @internal Resolves V1 leaf groups mirroring the router's group_identity content ids and validates explicit groups. */ export function assignRatifierV1Groups(leaves, groupId) { const offers = leaves.map((leaf) => leaf.offer.hasExplicitGroup ? leaf.offer : Offer.from({ ...leaf.offer, group: groupId([leaf]) })); const buckets = new Map(); for (const [index, leaf] of leaves.entries()) { if (!leaf.offer.hasExplicitGroup) continue; const label = leaf.offer.group.toLowerCase(); const bucket = buckets.get(label); if (bucket) bucket.push(index); else buckets.set(label, [index]); } for (const [label, indices] of buckets) { const bucketLeaves = indices.map((index) => leaves[index]); // Called only to throw on incompatible group members. OfferUtils.validateOfferGroup({ offers: bucketLeaves.map((leaf) => leaf.offer), }); if (GroupUtils.hash(bucketLeaves.map((leaf) => leaf.offer)).toLowerCase() !== label) { continue; } const group = groupId(bucketLeaves); for (const index of indices) { offers[index] = Offer.from({ ...leaves[index].offer, group }); } } const finalGroups = new Map(); for (const [index, offer] of offers.entries()) { const label = offer.group.toLowerCase(); const hasExplicitGroup = leaves[index].offer.hasExplicitGroup; const bucket = finalGroups.get(label); if (bucket) { bucket.offers.push(offer); bucket.hasExplicitGroup ||= hasExplicitGroup; } else { finalGroups.set(label, { offers: [offer], hasExplicitGroup }); } } for (const { offers: groupOffers, hasExplicitGroup, } of finalGroups.values()) { if (!hasExplicitGroup) continue; // Catches explicit groups that collide with a defaulted or re-derived id. OfferUtils.validateOfferGroup({ offers: groupOffers }); } return offers; } /** * @internal Pads, hash-checks, and roots a V1 ratifier leaf list. * * All non-padding entries must share one ratifier address and produce distinct * leaf hashes. Non-power-of-two lists are padded with `padding` at the highest * leaf indices, matching `TreeUtils.buildDescriptor` semantics. */ export function buildRatifierV1Descriptor(params) { const { entries, padding, hashLeaf, ratifierOf, label } = params; const first = entries[0]; if (first == null) { throw new InvalidTreeError("Tree must not be empty."); } const ratifier = ratifierOf(first); for (const entry of entries.slice(1)) { const other = ratifierOf(entry); if (!isAddressEqual(other, ratifier)) { throw new InvalidTreeError(`All offers in a ${label} tree must use one ratifier; expected "${ratifier}", got "${other}". Build separate trees per ratifier.`); } } const entryHashes = entries.map(hashLeaf); const seen = new Set(); for (const leafHash of entryHashes) { if (seen.has(leafHash)) { throw new InvalidTreeError(`Duplicate leaf hash "${leafHash}" in tree.`); } seen.add(leafHash); } const paddingCount = isPowerOfTwo(entries.length) ? 0 : nextPowerOfTwo(entries.length) - entries.length; const paddedEntries = [ ...entries, ...Array.from({ length: paddingCount }, () => padding), ]; const paddingHash = paddingCount === 0 ? undefined : hashLeaf(padding); const leaves = [ ...entryHashes, ...Array.from({ length: paddingCount }, () => paddingHash), ]; const { root, height } = TreeUtils.buildRootFromLeaves(leaves); return { entries: paddedEntries, leaves, root, height }; } /** * @internal Resolves a V1 ratifier tree input into a materialized descriptor. * * Caller-provided descriptors are fully re-validated: height, lengths, leaf * hashes, visible-offer correspondence, padding placement, and the Merkle * root must all agree, mirroring `Ratifier.normalizeTree`. An optional * `validateEntry` hook runs ratifier-specific checks on each visible * (non-padding) entry before leaf hashes are recomputed, so descriptor input * is held to the same bounds as `buildDescriptor`. */ export function resolveRatifierV1Tree(tree, helpers) { const { buildDescriptor, hashLeaf, isPadding, ratifierOf, label } = helpers; if (Array.isArray(tree)) return buildDescriptor(tree); const descriptor = tree; if ("type" in descriptor && descriptor.type != null && descriptor.type !== helpers.type) { throw new InvalidTreeError("Ratifier route does not match the tree route."); } if (!Number.isInteger(descriptor.height) || descriptor.height < 0 || descriptor.height > MAX_TREE_HEIGHT) { throw new InvalidTreeHeightError(descriptor.height); } if (descriptor.offers.length === 0) { throw new InvalidTreeError("Tree must not be empty."); } const expectedLength = 2 ** descriptor.height; if (descriptor.entries.length !== expectedLength || descriptor.leaves.length !== expectedLength || expectedLength !== nextPowerOfTwo(descriptor.offers.length)) { throw new InvalidTreeError("Tree entries, leaves, offers, and height describe different trees."); } const visibleEntries = descriptor.entries.slice(0, descriptor.offers.length); const ratifier = ratifierOf(visibleEntries[0]); for (const entry of visibleEntries.slice(1)) { const other = ratifierOf(entry); if (!isAddressEqual(other, ratifier)) { throw new InvalidTreeError(`All offers in a ${label} tree must use one ratifier; expected "${ratifier}", got "${other}". Build separate trees per ratifier.`); } } // Ratifier-specific entry gates run before any leaf hashing. for (const entry of visibleEntries) { if (isPadding(entry)) { throw new InvalidTreeError("Visible offers must not contain tree padding."); } helpers.validateEntry?.(entry); } const computedLeaves = descriptor.entries.map((entry) => hashLeaf(entry)); const seen = new Set(); for (const [index, offer] of descriptor.offers.entries()) { const entry = descriptor.entries[index]; if (OfferUtils.hashStruct(OfferUtils.toStruct({ offer: Offer.from(offer) })).toLowerCase() !== OfferUtils.hashStruct(entry.offer).toLowerCase()) { throw new InvalidTreeError("Visible offers do not match the tree entries."); } const leafHash = computedLeaves[index].toLowerCase(); if (seen.has(leafHash)) { throw new InvalidTreeError(`Duplicate leaf hash "${leafHash}" in tree.`); } seen.add(leafHash); } if (descriptor.entries .slice(descriptor.offers.length) .some((entry) => !isPadding(entry))) { throw new InvalidTreeError("Tree padding contains entries hidden from the visible offer list."); } if (computedLeaves.some((leaf, index) => leaf.toLowerCase() !== descriptor.leaves[index].toLowerCase())) { throw new InvalidTreeError("Tree leaves do not match its entries."); } if (TreeUtils.buildRootFromLeaves(descriptor.leaves).root.toLowerCase() !== descriptor.root.toLowerCase()) { throw new InvalidTreeError("Tree root does not match its leaves."); } return descriptor; } /** * @internal Asserts a V1 ratifier address is deployed (non-zero). */ export function assertRatifierV1Address(ratifier) { if (isZeroAddress(ratifier)) { throw new InvalidRatifierV1AddressError(ratifier); } } /** * @internal Asserts a take-side taker matches the leaf's allowed taker. */ export function assertRatifierV1Taker(params) { const { taker, allowedTaker } = params; if (taker == null || isAddressEqual(allowedTaker, zeroAddress) || isAddressEqual(taker, allowedTaker)) { return; } throw new RatifierV1TakerNotAllowedError({ taker, allowedTaker }); }