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.

619 lines (618 loc) • 23.7 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Offer = void 0; const viem_1 = require("viem"); const index_js_1 = require("../market/index.js"); const OfferUtils_js_1 = require("./OfferUtils.js"); /** * Maker-side Midnight offer. * * Build new maker offers with {@link Offer.create}, then pass them to * `Group.create` for shared-consumption ladders or directly to `Tree.create` * for standalone offers. API/take-side code can convert a plain `IOffer` * into this class before ABI encoding. The class resolves the onchain `group` * field when accessed. Standalone offers derive their * content-addressed singleton group id from the offer's zero-group hash; * `Group.create` copies offers and overrides the group on those copies when * several offers share one consumption bucket. Offers hydrated from API or * decoded data may also carry a known group id. * * @example * ```ts * import { Offer } from "@morpho-org/midnight-sdk"; * * const offer = Offer.create({ * market: { * chainId: 8453, * midnight: "0x0000000000000000000000000000000000001000", * loanToken: "0x0000000000000000000000000000000000000001", * collateralParams: [ * { * token: "0x0000000000000000000000000000000000007000", * lltv: 770000000000000000n, * liquidationCursor: 250000000000000000n, * oracle: "0x0000000000000000000000000000000000008000", * }, * ], * maturity: 1n, * rcfThreshold: 0n, * enterGate: "0x0000000000000000000000000000000000000000", * liquidatorGate: "0x0000000000000000000000000000000000000000", * }, * buy: false, * maker: "0x0000000000000000000000000000000000000002", * start: 0n, * expiry: 2n, * tick: 100n, * callback: "0x0000000000000000000000000000000000000000", * callbackData: "0x", * receiverIfMakerIsSeller: "0x0000000000000000000000000000000000000002", * ratifier: "0x0000000000000000000000000000000000000003", * reduceOnly: false, * maxUnits: 100n, * maxAssets: 0n, * continuousFeeCap: 317097919n, * }); * console.log(offer.buy); * ``` */ class Offer { /** Market this offer trades. */ market; /** Whether the maker buys units. */ buy; /** Offer maker. */ maker; /** Start timestamp. */ start; /** Expiry timestamp. */ expiry; /** Midnight tick. */ tick; explicitGroup; /** * Whether the group id was supplied at construction rather than derived. * * V1 ratifier tree builders only substitute their scheme's * content-addressed singleton group when this is `false`; an explicit * group is always committed as-is. * * @internal */ hasExplicitGroup; /** Optional maker callback. */ callback; /** Callback payload. */ callbackData; /** Receiver used when maker is seller. */ receiverIfMakerIsSeller; /** Ratifier contract. */ ratifier; /** Whether the offer can only reduce maker exposure. */ reduceOnly; /** Maximum units; zero means max assets controls consumption. */ maxUnits; /** Maximum buyer or seller assets, depending on side. */ maxAssets; /** Maximum market continuous fee accepted by this offer. */ continuousFeeCap; constructor(offer) { this.market = "params" in offer.market ? index_js_1.Market.from(offer.market) : index_js_1.MarketParams.from(offer.market); this.buy = offer.buy; this.maker = offer.maker; this.start = BigInt(offer.start); this.expiry = BigInt(offer.expiry); this.tick = BigInt(offer.tick); this.hasExplicitGroup = offer instanceof Offer ? offer.hasExplicitGroup : offer.group !== undefined; this.callback = offer.callback; this.callbackData = offer.callbackData; this.receiverIfMakerIsSeller = offer.receiverIfMakerIsSeller; this.ratifier = offer.ratifier; this.reduceOnly = offer.reduceOnly; this.maxUnits = BigInt(offer.maxUnits); this.maxAssets = BigInt(offer.maxAssets); this.continuousFeeCap = BigInt(offer.continuousFeeCap); this.explicitGroup = this.hasExplicitGroup ? offer.group : undefined; } /** * Returns an offer instance from class or plain input. * * Use at boundaries that accept either maker-created `Offer` instances or * decoded `IOffer` objects from an API response. For brand-new maker input, * prefer {@link Offer.create} so deterministic parameters are validated first. * * @param offer - Offer class or plain input. * @returns Offer instance. * @example * ```ts * import { Offer } from "@morpho-org/midnight-sdk"; * import { zeroAddress } from "viem"; * * const offer = Offer.from({ * 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", * start: 0n, * expiry: 3_600n, * tick: 5_000n, * callback: zeroAddress, * callbackData: "0x", * receiverIfMakerIsSeller: zeroAddress, * ratifier: "0x0000000000000000000000000000000000004000", * reduceOnly: false, * maxUnits: 100n, * maxAssets: 0n, * continuousFeeCap: 317097919n, * }); * console.log(offer.buy); * ``` */ static from(offer) { return offer instanceof Offer ? offer : new Offer(offer); } /** * Consumption group id encoded into this offer. * * When no group id was provided, the value is derived on access by hashing * this offer with the protocol zero group id, then hashing that result as a * singleton group. This is equivalent to `GroupUtils.hash([offer])`, but is * computed directly to keep the offers layer from importing signature * helpers and creating a circular dependency. * * @returns Consumption group id. * @example * ```ts * import { Offer } from "@morpho-org/midnight-sdk"; * import { zeroAddress } from "viem"; * * const loanToken = "0x0000000000000000000000000000000000006000"; * const collateralToken = "0x0000000000000000000000000000000000007000"; * const oracle = "0x0000000000000000000000000000000000008000"; * const maker = "0x0000000000000000000000000000000000009000"; * const ratifier = "0x0000000000000000000000000000000000004000"; * * const offer = Offer.create({ * market: { * chainId: 8453, * midnight: "0x0000000000000000000000000000000000001000", * loanToken, * collateralParams: [ * { * token: collateralToken, * lltv: 770000000000000000n, * liquidationCursor: 250000000000000000n, * oracle, * }, * ], * maturity: 2_000n, * rcfThreshold: 0n, * enterGate: zeroAddress, * liquidatorGate: zeroAddress, * }, * buy: true, * maker, * tick: 5_000n, * expiry: 2_100n, * ratifier, * maxAssets: 100n, * }); * * const group = offer.group; * console.log(group); * ``` */ get group() { return this.explicitGroup ?? (0, viem_1.keccak256)(OfferUtils_js_1.OfferUtils.groupHash(this)); } /** * Canonical protocol offer hash for this offer. * * The hash includes {@link Offer.group} and is computed when accessed. * * @returns Offer hash. * @example * ```ts * import { Offer } from "@morpho-org/midnight-sdk"; * import { zeroAddress } from "viem"; * * const loanToken = "0x0000000000000000000000000000000000006000"; * const collateralToken = "0x0000000000000000000000000000000000007000"; * const oracle = "0x0000000000000000000000000000000000008000"; * const maker = "0x0000000000000000000000000000000000009000"; * const ratifier = "0x0000000000000000000000000000000000004000"; * * const offer = Offer.create({ * market: { * chainId: 8453, * midnight: "0x0000000000000000000000000000000000001000", * loanToken, * collateralParams: [ * { * token: collateralToken, * lltv: 770000000000000000n, * liquidationCursor: 250000000000000000n, * oracle, * }, * ], * maturity: 2_000n, * rcfThreshold: 0n, * enterGate: zeroAddress, * liquidatorGate: zeroAddress, * }, * buy: true, * maker, * tick: 5_000n, * expiry: 2_100n, * ratifier, * maxAssets: 100n, * }); * * const hash = offer.hash; * // hash satisfies Hash * ``` */ get hash() { return OfferUtils_js_1.OfferUtils.hash(this); } /** * Returns the on-chain offer identifier emitted by Midnight's `Take` event. * * This `keccak256(abi.encode(offer))` hash identifies offers on-chain and is * distinct from `hash`, the typehash-prefixed ratifier hash. * It matches a `Take` event only for the offer exactly as published. For * RateRatifierV1 and PriceRatifierV1, hash the offers in the descriptor's * `offers`: `buildDescriptor` replaces both the default group and a * `Group.create` group. * * @returns The on-chain offer hash. * @throws {viem.InvalidAddressError} when an address has an invalid mixed-case checksum. * @throws {viem.IntegerOutOfRangeError} when a uint field overflows its ABI size. * @example * ```ts * 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, * group: "0x1111111111111111111111111111111111111111111111111111111111111111", * expiry: 3_600n, * ratifier: "0x0000000000000000000000000000000000004000", * maxUnits: 100n, * }); * const offerHash = offer.onchainHash; * console.log(offerHash); * ``` */ get onchainHash() { return OfferUtils_js_1.OfferUtils.onchainHash(this); } /** * WAD zero-coupon price at this offer's tick. * * @returns WAD price rounded to the protocol price quantum. * @throws {NegativeValueError} when `tick` is negative. * @throws {TickOutOfRangeError} when `tick` exceeds `MAX_TICK`. * @example * ```ts * import { Offer } from "@morpho-org/midnight-sdk"; * * const offer = Offer.create({ * market: { * loanToken: "0x0000000000000000000000000000000000006000", * collateralParams: [ * { * token: "0x0000000000000000000000000000000000007000", * lltv: 770000000000000000n, * liquidationCursor: 250000000000000000n, * oracle: "0x0000000000000000000000000000000000008000", * }, * ], * maturity: 54_000n, * rcfThreshold: 0n, * enterGate: "0x0000000000000000000000000000000000000000", * liquidatorGate: "0x0000000000000000000000000000000000000000", * }, * buy: true, * maker: "0x0000000000000000000000000000000000009000", * tick: 5_000n, * expiry: 3_600n, * ratifier: "0x0000000000000000000000000000000000004000", * maxUnits: 100n, * }); * console.log(offer.price); * ``` */ get price() { return OfferUtils_js_1.OfferUtils.getPrice(this); } /** * Converts this offer's tick into a WAD per-second simple rate at a timestamp. * * @param timestamp - Timestamp at which the rate is calculated. * @returns WAD per-second simple rate rounded up. * @throws {NegativeValueError} when market maturity, `timestamp`, or `tick` is negative. * @throws {TickOutOfRangeError} when `tick` exceeds `MAX_TICK`. * @throws {DivisionByZeroError} when the tick price is zero or `timestamp` is at or after maturity. * @example * ```ts * import { Offer } from "@morpho-org/midnight-sdk"; * * const offer = Offer.create({ * market: { * loanToken: "0x0000000000000000000000000000000000006000", * collateralParams: [ * { * token: "0x0000000000000000000000000000000000007000", * lltv: 770000000000000000n, * liquidationCursor: 250000000000000000n, * oracle: "0x0000000000000000000000000000000000008000", * }, * ], * maturity: 54_000n, * rcfThreshold: 0n, * enterGate: "0x0000000000000000000000000000000000000000", * liquidatorGate: "0x0000000000000000000000000000000000000000", * }, * buy: true, * maker: "0x0000000000000000000000000000000000009000", * tick: 5_000n, * expiry: 3_600n, * ratifier: "0x0000000000000000000000000000000000004000", * maxUnits: 100n, * }); * const rate = offer.getRate(1_000n); * console.log(rate); * ``` */ getRate(timestamp) { return OfferUtils_js_1.OfferUtils.getRate({ offer: this, timestamp }); } /** * Converts this offer's tick into a WAD simple annual percentage rate at a timestamp. * * @param timestamp - Timestamp at which the APR is calculated. * @returns WAD simple APR rounded up. * @throws {NegativeValueError} when market maturity, `timestamp`, or `tick` is negative. * @throws {TickOutOfRangeError} when `tick` exceeds `MAX_TICK`. * @throws {DivisionByZeroError} when the tick price is zero or `timestamp` is at or after maturity. * @example * ```ts * import { Offer } from "@morpho-org/midnight-sdk"; * * const offer = Offer.create({ * market: { * loanToken: "0x0000000000000000000000000000000000006000", * collateralParams: [ * { * token: "0x0000000000000000000000000000000000007000", * lltv: 770000000000000000n, * liquidationCursor: 250000000000000000n, * oracle: "0x0000000000000000000000000000000000008000", * }, * ], * maturity: 54_000n, * rcfThreshold: 0n, * enterGate: "0x0000000000000000000000000000000000000000", * liquidatorGate: "0x0000000000000000000000000000000000000000", * }, * buy: true, * maker: "0x0000000000000000000000000000000000009000", * tick: 5_000n, * expiry: 3_600n, * ratifier: "0x0000000000000000000000000000000000004000", * maxUnits: 100n, * }); * const apr = offer.getApr(1_000n); * console.log(apr); * ``` */ getApr(timestamp) { return OfferUtils_js_1.OfferUtils.getApr({ offer: this, timestamp }); } /** * Returns remaining units accepted by this offer's cap at a timestamp. * * The offer must carry a hydrated {@link Market} so the current market * continuous fee and settlement-fee buckets are available locally. Fetch the * current `consumed(maker, group)` value separately and pass it as input. * * Returns `0n` when Midnight `take` rejects this offer regardless of the * amount; see {@link OfferUtils.getConsumableUnits} for the mirrored checks. * * @param params.consumed - Amount already consumed from this offer's group. * @param params.timestamp - Timestamp used to compute the market time to maturity. * @returns Remaining consumable units accepted by Midnight `take`. * @throws {InvalidOfferParameterError} when this offer does not carry hydrated market state or has invalid caps. * @throws {NegativeValueError} when `consumed`, `timestamp`, offer limits, or delegated math inputs are negative. * @throws {TickOutOfRangeError} when `tick` exceeds `MAX_TICK`. * @throws {SettlementFeeExceedsPriceError} when settlement fee exceeds a buy-offer price. * @example * ```ts * import { Offer } from "@morpho-org/midnight-sdk"; * * const offer = Offer.from({ * market: { * params: { * chainId: 8453, * midnight: "0x0000000000000000000000000000000000001000", * loanToken: "0x0000000000000000000000000000000000006000", * collateralParams: [ * { * token: "0x0000000000000000000000000000000000007000", * lltv: 770000000000000000n, * liquidationCursor: 250000000000000000n, * oracle: "0x0000000000000000000000000000000000008000", * }, * ], * maturity: 54_000n, * rcfThreshold: 0n, * enterGate: "0x0000000000000000000000000000000000000000", * liquidatorGate: "0x0000000000000000000000000000000000000000", * }, * totalUnits: 1_000n, * lossFactor: 0n, * withdrawable: 500n, * continuousFeeCredit: 0n, * settlementFeeCbps: [1, 2, 3, 4, 5, 6, 7], * continuousFee: 10, * tickSpacing: 4, * }, * buy: true, * maker: "0x0000000000000000000000000000000000009000", * start: 0n, * expiry: 3_600n, * tick: 5_000n, * callback: "0x0000000000000000000000000000000000000000", * callbackData: "0x", * receiverIfMakerIsSeller: "0x0000000000000000000000000000000000000000", * ratifier: "0x0000000000000000000000000000000000004000", * reduceOnly: false, * maxUnits: 100n, * maxAssets: 0n, * continuousFeeCap: 317097919n, * }); * const consumed = await readContract(client, { * address: "0x0000000000000000000000000000000000001000", * abi: midnightAbi, * functionName: "consumed", * args: [offer.maker, offer.group], * }); * const units = offer.getConsumableUnits({ consumed, timestamp: 1_000n }); * console.log(units); * ``` */ getConsumableUnits(params) { return OfferUtils_js_1.OfferUtils.getConsumableUnits({ offer: this, ...params }); } /** * Creates a validated maker-side Midnight offer. * * This is the first step of the make-side flow. After creation, pass related * offers to `Group.create` when they share consumption, or pass standalone * offers directly to `Tree.create`. Omit `group` for brand-new maker offers; * provide it when hydrating an offer that already has a protocol group, such * as an offer decoded from the API. * * @param params.market - Market params or hydrated market this offer trades. * @param params.buy - Whether the maker buys loan assets. * @param params.maker - Maker address. * @param params.tick - Offer tick. * @param params.group - Optional consumption group id for already-grouped offers. * @param params.tickSpacing - Optional market tick spacing; defaults to `DEFAULT_TICK_SPACING`. * @param params.maxUnits - Optional unit cap; defaults to zero. * @param params.maxAssets - Optional buyer or seller asset cap; defaults to zero. * @param params.continuousFeeCap - Optional maximum market continuous fee accepted by this offer; defaults to `0n` (fail-closed: no market continuous fee accepted unless set explicitly). * @param params.start - Optional offer start timestamp; defaults to zero. * @param params.expiry - Offer expiry timestamp. * @param params.callback - Optional callback address; defaults to the zero address. * @param params.callbackData - Optional callback payload; defaults to `0x`. * @param params.receiverIfMakerIsSeller - Non-zero sell proceeds receiver (defaults to the maker); must be omitted or zero on buys. * @param params.ratifier - Ratifier contract address. * @param params.reduceOnly - Optional flag restricting the offer to exposure-reducing execution. * @returns Offer instance. * @throws {InvalidOfferParameterError} when the offer cannot satisfy protocol parameter rules. * @example * ```ts * import { Offer } from "@morpho-org/midnight-sdk"; * import { zeroAddress } from "viem"; * * const loanToken = "0x0000000000000000000000000000000000006000"; * const collateralToken = "0x0000000000000000000000000000000000007000"; * const oracle = "0x0000000000000000000000000000000000008000"; * const maker = "0x0000000000000000000000000000000000009000"; * const ratifier = "0x0000000000000000000000000000000000004000"; * const apiGroup = * "0x1111111111111111111111111111111111111111111111111111111111111111"; * * const offer = Offer.create({ * market: { * chainId: 8453, * midnight: "0x0000000000000000000000000000000000001000", * loanToken, * collateralParams: [ * { * token: collateralToken, * lltv: 770000000000000000n, * liquidationCursor: 250000000000000000n, * oracle, * }, * ], * maturity: 2_000n, * rcfThreshold: 0n, * enterGate: zeroAddress, * liquidatorGate: zeroAddress, * }, * buy: true, * maker, * tick: 5_000n, * group: apiGroup, * expiry: 2_100n, * ratifier, * maxAssets: 100n, * }); * // offer satisfies Offer * ``` */ static create(params) { const validated = OfferUtils_js_1.OfferUtils.validateOfferParams(params); return new Offer({ market: params.market, buy: params.buy, maker: params.maker, start: validated.start, expiry: validated.expiry, tick: validated.tick, group: params.group, callback: params.callback ?? viem_1.zeroAddress, callbackData: params.callbackData ?? "0x", receiverIfMakerIsSeller: validated.receiverIfMakerIsSeller, ratifier: params.ratifier, reduceOnly: params.reduceOnly ?? false, maxUnits: validated.maxUnits, maxAssets: validated.maxAssets, continuousFeeCap: validated.continuousFeeCap, }); } } exports.Offer = Offer;