@morpho-org/midnight-sdk 2.4.0-next.0 → 2.4.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 (37) hide show
  1. package/lib/cjs/abis.d.ts +382 -0
  2. package/lib/cjs/abis.js +488 -1
  3. package/lib/cjs/api/MidnightApi.d.ts +14 -12
  4. package/lib/cjs/api/MidnightApi.js +35 -25
  5. package/lib/cjs/api/helpers.d.ts +10 -0
  6. package/lib/cjs/api/helpers.js +97 -10
  7. package/lib/cjs/api/types.d.ts +5 -0
  8. package/lib/cjs/api/version.generated.d.ts +1 -1
  9. package/lib/cjs/api/version.generated.js +1 -1
  10. package/lib/cjs/errors.d.ts +27 -13
  11. package/lib/cjs/errors.js +39 -8
  12. package/lib/cjs/offers/Offer.d.ts +3 -0
  13. package/lib/cjs/offers/Offer.js +3 -0
  14. package/lib/cjs/offers/OfferUtils.d.ts +6 -0
  15. package/lib/cjs/offers/OfferUtils.js +14 -0
  16. package/lib/cjs/position/Position.d.ts +3 -0
  17. package/lib/cjs/position/Position.js +13 -0
  18. package/lib/cjs/position/PositionUtils.js +35 -11
  19. package/lib/esm/abis.d.ts +382 -0
  20. package/lib/esm/abis.js +487 -0
  21. package/lib/esm/api/MidnightApi.d.ts +14 -12
  22. package/lib/esm/api/MidnightApi.js +36 -26
  23. package/lib/esm/api/helpers.d.ts +10 -0
  24. package/lib/esm/api/helpers.js +91 -8
  25. package/lib/esm/api/types.d.ts +5 -0
  26. package/lib/esm/api/version.generated.d.ts +1 -1
  27. package/lib/esm/api/version.generated.js +1 -1
  28. package/lib/esm/errors.d.ts +27 -13
  29. package/lib/esm/errors.js +36 -8
  30. package/lib/esm/offers/Offer.d.ts +3 -0
  31. package/lib/esm/offers/Offer.js +3 -0
  32. package/lib/esm/offers/OfferUtils.d.ts +6 -0
  33. package/lib/esm/offers/OfferUtils.js +15 -1
  34. package/lib/esm/position/Position.d.ts +3 -0
  35. package/lib/esm/position/Position.js +14 -1
  36. package/lib/esm/position/PositionUtils.js +36 -12
  37. package/package.json +4 -4
@@ -2,7 +2,7 @@ import { assertNonNegative, MathLib } from "@morpho-org/morpho-ts";
2
2
  import { InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, } from "../errors.js";
3
3
  import { TakeAmountsLib } from "../math/index.js";
4
4
  import { Payload } from "../signatures/Payload.js";
5
- import { buildBookPath, mapBoundBookMarket, mapBoundBooks, mapBoundTakeableOffers, mapPriceLevels, parseValidationResponse, requestMidnightApi, } from "./helpers.js";
5
+ import { buildBookPath, mapBoundBookMarket, mapBoundBooks, mapBoundTakeableOffers, mapPriceLevels, parseResponseCursor, parseValidationResponse, requestMidnightApi, requireBigIntString, requireObject, requireResponseEnvelope, } from "./helpers.js";
6
6
  export { MempoolPayloadValidationRule } from "./types.js";
