@morpho-org/midnight-sdk 0.1.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 (157) hide show
  1. package/README.md +252 -0
  2. package/lib/cjs/abis.d.ts +3170 -0
  3. package/lib/cjs/abis.js +4073 -0
  4. package/lib/cjs/api/MidnightApi.d.ts +532 -0
  5. package/lib/cjs/api/MidnightApi.js +713 -0
  6. package/lib/cjs/api/helpers.d.ts +20 -0
  7. package/lib/cjs/api/helpers.js +189 -0
  8. package/lib/cjs/api/index.d.ts +2 -0
  9. package/lib/cjs/api/index.js +21 -0
  10. package/lib/cjs/api/types.d.ts +453 -0
  11. package/lib/cjs/api/types.js +2 -0
  12. package/lib/cjs/constants.d.ts +168 -0
  13. package/lib/cjs/constants.js +187 -0
  14. package/lib/cjs/errors.d.ts +253 -0
  15. package/lib/cjs/errors.js +309 -0
  16. package/lib/cjs/fetch/Market.d.ts +65 -0
  17. package/lib/cjs/fetch/Market.js +117 -0
  18. package/lib/cjs/fetch/Offer.d.ts +74 -0
  19. package/lib/cjs/fetch/Offer.js +119 -0
  20. package/lib/cjs/fetch/Position.d.ts +85 -0
  21. package/lib/cjs/fetch/Position.js +148 -0
  22. package/lib/cjs/fetch/Ratifier.d.ts +38 -0
  23. package/lib/cjs/fetch/Ratifier.js +57 -0
  24. package/lib/cjs/fetch/index.d.ts +5 -0
  25. package/lib/cjs/fetch/index.js +21 -0
  26. package/lib/cjs/fetch/types.d.ts +57 -0
  27. package/lib/cjs/fetch/types.js +2 -0
  28. package/lib/cjs/fetch/utils.d.ts +8 -0
  29. package/lib/cjs/fetch/utils.js +18 -0
  30. package/lib/cjs/index.d.ts +18 -0
  31. package/lib/cjs/index.js +57 -0
  32. package/lib/cjs/market/Market.d.ts +613 -0
  33. package/lib/cjs/market/Market.js +503 -0
  34. package/lib/cjs/market/MarketUtils.d.ts +189 -0
  35. package/lib/cjs/market/MarketUtils.js +303 -0
  36. package/lib/cjs/market/Position.d.ts +424 -0
  37. package/lib/cjs/market/Position.js +425 -0
  38. package/lib/cjs/market/PositionUtils.d.ts +115 -0
  39. package/lib/cjs/market/PositionUtils.js +194 -0
  40. package/lib/cjs/market/index.d.ts +4 -0
  41. package/lib/cjs/market/index.js +20 -0
  42. package/lib/cjs/math/ConsumableUnitsLib.d.ts +57 -0
  43. package/lib/cjs/math/ConsumableUnitsLib.js +77 -0
  44. package/lib/cjs/math/TakeAmountsLib.d.ts +175 -0
  45. package/lib/cjs/math/TakeAmountsLib.js +199 -0
  46. package/lib/cjs/math/TickLib.d.ts +200 -0
  47. package/lib/cjs/math/TickLib.js +272 -0
  48. package/lib/cjs/math/index.d.ts +3 -0
  49. package/lib/cjs/math/index.js +19 -0
  50. package/lib/cjs/offers/Offer.d.ts +534 -0
  51. package/lib/cjs/offers/Offer.js +343 -0
  52. package/lib/cjs/offers/OfferUtils.d.ts +565 -0
  53. package/lib/cjs/offers/OfferUtils.js +659 -0
  54. package/lib/cjs/offers/index.d.ts +2 -0
  55. package/lib/cjs/offers/index.js +18 -0
  56. package/lib/cjs/package.json +1 -0
  57. package/lib/cjs/queries/GetPosition.d.ts +55 -0
  58. package/lib/cjs/queries/GetPosition.js +74 -0
  59. package/lib/cjs/queries/index.d.ts +1 -0
  60. package/lib/cjs/queries/index.js +37 -0
  61. package/lib/cjs/signatures/EcrecoverRatifierUtils.d.ts +733 -0
  62. package/lib/cjs/signatures/EcrecoverRatifierUtils.js +618 -0
  63. package/lib/cjs/signatures/Group.d.ts +178 -0
  64. package/lib/cjs/signatures/Group.js +193 -0
  65. package/lib/cjs/signatures/GroupUtils.d.ts +191 -0
  66. package/lib/cjs/signatures/GroupUtils.js +127 -0
  67. package/lib/cjs/signatures/Payload.d.ts +283 -0
  68. package/lib/cjs/signatures/Payload.js +570 -0
  69. package/lib/cjs/signatures/RatifierUtils.d.ts +109 -0
  70. package/lib/cjs/signatures/RatifierUtils.js +76 -0
  71. package/lib/cjs/signatures/SetterRatifierUtils.d.ts +243 -0
  72. package/lib/cjs/signatures/SetterRatifierUtils.js +217 -0
  73. package/lib/cjs/signatures/Tree.d.ts +241 -0
  74. package/lib/cjs/signatures/Tree.js +263 -0
  75. package/lib/cjs/signatures/TreeUtils.d.ts +573 -0
  76. package/lib/cjs/signatures/TreeUtils.js +461 -0
  77. package/lib/cjs/signatures/index.d.ts +7 -0
  78. package/lib/cjs/signatures/index.js +23 -0
  79. package/lib/esm/abis.d.ts +3170 -0
  80. package/lib/esm/abis.js +4070 -0
  81. package/lib/esm/api/MidnightApi.d.ts +532 -0
  82. package/lib/esm/api/MidnightApi.js +709 -0
  83. package/lib/esm/api/helpers.d.ts +20 -0
  84. package/lib/esm/api/helpers.js +180 -0
  85. package/lib/esm/api/index.d.ts +2 -0
  86. package/lib/esm/api/index.js +2 -0
  87. package/lib/esm/api/types.d.ts +453 -0
  88. package/lib/esm/api/types.js +1 -0
  89. package/lib/esm/constants.d.ts +168 -0
  90. package/lib/esm/constants.js +184 -0
  91. package/lib/esm/errors.d.ts +253 -0
  92. package/lib/esm/errors.js +291 -0
  93. package/lib/esm/fetch/Market.d.ts +65 -0
  94. package/lib/esm/fetch/Market.js +113 -0
  95. package/lib/esm/fetch/Offer.d.ts +74 -0
  96. package/lib/esm/fetch/Offer.js +116 -0
  97. package/lib/esm/fetch/Position.d.ts +85 -0
  98. package/lib/esm/fetch/Position.js +144 -0
  99. package/lib/esm/fetch/Ratifier.d.ts +38 -0
  100. package/lib/esm/fetch/Ratifier.js +54 -0
  101. package/lib/esm/fetch/index.d.ts +5 -0
  102. package/lib/esm/fetch/index.js +5 -0
  103. package/lib/esm/fetch/types.d.ts +57 -0
  104. package/lib/esm/fetch/types.js +1 -0
  105. package/lib/esm/fetch/utils.d.ts +8 -0
  106. package/lib/esm/fetch/utils.js +12 -0
  107. package/lib/esm/index.d.ts +18 -0
  108. package/lib/esm/index.js +18 -0
  109. package/lib/esm/market/Market.d.ts +613 -0
  110. package/lib/esm/market/Market.js +498 -0
  111. package/lib/esm/market/MarketUtils.d.ts +189 -0
  112. package/lib/esm/market/MarketUtils.js +300 -0
  113. package/lib/esm/market/Position.d.ts +424 -0
  114. package/lib/esm/market/Position.js +420 -0
  115. package/lib/esm/market/PositionUtils.d.ts +115 -0
  116. package/lib/esm/market/PositionUtils.js +191 -0
  117. package/lib/esm/market/index.d.ts +4 -0
  118. package/lib/esm/market/index.js +4 -0
  119. package/lib/esm/math/ConsumableUnitsLib.d.ts +57 -0
  120. package/lib/esm/math/ConsumableUnitsLib.js +74 -0
  121. package/lib/esm/math/TakeAmountsLib.d.ts +175 -0
  122. package/lib/esm/math/TakeAmountsLib.js +196 -0
  123. package/lib/esm/math/TickLib.d.ts +200 -0
  124. package/lib/esm/math/TickLib.js +269 -0
  125. package/lib/esm/math/index.d.ts +3 -0
  126. package/lib/esm/math/index.js +3 -0
  127. package/lib/esm/offers/Offer.d.ts +534 -0
  128. package/lib/esm/offers/Offer.js +339 -0
  129. package/lib/esm/offers/OfferUtils.d.ts +565 -0
  130. package/lib/esm/offers/OfferUtils.js +656 -0
  131. package/lib/esm/offers/index.d.ts +2 -0
  132. package/lib/esm/offers/index.js +2 -0
  133. package/lib/esm/package.json +1 -0
  134. package/lib/esm/queries/GetPosition.d.ts +55 -0
  135. package/lib/esm/queries/GetPosition.js +71 -0
  136. package/lib/esm/queries/index.d.ts +1 -0
  137. package/lib/esm/queries/index.js +1 -0
  138. package/lib/esm/signatures/EcrecoverRatifierUtils.d.ts +733 -0
  139. package/lib/esm/signatures/EcrecoverRatifierUtils.js +615 -0
  140. package/lib/esm/signatures/Group.d.ts +178 -0
  141. package/lib/esm/signatures/Group.js +189 -0
  142. package/lib/esm/signatures/GroupUtils.d.ts +191 -0
  143. package/lib/esm/signatures/GroupUtils.js +124 -0
  144. package/lib/esm/signatures/Payload.d.ts +283 -0
  145. package/lib/esm/signatures/Payload.js +564 -0
  146. package/lib/esm/signatures/RatifierUtils.d.ts +109 -0
  147. package/lib/esm/signatures/RatifierUtils.js +73 -0
  148. package/lib/esm/signatures/SetterRatifierUtils.d.ts +243 -0
  149. package/lib/esm/signatures/SetterRatifierUtils.js +214 -0
  150. package/lib/esm/signatures/Tree.d.ts +241 -0
  151. package/lib/esm/signatures/Tree.js +259 -0
  152. package/lib/esm/signatures/TreeUtils.d.ts +573 -0
  153. package/lib/esm/signatures/TreeUtils.js +458 -0
  154. package/lib/esm/signatures/index.d.ts +7 -0
  155. package/lib/esm/signatures/index.js +7 -0
  156. package/package.json +69 -0
  157. package/src/index.ts +19 -0
