@morpho-org/midnight-sdk 0.1.0 → 1.1.1

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 (128) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +56 -46
  3. package/lib/cjs/abis.d.ts +1185 -996
  4. package/lib/cjs/abis.js +1445 -1211
  5. package/lib/cjs/api/MidnightApi.d.ts +22 -16
  6. package/lib/cjs/api/MidnightApi.js +89 -19
  7. package/lib/cjs/api/helpers.d.ts +11 -1
  8. package/lib/cjs/api/helpers.js +54 -4
  9. package/lib/cjs/api/types.d.ts +35 -9
  10. package/lib/cjs/constants.d.ts +12 -11
  11. package/lib/cjs/constants.js +14 -12
  12. package/lib/cjs/errors.d.ts +89 -1
  13. package/lib/cjs/errors.js +114 -3
  14. package/lib/cjs/fetch/Market.js +37 -3
  15. package/lib/cjs/fetch/index.d.ts +0 -1
  16. package/lib/cjs/fetch/index.js +0 -1
  17. package/lib/cjs/fetch/utils.d.ts +1 -1
  18. package/lib/cjs/fetch/utils.js +9 -2
  19. package/lib/cjs/index.d.ts +1 -1
  20. package/lib/cjs/index.js +2 -23
  21. package/lib/cjs/market/Market.d.ts +99 -33
  22. package/lib/cjs/market/Market.js +137 -28
  23. package/lib/cjs/market/MarketUtils.d.ts +61 -41
  24. package/lib/cjs/market/MarketUtils.js +108 -48
  25. package/lib/cjs/market/Position.d.ts +16 -11
  26. package/lib/cjs/market/Position.js +18 -12
  27. package/lib/cjs/market/PositionUtils.d.ts +6 -4
  28. package/lib/cjs/market/PositionUtils.js +9 -6
  29. package/lib/cjs/math/TickLib.d.ts +22 -0
  30. package/lib/cjs/math/TickLib.js +30 -0
  31. package/lib/cjs/math/index.d.ts +0 -1
  32. package/lib/cjs/math/index.js +0 -1
  33. package/lib/cjs/offers/Offer.d.ts +218 -12
  34. package/lib/cjs/offers/Offer.js +215 -7
  35. package/lib/cjs/offers/OfferUtils.d.ts +249 -143
  36. package/lib/cjs/offers/OfferUtils.js +326 -45
  37. package/lib/cjs/queries/GetPosition.d.ts +1 -1
  38. package/lib/cjs/queries/GetPosition.js +1 -1
  39. package/lib/cjs/signatures/EcrecoverRatifierUtils.d.ts +184 -38
  40. package/lib/cjs/signatures/EcrecoverRatifierUtils.js +296 -80
  41. package/lib/cjs/signatures/Group.d.ts +12 -4
  42. package/lib/cjs/signatures/Group.js +17 -7
  43. package/lib/cjs/signatures/GroupUtils.d.ts +60 -4
  44. package/lib/cjs/signatures/GroupUtils.js +57 -2
  45. package/lib/cjs/signatures/Payload.d.ts +277 -277
  46. package/lib/cjs/signatures/Payload.js +517 -534
  47. package/lib/cjs/signatures/RatifierUtils.d.ts +57 -0
  48. package/lib/cjs/signatures/RatifierUtils.js +105 -0
  49. package/lib/cjs/signatures/SetterRatifierUtils.d.ts +52 -13
  50. package/lib/cjs/signatures/SetterRatifierUtils.js +62 -19
  51. package/lib/cjs/signatures/Tree.d.ts +28 -16
  52. package/lib/cjs/signatures/Tree.js +35 -15
  53. package/lib/cjs/signatures/TreeUtils.d.ts +185 -63
  54. package/lib/cjs/signatures/TreeUtils.js +89 -79
  55. package/lib/cjs/signatures/eip712.d.ts +22 -0
  56. package/lib/cjs/signatures/eip712.js +26 -0
  57. package/lib/cjs/signatures/index.d.ts +2 -0
  58. package/lib/cjs/signatures/index.js +4 -0
  59. package/lib/cjs/signatures/offerStructInternal.d.ts +14 -0
  60. package/lib/cjs/signatures/offerStructInternal.js +72 -0
  61. package/lib/esm/abis.d.ts +1185 -996
  62. package/lib/esm/abis.js +1445 -1211
  63. package/lib/esm/api/MidnightApi.d.ts +22 -16
  64. package/lib/esm/api/MidnightApi.js +91 -21
  65. package/lib/esm/api/helpers.d.ts +11 -1
  66. package/lib/esm/api/helpers.js +54 -5
  67. package/lib/esm/api/types.d.ts +35 -9
  68. package/lib/esm/constants.d.ts +12 -11
  69. package/lib/esm/constants.js +13 -11
  70. package/lib/esm/errors.d.ts +89 -1
  71. package/lib/esm/errors.js +108 -2
  72. package/lib/esm/fetch/Market.js +38 -4
  73. package/lib/esm/fetch/index.d.ts +0 -1
  74. package/lib/esm/fetch/index.js +0 -1
  75. package/lib/esm/fetch/utils.d.ts +1 -1
  76. package/lib/esm/fetch/utils.js +9 -2
  77. package/lib/esm/index.d.ts +1 -1
  78. package/lib/esm/index.js +1 -1
  79. package/lib/esm/market/Market.d.ts +99 -33
  80. package/lib/esm/market/Market.js +137 -28
  81. package/lib/esm/market/MarketUtils.d.ts +61 -41
  82. package/lib/esm/market/MarketUtils.js +109 -49
  83. package/lib/esm/market/Position.d.ts +16 -11
  84. package/lib/esm/market/Position.js +19 -13
  85. package/lib/esm/market/PositionUtils.d.ts +6 -4
  86. package/lib/esm/market/PositionUtils.js +9 -6
  87. package/lib/esm/math/TickLib.d.ts +22 -0
  88. package/lib/esm/math/TickLib.js +31 -1
  89. package/lib/esm/math/index.d.ts +0 -1
  90. package/lib/esm/math/index.js +0 -1
  91. package/lib/esm/offers/Offer.d.ts +218 -12
  92. package/lib/esm/offers/Offer.js +216 -8
  93. package/lib/esm/offers/OfferUtils.d.ts +249 -143
  94. package/lib/esm/offers/OfferUtils.js +329 -48
  95. package/lib/esm/queries/GetPosition.d.ts +1 -1
  96. package/lib/esm/queries/GetPosition.js +1 -1
  97. package/lib/esm/signatures/EcrecoverRatifierUtils.d.ts +184 -38
  98. package/lib/esm/signatures/EcrecoverRatifierUtils.js +298 -82
  99. package/lib/esm/signatures/Group.d.ts +12 -4
  100. package/lib/esm/signatures/Group.js +17 -7
  101. package/lib/esm/signatures/GroupUtils.d.ts +60 -4
  102. package/lib/esm/signatures/GroupUtils.js +57 -2
  103. package/lib/esm/signatures/Payload.d.ts +277 -277
  104. package/lib/esm/signatures/Payload.js +517 -531
  105. package/lib/esm/signatures/RatifierUtils.d.ts +57 -0
  106. package/lib/esm/signatures/RatifierUtils.js +105 -0
  107. package/lib/esm/signatures/SetterRatifierUtils.d.ts +52 -13
  108. package/lib/esm/signatures/SetterRatifierUtils.js +62 -19
  109. package/lib/esm/signatures/Tree.d.ts +28 -16
  110. package/lib/esm/signatures/Tree.js +36 -16
  111. package/lib/esm/signatures/TreeUtils.d.ts +185 -63
  112. package/lib/esm/signatures/TreeUtils.js +91 -81
  113. package/lib/esm/signatures/eip712.d.ts +22 -0
  114. package/lib/esm/signatures/eip712.js +22 -0
  115. package/lib/esm/signatures/index.d.ts +2 -0
  116. package/lib/esm/signatures/index.js +2 -0
  117. package/lib/esm/signatures/offerStructInternal.d.ts +14 -0
  118. package/lib/esm/signatures/offerStructInternal.js +67 -0
  119. package/package.json +31 -34
  120. package/lib/cjs/fetch/Offer.d.ts +0 -74
  121. package/lib/cjs/fetch/Offer.js +0 -119
  122. package/lib/cjs/math/ConsumableUnitsLib.d.ts +0 -57
  123. package/lib/cjs/math/ConsumableUnitsLib.js +0 -77
  124. package/lib/esm/fetch/Offer.d.ts +0 -74
  125. package/lib/esm/fetch/Offer.js +0 -116
  126. package/lib/esm/math/ConsumableUnitsLib.d.ts +0 -57
  127. package/lib/esm/math/ConsumableUnitsLib.js +0 -74
  128. package/src/index.ts +0 -19