7
7
  /**
8
8
  * Midnight API client and stateless helper surface for books and mempool data.
@@ -75,7 +75,7 @@ export class MidnightApi {
75
75
  * @param params.request - Optional fetch options forwarded to this request.
76
76
  * @returns Paginated books mapped to SDK camelCase fields, with each book's price levels sorted best first (asks ascending tick, bids descending tick).
77
77
  * @throws {MidnightApiError} when the API returns a non-2xx response.
78
- * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON, when a returned book's `market_id` does not match, or cannot be derived from, its own market params, or when a returned book falls outside the supplied `marketIds`, `chainIds`, `loanTokens`, `collateralTokens`, or `maturities` filters.
78
+ * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope, cursor or price levels are malformed, when a returned book's `market_id` does not match, or cannot be derived from, its own market params, or when a returned book falls outside the supplied `marketIds`, `chainIds`, `loanTokens`, `collateralTokens`, or `maturities` filters.
79
79
  * @example
80
80
  * ```ts
81
81
  * import { MidnightApi } from "@morpho-org/midnight-sdk/api";
@@ -104,9 +104,10 @@ export class MidnightApi {
104
104
  cursor: input.cursor,
105
105
  },
106
106
  });
107
+ const envelope = requireResponseEnvelope(response, "books");
107
108
  return {
108
- cursor: response.cursor,
109
- data: mapBoundBooks(response.data, {
109
+ cursor: parseResponseCursor(envelope.cursor, "books"),
110
+ data: mapBoundBooks(envelope.data, {
110
111
  marketIds: input.marketIds,
111
112
  chainIds: input.chainIds,
112
113
  loanTokens: input.loanTokens,
@@ -127,7 +128,7 @@ export class MidnightApi {
127
128
  * @param params.request - Optional fetch options forwarded to this request.
128
129
  * @returns Book snapshot mapped to SDK camelCase fields, with price levels sorted best first (asks ascending tick, bids descending tick).
129
130
  * @throws {MidnightApiError} when the API returns a non-2xx response.
130
- * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON, when the returned book's `market_id` does not match, or cannot be derived from, its own market params, or when it differs from the requested `marketId`.
131
+ * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope or price levels are malformed, when the returned book's `market_id` does not match, or cannot be derived from, its own market params, or when it differs from the requested `marketId`.
131
132
  * @example
132
133
  * ```ts
133
134
  * import { MidnightApi } from "@morpho-org/midnight-sdk/api";
@@ -149,7 +150,7 @@ export class MidnightApi {
149
150
  },
150
151
  });
151
152
  return {
152
- data: mapBoundBookMarket(response.data, input.marketId),
153
+ data: mapBoundBookMarket(requireResponseEnvelope(response, "book").data, input.marketId),
153
154
  };
154
155
  }
155
156
  /**
@@ -165,7 +166,7 @@ export class MidnightApi {
165
166
  * @param params.request - Optional fetch options forwarded to this request.
166
167
  * @returns Price levels mapped to SDK camelCase fields, sorted best first (asks ascending tick, bids descending tick).
167
168
  * @throws {MidnightApiError} when the API returns a non-2xx response.
168
- * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON.
169
+ * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope or price levels are malformed.
169
170
  * @example
170
171
  * ```ts
171
172
  * import { MidnightApi } from "@morpho-org/midnight-sdk/api";
@@ -188,7 +189,7 @@ export class MidnightApi {
188
189
  },
189
190
  });
190
191
  return {
191
- data: mapPriceLevels(response.data, input.side),
192
+ data: mapPriceLevels(requireResponseEnvelope(response, "price levels").data, input.side),
192
193
  };
193
194
  }
194
195
  /**
@@ -203,7 +204,7 @@ export class MidnightApi {
203
204
  * @param params.request - Optional fetch options forwarded to this request.
204
205
  * @returns ABI-ready take objects mapped from the API response.
205
206
  * @throws {MidnightApiError} when the API returns a non-2xx response.
206
- * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON, when a returned offer cannot be mapped (malformed numeric or hex fields), when its `market_id` does not match, or cannot be derived from, its embedded market, when it falls outside the requested filters, when its `receiverIfMakerIsSeller` is not a well-formed address or is the zero address on a sell offer, when its caps or buy-side receiver are not executable, or when its units exceed its offer `maxUnits`.
207
+ * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope or takeable offers are malformed, when a returned offer cannot be mapped (malformed numeric or hex fields), when its `market_id` does not match, or cannot be derived from, its embedded market, when it falls outside the requested filters, when its `receiverIfMakerIsSeller` is not a well-formed address or is the zero address on a sell offer, when its caps or buy-side receiver are not executable, or when its units exceed its offer `maxUnits`.
207
208
  * @example
208
209
  * ```ts
209
210
  * import { MidnightApi } from "@morpho-org/midnight-sdk/api";
@@ -227,7 +228,7 @@ export class MidnightApi {
227
228
  }),
228
229
  });
229
230
  return {
230
- data: mapBoundTakeableOffers(response.data, {
231
+ data: mapBoundTakeableOffers(requireResponseEnvelope(response, "takeable offers").data, {
231
232
  marketId: input.marketId,
232
233
  side: input.side,
233
234
  }),
@@ -246,6 +247,7 @@ export class MidnightApi {
246
247
  * @param params.slippage - Optional slippage percentage used to derive the guard. Mutually exclusive with `params.averageWorstPrice`.
247
248
  * @param params.taker - Account that will execute the take (the `taker` passed to Midnight `take`).
248
249
  * The API leaves out offers made by this account, since Midnight rejects self-takes.
250
+ * @param params.limit - Optional maximum number of offers the API walks to build the quote (1 to 10,000, API default 10,000).
249
251
  * @param params.settlementFee - Optional current WAD-scaled settlement fee used for local guard validation. Defaults to zero.
250
252
  * @param params.baseUrl - Optional Midnight API base URL override.
251
253
  * @param params.fetch - Optional fetch implementation override.
@@ -260,7 +262,7 @@ export class MidnightApi {
260
262
  * @throws {InvalidMidnightApiQuoteTargetError} when the runtime input does not set exactly one of `units` or `assets`.
261
263
  * @throws {NegativeValueError} when `settlementFee` is negative.
262
264
  * @throws {MidnightApiError} when the API returns a non-2xx response.
263
- * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON, when a returned offer cannot be mapped (malformed numeric or hex fields), when its `market_id` does not match, or cannot be derived from, its embedded market, when it falls outside the requested filters, when an offer's maker matches the requested `taker`, when its `receiverIfMakerIsSeller` is not a well-formed address or is the zero address on a sell offer, when its caps or buy-side receiver are not executable, when its units exceed its offer `maxUnits`, or when the returned offers imply a rounded aggregate settlement price outside the effective average-worst-price guard.
265
+ * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope or quote aggregates are malformed, when a returned offer cannot be mapped (malformed numeric or hex fields), when its `market_id` does not match, or cannot be derived from, its embedded market, when it falls outside the requested filters, when an offer's maker matches the requested `taker`, when its `receiverIfMakerIsSeller` is not a well-formed address or is the zero address on a sell offer, when its caps or buy-side receiver are not executable, when its units exceed its offer `maxUnits`, or when the returned offers imply a rounded aggregate settlement price outside the effective average-worst-price guard.
264
266
  * @throws {SettlementFeeExceedsPriceError} when a bid's settlement fee exceeds its offer price.
265
267
  * @example
266
268
  * ```ts
@@ -295,9 +297,15 @@ export class MidnightApi {
295
297
  units: input.units,
296
298
  assets: input.assets,
297
299
  taker: input.taker,
300
+ limit: input.limit,
298
301
  },
299
302
  });
300
- const takeableOffers = mapBoundTakeableOffers(response.data.takeable_offers, {
303
+ const data = requireObject(requireResponseEnvelope(response, "quote").data, "quote data");
304
+ const averageBestPrice = requireBigIntString(data.average_best_price, "quote average_best_price");
305
+ const responseAverageWorstPrice = requireBigIntString(data.average_worst_price, "quote average_worst_price");
306
+ const availableAssets = requireBigIntString(data.available_assets, "quote available_assets");
307
+ const availableUnits = requireBigIntString(data.available_units, "quote available_units");
308
+ const takeableOffers = mapBoundTakeableOffers(data.takeable_offers, {
301
309
  marketId: input.marketId,
302
310
  side: input.side,
303
311
  taker: input.taker,
@@ -305,7 +313,7 @@ export class MidnightApi {
305
313
  const averageWorstPrice = "averageWorstPrice" in input && input.averageWorstPrice != null
306
314
  ? input.averageWorstPrice
307
315
  : "slippage" in input && input.slippage != null
308
- ? response.data.average_worst_price
316
+ ? responseAverageWorstPrice
309
317
  : undefined;
310
318
  const guard = averageWorstPrice == null ? undefined : BigInt(averageWorstPrice);
311
319
  if (guard != null) {
@@ -364,10 +372,10 @@ export class MidnightApi {
364
372
  }
365
373
  return {
366
374
  data: {
367
- averageBestPrice: response.data.average_best_price,
368
- averageWorstPrice: guard?.toString() ?? response.data.average_worst_price,
369
- availableAssets: response.data.available_assets,
370
- availableUnits: response.data.available_units,
375
+ averageBestPrice,
376
+ averageWorstPrice: guard?.toString() ?? responseAverageWorstPrice,
377
+ availableAssets,
378
+ availableUnits,
371
379
  takeableOffers,
372
380
  },
373
381
  };
@@ -387,7 +395,7 @@ export class MidnightApi {
387
395
  * @param params.request - Optional fetch options forwarded to this request.
388
396
  * @returns Paginated ABI-ready take objects mapped from the API response.
389
397
  * @throws {MidnightApiError} when the API returns a non-2xx response.
390
- * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON, when a returned offer cannot be mapped (malformed numeric or hex fields), when its `market_id` does not match, or cannot be derived from, its embedded market, when it falls outside the requested filters, when its `receiverIfMakerIsSeller` is not a well-formed address or is the zero address on a sell offer, when its caps or buy-side receiver are not executable, or when its units exceed its offer `maxUnits`.
398
+ * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope, cursor or takeable offers are malformed, when a returned offer cannot be mapped (malformed numeric or hex fields), when its `market_id` does not match, or cannot be derived from, its embedded market, when it falls outside the requested filters, when its `receiverIfMakerIsSeller` is not a well-formed address or is the zero address on a sell offer, when its caps or buy-side receiver are not executable, or when its units exceed its offer `maxUnits`.
391
399
  * @example
392
400
  * ```ts
393
401
  * import { MidnightApi } from "@morpho-org/midnight-sdk/api";
@@ -412,9 +420,10 @@ export class MidnightApi {
412
420
  cursor: input.cursor,
413
421
  },
414
422
  });
423
+ const envelope = requireResponseEnvelope(response, "takeable offers");
415
424
  return {
416
- cursor: response.cursor,
417
- data: mapBoundTakeableOffers(response.data, {
425
+ cursor: parseResponseCursor(envelope.cursor, "takeable offers"),
426
+ data: mapBoundTakeableOffers(envelope.data, {
418
427
  maker: input.maker,
419
428
  marketIds: input.marketIds,
420
429
  groups: input.groups,
@@ -554,7 +563,7 @@ export class MidnightApi {
554
563
  * @param params.cursor - Optional opaque pagination cursor from a previous response.
555
564
  * @returns Paginated books mapped to SDK camelCase fields, with each book's price levels sorted best first (asks ascending tick, bids descending tick).
556
565
  * @throws {MidnightApiError} when the API returns a non-2xx response.
557
- * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON, when a returned book's `market_id` does not match, or cannot be derived from, its own market params, or when a returned book falls outside the supplied `marketIds`, `chainIds`, `loanTokens`, `collateralTokens`, or `maturities` filters.
566
+ * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope, cursor or price levels are malformed, when a returned book's `market_id` does not match, or cannot be derived from, its own market params, or when a returned book falls outside the supplied `marketIds`, `chainIds`, `loanTokens`, `collateralTokens`, or `maturities` filters.
558
567
  * @example
559
568
  * ```ts
560
569
  * import { MidnightApi } from "@morpho-org/midnight-sdk/api";
@@ -579,7 +588,7 @@ export class MidnightApi {
579
588
  * @param params.depth - Optional maximum levels returned per side.
580
589
  * @returns Book snapshot mapped to SDK camelCase fields, with price levels sorted best first (asks ascending tick, bids descending tick).
581
590
  * @throws {MidnightApiError} when the API returns a non-2xx response.
582
- * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON, when the returned book's `market_id` does not match, or cannot be derived from, its own market params, or when it differs from the requested `marketId`.
591
+ * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope or price levels are malformed, when the returned book's `market_id` does not match, or cannot be derived from, its own market params, or when it differs from the requested `marketId`.
583
592
  * @example
584
593
  * ```ts
585
594
  * import { MidnightApi } from "@morpho-org/midnight-sdk/api";
@@ -607,7 +616,7 @@ export class MidnightApi {
607
616
  * @param params.depth - Optional maximum levels returned.
608
617
  * @returns Price levels mapped to SDK camelCase fields, sorted best first (asks ascending tick, bids descending tick).
609
618
  * @throws {MidnightApiError} when the API returns a non-2xx response.
610
- * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON.
619
+ * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope or price levels are malformed.
611
620
  * @example
612
621
  * ```ts
613
622
  * import { MidnightApi } from "@morpho-org/midnight-sdk/api";
@@ -635,7 +644,7 @@ export class MidnightApi {
635
644
  * @param params.side - Book side to query.
636
645
  * @returns ABI-ready take objects mapped from the API response.
637
646
  * @throws {MidnightApiError} when the API returns a non-2xx response.
638
- * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON, when a returned offer cannot be mapped (malformed numeric or hex fields), when its `market_id` does not match, or cannot be derived from, its embedded market, when it falls outside the requested filters, when its `receiverIfMakerIsSeller` is not a well-formed address or is the zero address on a sell offer, when its caps or buy-side receiver are not executable, or when its units exceed its offer `maxUnits`.
647
+ * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope or takeable offers are malformed, when a returned offer cannot be mapped (malformed numeric or hex fields), when its `market_id` does not match, or cannot be derived from, its embedded market, when it falls outside the requested filters, when its `receiverIfMakerIsSeller` is not a well-formed address or is the zero address on a sell offer, when its caps or buy-side receiver are not executable, or when its units exceed its offer `maxUnits`.
639
648
  * @example
640
649
  * ```ts
641
650
  * import { MidnightApi } from "@morpho-org/midnight-sdk/api";
@@ -667,6 +676,7 @@ export class MidnightApi {
667
676
  * @param params.slippage - Optional slippage percentage used to derive the guard. Mutually exclusive with `params.averageWorstPrice`.
668
677
  * @param params.taker - Account that will execute the take (the `taker` passed to Midnight `take`).
669
678
  * The API leaves out offers made by this account, since Midnight rejects self-takes.
679
+ * @param params.limit - Optional maximum number of offers the API walks to build the quote (1 to 10,000, API default 10,000).
670
680
  * @param params.settlementFee - Optional current WAD-scaled settlement fee used for local guard validation. Defaults to zero.
671
681
  * @returns Quote and ABI-ready take caps. `averageWorstPrice` equals the caller's guard when provided,
672
682
  * otherwise the API's guard. Offers are returned as the API sends them. An `asks` quote by
@@ -678,7 +688,7 @@ export class MidnightApi {
678
688
  * @throws {InvalidMidnightApiQuoteTargetError} when the runtime input does not set exactly one of `units` or `assets`.
679
689
  * @throws {NegativeValueError} when `settlementFee` is negative.
680
690
  * @throws {MidnightApiError} when the API returns a non-2xx response.
681
- * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON, when a returned offer cannot be mapped (malformed numeric or hex fields), when its `market_id` does not match, or cannot be derived from, its embedded market, when it falls outside the requested filters, when an offer's maker matches the requested `taker`, when its `receiverIfMakerIsSeller` is not a well-formed address or is the zero address on a sell offer, when its caps or buy-side receiver are not executable, when its units exceed its offer `maxUnits`, or when the returned offers imply a rounded aggregate settlement price outside the effective average-worst-price guard.
691
+ * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope or quote aggregates are malformed, when a returned offer cannot be mapped (malformed numeric or hex fields), when its `market_id` does not match, or cannot be derived from, its embedded market, when it falls outside the requested filters, when an offer's maker matches the requested `taker`, when its `receiverIfMakerIsSeller` is not a well-formed address or is the zero address on a sell offer, when its caps or buy-side receiver are not executable, when its units exceed its offer `maxUnits`, or when the returned offers imply a rounded aggregate settlement price outside the effective average-worst-price guard.
682
692
  * @throws {SettlementFeeExceedsPriceError} when a bid's settlement fee exceeds its offer price.
683
693
  * @example
684
694
  * ```ts
@@ -711,7 +721,7 @@ export class MidnightApi {
711
721
  * @param params.cursor - Optional opaque pagination cursor from a previous response.
712
722
  * @returns Paginated ABI-ready take objects mapped from the API response.
713
723
  * @throws {MidnightApiError} when the API returns a non-2xx response.
714
- * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON, when a returned offer cannot be mapped (malformed numeric or hex fields), when its `market_id` does not match, or cannot be derived from, its embedded market, when it falls outside the requested filters, when its `receiverIfMakerIsSeller` is not a well-formed address or is the zero address on a sell offer, when its caps or buy-side receiver are not executable, or when its units exceed its offer `maxUnits`.
724
+ * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope, cursor or takeable offers are malformed, when a returned offer cannot be mapped (malformed numeric or hex fields), when its `market_id` does not match, or cannot be derived from, its embedded market, when it falls outside the requested filters, when its `receiverIfMakerIsSeller` is not a well-formed address or is the zero address on a sell offer, when its caps or buy-side receiver are not executable, or when its units exceed its offer `maxUnits`.
715
725
  * @example
716
726
  * ```ts
717
727
  * import { MidnightApi } from "@morpho-org/midnight-sdk/api";
@@ -36,3 +36,13 @@ export interface TakeableOfferContext {
36
36
  export declare function mapBoundTakeableOffers(takeableOffers: readonly ApiTakeableOfferResponse[], context: TakeableOfferContext): MidnightApiTake[];
37
37
  /** @internal Parses the mempool validation response envelope. */