@@ -0,0 +1,564 @@
1
+ import { MathLib } from "@morpho-org/morpho-ts";
2
+ import { bytesToHex, decodeAbiParameters, encodeAbiParameters, hexToBytes, } from "viem";
3
+ import { LIQUIDATION_CURSOR_HIGH, LIQUIDATION_CURSOR_LOW, MAX_COLLATERALS, MAX_TICK, } from "../constants.js";
4
+ import { InvalidOfferParameterError } from "../errors.js";
5
+ import { MarketUtils } from "../market/index.js";
6
+ import { Offer, OfferUtils, } from "../offers/index.js";
7
+ /**
8
+ * Current Midnight mempool payload wire version.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { Payload } from "@morpho-org/midnight-sdk";
13
+ *
14
+ * console.log(Payload.CURRENT_VERSION);
15
+ * ```
16
+ */
17
+ export const CURRENT_VERSION = 1;
18
+ const VERSION_PREFIX_BYTES = 1;
19
+ const LENGTH_PREFIX_BYTES = 4;
20
+ const HEADER_BYTES = VERSION_PREFIX_BYTES + LENGTH_PREFIX_BYTES;
21
+ /**
22
+ * Upper bound on opaque bytes appended after the gzip stream (e.g. an app
23
+ * attribution tag). The suffix is meant to be small, so `decode` rejects a
24
+ * larger one: this keeps the `MAX_PAYLOAD_BYTES` ceiling meaningful for the
25
+ * whole input. Without it a tiny declared `gzipLen` could smuggle an
26
+ * arbitrarily large suffix past validation and into the indexer while still
27
+ * forcing the API to receive and hex-decode the whole blob.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * import { Payload } from "@morpho-org/midnight-sdk";
32
+ *
33
+ * console.log(Payload.MAX_ATTRIBUTION_SUFFIX_BYTES);
34
+ * ```
35
+ */
36
+ export const MAX_ATTRIBUTION_SUFFIX_BYTES = 256;
37
+ /**
38
+ * Largest fully framed wire payload, in bytes, matching the router/onchain
39
+ * mempool cap.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * import { Payload } from "@morpho-org/midnight-sdk";
44
+ *
45
+ * console.log(Payload.MAX_PAYLOAD_BYTES);
46
+ * ```
47
+ */
48
+ export const MAX_PAYLOAD_BYTES = 1_000_000;
49
+ /**
50
+ * Maximum gzip-compressed item bytes accepted by the payload codec.
51
+ *
52
+ * The budget reserves room for the fixed header and the largest accepted
53
+ * attribution suffix so the full wire payload never exceeds
54
+ * {@link MAX_PAYLOAD_BYTES}.
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * import { Payload } from "@morpho-org/midnight-sdk";
59
+ *
60
+ * console.log(Payload.MAX_COMPRESSED_ITEMS_BYTES);
61
+ * ```
62
+ */
63
+ export const MAX_COMPRESSED_ITEMS_BYTES = MAX_PAYLOAD_BYTES - HEADER_BYTES - MAX_ATTRIBUTION_SUFFIX_BYTES;
64
+ /**
65
+ * Maximum ABI-decoded item bytes accepted by the payload codec.
66
+ *
67
+ * @example
68
+ * ```ts
69
+ * import { Payload } from "@morpho-org/midnight-sdk";
70
+ *
71
+ * console.log(Payload.MAX_DECOMPRESSED_ITEMS_BYTES);
72
+ * ```
73
+ */
74
+ export const MAX_DECOMPRESSED_ITEMS_BYTES = 6_000_000;
75
+ const ABI_ARRAY_HEAD_BYTES = 64;
76
+ const ABI_LENGTH_LOW_OFFSET = 60;
77
+ const MAX_TIMESTAMP_SECONDS = 1000000000000n - 1n;
78
+ const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
79
+ const ZERO_BYTES32 = "0x0000000000000000000000000000000000000000000000000000000000000000";
80
+ /**
81
+ * Largest `0x`-prefixed hex string that can encode a wire payload.
82
+ *
83
+ * @example
84
+ * ```ts
85
+ * import { Payload } from "@morpho-org/midnight-sdk";
86
+ *
87
+ * console.log(Payload.MAX_PAYLOAD_HEX_LENGTH);
88
+ * ```
89
+ */
90
+ export const MAX_PAYLOAD_HEX_LENGTH = "0x".length + MAX_PAYLOAD_BYTES * 2;
91
+ /**
92
+ * Largest inbound HTTP request body, in bytes, accepted by the API and
93
+ * gatekeeper APIs.
94
+ *
95
+ * @example
96
+ * ```ts
97
+ * import { Payload } from "@morpho-org/midnight-sdk";
98
+ *
99
+ * console.log(Payload.MAX_REQUEST_BODY_BYTES);
100
+ * ```
101
+ */
102
+ export const MAX_REQUEST_BODY_BYTES = MAX_PAYLOAD_HEX_LENGTH + 1_024;
103
+ const offerStructAbiComponents = [
104
+ {
105
+ name: "market",
106
+ type: "tuple",
107
+ components: [
108
+ { name: "loanToken", type: "address" },
109
+ {
110
+ name: "collateralParams",
111
+ type: "tuple[]",
112
+ components: [
113
+ { name: "token", type: "address" },
114
+ { name: "lltv", type: "uint256" },
115
+ { name: "maxLif", type: "uint256" },
116
+ { name: "oracle", type: "address" },
117
+ ],
118
+ },
119
+ { name: "maturity", type: "uint256" },
120
+ { name: "rcfThreshold", type: "uint256" },
121
+ { name: "enterGate", type: "address" },
122
+ { name: "liquidatorGate", type: "address" },
123
+ ],
124
+ },
125
+ { name: "buy", type: "bool" },
126
+ { name: "maker", type: "address" },
127
+ { name: "start", type: "uint256" },
128
+ { name: "expiry", type: "uint256" },
129
+ { name: "tick", type: "uint256" },
130
+ { name: "group", type: "bytes32" },
131
+ { name: "callback", type: "address" },
132
+ { name: "callbackData", type: "bytes" },
133
+ { name: "receiverIfMakerIsSeller", type: "address" },
134
+ { name: "ratifier", type: "address" },
135
+ { name: "reduceOnly", type: "bool" },
136
+ { name: "maxUnits", type: "uint256" },
137
+ { name: "maxAssets", type: "uint256" },
138
+ { name: "continuousFeeCap", type: "uint256" },
139
+ ];
140
+ const itemsAbi = [
141
+ {
142
+ name: "items",
143
+ type: "tuple[]",
144
+ components: [
145
+ { name: "offer", type: "tuple", components: offerStructAbiComponents },
146
+ { name: "ratifierData", type: "bytes" },
147
+ ],
148
+ },
149
+ ];
150
+ /**
151
+ * ABI-encode `items` as `(Offer, bytes ratifierData)[]` and gzip the result,
152
+ * then emit the wire payload `version || uint32(gzipLen) || gzip(...)`. The
153
+ * single-byte version prefix lets future formats coexist on the wire; the
154
+ * 4-byte big-endian length delimits the gzip stream so `decode` finds its end
155
+ * without scanning. That delimiter is what lets a publisher append a small
156
+ * opaque suffix (e.g. an attribution tag) after the gzip stream — `decode`
157
+ * ignores up to `MAX_ATTRIBUTION_SUFFIX_BYTES` bytes past `gzipLen` and rejects
158
+ * a larger suffix. Item order is preserved verbatim and is the order a consumer
159
+ * sees on decode.
160
+ *
161
+ * Use after ratifier utilities have produced payload-ready items and before an
162
+ * onchain mempool submission. Normal SDK maker flows should validate the tree
163
+ * with `Tree.mempoolValidate` before ratification; use
164
+ * `MidnightApi.validateMempoolPayload` only when validating already encoded
165
+ * payload bytes.
166
+ *
167
+ * @param items - Per-leaf items in the order the maker committed to. Must
168
+ * contain at least one item and fit within payload byte-size limits.
169
+ * @returns The encoded payload as a `Hex` string, ready to include in onchain
170
+ * mempool submission calldata.
171
+ * @throws {DecodeError} when the item list is empty, encoding or compression
172
+ * exceeds SDK byte-size limits, or a non-empty offer fails payload validation
173
+ * for collateral requirements, maturity timing, expiry range, tick bounds, or
174
+ * `maxUnits`/`maxAssets` cap shape.
175
+ * @example
176
+ * ```ts
177
+ * import { Offer, Payload } from "@morpho-org/midnight-sdk";
178
+ * import { zeroAddress } from "viem";
179
+ *
180
+ * const offer = Offer.create({
181
+ * market: {
182
+ * loanToken: "0x0000000000000000000000000000000000006000",
183
+ * collateralParams: [
184
+ * {
185
+ * token: "0x0000000000000000000000000000000000007000",
186
+ * lltv: 770000000000000000n,
187
+ * maxLif: 1061007957559681697n,
188
+ * oracle: "0x0000000000000000000000000000000000008000",
189
+ * },
190
+ * ],
191
+ * maturity: 54_000n,
192
+ * rcfThreshold: 0n,
193
+ * enterGate: zeroAddress,
194
+ * liquidatorGate: zeroAddress,
195
+ * },
196
+ * buy: true,
197
+ * maker: "0x0000000000000000000000000000000000009000",
198
+ * tick: 5_000n,
199
+ * expiry: 3_600n,
200
+ * ratifier: "0x0000000000000000000000000000000000004000",
201
+ * maxUnits: 100n,
202
+ * });
203
+ * const encoded = await Payload.encode([{ offer, ratifierData: "0x" }]);
204
+ * console.log(encoded);
205
+ * ```
206
+ */
207
+ export async function encode(items) {
208
+ if (CURRENT_VERSION > 0xff) {
209
+ throw new DecodeError(`version overflow: ${CURRENT_VERSION} exceeds 255`);
210
+ }
211
+ assertNonEmptyItemCount(items.length);
212
+ const payloadItems = items.map((item) => {
213
+ const offer = OfferUtils.toStruct({ offer: item.offer });
214
+ assertApiValidOfferStruct(offer);
215
+ return {
216
+ offer,
217
+ ratifierData: item.ratifierData,
218
+ };
219
+ });
220
+ const itemBytes = hexToBytes(encodeAbiParameters(itemsAbi, [payloadItems]));
221
+ const compressed = await compressItemsPayload(itemBytes);
222
+ const encoded = new Uint8Array(HEADER_BYTES + compressed.length);
223
+ encoded[0] = CURRENT_VERSION;
224
+ new DataView(encoded.buffer, encoded.byteOffset, encoded.byteLength).setUint32(VERSION_PREFIX_BYTES, compressed.length);
225
+ encoded.set(compressed, HEADER_BYTES);
226
+ return bytesToHex(encoded);
227
+ }
228
+ /**
229
+ * Parse a wire payload back into its `(offer, ratifierData)` items. The version
230
+ * byte is validated against `CURRENT_VERSION` and not surfaced — any payload
231
+ * that decodes successfully is on the current wire format. The 4-byte length
232
+ * prefix bounds the gzip stream; up to `MAX_ATTRIBUTION_SUFFIX_BYTES` bytes
233
+ * after it (e.g. an attribution suffix appended by the publishing app) are
234
+ * ignored, so a tagged payload decodes identically to an untagged one. A larger
235
+ * trailing suffix is rejected so an oversized blob cannot ride a small payload
236
+ * past validation and into the indexer.
237
+ *
238
+ * Use on the take-side, in indexers, or in diagnostics when you need to inspect
239
+ * the offer structs and ratifier data that a maker published.
240
+ *
241
+ * @param payload - Hex payload bytes to decode.
242
+ * @param options - Optional decode bounds.
243
+ * @returns The decoded items in encoded order.
244
+ * @throws {DecodeError} when the payload is malformed or exceeds protocol limits.
245
+ * @example
246
+ * ```ts
247
+ * import { Offer, Payload } from "@morpho-org/midnight-sdk";
248
+ * import { zeroAddress } from "viem";
249
+ *
250
+ * const offer = Offer.create({
251
+ * market: {
252
+ * loanToken: "0x0000000000000000000000000000000000006000",
253
+ * collateralParams: [
254
+ * {
255
+ * token: "0x0000000000000000000000000000000000007000",
256
+ * lltv: 770000000000000000n,
257
+ * maxLif: 1061007957559681697n,
258
+ * oracle: "0x0000000000000000000000000000000000008000",
259
+ * },
260
+ * ],
261
+ * maturity: 54_000n,
262
+ * rcfThreshold: 0n,
263
+ * enterGate: zeroAddress,
264
+ * liquidatorGate: zeroAddress,
265
+ * },
266
+ * buy: true,
267
+ * maker: "0x0000000000000000000000000000000000009000",
268
+ * tick: 5_000n,
269
+ * expiry: 3_600n,
270
+ * ratifier: "0x0000000000000000000000000000000000004000",
271
+ * maxUnits: 100n,
272
+ * });
273
+ * const encoded = await Payload.encode([{ offer, ratifierData: "0x" }]);
274
+ * const items = await Payload.decode(encoded);
275
+ * console.log(items.length);
276
+ * ```
277
+ */
278
+ export async function decode(payload, options) {
279
+ const maxItems = resolveMaxItems(options?.maxItems);
280
+ if (payload.length > MAX_PAYLOAD_HEX_LENGTH) {
281
+ throw new DecodeError(`payload hex exceeds ${MAX_PAYLOAD_HEX_LENGTH} characters`);
282
+ }
283
+ const bytes = hexToBytes(payload);
284
+ if (bytes.length < HEADER_BYTES) {
285
+ throw new DecodeError("payload too short for header");
286
+ }
287
+ const version = bytes[0];
288
+ if (version !== (CURRENT_VERSION & 0xff)) {
289
+ throw new DecodeError(`invalid version: expected ${CURRENT_VERSION}, got ${version}`);
290
+ }
291
+ const compressedLength = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(VERSION_PREFIX_BYTES);
292
+ const compressedEnd = HEADER_BYTES + compressedLength;
293
+ if (compressedEnd > bytes.length) {
294
+ throw new DecodeError("payload truncated before declared gzip length");
295
+ }
296
+ const suffixLength = bytes.length - compressedEnd;
297
+ if (suffixLength > MAX_ATTRIBUTION_SUFFIX_BYTES) {
298
+ throw new DecodeError(`trailing suffix exceeds ${MAX_ATTRIBUTION_SUFFIX_BYTES} bytes: got ${suffixLength}`);
299
+ }
300
+ const compressed = bytes.subarray(HEADER_BYTES, compressedEnd);
301
+ const decoded = await decompressItemsPayload(compressed);
302
+ assertAbiItemCountWithinCallerLimit(decoded, maxItems);
303
+ const items = decodeItemsBytes(decoded);
304
+ assertNonEmptyItemCount(items.length);
305
+ assertCallerItemCountLimit(items.length, maxItems);
306
+ assertCanonicalItemsBytes(items, decoded);
307
+ return items;
308
+ }
309
+ function decodeItemsBytes(decoded) {
310
+ let raw;
311
+ try {
312
+ [raw] = decodeAbiParameters(itemsAbi, bytesToHex(decoded));
313
+ }
314
+ catch (error) {
315
+ throw new DecodeError("items abi decode failed", error instanceof Error ? error : undefined);
316
+ }
317
+ try {
318
+ return raw.map((entry) => {
319
+ assertApiValidOfferStruct(entry.offer);
320
+ return {
321
+ offer: Offer.from(entry.offer),
322
+ ratifierData: entry.ratifierData,
323
+ };
324
+ });
325
+ }
326
+ catch (error) {
327
+ if (error instanceof DecodeError)
328
+ throw error;
329
+ if (error instanceof Error) {
330
+ throw new DecodeError(`invalid offer bytes: ${error.message}`, error);
331
+ }
332
+ throw error;
333
+ }
334
+ }
335
+ function assertCanonicalItemsBytes(items, decoded) {
336
+ const canonical = encodeAbiParameters(itemsAbi, [
337
+ items.map((item) => ({
338
+ offer: OfferUtils.toStruct({ offer: item.offer }),
339
+ ratifierData: item.ratifierData,
340
+ })),
341
+ ]);
342
+ if (canonical !== bytesToHex(decoded)) {
343
+ throw new DecodeError("items payload has non-canonical ABI bytes");
344
+ }
345
+ }
346
+ function assertApiValidOfferStruct(offer) {
347
+ if (isEmptyOfferStruct(offer))
348
+ return;
349
+ assertCollateralParams(offer);
350
+ assertSafeTimestamp("market.maturity", offer.market.maturity);
351
+ assertMaturityAt15Utc(offer.market.maturity);
352
+ assertSafeTimestamp("start", offer.start);
353
+ assertSafeTimestamp("expiry", offer.expiry);
354
+ assertApiValidOfferTimeRange(offer);
355
+ if (offer.buy && !isZeroAddress(offer.receiverIfMakerIsSeller)) {
356
+ throw new DecodeError("invalid offer bytes: receiverIfMakerIsSeller must be zero for buy offers");
357
+ }
358
+ if (offer.expiry > offer.market.maturity) {
359
+ throw new DecodeError("invalid offer bytes: expiry must be before or equal to maturity");
360
+ }
361
+ if (offer.tick > MAX_TICK) {
362
+ throw new DecodeError(`invalid offer bytes: tick exceeds maximum ${MAX_TICK}`);
363
+ }
364
+ if ((offer.maxUnits === 0n) === (offer.maxAssets === 0n)) {
365
+ throw new DecodeError("invalid offer bytes: exactly one of maxUnits and maxAssets must be non-zero");
366
+ }
367
+ if (offer.continuousFeeCap < 0n) {
368
+ throw new DecodeError("invalid offer bytes: continuousFeeCap must be non-negative");
369
+ }
370
+ }
371
+ function assertApiValidOfferTimeRange(offer) {
372
+ try {
373
+ OfferUtils.validateOfferTimeRange(offer);
374
+ }
375
+ catch (error) {
376
+ if (error instanceof InvalidOfferParameterError) {
377
+ throw new DecodeError(`invalid offer bytes: ${error.message}`, error);
378
+ }
379
+ throw error;
380
+ }
381
+ }
382
+ function assertCollateralParams(offer) {
383
+ const collateralParams = offer.market.collateralParams;
384
+ if (collateralParams.length === 0) {
385
+ throw new DecodeError("invalid offer bytes: at least one collateral required");
386
+ }
387
+ if (collateralParams.length > Number(MAX_COLLATERALS)) {
388
+ throw new DecodeError(`invalid offer bytes: market.collateralParams has ${collateralParams.length} collaterals, exceeding the maximum of ${MAX_COLLATERALS}`);
389
+ }
390
+ let previousToken;
391
+ for (const params of collateralParams) {
392
+ if (params.lltv < 0n || params.lltv > MathLib.WAD) {
393
+ throw new DecodeError(`invalid offer bytes: collateral lltv must be between 0 and WAD, got ${params.lltv}`);
394
+ }
395
+ const lowMaxLif = MarketUtils.getLiquidationIncentiveFactor(params, LIQUIDATION_CURSOR_LOW);
396
+ const highMaxLif = MarketUtils.getLiquidationIncentiveFactor(params, LIQUIDATION_CURSOR_HIGH);
397
+ if (params.maxLif !== lowMaxLif && params.maxLif !== highMaxLif) {
398
+ throw new DecodeError(`invalid offer bytes: invalid collateral maxLif ${params.maxLif}`);
399
+ }
400
+ const token = params.token.toLowerCase();
401
+ if (isZeroAddress(token)) {
402
+ throw new DecodeError("invalid offer bytes: collateral token must be non-zero");
403
+ }
404
+ if (previousToken != null && previousToken >= token) {
405
+ throw new DecodeError("invalid offer bytes: collaterals must be sorted and unique");
406
+ }
407
+ previousToken = token;
408
+ }
409
+ }
410
+ function assertSafeTimestamp(field, value) {
411
+ if (value > MAX_TIMESTAMP_SECONDS) {
412
+ throw new DecodeError(`invalid offer bytes: ${field} exceeds ${MAX_TIMESTAMP_SECONDS}`);
413
+ }
414
+ }
415
+ function assertMaturityAt15Utc(value) {
416
+ const date = new Date(Number(value) * 1000);
417
+ if (date.getUTCHours() !== 15 ||
418
+ date.getUTCMinutes() !== 0 ||
419
+ date.getUTCSeconds() !== 0 ||
420
+ date.getUTCMilliseconds() !== 0) {
421
+ throw new DecodeError("invalid offer bytes: maturity must be at 15:00:00 UTC");
422
+ }
423
+ }
424
+ function isEmptyOfferStruct(offer) {
425
+ return (isZeroAddress(offer.market.loanToken) &&
426
+ offer.market.collateralParams.length === 0 &&
427
+ offer.market.maturity === 0n &&
428
+ offer.market.rcfThreshold === 0n &&
429
+ isZeroAddress(offer.market.enterGate) &&
430
+ isZeroAddress(offer.market.liquidatorGate) &&
431
+ offer.buy === false &&
432
+ isZeroAddress(offer.maker) &&
433
+ offer.start === 0n &&
434
+ offer.expiry === 0n &&
435
+ offer.tick === 0n &&
436
+ offer.group === ZERO_BYTES32 &&
437
+ isZeroAddress(offer.callback) &&
438
+ offer.callbackData === "0x" &&
439
+ isZeroAddress(offer.receiverIfMakerIsSeller) &&
440
+ isZeroAddress(offer.ratifier) &&
441
+ offer.reduceOnly === false &&
442
+ offer.maxUnits === 0n &&
443
+ offer.maxAssets === 0n &&
444
+ offer.continuousFeeCap === 0n);
445
+ }
446
+ function isZeroAddress(value) {
447
+ return value.toLowerCase() === ZERO_ADDRESS;
448
+ }
449
+ function resolveMaxItems(maxItems) {
450
+ if (maxItems === undefined)
451
+ return undefined;
452
+ if (!Number.isInteger(maxItems) || maxItems < 1) {
453
+ throw new DecodeError(`maxItems must be a positive integer: got ${maxItems}`);
454
+ }
455
+ return maxItems;
456
+ }
457
+ function assertNonEmptyItemCount(count) {
458
+ if (count === 0)
459
+ throw new DecodeError("items payload is empty");
460
+ }
461
+ function assertCallerItemCountLimit(count, maxItems) {
462
+ if (maxItems === undefined)
463
+ return;
464
+ if (count > maxItems) {
465
+ throw new DecodeError(`items payload exceeds ${maxItems} items`);
466
+ }
467
+ }
468
+ async function compressItemsPayload(payload) {
469
+ if (payload.length > MAX_DECOMPRESSED_ITEMS_BYTES) {
470
+ throw new DecodeError(`decompressed items exceed ${MAX_DECOMPRESSED_ITEMS_BYTES} bytes`);
471
+ }
472
+ let compressed;
473
+ try {
474
+ const stream = singleChunkStream(payload).pipeThrough(new CompressionStream("gzip"));
475
+ compressed = new Uint8Array(await new Response(stream).arrayBuffer());
476
+ }
477
+ catch (error) {
478
+ throw new DecodeError("compression failed", error instanceof Error ? error : undefined);
479
+ }
480
+ if (compressed.length > MAX_COMPRESSED_ITEMS_BYTES) {
481
+ throw new DecodeError(`compressed items exceed ${MAX_COMPRESSED_ITEMS_BYTES} bytes`);
482
+ }
483
+ return compressed;
484
+ }
485
+ async function decompressItemsPayload(compressed) {
486
+ if (compressed.length === 0)
487
+ throw new DecodeError("decompression failed");
488
+ if (compressed.length > MAX_COMPRESSED_ITEMS_BYTES) {
489
+ throw new DecodeError(`compressed items exceed ${MAX_COMPRESSED_ITEMS_BYTES} bytes`);
490
+ }
491
+ const reader = singleChunkStream(compressed)
492
+ .pipeThrough(new DecompressionStream("gzip"))
493
+ .getReader();
494
+ const chunks = [];
495
+ let totalLength = 0;
496
+ try {
497
+ while (true) {
498
+ const { done, value } = await reader.read();
499
+ if (done)
500
+ break;
501
+ totalLength += value.length;
502
+ if (totalLength > MAX_DECOMPRESSED_ITEMS_BYTES) {
503
+ await reader.cancel();
504
+ throw new DecodeError(`decompressed items exceed ${MAX_DECOMPRESSED_ITEMS_BYTES} bytes`);
505
+ }
506
+ chunks.push(value);
507
+ }
508
+ }
509
+ catch (error) {
510
+ if (error instanceof DecodeError)
511
+ throw error;
512
+ throw new DecodeError("decompression failed", error instanceof Error ? error : undefined);
513
+ }
514
+ const result = new Uint8Array(totalLength);
515
+ let offset = 0;
516
+ for (const chunk of chunks) {
517
+ result.set(chunk, offset);
518
+ offset += chunk.length;
519
+ }
520
+ return result;
521
+ }
522
+ function singleChunkStream(bytes) {
523
+ return new ReadableStream({
524
+ start(controller) {
525
+ controller.enqueue(new Uint8Array(bytes));
526
+ controller.close();
527
+ },
528
+ });
529
+ }
530
+ function assertAbiItemCountWithinCallerLimit(decoded, maxItems) {
531
+ if (decoded.length < ABI_ARRAY_HEAD_BYTES) {
532
+ throw new DecodeError("items payload truncated before ABI array head");
533
+ }
534
+ if (maxItems === undefined)
535
+ return;
536
+ for (let i = 32; i < ABI_LENGTH_LOW_OFFSET; i++) {
537
+ if (decoded[i] !== 0) {
538
+ throw new DecodeError(`items payload exceeds ${maxItems} items`);
539
+ }
540
+ }
541
+ const length = new DataView(decoded.buffer, decoded.byteOffset, decoded.byteLength).getUint32(ABI_LENGTH_LOW_OFFSET);
542
+ if (length > maxItems) {
543
+ throw new DecodeError(`items payload exceeds ${maxItems} items`);
544
+ }
545
+ }
546
+ /**
547
+ * Error thrown when a Midnight mempool payload cannot be decoded.
548
+ *
549
+ * @example
550
+ * ```ts
551
+ * import { Payload } from "@morpho-org/midnight-sdk";
552
+ *
553
+ * throw new Payload.DecodeError("payload too short for header");
554
+ * ```
555
+ */
556
+ export class DecodeError extends Error {
557
+ /** Machine-readable decode failure reason without the class message prefix. */
558
+ reason;
559
+ constructor(reason, cause) {
560
+ super(`Failed to decode payload: ${reason}`, cause ? { cause } : undefined);
561
+ this.name = "Payload.DecodeError";
562
+ this.reason = reason;
563
+ }
564
+ }
@@ -0,0 +1,109 @@
1
+ import type { Address, Hex } from "viem";
2
+ /**
3
+ * Parameters for {@link RatifierUtils.getRatifierInfo}.
4
+ *
5
+ * Pass the maker account bytecode read at the same block context used to build
6
+ * the offer. The bytecode is used only to choose the ratifier address to put on
7
+ * the offer.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import type { GetRatifierInfoParams } from "@morpho-org/midnight-sdk";
12
+ *
13
+ * const params: GetRatifierInfoParams = {
14
+ * bytecode: "0x",
15
+ * ecrecoverRatifier: "0x0000000000000000000000000000000000000001",
16
+ * setterRatifier: "0x0000000000000000000000000000000000000002",
17
+ * };
18
+ * console.log(params.bytecode);
19
+ * ```
20
+ */
21
+ export interface GetRatifierInfoParams {
22
+ /** Maker account bytecode returned by viem `getBytecode`; `undefined`, `null`, and `0x` mean no deployed code. */
23
+ readonly bytecode?: Hex | null;
24
+ /** Ecrecover ratifier address. */
25
+ readonly ecrecoverRatifier: Address;
26
+ /** Setter ratifier address. */
27
+ readonly setterRatifier: Address;
28
+ }
29
+ /**
30
+ * Classification of the ratifier route for a maker account.
31
+ *
32
+ * Put `ratifier` on each new `Offer.create` call for this maker. Use `type` to
33
+ * decide whether the tree later needs an Ecrecover signature or a Setter root
34
+ * approval before payload encoding.
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * import type { RatifierInfo } from "@morpho-org/midnight-sdk";
39
+ *
40
+ * const info: RatifierInfo = {
41
+ * type: "ecrecover",
42
+ * ratifier: "0x0000000000000000000000000000000000000001",
43
+ * };
44
+ * ```
45
+ */
46
+ export interface RatifierInfo {
47
+ /** Ratifier family selected for the maker account. */
48
+ readonly type: "ecrecover" | "setter";
49
+ /** Ratifier contract address to put on the offer. */
50
+ readonly ratifier: Address;
51
+ }
52
+ /**
53
+ * Utilities for selecting Midnight ratifier routes.
54
+ *
55
+ * Call these during make-side preparation, before `Offer.create`, when an app
56
+ * must decide whether a maker can sign an Ecrecover root or must approve a
57
+ * Setter root onchain. Fetch helpers read bytecode for you; this namespace is
58
+ * the pure classification logic.
59
+ *
60
+ * @example
61
+ * ```ts
62
+ * import { RatifierUtils } from "@morpho-org/midnight-sdk";
63
+ *
64
+ * console.log(RatifierUtils.isEip7702Designator("0xef0100"));
65
+ * ```
66
+ */
67
+ export declare namespace RatifierUtils {
68
+ /**
69
+ * Checks whether bytecode is an EIP-7702 designator.
70
+ *
71
+ * EIP-7702 accounts have code-like bytecode but still sign as the owning EOA,
72
+ * so they use the Ecrecover ratifier route instead of the Setter route.
73
+ *
74
+ * @param bytecode - Account bytecode.
75
+ * @returns Whether the bytecode starts with `0xef0100`.
76
+ * @example
77
+ * ```ts
78
+ * import { RatifierUtils } from "@morpho-org/midnight-sdk";
79
+ *
80
+ * console.log(RatifierUtils.isEip7702Designator("0xef0100"));
81
+ * ```
82
+ */
83
+ function isEip7702Designator(bytecode: Hex): boolean;
84
+ /**
85
+ * Selects Ecrecover for EOAs/EIP-7702 accounts and Setter for deployed-code
86
+ * accounts.
87
+ *
88
+ * Use the returned `ratifier` address in `Offer.create`. Later, use
89
+ * `EcrecoverRatifierUtils.ratify` when `type` is `ecrecover`, or approve the
90
+ * root and call `SetterRatifierUtils.ratify` when `type` is `setter`.
91
+ *
92
+ * @param params.bytecode - Maker bytecode returned by `eth_getCode`.
93
+ * @param params.ecrecoverRatifier - Ratifier address used for EOAs and EIP-7702 accounts.
94
+ * @param params.setterRatifier - Ratifier address used for deployed-code accounts.
95
+ * @returns Ratifier information for the maker.
96
+ * @example
97
+ * ```ts
98
+ * import { RatifierUtils } from "@morpho-org/midnight-sdk";
99
+ *
100
+ * const info = RatifierUtils.getRatifierInfo({
101
+ * bytecode: "0x",
102
+ * ecrecoverRatifier: "0x0000000000000000000000000000000000000001",
103
+ * setterRatifier: "0x0000000000000000000000000000000000000002",
104
+ * });
105
+ * console.log(info.type);
106
+ * ```
107
+ */
108
+ function getRatifierInfo(params: GetRatifierInfoParams): RatifierInfo;
109
+ }