@morpho-org/midnight-sdk 1.7.0-next.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +61 -61
  2. package/lib/cjs/abis.d.ts +794 -0
  3. package/lib/cjs/abis.js +502 -1
  4. package/lib/cjs/api/version.generated.d.ts +1 -1
  5. package/lib/cjs/api/version.generated.js +2 -2
  6. package/lib/cjs/constants.d.ts +34 -0
  7. package/lib/cjs/constants.js +35 -1
  8. package/lib/cjs/errors.d.ts +107 -0
  9. package/lib/cjs/errors.js +139 -1
  10. package/lib/cjs/fetch/Ratifier.d.ts +4 -3
  11. package/lib/cjs/fetch/Ratifier.js +5 -4
  12. package/lib/cjs/index.d.ts +7 -0
  13. package/lib/cjs/index.js +16 -1
  14. package/lib/cjs/offers/Offer.d.ts +10 -0
  15. package/lib/cjs/offers/Offer.js +15 -1
  16. package/lib/cjs/offers/OfferUtils.d.ts +3 -0
  17. package/lib/cjs/offers/OfferUtils.js +3 -0
  18. package/lib/cjs/signatures/{EcrecoverRatifierUtils.d.ts → EcrecoverRatifier.d.ts} +118 -2
  19. package/lib/cjs/signatures/{EcrecoverRatifierUtils.js → EcrecoverRatifier.js} +146 -9
  20. package/lib/cjs/signatures/GroupUtils.d.ts +55 -2
  21. package/lib/cjs/signatures/GroupUtils.js +64 -5
  22. package/lib/cjs/signatures/Payload.d.ts +3 -3
  23. package/lib/cjs/signatures/PriceRatifierV1.d.ts +472 -0
  24. package/lib/cjs/signatures/PriceRatifierV1.js +521 -0
  25. package/lib/cjs/signatures/RateRatifierV1.d.ts +581 -0
  26. package/lib/cjs/signatures/RateRatifierV1.js +696 -0
  27. package/lib/{esm/signatures/RatifierUtils.d.ts → cjs/signatures/Ratifier.d.ts} +14 -12
  28. package/lib/cjs/signatures/{RatifierUtils.js → Ratifier.js} +29 -29
  29. package/lib/cjs/signatures/{SetterRatifierUtils.d.ts → SetterRatifier.d.ts} +50 -3
  30. package/lib/cjs/signatures/{SetterRatifierUtils.js → SetterRatifier.js} +65 -7
  31. package/lib/cjs/signatures/Tree.d.ts +94 -17
  32. package/lib/cjs/signatures/Tree.js +146 -111
  33. package/lib/cjs/signatures/TreeUtils.d.ts +191 -21
  34. package/lib/cjs/signatures/TreeUtils.js +320 -134
  35. package/lib/cjs/signatures/index.d.ts +7 -3
  36. package/lib/cjs/signatures/index.js +5 -3
  37. package/lib/cjs/signatures/ratifierRequests.d.ts +55 -0
  38. package/lib/cjs/signatures/ratifierRequests.js +2 -0
  39. package/lib/cjs/signatures/ratifierV1Internal.d.ts +57 -0
  40. package/lib/cjs/signatures/ratifierV1Internal.js +183 -0
  41. package/lib/cjs/signatures/standardRatifierInternal.d.ts +4 -0
  42. package/lib/cjs/signatures/standardRatifierInternal.js +12 -0
  43. package/lib/cjs/signatures/treeMathInternal.d.ts +4 -0
  44. package/lib/cjs/signatures/treeMathInternal.js +12 -0
  45. package/lib/cjs/signatures/treeTypes.d.ts +109 -0
  46. package/lib/cjs/signatures/treeTypes.js +2 -0
  47. package/lib/esm/abis.d.ts +794 -0
  48. package/lib/esm/abis.js +501 -0
  49. package/lib/esm/api/version.generated.d.ts +1 -1
  50. package/lib/esm/api/version.generated.js +2 -2
  51. package/lib/esm/constants.d.ts +34 -0
  52. package/lib/esm/constants.js +34 -0
  53. package/lib/esm/errors.d.ts +107 -0
  54. package/lib/esm/errors.js +132 -0
  55. package/lib/esm/fetch/Ratifier.d.ts +4 -3
  56. package/lib/esm/fetch/Ratifier.js +5 -4
  57. package/lib/esm/index.d.ts +7 -0
  58. package/lib/esm/index.js +5 -0
  59. package/lib/esm/offers/Offer.d.ts +10 -0
  60. package/lib/esm/offers/Offer.js +15 -1
  61. package/lib/esm/offers/OfferUtils.d.ts +3 -0
  62. package/lib/esm/offers/OfferUtils.js +3 -0
  63. package/lib/esm/signatures/{EcrecoverRatifierUtils.d.ts → EcrecoverRatifier.d.ts} +118 -2
  64. package/lib/esm/signatures/{EcrecoverRatifierUtils.js → EcrecoverRatifier.js} +146 -9
  65. package/lib/esm/signatures/GroupUtils.d.ts +55 -2
  66. package/lib/esm/signatures/GroupUtils.js +64 -5
  67. package/lib/esm/signatures/Payload.d.ts +3 -3
  68. package/lib/esm/signatures/PriceRatifierV1.d.ts +472 -0
  69. package/lib/esm/signatures/PriceRatifierV1.js +520 -0
  70. package/lib/esm/signatures/RateRatifierV1.d.ts +581 -0
  71. package/lib/esm/signatures/RateRatifierV1.js +695 -0
  72. package/lib/{cjs/signatures/RatifierUtils.d.ts → esm/signatures/Ratifier.d.ts} +14 -12
  73. package/lib/esm/signatures/{RatifierUtils.js → Ratifier.js} +31 -29
  74. package/lib/esm/signatures/{SetterRatifierUtils.d.ts → SetterRatifier.d.ts} +50 -3
  75. package/lib/esm/signatures/{SetterRatifierUtils.js → SetterRatifier.js} +65 -7
  76. package/lib/esm/signatures/Tree.d.ts +94 -17
  77. package/lib/esm/signatures/Tree.js +147 -112
  78. package/lib/esm/signatures/TreeUtils.d.ts +191 -21
  79. package/lib/esm/signatures/TreeUtils.js +318 -132
  80. package/lib/esm/signatures/index.d.ts +7 -3
  81. package/lib/esm/signatures/index.js +5 -3
  82. package/lib/esm/signatures/ratifierRequests.d.ts +55 -0
  83. package/lib/esm/signatures/ratifierRequests.js +1 -0
  84. package/lib/esm/signatures/ratifierV1Internal.d.ts +57 -0
  85. package/lib/esm/signatures/ratifierV1Internal.js +176 -0
  86. package/lib/esm/signatures/standardRatifierInternal.d.ts +4 -0
  87. package/lib/esm/signatures/standardRatifierInternal.js +9 -0
  88. package/lib/esm/signatures/treeMathInternal.d.ts +4 -0
  89. package/lib/esm/signatures/treeMathInternal.js +8 -0
  90. package/lib/esm/signatures/treeTypes.d.ts +109 -0
  91. package/lib/esm/signatures/treeTypes.js +1 -0
  92. package/package.json +4 -4