38
38
  export declare function parseValidationResponse(response: unknown): MempoolPayloadValidationResult;
39
+ /** @internal Returns `value` when it is a non-null, non-array object. */
40
+ export declare function requireObject<T extends object>(value: T, context: string): T;
41
+ /** @internal Returns a Midnight API response envelope after checking it carries `data`. */
42
+ export declare function requireResponseEnvelope<T extends {
43
+ readonly data: object;
44
+ }>(response: T, context: string): T;
45
+ /** @internal Parses a paginated response cursor, treating a missing cursor as the last page. */
46
+ export declare function parseResponseCursor(cursor: string | null | undefined, context: string): string | null;
47
+ /** @internal Returns `value` when it is a decimal string of a uint256. */
48
+ export declare function requireBigIntString(value: string, context: string): string;
@@ -1,7 +1,8 @@
1
1
  import { BLUE_API_BASE_URL, isHexEqual } from "@morpho-org/morpho-ts";
2
- import { isAddress, isAddressEqual, maxUint256, zeroAddress, } from "viem";
2
+ import { isAddress, isAddressEqual, isHex, maxUint256, zeroAddress, } from "viem";
3
3
  import { InvalidMidnightApiResponseError, InvalidOfferParameterError, MidnightApiError, } from "../errors.js";