@@ -1,9 +1,9 @@
1
1
  import type { FetchBookParams, FetchBookPriceLevelsParams, FetchBookQuoteParams, FetchBooksParams, FetchBookTakeableOffersParams, FetchTakeableOffersParams, MempoolPayloadValidationResult, MidnightApiBookPriceLevelsResult, MidnightApiBookResult, MidnightApiBooksResult, MidnightApiBookTakeableOffersResult, MidnightApiClientParams, MidnightApiConstructorConfig, MidnightApiQuoteResult, MidnightApiTakeableOffersResult, ValidateMempoolItemsParams, ValidateMempoolPayloadParams } from "./types.js";
2
- export type { FetchBookParams, FetchBookPriceLevelsParams, FetchBookQuoteParams, FetchBooksParams, FetchBookTakeableOffersParams, FetchTakeableOffersParams, MempoolPayloadValidationIssue, MempoolPayloadValidationResult, MidnightApiBookMarket, MidnightApiBookPriceLevelsResult, MidnightApiBookResult, MidnightApiBookSide, MidnightApiBookSort, MidnightApiBookSortField, MidnightApiBookSortTerm, MidnightApiBooksResult, MidnightApiBookTakeableOffersResult, MidnightApiClientParams, MidnightApiCollateral, MidnightApiConfig, MidnightApiConstructorConfig, MidnightApiFetch, MidnightApiPriceLevel, MidnightApiQuote, MidnightApiQuoteAssetsTarget, MidnightApiQuoteAverageWorstPriceGuard, MidnightApiQuoteResult, MidnightApiQuoteSlippageGuard, MidnightApiQuoteUnitsTarget, MidnightApiQuoteWithoutGuard, MidnightApiRequestOptions, MidnightApiSlippage, MidnightApiTake, MidnightApiTakeableOffersResult, ValidateMempoolItemsParams, ValidateMempoolPayloadParams, } from "./types.js";
2
+ export type { FetchBookParams, FetchBookPriceLevelsParams, FetchBookQuoteParams, FetchBooksParams, FetchBookTakeableOffersParams, FetchTakeableOffersParams, MempoolPayloadValidationIssue, MempoolPayloadValidationResult, MempoolPayloadValidationSuccess, MidnightApiBookMarket, MidnightApiBookPriceLevelsResult, MidnightApiBookResult, MidnightApiBookSide, MidnightApiBookSort, MidnightApiBookSortField, MidnightApiBookSortTerm, MidnightApiBooksResult, MidnightApiBookTakeableOffersResult, MidnightApiClientParams, MidnightApiCollateral, MidnightApiConfig, MidnightApiConstructorConfig, MidnightApiFetch, MidnightApiPriceLevel, MidnightApiQuote, MidnightApiQuoteAssetsTarget, MidnightApiQuoteAverageWorstPriceGuard, MidnightApiQuoteResult, MidnightApiQuoteSlippageGuard, MidnightApiQuoteUnitsTarget, MidnightApiQuoteWithoutGuard, MidnightApiRequestOptions, MidnightApiSlippage, MidnightApiTake, MidnightApiTakeableOffersResult, ValidateMempoolItemsParams, ValidateMempoolPayloadParams, } from "./types.js";
3
3
  /**
4
4
  * Midnight API client and stateless helper surface for books and mempool data.
5
5
  *
6
- * Static methods use `https://api.morpho.org/v1/midnight` by default and accept
6
+ * Static methods use `https://api.morpho.org/v0/midnight` by default and accept
7
7
  * per-call configuration. Instances keep shared `baseUrl`, `fetch`, and request
8
8
  * options for integrations that make repeated calls.
9
9
  * Caller input and successful JSON output shapes are trusted at runtime;
@@ -18,7 +18,7 @@ export type { FetchBookParams, FetchBookPriceLevelsParams, FetchBookQuoteParams,
18
18
  * payload: "0x0100000000",
19
19
  * });
20
20
  *
21
- * const api = new MidnightApi("https://api.morpho.org/v1/midnight");
21
+ * const api = new MidnightApi("https://api.morpho.org/v0/midnight");
22
22
  * const configured = await api.validateMempoolPayload({
23
23
  * chainId: 8453,
24
24
  * payload: "0x0100000000",
@@ -42,7 +42,7 @@ export declare class MidnightApi {
42
42
  * import { MidnightApi } from "@morpho-org/midnight-sdk/api";
43
43
  *
44
44
  * const api = new MidnightApi({
45
- * baseUrl: "https://api.morpho.org/v1/midnight",
45
+ * baseUrl: "https://api.morpho.org/v0/midnight",
46
46
  * });
47
47
  * console.log(api);
48
48
  * ```
@@ -216,9 +216,9 @@ export declare class MidnightApi {
216
216
  * Validates an encoded Midnight mempool payload against API policy.
217
217
  *
218
218
  * Use when an integration already has encoded payload bytes and wants API
219
- * feedback before publishing those bytes onchain. Normal SDK maker flows
220
- * should call `Tree.mempoolValidate` before ratification instead of
221
- * validating again after `Payload.encode`.
219
+ * feedback before publishing those bytes onchain. Normal SDK maker flows can
220
+ * call `Tree.mempoolValidate` before ratification, or pass ratification
221
+ * inputs to that helper when validating final payload bytes.
222
222
  *
223
223
  * Sends `POST /mempool/validate` to the Midnight API. Does not read onchain RPC state.
224
224
  *
@@ -247,9 +247,10 @@ export declare class MidnightApi {
247
247
  * Encodes SDK-native payload items and validates them against API policy.
248
248
  *
249
249
  * Use when an integration already has payload-ready items but not encoded
250
- * payload bytes. Normal SDK maker flows should call `Tree.mempoolValidate`
251
- * before ratification. This helper owns the temporary payload encoding for
252
- * validation only.
250
+ * payload bytes. Normal SDK maker flows can call `Tree.mempoolValidate`
251
+ * before ratification, or pass ratification inputs to that helper when
252
+ * validating final payload bytes. This helper owns the temporary payload
253
+ * encoding for validation only.
253
254
  *
254
255
  * Encodes `params.items`, then sends `POST /mempool/validate` to the Midnight API. Does not read onchain RPC state.
255
256
  *
@@ -260,7 +261,7 @@ export declare class MidnightApi {
260
261
  * @param params.fetch - Optional fetch implementation override.
261
262
  * @param params.request - Optional fetch options forwarded to this request.
262
263
  * @returns API issues and `valid` summary.
263
- * @throws {Payload.DecodeError} when item encoding fails.
264
+ * @throws {PayloadDecodeError} when item encoding fails.
264
265
  * @throws {MidnightApiError} when the API returns a non-2xx response.
265
266
  * @throws {InvalidMidnightApiResponseError} when the API returns malformed success JSON.
266
267
  * @example
@@ -271,12 +272,14 @@ export declare class MidnightApi {
271
272
  *
272
273
  * const offer = Offer.create({
273
274
  * market: {
275
+ * chainId: 8453,
276
+ * midnight: "0x0000000000000000000000000000000000001000",
274
277
  * loanToken: "0x0000000000000000000000000000000000006000",
275
278
  * collateralParams: [
276
279
  * {
277
280
  * token: "0x0000000000000000000000000000000000007000",
278
281
  * lltv: 770000000000000000n,
279
- * maxLif: 1061007957559681697n,
282
+ * liquidationCursor: 250000000000000000n,
280
283
  * oracle: "0x0000000000000000000000000000000000008000",
281
284
  * },
282
285
  * ],
@@ -479,8 +482,9 @@ export declare class MidnightApi {
479
482
  * Validates payload-ready items with this client's configuration.
480
483
  *
481
484
  * Use when an integration already has payload-ready items but not encoded
482
- * payload bytes. Normal SDK maker flows should call `Tree.mempoolValidate`
483
- * before ratification.
485
+ * payload bytes. Normal SDK maker flows can call `Tree.mempoolValidate`
486
+ * before ratification, or pass ratification inputs to that helper when
487
+ * validating final payload bytes.
484
488
  *
485
489
  * Encodes `params.items`, then sends `POST /mempool/validate` to the Midnight API using this client's configuration. Does not read onchain RPC state.
486
490
  *
@@ -488,7 +492,7 @@ export declare class MidnightApi {
488
492
  * @param params.items - SDK-native payload items to encode before API validation.
489
493
  * @param params.timestamp - Optional ISO-8601 timestamp or `Date` selecting the API policy snapshot.
490
494
  * @returns API validation result.
491
- * @throws {Payload.DecodeError} when item encoding fails.
495
+ * @throws {PayloadDecodeError} when item encoding fails.
492
496
  * @throws {MidnightApiError} when the API returns a non-2xx response.
493
497
  * @throws {InvalidMidnightApiResponseError} when the API returns malformed success JSON.
494
498
  * @example
@@ -500,12 +504,14 @@ export declare class MidnightApi {
500
504
  * const api = new MidnightApi();
501
505
  * const offer = Offer.create({
502
506
  * market: {
507
+ * chainId: 8453,
508
+ * midnight: "0x0000000000000000000000000000000000001000",
503
509
  * loanToken: "0x0000000000000000000000000000000000006000",
504
510
  * collateralParams: [
505
511
  * {
506
512
  * token: "0x0000000000000000000000000000000000007000",
507
513
  * lltv: 770000000000000000n,
508
- * maxLif: 1061007957559681697n,
514
+ * liquidationCursor: 250000000000000000n,
509
515
  * oracle: "0x0000000000000000000000000000000000008000",
510
516
  * },
511
517
  * ],
@@ -1,12 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MidnightApi = void 0;
4
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
5
+ const errors_js_1 = require("../errors.js");
6
+ const index_js_1 = require("../math/index.js");
4
7
  const Payload_js_1 = require("../signatures/Payload.js");
5
8
  const helpers_js_1 = require("./helpers.js");
6
9
  /**
7
10
  * Midnight API client and stateless helper surface for books and mempool data.
8
11
  *
9
- * Static methods use `https://api.morpho.org/v1/midnight` by default and accept
12
+ * Static methods use `https://api.morpho.org/v0/midnight` by default and accept
10
13
  * per-call configuration. Instances keep shared `baseUrl`, `fetch`, and request
11
14
  * options for integrations that make repeated calls.
12
15
  * Caller input and successful JSON output shapes are trusted at runtime;
@@ -21,7 +24,7 @@ const helpers_js_1 = require("./helpers.js");
21
24
  * payload: "0x0100000000",
22
25
  * });
23
26
  *
24
- * const api = new MidnightApi("https://api.morpho.org/v1/midnight");
27
+ * const api = new MidnightApi("https://api.morpho.org/v0/midnight");
25
28
  * const configured = await api.validateMempoolPayload({
26
29
  * chainId: 8453,
27
30
  * payload: "0x0100000000",
@@ -45,7 +48,7 @@ class MidnightApi {
45
48
  * import { MidnightApi } from "@morpho-org/midnight-sdk/api";
46
49
  *
47
50
  * const api = new MidnightApi({
48
- * baseUrl: "https://api.morpho.org/v1/midnight",
51
+ * baseUrl: "https://api.morpho.org/v0/midnight",
49
52
  * });
50
53
  * console.log(api);
51
54
  * ```
@@ -220,7 +223,10 @@ class MidnightApi {
220
223
  }),
221
224
  });
222
225
  return {
223
- data: response.data.map(helpers_js_1.mapTakeableOffer),
226
+ data: (0, helpers_js_1.mapBoundTakeableOffers)(response.data, {
227
+ marketId: input.marketId,
228
+ side: input.side,
229
+ }),
224
230
  };
225
231
  }
226
232
  /**
@@ -270,7 +276,61 @@ class MidnightApi {
270
276
  assets: input.assets,
271
277
  },
272
278
  });
273
- const takeableOffers = response.data.takeable_offers.map(helpers_js_1.mapTakeableOffer);
279
+ const takeableOffers = (0, helpers_js_1.mapBoundTakeableOffers)(response.data.takeable_offers, {
280
+ marketId: input.marketId,
281
+ side: input.side,
282
+ });
283
+ const averageWorstPrice = "averageWorstPrice" in input && input.averageWorstPrice != null
284
+ ? input.averageWorstPrice
285
+ : "slippage" in input && input.slippage != null
286
+ ? response.data.average_worst_price
287
+ : undefined;
288
+ if (averageWorstPrice != null) {
289
+ const guard = BigInt(averageWorstPrice);
290
+ let filledUnits = 0n;
291
+ let weightedPrice = 0n;
292
+ if ("units" in input && input.units != null) {
293
+ let remainingUnits = BigInt(input.units);
294
+ for (const take of takeableOffers) {
295
+ if (remainingUnits === 0n)
296
+ break;
297
+ const price = index_js_1.TickLib.tickToPrice(take.offer.tick);
298
+ const filled = take.units < remainingUnits ? take.units : remainingUnits;
299
+ filledUnits += filled;
300
+ weightedPrice += filled * price;
301
+ remainingUnits -= filled;
302
+ }
303
+ }
304
+ else {
305
+ let remainingAssets = BigInt(input.assets);
306
+ for (const take of takeableOffers) {
307
+ if (remainingAssets === 0n)
308
+ break;
309
+ const price = index_js_1.TickLib.tickToPrice(take.offer.tick);
310
+ const takeAssets = input.side === "asks"
311
+ ? morpho_ts_1.MathLib.mulDivUp(take.units, price, morpho_ts_1.MathLib.WAD)
312
+ : morpho_ts_1.MathLib.mulDivDown(take.units, price, morpho_ts_1.MathLib.WAD);
313
+ if (takeAssets === 0n)
314
+ continue;
315
+ const fillsEntireTake = takeAssets <= remainingAssets;
316
+ const filled = fillsEntireTake
317
+ ? take.units
318
+ : morpho_ts_1.MathLib.mulDiv(remainingAssets, morpho_ts_1.MathLib.WAD, price, input.side === "asks" ? "Down" : "Up");
319
+ if (filled === 0n)
320
+ continue;
321
+ filledUnits += filled;
322
+ weightedPrice += filled * price;
323
+ remainingAssets = fillsEntireTake ? remainingAssets - takeAssets : 0n;
324
+ }
325
+ }
326
+ if (filledUnits > 0n) {
327
+ const averagePrice = morpho_ts_1.MathLib.mulDivDown(weightedPrice, 1n, filledUnits);
328
+ const violatesGuard = input.side === "asks" ? averagePrice > guard : averagePrice < guard;
329
+ if (violatesGuard) {
330
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API quote takeable offers imply average price "${averagePrice}" outside average_worst_price guard "${guard}".`);
331
+ }
332
+ }
333
+ }
274
334
  return {
275
335
  data: {
276
336
  averageBestPrice: response.data.average_best_price,
@@ -323,16 +383,20 @@ class MidnightApi {
323
383
  });
324
384
  return {
325
385
  cursor: response.cursor,
326
- data: response.data.map(helpers_js_1.mapTakeableOffer),
386
+ data: (0, helpers_js_1.mapBoundTakeableOffers)(response.data, {
387
+ maker: input.maker,
388
+ marketIds: input.marketIds,
389
+ groups: input.groups,
390
+ }),
327
391
  };
328
392
  }
329
393
  /**
330
394
  * Validates an encoded Midnight mempool payload against API policy.
331
395
  *
332
396
  * Use when an integration already has encoded payload bytes and wants API
333
- * feedback before publishing those bytes onchain. Normal SDK maker flows
334
- * should call `Tree.mempoolValidate` before ratification instead of
335
- * validating again after `Payload.encode`.
397
+ * feedback before publishing those bytes onchain. Normal SDK maker flows can
398
+ * call `Tree.mempoolValidate` before ratification, or pass ratification
399
+ * inputs to that helper when validating final payload bytes.
336
400
  *
337
401
  * Sends `POST /mempool/validate` to the Midnight API. Does not read onchain RPC state.
338
402
  *
@@ -376,9 +440,10 @@ class MidnightApi {
376
440
  * Encodes SDK-native payload items and validates them against API policy.
377
441
  *
378
442
  * Use when an integration already has payload-ready items but not encoded
379
- * payload bytes. Normal SDK maker flows should call `Tree.mempoolValidate`
380
- * before ratification. This helper owns the temporary payload encoding for
381
- * validation only.
443
+ * payload bytes. Normal SDK maker flows can call `Tree.mempoolValidate`
444
+ * before ratification, or pass ratification inputs to that helper when
445
+ * validating final payload bytes. This helper owns the temporary payload
446
+ * encoding for validation only.
382
447
  *
383
448
  * Encodes `params.items`, then sends `POST /mempool/validate` to the Midnight API. Does not read onchain RPC state.
384
449
  *
@@ -389,7 +454,7 @@ class MidnightApi {
389
454
  * @param params.fetch - Optional fetch implementation override.
390
455
  * @param params.request - Optional fetch options forwarded to this request.
391
456
  * @returns API issues and `valid` summary.
392
- * @throws {Payload.DecodeError} when item encoding fails.
457
+ * @throws {PayloadDecodeError} when item encoding fails.
393
458
  * @throws {MidnightApiError} when the API returns a non-2xx response.
394
459
  * @throws {InvalidMidnightApiResponseError} when the API returns malformed success JSON.
395
460
  * @example
@@ -400,12 +465,14 @@ class MidnightApi {
400
465
  *
401
466
  * const offer = Offer.create({
402
467
  * market: {
468
+ * chainId: 8453,
469
+ * midnight: "0x0000000000000000000000000000000000001000",
403
470
  * loanToken: "0x0000000000000000000000000000000000006000",
404
471
  * collateralParams: [
405
472
  * {
406
473
  * token: "0x0000000000000000000000000000000000007000",
407
474
  * lltv: 770000000000000000n,
408
- * maxLif: 1061007957559681697n,
475
+ * liquidationCursor: 250000000000000000n,
409
476
  * oracle: "0x0000000000000000000000000000000000008000",
410
477
  * },
411
478
  * ],
@@ -431,7 +498,7 @@ class MidnightApi {
431
498
  */
