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.

207 lines (206 loc) • 9.42 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.assignRatifierV1Groups = assignRatifierV1Groups; exports.buildRatifierV1Descriptor = buildRatifierV1Descriptor; exports.resolveRatifierV1Tree = resolveRatifierV1Tree; exports.assertRatifierV1Address = assertRatifierV1Address; exports.assertRatifierV1Taker = assertRatifierV1Taker; const viem_1 = require("viem"); const constants_js_1 = require("../constants.js"); const errors_js_1 = require("../errors.js"); const index_js_1 = require("../offers/index.js"); const GroupUtils_js_1 = require("./GroupUtils.js"); const offerStructInternal_js_1 = require("./offerStructInternal.js"); const TreeUtils_js_1 = require("./TreeUtils.js"); const treeMathInternal_js_1 = require("./treeMathInternal.js"); /** @internal Resolves V1 leaf groups mirroring the router's group_identity content ids and validates explicit groups. */ function assignRatifierV1Groups(leaves, groupId) { const offers = leaves.map((leaf) => leaf.offer.hasExplicitGroup ? leaf.offer : index_js_1.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. index_js_1.OfferUtils.validateOfferGroup({ offers: bucketLeaves.map((leaf) => leaf.offer), }); if (GroupUtils_js_1.GroupUtils.hash(bucketLeaves.map((leaf) => leaf.offer)).toLowerCase() !== label) { continue; } const group = groupId(bucketLeaves); for (const index of indices) { offers[index] = index_js_1.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. index_js_1.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. */ function buildRatifierV1Descriptor(params) { const { entries, padding, hashLeaf, ratifierOf, label } = params; const first = entries[0]; if (first == null) { throw new errors_js_1.InvalidTreeError("Tree must not be empty."); } const ratifier = ratifierOf(first); for (const entry of entries.slice(1)) { const other = ratifierOf(entry); if (!(0, viem_1.isAddressEqual)(other, ratifier)) { throw new errors_js_1.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 errors_js_1.InvalidTreeError(`Duplicate leaf hash "${leafHash}" in tree.`); } seen.add(leafHash); } const paddingCount = (0, treeMathInternal_js_1.isPowerOfTwo)(entries.length) ? 0 : (0, treeMathInternal_js_1.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_js_1.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`. */ 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 errors_js_1.InvalidTreeError("Ratifier route does not match the tree route."); } if (!Number.isInteger(descriptor.height) || descriptor.height < 0 || descriptor.height > constants_js_1.MAX_TREE_HEIGHT) { throw new errors_js_1.InvalidTreeHeightError(descriptor.height); } if (descriptor.offers.length === 0) { throw new errors_js_1.InvalidTreeError("Tree must not be empty."); } const expectedLength = 2 ** descriptor.height; if (descriptor.entries.length !== expectedLength || descriptor.leaves.length !== expectedLength || expectedLength !== (0, treeMathInternal_js_1.nextPowerOfTwo)(descriptor.offers.length)) { throw new errors_js_1.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 (!(0, viem_1.isAddressEqual)(other, ratifier)) { throw new errors_js_1.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 errors_js_1.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 (index_js_1.OfferUtils.hashStruct(index_js_1.OfferUtils.toStruct({ offer: index_js_1.Offer.from(offer) })).toLowerCase() !== index_js_1.OfferUtils.hashStruct(entry.offer).toLowerCase()) { throw new errors_js_1.InvalidTreeError("Visible offers do not match the tree entries."); } const leafHash = computedLeaves[index].toLowerCase(); if (seen.has(leafHash)) { throw new errors_js_1.InvalidTreeError(`Duplicate leaf hash "${leafHash}" in tree.`); } seen.add(leafHash); } if (descriptor.entries .slice(descriptor.offers.length) .some((entry) => !isPadding(entry))) { throw new errors_js_1.InvalidTreeError("Tree padding contains entries hidden from the visible offer list."); } if (computedLeaves.some((leaf, index) => leaf.toLowerCase() !== descriptor.leaves[index].toLowerCase())) { throw new errors_js_1.InvalidTreeError("Tree leaves do not match its entries."); } if (TreeUtils_js_1.TreeUtils.buildRootFromLeaves(descriptor.leaves).root.toLowerCase() !== descriptor.root.toLowerCase()) { throw new errors_js_1.InvalidTreeError("Tree root does not match its leaves."); } return descriptor; } /** * @internal Asserts a V1 ratifier address is deployed (non-zero). */ function assertRatifierV1Address(ratifier) { if ((0, offerStructInternal_js_1.isZeroAddress)(ratifier)) { throw new errors_js_1.InvalidRatifierV1AddressError(ratifier); } } /** * @internal Asserts a take-side taker matches the leaf's allowed taker. */ function assertRatifierV1Taker(params) { const { taker, allowedTaker } = params; if (taker == null || (0, viem_1.isAddressEqual)(allowedTaker, viem_1.zeroAddress) || (0, viem_1.isAddressEqual)(taker, allowedTaker)) { return; } throw new errors_js_1.RatifierV1TakerNotAllowedError({ taker, allowedTaker }); }