4
4
  import { MarketUtils } from "../market/index.js";
5
+ import { TickLib } from "../math/index.js";
5
6
  import { OfferUtils } from "../offers/index.js";
6
7
  import { MempoolPayloadValidationRule, } from "./types.js";
7
8
  import { MIDNIGHT_SDK_VERSION } from "./version.generated.js";
@@ -91,6 +92,11 @@ export function buildBookPath(params) {
91
92
  * the onchain `collateralIndex`.
92
93
  */
93
94
  function mapBookMarket(book) {
95
+ // Validate the response shape before reading its fields.
96
+ requireObject(book, "book");
97
+ if (typeof book.market_id !== "string") {
98
+ throw new InvalidMidnightApiResponseError("Midnight API book market_id is not a string.");
99
+ }
94
100
  let derivedMarketId;
95
101
  let matchesAdvertisedId;
96
102
  try {
@@ -145,7 +151,7 @@ export function mapBoundBookMarket(book, requestedMarketId) {
145
151
  }
146
152
  /** @internal Maps listed book markets, binding each verified id to requested filters when present. */
147
153
  export function mapBoundBooks(books, context = {}) {
148
- return books.map((book) => {
154
+ return requireArray(books, "books").map((book) => {
149
155
  const market = mapBookMarket(book);
150
156
  if (context.marketIds != null &&
151
157
  context.marketIds.length > 0 &&
@@ -187,17 +193,28 @@ function mapCollateral(collateral) {
187
193
  }
188
194
  /** @internal Maps a price-level API payload to the SDK response shape. */
189
195
  function mapPriceLevel(level) {
196
+ // Validate the response shape before reading its fields.
197
+ requireObject(level, "price level");
198
+ if (typeof level.tick !== "number" || !Number.isSafeInteger(level.tick)) {
199
+ throw new InvalidMidnightApiResponseError(`Midnight API price level tick (${typeof level.tick}) is not a safe integer.`);
200
+ }
201
+ const price = requireBigIntString(level.price, "price level price");
202
+ const units = requireBigIntString(level.units, "price level units");
203
+ const assets = requireBigIntString(level.assets, "price level assets");
204
+ if (typeof level.count !== "number" || !Number.isSafeInteger(level.count)) {
205
+ throw new InvalidMidnightApiResponseError(`Midnight API price level count (${typeof level.count}) is not a safe integer.`);
206
+ }
190
207
  return {
191
208
  tick: level.tick,
192
- price: level.price,
193
- units: level.units,
194
- assets: level.assets,
209
+ price,
210
+ units,
211
+ assets,
195
212
  count: level.count,
196
213
  };
197
214
  }
198
215
  /** @internal Maps API price levels and sorts them best first: asks by ascending tick, bids by descending tick. */
199
216
  export function mapPriceLevels(levels, side) {
200
- return levels
217
+ return requireArray(levels, "price levels")
201
218
  .map(mapPriceLevel)
202
219
  .sort((a, b) => (side === "asks" ? a.tick - b.tick : b.tick - a.tick));
203
220
  }
@@ -208,6 +225,26 @@ export function mapPriceLevels(levels, side) {
208
225
  */
209
226
  function mapTakeableOffer(takeableOffer) {
210
227
  const offer = takeableOffer.offer;
228
+ // The filters after mapping call viem helpers that throw their own errors on non-address values.
229
+ for (const [field, value] of [
230
+ ["maker", offer.maker],
231
+ ["receiver_if_maker_is_seller", offer.receiver_if_maker_is_seller],
232
+ ]) {
233
+ if (typeof value !== "string" || !isAddress(value, { strict: false })) {
234
+ throw new InvalidMidnightApiResponseError(`Midnight API takeable offer ${field} (${typeof value}) is not an address.`);
235
+ }
236
+ }
237
+ if (typeof offer.group !== "string" || !isHex(offer.group)) {
238
+ throw new InvalidMidnightApiResponseError(`Midnight API takeable offer group (${typeof offer.group}) is not a hex string.`);
239
+ }
240
+ for (const [field, value] of [
241
+ ["buy", offer.buy],
242
+ ["reduce_only", offer.reduce_only],
243
+ ]) {
244
+ if (typeof value !== "boolean") {
245
+ throw new InvalidMidnightApiResponseError(`Midnight API takeable offer ${field} (${typeof value}) is not a boolean.`);
246
+ }
247
+ }
211
248
  return {
212
249
  marketId: takeableOffer.market_id,
213
250
  units: BigInt(takeableOffer.units),
@@ -233,7 +270,7 @@ function mapTakeableOffer(takeableOffer) {
233
270
  maker: offer.maker,
234
271
  start: BigInt(offer.start),
235
272
  expiry: BigInt(offer.expiry),
236
- tick: BigInt(offer.tick),
273
+ tick: TickLib.assertTickInRange(BigInt(offer.tick)),
237
274
  group: offer.group,
238
275
  callback: offer.callback,
239
276
  callbackData: offer.callback_data,
@@ -249,7 +286,13 @@ function mapTakeableOffer(takeableOffer) {
249
286
  }
250
287
  /** @internal Maps, validates offer caps and units, and best-price-sorts API takeable offers. */
251
288
  export function mapBoundTakeableOffers(takeableOffers, context) {
252
- const mapped = takeableOffers.map((takeableOffer) => {
289
+ const mapped = requireArray(takeableOffers, "takeable offers").map((takeableOffer) => {
290
+ // Validate the response shape before reading its fields.
291
+ requireObject(takeableOffer, "takeable offer");
292
+ // Rejects malformed entries before the catch below interpolates their market_id.
293
+ if (typeof takeableOffer.market_id !== "string") {
294
+ throw new InvalidMidnightApiResponseError("Midnight API takeable offer market_id is not a string.");
295
+ }
253
296
  let take;
254
297
  let matchesAdvertisedId;
255
298
  let embeddedMarketId;
@@ -380,6 +423,46 @@ export function parseValidationResponse(response) {
380
423
  issues,
381
424
  };
382
425
  }
426
+ /** @internal Returns `value` when it is a non-null, non-array object. */
427
+ export function requireObject(value, context) {
428
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
429
+ throw new InvalidMidnightApiResponseError(`Midnight API ${context} is malformed.`);
430
+ }
431
+ return value;
432
+ }
433
+ /** @internal Returns a Midnight API response envelope after checking it carries `data`. */
434
+ export function requireResponseEnvelope(response, context) {
435
+ // Validate the response shape before reading its fields.
436
+ requireObject(response, `${context} response`);
437
+ if (response.data == null) {
438
+ throw new InvalidMidnightApiResponseError(`Midnight API ${context} response is missing "data".`);
439
+ }
440
+ return response;
441
+ }
442
+ /** @internal Parses a paginated response cursor, treating a missing cursor as the last page. */
443
+ export function parseResponseCursor(cursor, context) {
444
+ if (cursor == null)
445
+ return null;
446
+ if (typeof cursor === "string")
447
+ return cursor;
448
+ throw new InvalidMidnightApiResponseError(`Midnight API ${context} cursor is malformed.`);
449
+ }
450
+ /** @internal Returns `value` when it is a decimal string of a uint256. */
451
+ export function requireBigIntString(value, context) {
452
+ if (typeof value === "string" &&
453
+ value.length <= MAX_UINT256_DECIMAL_LENGTH &&
454
+ /^\d+$/.test(value) &&
455
+ BigInt(value) <= maxUint256) {
456
+ return value;
457
+ }
458
+ throw new InvalidMidnightApiResponseError(`Midnight API ${context} (${typeof value}) is not a decimal uint256 string.`);
459
+ }
460
+ function requireArray(value, context) {
461
+ if (Array.isArray(value))
462
+ return value;
463
+ throw new InvalidMidnightApiResponseError(`Midnight API ${context} is malformed.`);
464
+ }
465
+ /** @internal Returns `value` when it is a plain object, else throws `InvalidMidnightApiResponseError`. */
383
466
  function requireRecord(value, context) {
384
467
  if (isRecord(value))
385
468
  return value;
@@ -182,6 +182,11 @@ export type FetchBookQuoteParams = MidnightApiConfig & {
182
182
  * offers made by this account, since Midnight rejects self-takes.
183
183
  */
184
184
  readonly taker?: Address;
185
+ /**
186
+ * Maximum number of offers the API walks to build the quote. The API accepts 1 to 10,000 and
187
+ * defaults to 10,000. Set it to cap the offers a quote can return, e.g. to fit one bundle.
188
+ */
189
+ readonly limit?: number;
185
190
  /** Current WAD-scaled settlement fee used for local guard validation. Defaults to zero. */
186
191
  readonly settlementFee?: BigIntish;
187
192
  } & (MidnightApiQuoteAssetsTarget | MidnightApiQuoteUnitsTarget) & (MidnightApiQuoteAverageWorstPriceGuard | MidnightApiQuoteSlippageGuard | MidnightApiQuoteWithoutGuard);
@@ -1,2 +1,2 @@
1
1
  /** @internal Installed Midnight SDK package version. */
2
- export declare const MIDNIGHT_SDK_VERSION = "2.4.0-next.0";
2
+ export declare const MIDNIGHT_SDK_VERSION = "2.4.0";
@@ -1,3 +1,3 @@
1
1
  // Generated by scripts/generate-midnight-package-version.ts. Do not edit.
2
2
  /** @internal Installed Midnight SDK package version. */
3
- export const MIDNIGHT_SDK_VERSION = "2.4.0-next.0";
3
+ export const MIDNIGHT_SDK_VERSION = "2.4.0";
@@ -1,4 +1,3 @@
1
- import { InvalidPositionAccrualStateError as SharedInvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError as SharedInvalidPositionAccrualTimestampError, InvalidPositionLossFactorError as SharedInvalidPositionLossFactorError } from "@morpho-org/morpho-ts";
2
1
  import type { Address } from "viem";
3
2
  import type { MempoolPayloadValidationIssue } from "./api/types.js";
4
3
  /**
@@ -71,27 +70,42 @@ export declare class SettlementFeeExceedsPriceError extends Error {
71
70
  /**
72
71
  * Thrown when a local position accrual is requested for an impossible timestamp.
73
72
  *
74
- * @deprecated Import `InvalidPositionAccrualTimestampError` from `@morpho-org/morpho-ts`. Removed in the next major.
73
+ * @example
74
+ * ```ts
75
+ * import { InvalidPositionAccrualTimestampError } from "@morpho-org/midnight-sdk";
76
+ *
77
+ * throw new InvalidPositionAccrualTimestampError(1n, 2n);
78
+ * ```
75
79
  */
76
- export declare const InvalidPositionAccrualTimestampError: typeof SharedInvalidPositionAccrualTimestampError;
77
- /** @deprecated Import `InvalidPositionAccrualTimestampError` from `@morpho-org/morpho-ts`. Removed in the next major. */
78
- export type InvalidPositionAccrualTimestampError = SharedInvalidPositionAccrualTimestampError;
80
+ export declare class InvalidPositionAccrualTimestampError extends Error {
81
+ constructor(timestamp: bigint, lastAccrual: bigint);
82
+ }
79
83
  /**
80
84
  * Thrown when a local position accrual sees a market loss factor older than the position.
81
85
  *
82
- * @deprecated Import `InvalidPositionLossFactorError` from `@morpho-org/morpho-ts`. Removed in the next major.
86
+ * @example
87
+ * ```ts
88
+ * import { InvalidPositionLossFactorError } from "@morpho-org/midnight-sdk";
89
+ *
90
+ * throw new InvalidPositionLossFactorError(1n, 2n);
91
+ * ```
83
92
  */
84
- export declare const InvalidPositionLossFactorError: typeof SharedInvalidPositionLossFactorError;
85
- /** @deprecated Import `InvalidPositionLossFactorError` from `@morpho-org/morpho-ts`. Removed in the next major. */
86
- export type InvalidPositionLossFactorError = SharedInvalidPositionLossFactorError;
93
+ export declare class InvalidPositionLossFactorError extends Error {
94
+ constructor(marketLossFactor: bigint, positionLossFactor: bigint);
95
+ }
87
96
  /**
88
97
  * Thrown when local position accrual inputs violate Midnight accounting invariants.
89
98
  *
90
- * @deprecated Import `InvalidPositionAccrualStateError` from `@morpho-org/morpho-ts`. Removed in the next major.
99
+ * @example
100
+ * ```ts
101
+ * import { InvalidPositionAccrualStateError } from "@morpho-org/midnight-sdk";
102
+ *
103
+ * throw new InvalidPositionAccrualStateError("Pending fee exceeds credit.");
104
+ * ```
91
105
  */
92
- export declare const InvalidPositionAccrualStateError: typeof SharedInvalidPositionAccrualStateError;
93
- /** @deprecated Import `InvalidPositionAccrualStateError` from `@morpho-org/morpho-ts`. Removed in the next major. */
94
- export type InvalidPositionAccrualStateError = SharedInvalidPositionAccrualStateError;
106
+ export declare class InvalidPositionAccrualStateError extends Error {
107
+ constructor(reason: string);
108
+ }
95
109
  /**
96
110
  * Thrown when a market parameter cannot satisfy Midnight protocol rules.
97
111
  *
package/lib/esm/errors.js CHANGED
@@ -1,4 +1,3 @@
1
- import { InvalidPositionAccrualStateError as SharedInvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError as SharedInvalidPositionAccrualTimestampError, InvalidPositionLossFactorError as SharedInvalidPositionLossFactorError, } from "@morpho-org/morpho-ts";
2
1
  /**
3
2
  * Thrown when a Midnight offer group violates protocol-level group mechanics.
4
3
  *
@@ -82,25 +81,54 @@ export class SettlementFeeExceedsPriceError extends Error {
82
81
  this.name = "SettlementFeeExceedsPriceError";
83
82
  }
84
83
  }
85
- // Temporary compatibility exception for these shared morpho-ts errors.
86
84
  /**
87
85
  * Thrown when a local position accrual is requested for an impossible timestamp.
88
86
  *
89
- * @deprecated Import `InvalidPositionAccrualTimestampError` from `@morpho-org/morpho-ts`. Removed in the next major.
87
+ * @example
88
+ * ```ts
89
+ * import { InvalidPositionAccrualTimestampError } from "@morpho-org/midnight-sdk";
90
+ *
91
+ * throw new InvalidPositionAccrualTimestampError(1n, 2n);
92
+ * ```
90
93
  */
91
- export const InvalidPositionAccrualTimestampError = SharedInvalidPositionAccrualTimestampError;
94
+ export class InvalidPositionAccrualTimestampError extends Error {
95
+ constructor(timestamp, lastAccrual) {
96
+ super(`Position accrual timestamp "${timestamp}" is before last accrual "${lastAccrual}". Use a timestamp greater than or equal to last accrual.`);
97
+ this.name = "InvalidPositionAccrualTimestampError";
98
+ }
99
+ }
92
100
  /**
93
101
  * Thrown when a local position accrual sees a market loss factor older than the position.
94
102
  *
95
- * @deprecated Import `InvalidPositionLossFactorError` from `@morpho-org/morpho-ts`. Removed in the next major.
103
+ * @example
104
+ * ```ts
105
+ * import { InvalidPositionLossFactorError } from "@morpho-org/midnight-sdk";
106
+ *
107
+ * throw new InvalidPositionLossFactorError(1n, 2n);
108
+ * ```
96
109
  */
97
- export const InvalidPositionLossFactorError = SharedInvalidPositionLossFactorError;
110
+ export class InvalidPositionLossFactorError extends Error {
111
+ constructor(marketLossFactor, positionLossFactor) {
112
+ super(`Market loss factor "${marketLossFactor}" is below position loss factor "${positionLossFactor}". Fetch a consistent market and position at the same block.`);
113
+ this.name = "InvalidPositionLossFactorError";
114
+ }
115
+ }
98
116
  /**
99
117
  * Thrown when local position accrual inputs violate Midnight accounting invariants.
100
118
  *
101
- * @deprecated Import `InvalidPositionAccrualStateError` from `@morpho-org/morpho-ts`. Removed in the next major.
119
+ * @example
120
+ * ```ts
121
+ * import { InvalidPositionAccrualStateError } from "@morpho-org/midnight-sdk";
122
+ *
123
+ * throw new InvalidPositionAccrualStateError("Pending fee exceeds credit.");
124
+ * ```
102
125
  */
103
- export const InvalidPositionAccrualStateError = SharedInvalidPositionAccrualStateError;
126
+ export class InvalidPositionAccrualStateError extends Error {
127
+ constructor(reason) {
128
+ super(`Invalid Midnight position accrual state. ${reason}`);
129
+ this.name = "InvalidPositionAccrualStateError";
130
+ }
131
+ }
104
132
  /**
105
133
  * Thrown when a market parameter cannot satisfy Midnight protocol rules.
106
134
  *
@@ -499,6 +499,9 @@ export declare class Offer {
499
499
  * continuous fee and settlement-fee buckets are available locally. Fetch the
500
500
  * current `consumed(maker, group)` value separately and pass it as input.
501
501
  *
502
+ * Returns `0n` when Midnight `take` rejects this offer regardless of the
503
+ * amount; see {@link OfferUtils.getConsumableUnits} for the mirrored checks.
504
+ *
502
505
  * @param params.consumed - Amount already consumed from this offer's group.
503
506
  * @param params.timestamp - Timestamp used to compute the market time to maturity.
504
507
  * @returns Remaining consumable units accepted by Midnight `take`.
@@ -454,6 +454,9 @@ export class Offer {
454
454
  * continuous fee and settlement-fee buckets are available locally. Fetch the
455
455
  * current `consumed(maker, group)` value separately and pass it as input.
456
456
  *
457
+ * Returns `0n` when Midnight `take` rejects this offer regardless of the
458
+ * amount; see {@link OfferUtils.getConsumableUnits} for the mirrored checks.
459
+ *
457
460
  * @param params.consumed - Amount already consumed from this offer's group.
458
461
  * @param params.timestamp - Timestamp used to compute the market time to maturity.
459
462
  * @returns Remaining consumable units accepted by Midnight `take`.
@@ -663,6 +663,12 @@ export declare namespace OfferUtils {
663
663
  * continuous fee and settlement-fee buckets are available locally. Fetch the
664
664
  * current `consumed(maker, group)` value separately and pass it as input.
665
665
  *
666
+ * Returns `0n` when Midnight `take` rejects the offer regardless of the
667
+ * amount: outside its `start`/`expiry` window, above its `continuousFeeCap`,
668
+ * on a tick off the market's tick spacing (the default spacing on an
669
+ * untouched market), or on a market whose loss factor is maxed out. Taker-dependent checks (`SelfTake`, ratification) and the
670
+ * seller's post-maturity debt check are not mirrored.
671
+ *
666
672
  * @param params.offer - Offer to inspect. Its market must be hydrated.
667
673
  * @param params.consumed - Amount already consumed from the offer group.
668
674
  * @param params.timestamp - Timestamp used to compute market time to maturity.
@@ -1,5 +1,5 @@
1
1
  import { assertNonNegative, DivisionByZeroError, MathLib, } from "@morpho-org/morpho-ts";
2
- import { encodeAbiParameters, getAbiItem, isAddressEqual, keccak256, zeroAddress, zeroHash, } from "viem";
2
+ import { encodeAbiParameters, getAbiItem, isAddressEqual, keccak256, maxUint128, zeroAddress, zeroHash, } from "viem";
3
3
  import { midnightAbi } from "../abis.js";
4
4
  import { DEFAULT_TICK_SPACING, MAX_OFFER_CAP, MAX_TICK, OFFER_TYPEHASH, } from "../constants.js";
5
5
  import { InvalidOfferGroupError, InvalidOfferParameterError, } from "../errors.js";
@@ -888,6 +888,12 @@ export var OfferUtils;
888
888
  * continuous fee and settlement-fee buckets are available locally. Fetch the
889
889
  * current `consumed(maker, group)` value separately and pass it as input.
890
890
  *
891
+ * Returns `0n` when Midnight `take` rejects the offer regardless of the
892
+ * amount: outside its `start`/`expiry` window, above its `continuousFeeCap`,
893
+ * on a tick off the market's tick spacing (the default spacing on an
894
+ * untouched market), or on a market whose loss factor is maxed out. Taker-dependent checks (`SelfTake`, ratification) and the
895
+ * seller's post-maturity debt check are not mirrored.
896
+ *
891
897
  * @param params.offer - Offer to inspect. Its market must be hydrated.
892
898
  * @param params.consumed - Amount already consumed from the offer group.
893
899
  * @param params.timestamp - Timestamp used to compute market time to maturity.
@@ -984,6 +990,14 @@ export var OfferUtils;
984
990
  return 0n;
985
991
  if (continuousFeeCap < BigInt(market.continuousFee))
986
992
  return 0n;
993
+ if (market.lossFactor >= maxUint128)
994
+ return 0n;
995
+ // A zero spacing marks an untouched market, which `take` creates with its default spacing.
996
+ const tickSpacing = market.tickSpacing === 0
997
+ ? DEFAULT_TICK_SPACING
998
+ : BigInt(market.tickSpacing);
999
+ if (BigInt(offer.tick) % tickSpacing !== 0n)
1000
+ return 0n;
987
1001
  const settlementFee = market.getSettlementFee(market.timeToMaturity(timestamp));
988
1002
  // Validates the settlement fee against the offer price for both cap modes.
989
1003
  const { sellerPrice, buyerPrice } = TakeAmountsLib.prices({
@@ -170,6 +170,9 @@ export interface IAccrualPosition extends Omit<IPosition, "marketId"> {
170
170
  */
171
171
  export declare class AccrualPosition extends Position implements IAccrualPosition {
172
172
  protected readonly _market: Market;
173
+ /**
174
+ * @throws {InvalidMarketParameterError} when `position` carries a `marketId` that differs from `market.id`.
175
+ */
173
176
  constructor(position: IAccrualPosition, market: IMarket | Market);
174
177
  /** Hydrated market for this position. */
175
178
  get market(): Market;