432
499
  static async validateMempoolItems(params) {
433
500
  const input = params;
434
- const payload = await (0, Payload_js_1.encode)(input.items);
501
+ const payload = await Payload_js_1.Payload.encode(input.items);
435
502
  return MidnightApi.validateMempoolPayload({
436
503
  baseUrl: input.baseUrl,
437
504
  fetch: input.fetch,
@@ -654,8 +721,9 @@ class MidnightApi {
654
721
  * Validates payload-ready items with this client's configuration.
655
722
  *
656
723
  * Use when an integration already has payload-ready items but not encoded
657
- * payload bytes. Normal SDK maker flows should call `Tree.mempoolValidate`
658
- * before ratification.
724
+ * payload bytes. Normal SDK maker flows can call `Tree.mempoolValidate`
725
+ * before ratification, or pass ratification inputs to that helper when
726
+ * validating final payload bytes.
659
727
  *
660
728
  * Encodes `params.items`, then sends `POST /mempool/validate` to the Midnight API using this client's configuration. Does not read onchain RPC state.
661
729
  *
@@ -663,7 +731,7 @@ class MidnightApi {
663
731
  * @param params.items - SDK-native payload items to encode before API validation.
664
732
  * @param params.timestamp - Optional ISO-8601 timestamp or `Date` selecting the API policy snapshot.
665
733
  * @returns API validation result.
666
- * @throws {Payload.DecodeError} when item encoding fails.
734
+ * @throws {PayloadDecodeError} when item encoding fails.
667
735
  * @throws {MidnightApiError} when the API returns a non-2xx response.
668
736
  * @throws {InvalidMidnightApiResponseError} when the API returns malformed success JSON.
669
737
  * @example
@@ -675,12 +743,14 @@ class MidnightApi {
675
743
  * const api = new MidnightApi();
676
744
  * const offer = Offer.create({
677
745
  * market: {
746
+ * chainId: 8453,
747
+ * midnight: "0x0000000000000000000000000000000000001000",
678
748
  * loanToken: "0x0000000000000000000000000000000000006000",
679
749
  * collateralParams: [
680
750
  * {
681
751
  * token: "0x0000000000000000000000000000000000007000",
682
752
  * lltv: 770000000000000000n,
683
- * maxLif: 1061007957559681697n,
753
+ * liquidationCursor: 250000000000000000n,
684
754
  * oracle: "0x0000000000000000000000000000000000008000",
685
755
  * },
686
756
  * ],
@@ -1,4 +1,4 @@
1
- import type { Hash } from "viem";
1
+ import { type Address, type Hash } from "viem";
2
2
  import type { ApiBookMarketResponse, ApiCollateralResponse, ApiPriceLevelResponse, ApiRequestParams, ApiTakeableOfferResponse, MempoolPayloadValidationResult, MidnightApiBookMarket, MidnightApiBookSide, MidnightApiCollateral, MidnightApiPriceLevel, MidnightApiTake } from "./types.js";
3
3
  /** @internal Sends one Midnight API request and maps non-2xx responses to SDK errors. */
4
4
  export declare function requestMidnightApi<Response = unknown>(params: ApiRequestParams): Promise<Response>;
@@ -16,5 +16,15 @@ export declare function mapCollateral(collateral: ApiCollateralResponse): Midnig
16
16
  export declare function mapPriceLevel(level: ApiPriceLevelResponse): MidnightApiPriceLevel;
17
17
  /** @internal Maps a takeable-offer API payload to the SDK response shape. */
18
18
  export declare function mapTakeableOffer(takeableOffer: ApiTakeableOfferResponse): MidnightApiTake;
19
+ /** @internal API response context required for a takeable offer to be executable for the caller's request. */
20
+ export interface TakeableOfferContext {
21
+ readonly marketId?: Hash;
22
+ readonly side?: MidnightApiBookSide;
23
+ readonly maker?: Address;
24
+ readonly marketIds?: readonly Hash[];
25
+ readonly groups?: readonly Hash[];
26
+ }
27
+ /** @internal Maps, validates, and best-price-sorts API takeable offers. */
28
+ export declare function mapBoundTakeableOffers(takeableOffers: readonly ApiTakeableOfferResponse[], context: TakeableOfferContext): MidnightApiTake[];
19
29
  /** @internal Parses the mempool validation response envelope. */
20
30
  export declare function parseValidationResponse(response: unknown): MempoolPayloadValidationResult;
@@ -6,13 +6,16 @@ exports.mapBookMarket = mapBookMarket;
6
6
  exports.mapCollateral = mapCollateral;
7
7
  exports.mapPriceLevel = mapPriceLevel;
8
8
  exports.mapTakeableOffer = mapTakeableOffer;
9
+ exports.mapBoundTakeableOffers = mapBoundTakeableOffers;
9
10
  exports.parseValidationResponse = parseValidationResponse;
10
11
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
12
+ const viem_1 = require("viem");
11
13
  const errors_js_1 = require("../errors.js");
12
- const DEFAULT_MIDNIGHT_API_URL = new URL("/v1/midnight", morpho_ts_1.BLUE_API_BASE_URL);
14
+ const index_js_1 = require("../market/index.js");
15
+ const DEFAULT_MIDNIGHT_API_URL = new URL("/v0/midnight", morpho_ts_1.BLUE_API_BASE_URL);
13
16
  // Keep this literal in source so the browser ESM build does not import package.json
14
17
  // through Node-only createRequire/module shims.
15
- const MIDNIGHT_SDK_VERSION = "0.1.0";
18
+ const MIDNIGHT_SDK_VERSION = "1.0.1";
16
19
  /** @internal Sends one Midnight API request and maps non-2xx responses to SDK errors. */
17
20
  async function requestMidnightApi(params) {
18
21
  const baseUrl = new URL(params.baseUrl ?? DEFAULT_MIDNIGHT_API_URL);
@@ -92,6 +95,7 @@ function mapBookMarket(book) {
92
95
  return {
93
96
  marketId: book.market_id,
94
97
  chainId: book.chain_id,
98
+ midnight: book.midnight,
95
99
  loanToken: book.loan_token,
96
100
  collaterals: book.collaterals.map(mapCollateral),
97
101
  maturity: book.maturity,
@@ -107,7 +111,7 @@ function mapCollateral(collateral) {
107
111
  return {
108
112
  token: collateral.token,
109
113
  lltv: collateral.lltv,
110
- maxLif: collateral.max_lif,
114
+ liquidationCursor: collateral.liquidation_cursor,
111
115
  oracle: collateral.oracle,
112
116
  };
113
117
  }
@@ -129,11 +133,13 @@ function mapTakeableOffer(takeableOffer) {
129
133
  units: BigInt(takeableOffer.units),
130
134
  offer: {
131
135
  market: {
136
+ chainId: BigInt(offer.market.chain_id),
137
+ midnight: offer.market.midnight,
132
138
  loanToken: offer.market.loan_token,
133
139
  collateralParams: offer.market.collaterals.map((collateral) => ({
134
140
  token: collateral.token,
135
141
  lltv: BigInt(collateral.lltv),
136
- maxLif: BigInt(collateral.max_lif),
142
+ liquidationCursor: BigInt(collateral.liquidation_cursor),
137
143
  oracle: collateral.oracle,
138
144
  })),
139
145
  maturity: BigInt(offer.market.maturity),
@@ -159,6 +165,50 @@ function mapTakeableOffer(takeableOffer) {
159
165
  ratifierData: takeableOffer.ratifier_data,
160
166
  };
161
167
  }
168
+ /** @internal Maps, validates, and best-price-sorts API takeable offers. */
169
+ function mapBoundTakeableOffers(takeableOffers, context) {
170
+ const mapped = takeableOffers.map((takeableOffer) => {
171
+ const take = mapTakeableOffer(takeableOffer);
172
+ const embeddedMarketId = index_js_1.MarketUtils.toId(take.offer.market);
173
+ if (!(0, morpho_ts_1.isHexEqual)(embeddedMarketId, take.marketId)) {
174
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API takeable offer market_id "${take.marketId}" does not match embedded offer market "${embeddedMarketId}".`);
175
+ }
176
+ if (context.marketId != null &&
177
+ !(0, morpho_ts_1.isHexEqual)(take.marketId, context.marketId)) {
178
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API takeable offer market_id "${take.marketId}" does not match requested market "${context.marketId}".`);
179
+ }
180
+ if (context.marketIds != null &&
181
+ context.marketIds.length > 0 &&
182
+ !context.marketIds.some((marketId) => (0, morpho_ts_1.isHexEqual)(marketId, take.marketId))) {
183
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API takeable offer market_id "${take.marketId}" is outside the requested market_ids filter.`);
184
+ }
185
+ if (context.side != null) {
186
+ const expectedBuy = context.side === "bids";
187
+ if (take.offer.buy !== expectedBuy) {
188
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API ${context.side} takeable offer returned offer.buy "${take.offer.buy}".`);
189
+ }
190
+ }
191
+ if (context.maker != null &&
192
+ !(0, viem_1.isAddressEqual)(take.offer.maker, context.maker)) {
193
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API takeable offer maker "${take.offer.maker}" does not match requested maker "${context.maker}".`);
194
+ }
195
+ if (context.groups != null &&
196
+ context.groups.length > 0 &&
197
+ !context.groups.some((group) => (0, morpho_ts_1.isHexEqual)(group, take.offer.group))) {
198
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API takeable offer group "${take.offer.group}" is outside the requested groups filter.`);
199
+ }
200
+ return take;
201
+ });
202
+ if (context.side == null)
203
+ return mapped;
204
+ return [...mapped].sort((a, b) => {
205
+ if (a.offer.tick === b.offer.tick)
206
+ return 0;
207
+ if (context.side === "asks")
208
+ return a.offer.tick < b.offer.tick ? -1 : 1;
209
+ return a.offer.tick > b.offer.tick ? -1 : 1;
210
+ });
211
+ }
162
212
  /** @internal Parses the mempool validation response envelope. */
163
213
  function parseValidationResponse(response) {
164
214
  const parsedResponse = requireRecord(response, "validation response");
@@ -1,7 +1,7 @@
1
1
  import type { BigIntish } from "@morpho-org/morpho-ts";
2
2
  import type { Address, Hash, Hex } from "viem";
3
3
  import type { OfferStruct } from "../offers/Offer.js";
4
- import type { Item as MidnightPayloadItem } from "../signatures/Payload.js";
4
+ import type { Payload } from "../signatures/Payload.js";
5
5
  /**
6
6
  * Fetch implementation used by Midnight API helpers.
7
7
  */
@@ -17,7 +17,7 @@ export type MidnightApiRequestOptions = Omit<RequestInit, "method" | "body">;
17
17
  * Shared configuration for Midnight API calls.
18
18
  */
19
19
  export interface MidnightApiConfig {
20
- /** Midnight API base URL. Defaults to `https://api.morpho.org/v1/midnight`. */
20
+ /** Midnight API base URL. Defaults to `https://api.morpho.org/v0/midnight`. */
21
21
  readonly baseUrl?: string | URL;
22
22
  /** Fetch implementation. Defaults to the global `fetch`. */
23
23
  readonly fetch?: MidnightApiFetch;
@@ -70,7 +70,7 @@ export interface ValidateMempoolItemsParams extends MidnightApiConfig {
70
70
  /** Chain id whose API policy should validate the payload. */
71
71
  readonly chainId: number;
72
72
  /** SDK-native payload items to encode before API validation. */
73
- readonly items: readonly MidnightPayloadItem[];
73
+ readonly items: readonly Payload.Item[];
74
74
  /** Optional ISO-8601 timestamp or `Date` selecting the API policy snapshot. */
75
75
  readonly timestamp?: string | Date;
76
76
  }
@@ -209,6 +209,28 @@ export interface MempoolPayloadValidationResult {
209
209
  /** Payload-level API issues. */
210
210
  readonly issues: readonly MempoolPayloadValidationIssue[];
211
211
  }
212
+ /**
213
+ * Successful Midnight mempool validation result.
214
+ *
215
+ * Returned by `Tree.mempoolValidate` and `TreeUtils.mempoolValidate`, which
216
+ * throw `MidnightMempoolValidationError` instead of returning unsuccessful API
217
+ * validation results.
218
+ *
219
+ * @example
220
+ * ```ts
221
+ * import type { MempoolPayloadValidationSuccess } from "@morpho-org/midnight-sdk/api";
222
+ *
223
+ * const result: MempoolPayloadValidationSuccess = {
224
+ * valid: true,
225
+ * issues: [],
226
+ * };
227
+ * console.log(result.valid);
228
+ * ```
229
+ */
230
+ export type MempoolPayloadValidationSuccess = MempoolPayloadValidationResult & {
231
+ /** Successful tree validation always has `valid: true`. */
232
+ readonly valid: true;
233
+ };
212
234
  /**
213
235
  * Collateral metadata returned by Midnight API book routes.
214
236
  */
@@ -217,8 +239,8 @@ export interface MidnightApiCollateral {
217
239
  readonly token: Address;
218
240
  /** WAD-scaled liquidation loan-to-value. */
219
241
  readonly lltv: string;
220
- /** WAD-scaled maximum liquidation incentive factor. */
221
- readonly maxLif: string;
242
+ /** WAD-scaled liquidation cursor used to compute the maximum liquidation incentive factor. */
243
+ readonly liquidationCursor: string;
222
244
  /** Oracle address used to price this collateral. */
223
245
  readonly oracle: Address;
224
246
  }
@@ -245,6 +267,8 @@ export interface MidnightApiBookMarket {
245
267
  readonly marketId: Hash;
246
268
  /** Chain id the market lives on. */
247
269
  readonly chainId: number;
270
+ /** Core Midnight contract address for the market chain. */
271
+ readonly midnight: Address;
248
272
  /** Loan token address. */
249
273
  readonly loanToken: Address;
250
274
  /** Collateral definitions for the market. */
@@ -282,9 +306,8 @@ export interface MidnightApiBookResult {
282
306
  * ABI-ready take returned by Midnight API book and quote routes.
283
307
  *
284
308
  * This shape matches the Midnight periphery `Take` tuple. Pass `offer`,
285
- * `ratifierData`, and `units` directly to `IMidnight.take`, or pass the object
286
- * in the `takes` array of a target-aware `MidnightBundles` call. `marketId` is
287
- * API metadata and is ignored by ABI encoders.
309
+ * `ratifierData`, and `units` directly to `IMidnight.take`. `marketId` is API
310
+ * metadata and is ignored by ABI encoders.
288
311
  */
289
312
  export interface MidnightApiTake {
290
313
  /** Market id the offer belongs to. */
@@ -361,7 +384,7 @@ export type ApiRequestParams = MidnightApiConfig & {
361
384
  export type ApiCollateralResponse = {
362
385
  readonly token: Address;
363
386
  readonly lltv: string;
364
- readonly max_lif: string;
387
+ readonly liquidation_cursor: string;
365
388
  readonly oracle: Address;
366
389
  };
367
390
  /** @internal Price-level response shape returned by the API. */
@@ -376,6 +399,7 @@ export type ApiPriceLevelResponse = {
376
399
  export type ApiBookMarketResponse = {
377
400
  readonly market_id: Hash;
378
401
  readonly chain_id: number;
402
+ readonly midnight: Address;
379
403
  readonly loan_token: Address;
380
404
  readonly collaterals: readonly ApiCollateralResponse[];
381
405
  readonly maturity: number;
@@ -400,6 +424,8 @@ export type ApiPriceLevelsResponse = {
400
424
  };
401
425
  /** @internal Offer market response shape returned by the API. */
402
426
  export type ApiOfferMarketResponse = {
427
+ readonly chain_id: number;
428
+ readonly midnight: Address;
403
429
  readonly loan_token: Address;
404
430
  readonly collaterals: readonly ApiCollateralResponse[];
405
431
  readonly maturity: number;
@@ -101,27 +101,28 @@ export declare const MAX_SETTLEMENT_FEES: readonly [14000000000000n, 14000000000
101
101
  */
102
102
  export declare const MAX_CONTINUOUS_FEE = 317097919n;
103
103
  /**
104
- * Low liquidation cursor used by liquidation incentive factor helpers.
104
+ * Maximum value accepted by the uint128 offer cap fields.
105
105
  *
106
106
  * @example
107
107
  * ```ts
108
- * import { LIQUIDATION_CURSOR_LOW } from "@morpho-org/midnight-sdk";
108
+ * import { MAX_OFFER_CAP } from "@morpho-org/midnight-sdk";
109
109
  *
110
- * console.log(LIQUIDATION_CURSOR_LOW);
110
+ * console.log(MAX_OFFER_CAP);
111
111
  * ```
112
112
  */
113
- export declare const LIQUIDATION_CURSOR_LOW = 250000000000000000n;
113
+ export declare const MAX_OFFER_CAP: bigint;
114
114
  /**
115
- * High liquidation cursor from Midnight ConstantsLib.
115
+ * Seconds after maturity over which post-maturity LIF reaches the computed
116
+ * maximum liquidation incentive factor.
116
117
  *
117
118
  * @example
118
119
  * ```ts
119
- * import { LIQUIDATION_CURSOR_HIGH } from "@morpho-org/midnight-sdk";
120
+ * import { TIME_TO_MAX_LIF } from "@morpho-org/midnight-sdk";
120
121
  *
121
- * console.log(LIQUIDATION_CURSOR_HIGH);
122
+ * console.log(TIME_TO_MAX_LIF);
122
123
  * ```
123
124
  */
124
- export declare const LIQUIDATION_CURSOR_HIGH = 500000000000000000n;
125
+ export declare const TIME_TO_MAX_LIF: bigint;
125
126
  /**
126
127
  * HashLib collateral params typehash.
127
128
  *
@@ -132,7 +133,7 @@ export declare const LIQUIDATION_CURSOR_HIGH = 500000000000000000n;
132
133
  * console.log(COLLATERAL_PARAMS_TYPEHASH);
133
134
  * ```
134
135
  */
135
- export declare const COLLATERAL_PARAMS_TYPEHASH = "0xaf44a88eb50ebdbbebd980e5a23045c44f61ece5f80ab708a1bbe8718102e6af";
136
+ export declare const COLLATERAL_PARAMS_TYPEHASH = "0x39ed3f928d24fd00574b1a02aba9c2483abcf5d9a3a366118c9a5aa29885b841";
136
137
  /**
137
138
  * HashLib market typehash.
138
139
  *
@@ -143,7 +144,7 @@ export declare const COLLATERAL_PARAMS_TYPEHASH = "0xaf44a88eb50ebdbbebd980e5a23
143
144
  * console.log(MARKET_TYPEHASH);
144
145
  * ```
145
146
  */
146
- export declare const MARKET_TYPEHASH = "0x358117e98511cc3df97175dca58053b06675b43ad090b0553f8a1eff008b6e2e";
147
+ export declare const MARKET_TYPEHASH = "0x510b3862f3816a109c9340b76972e8a30984246be06e034ae12ed2934220391a";
147
148
  /**
148
149
  * HashLib offer typehash.
149
150
  *
@@ -154,7 +155,7 @@ export declare const MARKET_TYPEHASH = "0x358117e98511cc3df97175dca58053b06675b4
154
155
  * console.log(OFFER_TYPEHASH);
155
156
  * ```
156
157
  */
157
- export declare const OFFER_TYPEHASH = "0x6bd2a06ec6952feb97c3e3b4f7de6c342f12b1ac769d5c91368271af636c85b7";
158
+ export declare const OFFER_TYPEHASH = "0x9905214264a9fb7b6cc1b0e33db7a04687c6e4185a84755d29914314aa9d8906";
158
159
  /**
159
160
  * EcrecoverRatifier EIP-712 domain typehash.
160
161
  *