@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,9 +1,12 @@
1
- import { encode as encodePayload } from "../signatures/Payload.js";
2
- import { buildBookPath, mapBookMarket, mapPriceLevel, mapTakeableOffer, parseValidationResponse, requestMidnightApi, } from "./helpers.js";
1
+ import { MathLib } from "@morpho-org/morpho-ts";
2
+ import { InvalidMidnightApiResponseError } from "../errors.js";
3
+ import { TickLib } from "../math/index.js";
4
+ import { Payload } from "../signatures/Payload.js";
5
+ import { buildBookPath, mapBookMarket, mapBoundTakeableOffers, mapPriceLevel, parseValidationResponse, requestMidnightApi, } from "./helpers.js";
3
6
  /**
4
7
  * Midnight API client and stateless helper surface for books and mempool data.
5
8
  *
6
- * Static methods use `https://api.morpho.org/v1/midnight` by default and accept
9
+ * Static methods use `https://api.morpho.org/v0/midnight` by default and accept
7
10
  * per-call configuration. Instances keep shared `baseUrl`, `fetch`, and request
8
11
  * options for integrations that make repeated calls.
9
12
  * Caller input and successful JSON output shapes are trusted at runtime;
@@ -18,7 +21,7 @@ import { buildBookPath, mapBookMarket, mapPriceLevel, mapTakeableOffer, parseVal
18
21
  * payload: "0x0100000000",
19
22
  * });
20
23
  *
21
- * const api = new MidnightApi("https://api.morpho.org/v1/midnight");
24
+ * const api = new MidnightApi("https://api.morpho.org/v0/midnight");
22
25
  * const configured = await api.validateMempoolPayload({
23
26
  * chainId: 8453,
24
27
  * payload: "0x0100000000",
@@ -42,7 +45,7 @@ export class MidnightApi {
42
45
  * import { MidnightApi } from "@morpho-org/midnight-sdk/api";
43
46
  *
44
47
  * const api = new MidnightApi({
45
- * baseUrl: "https://api.morpho.org/v1/midnight",
48
+ * baseUrl: "https://api.morpho.org/v0/midnight",
46
49
  * });
47
50
  * console.log(api);
48
51
  * ```
@@ -217,7 +220,10 @@ export class MidnightApi {
217
220
  }),
218
221
  });
219
222
  return {
220
- data: response.data.map(mapTakeableOffer),
223
+ data: mapBoundTakeableOffers(response.data, {
224
+ marketId: input.marketId,
225
+ side: input.side,
226
+ }),
221
227
  };
222
228
  }
223
229
  /**
@@ -267,7 +273,61 @@ export class MidnightApi {
267
273
  assets: input.assets,
268
274
  },
269
275
  });
270
- const takeableOffers = response.data.takeable_offers.map(mapTakeableOffer);
276
+ const takeableOffers = mapBoundTakeableOffers(response.data.takeable_offers, {
277
+ marketId: input.marketId,
278
+ side: input.side,
279
+ });
280
+ const averageWorstPrice = "averageWorstPrice" in input && input.averageWorstPrice != null
281
+ ? input.averageWorstPrice
282
+ : "slippage" in input && input.slippage != null
283
+ ? response.data.average_worst_price
284
+ : undefined;
285
+ if (averageWorstPrice != null) {
286
+ const guard = BigInt(averageWorstPrice);
287
+ let filledUnits = 0n;
288
+ let weightedPrice = 0n;
289
+ if ("units" in input && input.units != null) {
290
+ let remainingUnits = BigInt(input.units);
291
+ for (const take of takeableOffers) {
292
+ if (remainingUnits === 0n)
293
+ break;
294
+ const price = TickLib.tickToPrice(take.offer.tick);
295
+ const filled = take.units < remainingUnits ? take.units : remainingUnits;
296
+ filledUnits += filled;
297
+ weightedPrice += filled * price;
298
+ remainingUnits -= filled;
299
+ }
300
+ }
301
+ else {
302
+ let remainingAssets = BigInt(input.assets);
303
+ for (const take of takeableOffers) {
304
+ if (remainingAssets === 0n)
305
+ break;
306
+ const price = TickLib.tickToPrice(take.offer.tick);
307
+ const takeAssets = input.side === "asks"
308
+ ? MathLib.mulDivUp(take.units, price, MathLib.WAD)
309
+ : MathLib.mulDivDown(take.units, price, MathLib.WAD);
310
+ if (takeAssets === 0n)
311
+ continue;
312
+ const fillsEntireTake = takeAssets <= remainingAssets;
313
+ const filled = fillsEntireTake
314
+ ? take.units
315
+ : MathLib.mulDiv(remainingAssets, MathLib.WAD, price, input.side === "asks" ? "Down" : "Up");
316
+ if (filled === 0n)
317
+ continue;
318
+ filledUnits += filled;
319
+ weightedPrice += filled * price;
320
+ remainingAssets = fillsEntireTake ? remainingAssets - takeAssets : 0n;
321
+ }
322
+ }
323
+ if (filledUnits > 0n) {
324
+ const averagePrice = MathLib.mulDivDown(weightedPrice, 1n, filledUnits);
325
+ const violatesGuard = input.side === "asks" ? averagePrice > guard : averagePrice < guard;
326
+ if (violatesGuard) {
327
+ throw new InvalidMidnightApiResponseError(`Midnight API quote takeable offers imply average price "${averagePrice}" outside average_worst_price guard "${guard}".`);
328
+ }
329
+ }
330
+ }
271
331
  return {
272
332
  data: {
273
333
  averageBestPrice: response.data.average_best_price,
@@ -320,16 +380,20 @@ export class MidnightApi {
320
380
  });
321
381
  return {
322
382
  cursor: response.cursor,
323
- data: response.data.map(mapTakeableOffer),
383
+ data: mapBoundTakeableOffers(response.data, {
384
+ maker: input.maker,
385
+ marketIds: input.marketIds,
386
+ groups: input.groups,
387
+ }),
324
388
  };
325
389
  }
326
390
  /**
327
391
  * Validates an encoded Midnight mempool payload against API policy.
328
392
  *
329
393
  * Use when an integration already has encoded payload bytes and wants API
330
- * feedback before publishing those bytes onchain. Normal SDK maker flows
331
- * should call `Tree.mempoolValidate` before ratification instead of
332
- * validating again after `Payload.encode`.
394
+ * feedback before publishing those bytes onchain. Normal SDK maker flows can
395
+ * call `Tree.mempoolValidate` before ratification, or pass ratification
396
+ * inputs to that helper when validating final payload bytes.
333
397
  *
334
398
  * Sends `POST /mempool/validate` to the Midnight API. Does not read onchain RPC state.
335
399
  *
@@ -373,9 +437,10 @@ export class MidnightApi {
373
437
  * Encodes SDK-native payload items and validates them against API policy.
374
438
  *
375
439
  * Use when an integration already has payload-ready items but not encoded
376
- * payload bytes. Normal SDK maker flows should call `Tree.mempoolValidate`
377
- * before ratification. This helper owns the temporary payload encoding for
378
- * validation only.
440
+ * payload bytes. Normal SDK maker flows can call `Tree.mempoolValidate`
441
+ * before ratification, or pass ratification inputs to that helper when
442
+ * validating final payload bytes. This helper owns the temporary payload
443
+ * encoding for validation only.
379
444
  *
380
445
  * Encodes `params.items`, then sends `POST /mempool/validate` to the Midnight API. Does not read onchain RPC state.
381
446
  *
@@ -386,7 +451,7 @@ export class MidnightApi {
386
451
  * @param params.fetch - Optional fetch implementation override.
387
452
  * @param params.request - Optional fetch options forwarded to this request.
388
453
  * @returns API issues and `valid` summary.
389
- * @throws {Payload.DecodeError} when item encoding fails.
454
+ * @throws {PayloadDecodeError} when item encoding fails.
390
455
  * @throws {MidnightApiError} when the API returns a non-2xx response.
391
456
  * @throws {InvalidMidnightApiResponseError} when the API returns malformed success JSON.
392
457
  * @example
@@ -397,12 +462,14 @@ export class MidnightApi {
397
462
  *
398
463
  * const offer = Offer.create({
399
464
  * market: {
465
+ * chainId: 8453,
466
+ * midnight: "0x0000000000000000000000000000000000001000",
400
467
  * loanToken: "0x0000000000000000000000000000000000006000",
401
468
  * collateralParams: [
402
469
  * {
403
470
  * token: "0x0000000000000000000000000000000000007000",
404
471
  * lltv: 770000000000000000n,
405
- * maxLif: 1061007957559681697n,
472
+ * liquidationCursor: 250000000000000000n,
406
473
  * oracle: "0x0000000000000000000000000000000000008000",
407
474
  * },
408
475
  * ],
@@ -428,7 +495,7 @@ export class MidnightApi {
428
495
  */