@@ -0,0 +1,695 @@
1
+ import { deepFreeze, MathLib } from "@morpho-org/morpho-ts";
2
+ import { decodeAbiParameters, encodeAbiParameters, encodeFunctionData, keccak256, maxUint256, zeroAddress, zeroHash, } from "viem";
3
+ import { rateRatifierV1Abi } from "../abis.js";
4
+ import { RATE_RATIFIER_V1_OFFER_TYPEHASH } from "../constants.js";
5
+ import { InvalidRateRatifierV1RateError, InvalidRateRatifierV1TickError, InvalidRateRatifierV1TimeError, InvalidTreeError, RateRatifierV1BoundOverflowError, } from "../errors.js";
6
+ import { MarketUtils } from "../market/index.js";
7
+ import { TickLib } from "../math/index.js";
8
+ import { Offer, OfferUtils, } from "../offers/index.js";
9
+ import { GroupUtils } from "./GroupUtils.js";
10
+ import { EMPTY_OFFER_STRUCT, isEmptyOfferStruct, isZeroAddress, } from "./offerStructInternal.js";
11
+ import { assertRatifierV1Address, assertRatifierV1Taker, assignRatifierV1Groups, buildRatifierV1Descriptor, resolveRatifierV1Tree, } from "./ratifierV1Internal.js";
12
+ import { TreeUtils } from "./TreeUtils.js";
13
+ const rateRatifierV1DataAbi = [
14
+ { name: "root", type: "bytes32" },
15
+ { name: "leafIndex", type: "uint256" },
16
+ { name: "proof", type: "bytes32[]" },
17
+ { name: "rate", type: "uint256" },
18
+ { name: "allowedTaker", type: "address" },
19
+ ];
20
+ const rateRatifierV1LeafHashParams = [
21
+ { name: "typehash", type: "bytes32" },
22
+ { name: "marketHash", type: "bytes32" },
23
+ { name: "buy", type: "bool" },
24
+ { name: "maker", type: "address" },
25
+ { name: "start", type: "uint256" },
26
+ { name: "expiry", type: "uint256" },
27
+ { name: "rate", type: "uint256" },
28
+ { name: "allowedTaker", type: "address" },
29
+ { name: "group", type: "bytes32" },
30
+ { name: "callback", type: "address" },
31
+ { name: "callbackDataHash", type: "bytes32" },
32
+ { name: "receiverIfMakerIsSeller", type: "address" },
33
+ { name: "ratifier", type: "address" },
34
+ { name: "reduceOnly", type: "bool" },
35
+ { name: "maxUnits", type: "uint128" },
36
+ { name: "maxAssets", type: "uint128" },
37
+ { name: "continuousFeeCap", type: "uint256" },
38
+ ];
39
+ const isPaddingEntry = (entry) => isEmptyOfferStruct(entry.offer) &&
40
+ entry.rate === 0n &&
41
+ isZeroAddress(entry.allowedTaker);
42
+ /**
43
+ * RateRatifierV1-specific pure utilities.
44
+ *
45
+ * Use this route when makers ratify a Merkle root of rate-bounded offers
46
+ * onchain. The make-side sequence is: create offers with the RateRatifierV1
47
+ * address, build the tree descriptor, ratify the root onchain (directly or
48
+ * through `setIsRootRatified`), then call `ratify` and pass the returned items
49
+ * to `Payload.encode`.
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * import { RateRatifierV1 } from "@morpho-org/midnight-sdk";
54
+ *
55
+ * console.log(typeof RateRatifierV1.ratify);
56
+ * ```
57
+ */
58
+ export var RateRatifierV1;
59
+ (function (RateRatifierV1) {
60
+ /**
61
+ * Lowest nominal `offer.tick` the router accepts for a RateRatifierV1 leaf
62
+ * (tick 3372, price >= 0.5 WAD).
63
+ *
64
+ * The router prices RateRatifierV1 offers from `rate`, but its gatekeeper
65
+ * still validates the committed `offer.tick`; ticks below this are rejected
66
+ * as `min_tick`.
67
+ *
68
+ * @example
69
+ * ```ts
70
+ * import { RateRatifierV1 } from "@morpho-org/midnight-sdk";
71
+ *
72
+ * console.log(RateRatifierV1.MIN_TICK); // 3372n
73
+ * ```
74
+ */
75
+ RateRatifierV1.MIN_TICK = TickLib.priceToTick(MathLib.WAD / 2n, 1n);
76
+ /**
77
+ * Computes the RateRatifierV1 EIP-712 leaf hash for one leaf struct.
78
+ *
79
+ * This is the SDK port of `HashLib.hashRateRatifierV1Offer`: the offer's
80
+ * `tick` field is replaced by `rate`, and `allowedTaker` is appended.
81
+ *
82
+ * @param leaf - ABI-compatible leaf to hash.
83
+ * @returns Leaf hash used in the ratified Merkle tree.
84
+ * @example
85
+ * ```ts
86
+ * import { RateRatifierV1, type OfferStruct } from "@morpho-org/midnight-sdk";
87
+ * import { zeroAddress } from "viem";
88
+ *
89
+ * function hash(offer: OfferStruct) {
90
+ * return RateRatifierV1.hashLeaf({
91
+ * offer,
92
+ * rate: 0n,
93
+ * allowedTaker: zeroAddress,
94
+ * });
95
+ * }
96
+ * ```
97
+ */
98
+ function hashLeaf(leaf) {
99
+ const { offer } = leaf;
100
+ return keccak256(encodeAbiParameters(rateRatifierV1LeafHashParams, [
101
+ RATE_RATIFIER_V1_OFFER_TYPEHASH,
102
+ MarketUtils.hash(offer.market),
103
+ offer.buy,
104
+ offer.maker,
105
+ offer.start,
106
+ offer.expiry,
107
+ leaf.rate,
108
+ leaf.allowedTaker,
109
+ offer.group,
110
+ offer.callback,
111
+ keccak256(offer.callbackData),
112
+ offer.receiverIfMakerIsSeller,
113
+ offer.ratifier,
114
+ offer.reduceOnly,
115
+ offer.maxUnits,
116
+ offer.maxAssets,
117
+ offer.continuousFeeCap,
118
+ ]));
119
+ }
120
+ RateRatifierV1.hashLeaf = hashLeaf;
121
+ /**
122
+ * Zero-group member hash of one leaf, as consumed by `GroupUtils.hashMembers`.
123
+ *
124
+ * This is what the router recomputes for its `group_identity` check: the
125
+ * RateRatifierV1 leaf hash with `group = 0`, so the id commits to `rate`
126
+ * and `allowedTaker` rather than to `tick`.
127
+ *
128
+ * @param leaf - Rate-bounded offer leaf.
129
+ * @returns Zero-group RateRatifierV1 leaf hash.
130
+ * @throws {InvalidRateRatifierV1RateError} when `leaf.rate` is negative.
131
+ * @example
132
+ * ```ts
133
+ * import { Offer, RateRatifierV1 } from "@morpho-org/midnight-sdk";
134
+ * import { zeroAddress } from "viem";
135
+ *
136
+ * const offer = Offer.create({
137
+ * market: {
138
+ * chainId: 8453,
139
+ * midnight: "0x0000000000000000000000000000000000001000",
140
+ * loanToken: "0x0000000000000000000000000000000000006000",
141
+ * collateralParams: [
142
+ * {
143
+ * token: "0x0000000000000000000000000000000000007000",
144
+ * lltv: 770000000000000000n,
145
+ * liquidationCursor: 250000000000000000n,
146
+ * oracle: "0x0000000000000000000000000000000000008000",
147
+ * },
148
+ * ],
149
+ * maturity: 54_000n,
150
+ * rcfThreshold: 0n,
151
+ * enterGate: zeroAddress,
152
+ * liquidatorGate: zeroAddress,
153
+ * },
154
+ * buy: true,
155
+ * maker: "0x0000000000000000000000000000000000009000",
156
+ * tick: 5_000n,
157
+ * expiry: 3_600n,
158
+ * ratifier: "0x000000000000000000000000000000000000a111",
159
+ * maxUnits: 100n,
160
+ * });
161
+ *
162
+ * console.log(RateRatifierV1.memberHash({ offer, rate: 0n }));
163
+ * ```
164
+ */
165
+ function memberHash(leaf) {
166
+ const rate = BigInt(leaf.rate);
167
+ if (rate < 0n)
168
+ throw new InvalidRateRatifierV1RateError(rate);
169
+ return hashLeaf({
170
+ offer: OfferUtils.toStruct({ offer: leaf.offer, group: zeroHash }),
171
+ rate,
172
+ allowedTaker: leaf.allowedTaker ?? zeroAddress,
173
+ });
174
+ }
175
+ RateRatifierV1.memberHash = memberHash;
176
+ /**
177
+ * Content-addressed consumption group id for RateRatifierV1 leaves.
178
+ *
179
+ * Mirrors `GroupUtils.hash` with the RateRatifierV1 {@link memberHash}, so
180
+ * it matches the router-derived group. Use it to share one group across
181
+ * several leaves; single leaves get this id by default in
182
+ * {@link buildDescriptor}. Leaves sharing a group must satisfy the same
183
+ * constraints as `Group.create` (one maker, side, and cap mode/value); this
184
+ * helper only derives the id and does not check them.
185
+ *
186
+ * @param leaves - Leaves sharing one consumption group.
187
+ * @returns Content-addressed group id.
188
+ * @throws {InvalidOfferGroupError} when `leaves` is empty.
189
+ * @throws {InvalidRateRatifierV1RateError} when a leaf rate is negative.
190
+ * @example
191
+ * ```ts
192
+ * import { Offer, RateRatifierV1 } from "@morpho-org/midnight-sdk";
193
+ * import { zeroAddress } from "viem";
194
+ *
195
+ * const offer = Offer.create({
196
+ * market: {
197
+ * chainId: 8453,
198
+ * midnight: "0x0000000000000000000000000000000000001000",
199
+ * loanToken: "0x0000000000000000000000000000000000006000",
200
+ * collateralParams: [
201
+ * {
202
+ * token: "0x0000000000000000000000000000000000007000",
203
+ * lltv: 770000000000000000n,
204
+ * liquidationCursor: 250000000000000000n,
205
+ * oracle: "0x0000000000000000000000000000000000008000",
206
+ * },
207
+ * ],
208
+ * maturity: 54_000n,
209
+ * rcfThreshold: 0n,
210
+ * enterGate: zeroAddress,
211
+ * liquidatorGate: zeroAddress,
212
+ * },
213
+ * buy: true,
214
+ * maker: "0x0000000000000000000000000000000000009000",
215
+ * tick: 5_000n,
216
+ * expiry: 3_600n,
217
+ * ratifier: "0x000000000000000000000000000000000000a111",
218
+ * maxUnits: 100n,
219
+ * });
220
+ * const leaves = [
221
+ * { offer, rate: 50_000_000_000_000_000n },
222
+ * { offer: Offer.from({ ...offer, tick: 5_004n }), rate: 60_000_000_000_000_000n },
223
+ * ];
224
+ *
225
+ * const group = RateRatifierV1.groupId(leaves);
226
+ * const grouped = leaves.map((leaf) => ({
227
+ * ...leaf,
228
+ * offer: Offer.from({ ...leaf.offer, group }),
229
+ * }));
230
+ * ```
231
+ */
232
+ function groupId(leaves) {
233
+ return GroupUtils.hashMembers(Array.from(leaves, memberHash));
234
+ }
235
+ RateRatifierV1.groupId = groupId;
236
+ /**
237
+ * Builds a RateRatifierV1 tree descriptor from leaf input.
238
+ *
239
+ * Non-power-of-two leaf lists are padded with protocol-zero leaves at the
240
+ * highest leaf indices. A group matching the generic content id of all
241
+ * leaves sharing it (for example from `OfferUtils.toStruct` or
242
+ * `Group.create`) is re-derived with {@link groupId}; other explicit groups
243
+ * are committed as-is. An omitted `group` defaults to the leaf's
244
+ * content-addressed singleton {@link groupId}, which commits to `rate` and
245
+ * `allowedTaker` like the router does.
246
+ *
247
+ * @param leaves - Rate-bounded offer leaves in leaf order.
248
+ * @returns RateRatifierV1 tree descriptor.
249
+ * @throws {InvalidTreeError} when the leaf list is empty, contains duplicate leaf hashes, or mixes ratifier addresses.
250
+ * @throws {InvalidRateRatifierV1RateError} when a leaf rate is negative.
251
+ * @throws {InvalidRateRatifierV1TickError} when a leaf offer tick is below {@link MIN_TICK}.
252
+ * @throws {InvalidTreeHeightError} when the padded tree exceeds supported ratifier typehashes.
253
+ * @example
254
+ * ```ts
255
+ * import { RateRatifierV1, type IOffer } from "@morpho-org/midnight-sdk";
256
+ *
257
+ * function build(offer: IOffer) {
258
+ * return RateRatifierV1.buildDescriptor([{ offer, rate: 0n }]);
259
+ * }
260
+ * ```
261
+ */
262
+ function buildDescriptor(leaves) {
263
+ const normalized = leaves.map((leaf) => {
264
+ const rate = BigInt(leaf.rate);
265
+ if (rate < 0n)
266
+ throw new InvalidRateRatifierV1RateError(rate);
267
+ const allowedTaker = leaf.allowedTaker ?? zeroAddress;
268
+ const input = Offer.from(leaf.offer);
269
+ if (input.tick < RateRatifierV1.MIN_TICK)
270
+ throw new InvalidRateRatifierV1TickError(input.tick, RateRatifierV1.MIN_TICK);
271
+ return { offer: input, rate, allowedTaker };
272
+ });
273
+ const assignedOffers = assignRatifierV1Groups(normalized, groupId);
274
+ const offers = [];
275
+ const structs = normalized.map(({ rate, allowedTaker }, index) => {
276
+ const offer = assignedOffers[index];
277
+ offers.push(offer);
278
+ return { offer: OfferUtils.toStruct({ offer }), rate, allowedTaker };
279
+ });
280
+ const descriptor = buildRatifierV1Descriptor({
281
+ entries: structs,
282
+ padding: {
283
+ offer: EMPTY_OFFER_STRUCT,
284
+ rate: 0n,
285
+ allowedTaker: zeroAddress,
286
+ },
287
+ hashLeaf,
288
+ ratifierOf: (leafStruct) => leafStruct.offer.ratifier,
289
+ label: "RateRatifierV1",
290
+ });
291
+ return Object.freeze({
292
+ entries: deepFreeze(descriptor.entries),
293
+ leaves: deepFreeze(descriptor.leaves),
294
+ root: descriptor.root,
295
+ height: descriptor.height,
296
+ offers: Object.freeze([...offers]),
297
+ });
298
+ }
299
+ RateRatifierV1.buildDescriptor = buildDescriptor;
300
+ const treeHelpers = {
301
+ buildDescriptor,
302
+ hashLeaf,
303
+ isPadding: isPaddingEntry,
304
+ ratifierOf: (leafStruct) => leafStruct.offer.ratifier,
305
+ validateEntry: (entry) => {
306
+ if (entry.rate < 0n)
307
+ throw new InvalidRateRatifierV1RateError(entry.rate);
308
+ if (entry.offer.tick < RateRatifierV1.MIN_TICK)
309
+ throw new InvalidRateRatifierV1TickError(entry.offer.tick, RateRatifierV1.MIN_TICK);
310
+ },
311
+ label: "RateRatifierV1",
312
+ type: "rateV1",
313
+ };
314
+ /**
315
+ * Builds a Merkle proof for one RateRatifierV1 leaf.
316
+ *
317
+ * @param params.tree - RateRatifierV1 tree descriptor or raw leaf input.
318
+ * @param params.leafIndex - Leaf index to prove.
319
+ * @returns Proof descriptor.
320
+ * @throws {InvalidTreeError} when the tree is invalid or the leaf index is out of range.
321
+ * @throws {InvalidTreeHeightError} when the tree exceeds the supported height.
322
+ * @throws {InvalidRateRatifierV1RateError} when a raw leaf carries a negative rate.
323
+ * @throws {InvalidRateRatifierV1TickError} when a leaf offer tick is below {@link MIN_TICK}, including inside a caller-supplied descriptor.
324
+ * @example
325
+ * ```ts
326
+ * import { RateRatifierV1, type IOffer } from "@morpho-org/midnight-sdk";
327
+ *
328
+ * function build(offer: IOffer) {
329
+ * return RateRatifierV1.buildProof({
330
+ * tree: RateRatifierV1.buildDescriptor([{ offer, rate: 0n }]),
331
+ * leafIndex: 0n,
332
+ * });
333
+ * }
334
+ * ```
335
+ */
336
+ function buildProof(params) {
337
+ const tree = resolveRatifierV1Tree(params.tree, treeHelpers);
338
+ return TreeUtils.buildProof({ tree, leafIndex: params.leafIndex });
339
+ }
340
+ RateRatifierV1.buildProof = buildProof;
341
+ /**
342
+ * Encodes RateRatifierV1 ratifier data.
343
+ *
344
+ * Use only when you already have a root, proof, rate, and allowed taker.
345
+ * Most maker flows call `ratifierData` for one leaf or `ratify` for every
346
+ * leaf in the ratified tree.
347
+ *
348
+ * @param params.root - Merkle root ratified by the maker's RateRatifierV1.
349
+ * @param params.leafIndex - Leaf index proven by `params.proof`.
350
+ * @param params.proof - Merkle proof siblings for the leaf.
351
+ * @param params.rate - WAD-scaled per-second rate bound carried by the leaf.
352
+ * @param params.allowedTaker - Taker restriction carried by the leaf.
353
+ * @returns ABI-encoded ratifier data.
354
+ * @example
355
+ * ```ts
356
+ * import { RateRatifierV1 } from "@morpho-org/midnight-sdk";
357
+ * import { zeroAddress, zeroHash } from "viem";
358
+ *
359
+ * const data = RateRatifierV1.encodeRatifierData({
360
+ * root: zeroHash,
361
+ * leafIndex: 0n,
362
+ * proof: [],
363
+ * rate: 0n,
364
+ * allowedTaker: zeroAddress,
365
+ * });
366
+ * console.log(data);
367
+ * ```
368
+ */
369
+ function encodeRatifierData(params) {
370
+ return encodeAbiParameters(rateRatifierV1DataAbi, [
371
+ params.root,
372
+ BigInt(params.leafIndex),
373
+ params.proof,
374
+ BigInt(params.rate),
375
+ params.allowedTaker,
376
+ ]);
377
+ }
378
+ RateRatifierV1.encodeRatifierData = encodeRatifierData;
379
+ /**
380
+ * Decodes RateRatifierV1 ratifier data.
381
+ *
382
+ * Use on the take-side or in tests after `Payload.decode` to inspect the
383
+ * proof, rate, and allowed taker attached to a published offer.
384
+ *
385
+ * @param data - ABI-encoded ratifier data.
386
+ * @returns Decoded RateRatifierV1 ratifier data.
387
+ * @example
388
+ * ```ts
389
+ * import { RateRatifierV1 } from "@morpho-org/midnight-sdk";
390
+ * import { zeroAddress, zeroHash } from "viem";
391
+ *
392
+ * const decoded = RateRatifierV1.decodeRatifierData(
393
+ * RateRatifierV1.encodeRatifierData({
394
+ * root: zeroHash,
395
+ * leafIndex: 0n,
396
+ * proof: [],
397
+ * rate: 0n,
398
+ * allowedTaker: zeroAddress,
399
+ * }),
400
+ * );
401
+ * console.log(decoded.rate);
402
+ * ```
403
+ */
404
+ function decodeRatifierData(data) {
405
+ const [root, leafIndex, proof, rate, allowedTaker] = decodeAbiParameters(rateRatifierV1DataAbi, data);
406
+ return deepFreeze({
407
+ root,
408
+ leafIndex,
409
+ proof: [...proof],
410
+ rate,
411
+ allowedTaker,
412
+ });
413
+ }
414
+ RateRatifierV1.decodeRatifierData = decodeRatifierData;
415
+ /**
416
+ * Verifies that RateRatifierV1 ratifier data proves one payload offer
417
+ * belongs to its root.
418
+ *
419
+ * This helper intentionally does not check the onchain
420
+ * `RateRatifierV1.ratification` state or the rate-implied price bound.
421
+ * Consumers can query those values at their own block context after local
422
+ * proof verification.
423
+ *
424
+ * @param params.offer - Offer carried by the payload item.
425
+ * @param params.ratifierData - ABI-encoded RateRatifierV1 ratifier data.
426
+ * @param params.taker - Optional taker to check against the leaf's allowed taker.
427
+ * @returns Decoded RateRatifierV1 ratifier data after proof verification.
428
+ * @throws {InvalidTreeError} when the proof does not include `offer` in `root`.
429
+ * @throws {RatifierV1TakerNotAllowedError} when `taker` is not the leaf's allowed taker.
430
+ * @example
431
+ * ```ts
432
+ * import { RateRatifierV1, type IOffer } from "@morpho-org/midnight-sdk";
433
+ * import type { Hex } from "viem";
434
+ *
435
+ * function check(offer: IOffer, ratifierData: Hex) {
436
+ * return RateRatifierV1.verifyRatifierData({ offer, ratifierData });
437
+ * }
438
+ * ```
439
+ */
440
+ function verifyRatifierData(params) {
441
+ const decoded = decodeRatifierData(params.ratifierData);
442
+ const leaf = hashLeaf({
443
+ offer: OfferUtils.toStruct({ offer: Offer.from(params.offer) }),
444
+ rate: decoded.rate,
445
+ allowedTaker: decoded.allowedTaker,
446
+ });
447
+ if (!TreeUtils.verifyLeafProof({
448
+ leaf,
449
+ root: decoded.root,
450
+ leafIndex: decoded.leafIndex,
451
+ proof: decoded.proof,
452
+ })) {
453
+ throw new InvalidTreeError("Ratifier data proof does not include offer.");
454
+ }
455
+ assertRatifierV1Taker({
456
+ taker: params.taker,
457
+ allowedTaker: decoded.allowedTaker,
458
+ });
459
+ return decoded;
460
+ }
461
+ RateRatifierV1.verifyRatifierData = verifyRatifierData;
462
+ /**
463
+ * Builds one ratifier-data value for a tree leaf.
464
+ *
465
+ * Use after root ratification when a caller needs data for one offer leaf.
466
+ * Use `ratify` to produce payload-ready items for the whole tree.
467
+ *
468
+ * @param params.tree - RateRatifierV1 tree descriptor or raw leaf input.
469
+ * @param params.leafIndex - Leaf index to prove.
470
+ * @returns ABI-encoded RateRatifierV1 data.
471
+ * @throws {InvalidTreeError} when the tree is invalid, the leaf index is outside the tree, or the tree contains multiple ratifiers.
472
+ * @throws {InvalidTreeHeightError} when the tree exceeds the supported height.
473
+ * @throws {InvalidRateRatifierV1RateError} when a raw leaf carries a negative rate.
474
+ * @throws {InvalidRateRatifierV1TickError} when a leaf offer tick is below {@link MIN_TICK}, including inside a caller-supplied descriptor.
475
+ * @example
476
+ * ```ts
477
+ * import { RateRatifierV1, type IOffer } from "@morpho-org/midnight-sdk";
478
+ *
479
+ * function build(offer: IOffer) {
480
+ * return RateRatifierV1.ratifierData({
481
+ * tree: [{ offer, rate: 0n }],
482
+ * leafIndex: 0n,
483
+ * });
484
+ * }
485
+ * ```
486
+ */
487
+ function ratifierData(params) {
488
+ const tree = resolveRatifierV1Tree(params.tree, treeHelpers);
489
+ const proof = TreeUtils.buildProof({ tree, leafIndex: params.leafIndex });
490
+ const entry = tree.entries[Number(proof.leafIndex)];
491
+ return encodeRatifierData({
492
+ root: proof.root,
493
+ leafIndex: proof.leafIndex,
494
+ proof: proof.proof,
495
+ rate: entry.rate,
496
+ allowedTaker: entry.allowedTaker,
497
+ });
498
+ }
499
+ RateRatifierV1.ratifierData = ratifierData;
500
+ /**
501
+ * Returns payload-ready items after a RateRatifierV1 root has been ratified.
502
+ *
503
+ * Use after the root ratification transaction has been submitted for every
504
+ * maker in the tree. The returned items can be passed directly to
505
+ * `Payload.encode`. All offers in the tree must use one ratifier address;
506
+ * build separate trees per ratifier.
507
+ *
508
+ * @param params.tree - RateRatifierV1 tree descriptor or raw leaf input whose root has already been ratified onchain.
509
+ * @returns Items containing each non-padding offer and its ratifier data.
510
+ * @throws {InvalidTreeError} when the tree is invalid or contains multiple ratifiers.
511
+ * @throws {InvalidTreeHeightError} when the tree exceeds the supported height.
512
+ * @throws {InvalidRateRatifierV1RateError} when a raw leaf carries a negative rate.
513
+ * @throws {InvalidRateRatifierV1TickError} when a leaf offer tick is below {@link MIN_TICK}, including inside a caller-supplied descriptor.
514
+ * @example
515
+ * ```ts
516
+ * import { RateRatifierV1, type IOffer } from "@morpho-org/midnight-sdk";
517
+ *
518
+ * function build(offer: IOffer) {
519
+ * return RateRatifierV1.ratify({
520
+ * tree: [{ offer, rate: 0n }],
521
+ * });
522
+ * }
523
+ * ```
524
+ */
525
+ function ratify(params) {
526
+ const tree = resolveRatifierV1Tree(params.tree, treeHelpers);
527
+ const proofs = TreeUtils.buildProofs({
528
+ tree,
529
+ count: tree.offers.length,
530
+ });
531
+ return tree.offers.map((offer, leafIndex) => {
532
+ const entry = tree.entries[leafIndex];
533
+ const proof = proofs[leafIndex];
534
+ return {
535
+ offer,
536
+ ratifierData: encodeRatifierData({
537
+ root: proof.root,
538
+ leafIndex: proof.leafIndex,
539
+ proof: proof.proof,
540
+ rate: entry.rate,
541
+ allowedTaker: entry.allowedTaker,
542
+ }),
543
+ };
544
+ });
545
+ }
546
+ RateRatifierV1.ratify = ratify;
547
+ /**
548
+ * Converts a WAD-scaled per-second rate into the price bound used by
549
+ * `RateRatifierV1.isRatified`.
550
+ *
551
+ * The bound is `WAD * WAD / (WAD + rate * timeToMaturity)`, rounded down
552
+ * for buy offers and up for sell offers, matching the onchain comparison
553
+ * direction.
554
+ *
555
+ * @param params.rate - WAD-scaled per-second rate.
556
+ * @param params.timeToMaturity - Seconds remaining until market maturity.
557
+ * @param params.buy - Whether the maker buys units.
558
+ * @returns WAD-scaled price bound.
559
+ * @throws {InvalidRateRatifierV1RateError} when `rate` is negative.
560
+ * @throws {InvalidRateRatifierV1TimeError} when `timeToMaturity` is negative.
561
+ * @throws {RateRatifierV1BoundOverflowError} when the bound arithmetic exceeds uint256, matching the contract's checked math.
562
+ * @example
563
+ * ```ts
564
+ * import { RateRatifierV1 } from "@morpho-org/midnight-sdk";
565
+ *
566
+ * const bound = RateRatifierV1.priceBound({
567
+ * rate: 0n,
568
+ * timeToMaturity: 0n,
569
+ * buy: true,
570
+ * });
571
+ * console.log(bound);
572
+ * ```
573
+ */
574
+ function priceBound(params) {
575
+ const rate = BigInt(params.rate);
576
+ if (rate < 0n)
577
+ throw new InvalidRateRatifierV1RateError(rate);
578
+ const timeToMaturity = BigInt(params.timeToMaturity);
579
+ if (timeToMaturity < 0n) {
580
+ throw new InvalidRateRatifierV1TimeError(timeToMaturity, "timeToMaturity");
581
+ }
582
+ const product = rate * timeToMaturity;
583
+ if (product > maxUint256) {
584
+ throw new RateRatifierV1BoundOverflowError(rate, timeToMaturity);
585
+ }
586
+ const denominator = MathLib.WAD + product;
587
+ if (denominator > maxUint256) {
588
+ throw new RateRatifierV1BoundOverflowError(rate, timeToMaturity);
589
+ }
590
+ if (!params.buy &&
591
+ MathLib.WAD * MathLib.WAD + denominator - 1n > maxUint256) {
592
+ throw new RateRatifierV1BoundOverflowError(rate, timeToMaturity);
593
+ }
594
+ return params.buy
595
+ ? MathLib.mulDivDown(MathLib.WAD, MathLib.WAD, denominator)
596
+ : MathLib.mulDivUp(MathLib.WAD, MathLib.WAD, denominator);
597
+ }
598
+ RateRatifierV1.priceBound = priceBound;
599
+ /**
600
+ * Checks whether an offer's tick satisfies its rate bound at a timestamp.
601
+ *
602
+ * Mirrors `RateRatifierV1.isRatified`: the offer price must be at or below
603
+ * the rate-implied bound for buy offers, and at or above it for sell
604
+ * offers. Time to maturity floors at zero. Bounds that overflow uint256
605
+ * are unacceptable, matching the contract's revert.
606
+ *
607
+ * @param params.offer - Offer whose `tick`, `buy`, and `market.maturity` are checked.
608
+ * @param params.rate - WAD-scaled per-second rate bound proven by the leaf.
609
+ * @param params.timestamp - Timestamp at which acceptance is evaluated.
610
+ * @returns Whether the offer's tick price satisfies the rate bound.
611
+ * @throws {InvalidRateRatifierV1RateError} when `rate` is negative.
612
+ * @throws {InvalidRateRatifierV1TimeError} when `timestamp` is negative.
613
+ * @throws {NegativeValueError} when `offer.tick` is negative.
614
+ * @throws {TickOutOfRangeError} when `offer.tick` exceeds `MAX_TICK`.
615
+ * @example
616
+ * ```ts
617
+ * import { RateRatifierV1, type IOffer } from "@morpho-org/midnight-sdk";
618
+ *
619
+ * function check(offer: IOffer) {
620
+ * return RateRatifierV1.isPriceAcceptable({
621
+ * offer,
622
+ * rate: 0n,
623
+ * timestamp: 0n,
624
+ * });
625
+ * }
626
+ * ```
627
+ */
628
+ function isPriceAcceptable(params) {
629
+ const timestamp = BigInt(params.timestamp);
630
+ if (timestamp < 0n) {
631
+ throw new InvalidRateRatifierV1TimeError(timestamp, "timestamp");
632
+ }
633
+ const maturity = BigInt("params" in params.offer.market
634
+ ? params.offer.market.params.maturity
635
+ : params.offer.market.maturity);
636
+ const timeToMaturity = maturity - timestamp;
637
+ let bound;
638
+ try {
639
+ bound = priceBound({
640
+ rate: params.rate,
641
+ timeToMaturity: timeToMaturity > 0n ? timeToMaturity : 0n,
642
+ buy: params.offer.buy,
643
+ });
644
+ }
645
+ catch (error) {
646
+ if (error instanceof RateRatifierV1BoundOverflowError)
647
+ return false;
648
+ throw error;
649
+ }
650
+ const offerPrice = TickLib.tickToPrice(params.offer.tick);
651
+ return params.offer.buy ? offerPrice <= bound : offerPrice >= bound;
652
+ }
653
+ RateRatifierV1.isPriceAcceptable = isPriceAcceptable;
654
+ /**
655
+ * Encodes a `setIsRootRatified` call to a RateRatifierV1 contract.
656
+ *
657
+ * Onchain, the caller must be the maker or an address authorized by the
658
+ * maker on the Midnight instance. The returned descriptor is neutral and
659
+ * never signs or submits anything.
660
+ *
661
+ * @param params.ratifier - RateRatifierV1 contract address.
662
+ * @param params.maker - Maker whose ratification entry is updated.
663
+ * @param params.root - Merkle root to ratify or unratify.
664
+ * @param params.isRatified - New ratification flag for the root.
665
+ * @returns Neutral call descriptor.
666
+ * @throws {InvalidRatifierV1AddressError} when the ratifier address is the zero address.
667
+ * @example
668
+ * ```ts
669
+ * import { RateRatifierV1 } from "@morpho-org/midnight-sdk";
670
+ * import { zeroAddress, zeroHash } from "viem";
671
+ *
672
+ * const call = RateRatifierV1.encodeSetIsRootRatified({
673
+ * ratifier: "0x0000000000000000000000000000000000000001",
674
+ * maker: zeroAddress,
675
+ * root: zeroHash,
676
+ * isRatified: true,
677
+ * });
678
+ * console.log(call.to);
679
+ * ```
680
+ */
681
+ function encodeSetIsRootRatified(params) {
682
+ assertRatifierV1Address(params.ratifier);
683
+ return deepFreeze({
684
+ to: params.ratifier,
685
+ data: encodeFunctionData({
686
+ abi: rateRatifierV1Abi,
687
+ functionName: "setIsRootRatified",
688
+ args: [params.maker, params.root, params.isRatified],
689
+ }),
690
+ });
691
+ }
692
+ RateRatifierV1.encodeSetIsRootRatified = encodeSetIsRootRatified;
693
+ })(RateRatifierV1 || (RateRatifierV1 = {}));
694
+ /** @deprecated Use {@link RateRatifierV1}. Retained for compatibility. */
695
+ export { RateRatifierV1 as RateRatifierV1Utils };