429
496
  static async validateMempoolItems(params) {
430
497
  const input = params;
431
- const payload = await encodePayload(input.items);
498
+ const payload = await Payload.encode(input.items);
432
499
  return MidnightApi.validateMempoolPayload({
433
500
  baseUrl: input.baseUrl,
434
501
  fetch: input.fetch,
@@ -651,8 +718,9 @@ export class MidnightApi {
651
718
  * Validates payload-ready items with this client's configuration.
652
719
  *
653
720
  * Use when an integration already has payload-ready items but not encoded
654
- * payload bytes. Normal SDK maker flows should call `Tree.mempoolValidate`
655
- * before ratification.
721
+ * payload bytes. Normal SDK maker flows can call `Tree.mempoolValidate`
722
+ * before ratification, or pass ratification inputs to that helper when
723
+ * validating final payload bytes.
656
724
  *
657
725
  * Encodes `params.items`, then sends `POST /mempool/validate` to the Midnight API using this client's configuration. Does not read onchain RPC state.
658
726
  *
@@ -660,7 +728,7 @@ export class MidnightApi {
660
728
  * @param params.items - SDK-native payload items to encode before API validation.
661
729
  * @param params.timestamp - Optional ISO-8601 timestamp or `Date` selecting the API policy snapshot.
662
730
  * @returns API validation result.
663
- * @throws {Payload.DecodeError} when item encoding fails.
731
+ * @throws {PayloadDecodeError} when item encoding fails.
664
732
  * @throws {MidnightApiError} when the API returns a non-2xx response.
665
733
  * @throws {InvalidMidnightApiResponseError} when the API returns malformed success JSON.
666
734
  * @example
@@ -672,12 +740,14 @@ export class MidnightApi {
672
740
  * const api = new MidnightApi();
673
741
  * const offer = Offer.create({
674
742
  * market: {
743
+ * chainId: 8453,
744
+ * midnight: "0x0000000000000000000000000000000000001000",
675
745
  * loanToken: "0x0000000000000000000000000000000000006000",
676
746
  * collateralParams: [
677
747
  * {
678
748
  * token: "0x0000000000000000000000000000000000007000",
679
749
  * lltv: 770000000000000000n,
680
- * maxLif: 1061007957559681697n,
750
+ * liquidationCursor: 250000000000000000n,
681
751
  * oracle: "0x0000000000000000000000000000000000008000",
682
752
  * },
683
753
  * ],
@@ -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;
@@ -1,9 +1,11 @@
1
- import { BLUE_API_BASE_URL } from "@morpho-org/morpho-ts";
1
+ import { BLUE_API_BASE_URL, isHexEqual } from "@morpho-org/morpho-ts";
2
+ import { isAddressEqual } from "viem";
2
3
  import { InvalidMidnightApiResponseError, MidnightApiError, } from "../errors.js";
3
- const DEFAULT_MIDNIGHT_API_URL = new URL("/v1/midnight", BLUE_API_BASE_URL);
4
+ import { MarketUtils } from "../market/index.js";
5
+ const DEFAULT_MIDNIGHT_API_URL = new URL("/v0/midnight", BLUE_API_BASE_URL);
4
6
  // Keep this literal in source so the browser ESM build does not import package.json
5
7
  // through Node-only createRequire/module shims.
6
- const MIDNIGHT_SDK_VERSION = "0.1.0";
8
+ const MIDNIGHT_SDK_VERSION = "1.0.1";
7
9
  /** @internal Sends one Midnight API request and maps non-2xx responses to SDK errors. */
8
10
  export async function requestMidnightApi(params) {
9
11
  const baseUrl = new URL(params.baseUrl ?? DEFAULT_MIDNIGHT_API_URL);
@@ -83,6 +85,7 @@ export function mapBookMarket(book) {
83
85
  return {
84
86
  marketId: book.market_id,
85
87
  chainId: book.chain_id,
88
+ midnight: book.midnight,
86
89
  loanToken: book.loan_token,
87
90
  collaterals: book.collaterals.map(mapCollateral),
88
91
  maturity: book.maturity,
@@ -98,7 +101,7 @@ export function mapCollateral(collateral) {
98
101
  return {
99
102
  token: collateral.token,
100
103
  lltv: collateral.lltv,
101
- maxLif: collateral.max_lif,
104
+ liquidationCursor: collateral.liquidation_cursor,
102
105
  oracle: collateral.oracle,
103
106
  };
104
107
  }
@@ -120,11 +123,13 @@ export function mapTakeableOffer(takeableOffer) {
120
123
  units: BigInt(takeableOffer.units),
121
124
  offer: {
122
125
  market: {
126
+ chainId: BigInt(offer.market.chain_id),
127
+ midnight: offer.market.midnight,
123
128
  loanToken: offer.market.loan_token,
124
129
  collateralParams: offer.market.collaterals.map((collateral) => ({
125
130
  token: collateral.token,
126
131
  lltv: BigInt(collateral.lltv),
127
- maxLif: BigInt(collateral.max_lif),
132
+ liquidationCursor: BigInt(collateral.liquidation_cursor),
128
133
  oracle: collateral.oracle,
129
134
  })),
130
135
  maturity: BigInt(offer.market.maturity),
@@ -150,6 +155,50 @@ export function mapTakeableOffer(takeableOffer) {
150
155
  ratifierData: takeableOffer.ratifier_data,
151
156
  };
152
157
  }
158
+ /** @internal Maps, validates, and best-price-sorts API takeable offers. */
159
+ export function mapBoundTakeableOffers(takeableOffers, context) {
160
+ const mapped = takeableOffers.map((takeableOffer) => {
161
+ const take = mapTakeableOffer(takeableOffer);
162
+ const embeddedMarketId = MarketUtils.toId(take.offer.market);
163
+ if (!isHexEqual(embeddedMarketId, take.marketId)) {
164
+ throw new InvalidMidnightApiResponseError(`Midnight API takeable offer market_id "${take.marketId}" does not match embedded offer market "${embeddedMarketId}".`);
165
+ }
166
+ if (context.marketId != null &&
167
+ !isHexEqual(take.marketId, context.marketId)) {
168
+ throw new InvalidMidnightApiResponseError(`Midnight API takeable offer market_id "${take.marketId}" does not match requested market "${context.marketId}".`);
169
+ }
170
+ if (context.marketIds != null &&
171
+ context.marketIds.length > 0 &&
172
+ !context.marketIds.some((marketId) => isHexEqual(marketId, take.marketId))) {
173
+ throw new InvalidMidnightApiResponseError(`Midnight API takeable offer market_id "${take.marketId}" is outside the requested market_ids filter.`);
174
+ }
175
+ if (context.side != null) {
176
+ const expectedBuy = context.side === "bids";
177
+ if (take.offer.buy !== expectedBuy) {
178
+ throw new InvalidMidnightApiResponseError(`Midnight API ${context.side} takeable offer returned offer.buy "${take.offer.buy}".`);
179
+ }
180
+ }
181
+ if (context.maker != null &&
182
+ !isAddressEqual(take.offer.maker, context.maker)) {
183
+ throw new InvalidMidnightApiResponseError(`Midnight API takeable offer maker "${take.offer.maker}" does not match requested maker "${context.maker}".`);
184
+ }
185
+ if (context.groups != null &&
186
+ context.groups.length > 0 &&
187
+ !context.groups.some((group) => isHexEqual(group, take.offer.group))) {
188
+ throw new InvalidMidnightApiResponseError(`Midnight API takeable offer group "${take.offer.group}" is outside the requested groups filter.`);
189
+ }
190
+ return take;
191
+ });
192
+ if (context.side == null)
193
+ return mapped;
194
+ return [...mapped].sort((a, b) => {
195
+ if (a.offer.tick === b.offer.tick)
196
+ return 0;
197
+ if (context.side === "asks")
198
+ return a.offer.tick < b.offer.tick ? -1 : 1;
199
+ return a.offer.tick > b.offer.tick ? -1 : 1;
200
+ });
201
+ }
153
202
  /** @internal Parses the mempool validation response envelope. */
154
203
  export function parseValidationResponse(response) {
155
204
  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
  *