@morpho-org/midnight-sdk 2.3.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.
@@ -79,7 +79,7 @@ class MidnightApi {
79
79
  * @param params.request - Optional fetch options forwarded to this request.
80
80
  * @returns Paginated books mapped to SDK camelCase fields, with each book's price levels sorted best first (asks ascending tick, bids descending tick).
81
81
  * @throws {MidnightApiError} when the API returns a non-2xx response.
82
- * @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.
82
+ * @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.
83
83
  * @example
84
84
  * ```ts
85
85
  * import { MidnightApi } from "@morpho-org/midnight-sdk/api";
@@ -108,9 +108,10 @@ class MidnightApi {
108
108
  cursor: input.cursor,
109
109
  },
110
110
  });
111
+ const envelope = (0, helpers_js_1.requireResponseEnvelope)(response, "books");
111
112
  return {
112
- cursor: response.cursor,
113
- data: (0, helpers_js_1.mapBoundBooks)(response.data, {
113
+ cursor: (0, helpers_js_1.parseResponseCursor)(envelope.cursor, "books"),
114
+ data: (0, helpers_js_1.mapBoundBooks)(envelope.data, {
114
115
  marketIds: input.marketIds,
115
116
  chainIds: input.chainIds,
116
117
  loanTokens: input.loanTokens,
@@ -131,7 +132,7 @@ class MidnightApi {
131
132
  * @param params.request - Optional fetch options forwarded to this request.
132
133
  * @returns Book snapshot mapped to SDK camelCase fields, with price levels sorted best first (asks ascending tick, bids descending tick).
133
134
  * @throws {MidnightApiError} when the API returns a non-2xx response.
134
- * @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`.
135
+ * @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`.
135
136
  * @example
136
137
  * ```ts
137
138
  * import { MidnightApi } from "@morpho-org/midnight-sdk/api";
@@ -153,7 +154,7 @@ class MidnightApi {
153
154
  },
154
155
  });
155
156
  return {
156
- data: (0, helpers_js_1.mapBoundBookMarket)(response.data, input.marketId),
157
+ data: (0, helpers_js_1.mapBoundBookMarket)((0, helpers_js_1.requireResponseEnvelope)(response, "book").data, input.marketId),
157
158
  };
158
159
  }
159
160
  /**
@@ -169,7 +170,7 @@ class MidnightApi {
169
170
  * @param params.request - Optional fetch options forwarded to this request.
170
171
  * @returns Price levels mapped to SDK camelCase fields, sorted best first (asks ascending tick, bids descending tick).
171
172
  * @throws {MidnightApiError} when the API returns a non-2xx response.
172
- * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON.
173
+ * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope or price levels are malformed.
173
174
  * @example
174
175
  * ```ts
175
176
  * import { MidnightApi } from "@morpho-org/midnight-sdk/api";
@@ -192,7 +193,7 @@ class MidnightApi {
192
193
  },
193
194
  });
194
195
  return {
195
- data: (0, helpers_js_1.mapPriceLevels)(response.data, input.side),
196
+ data: (0, helpers_js_1.mapPriceLevels)((0, helpers_js_1.requireResponseEnvelope)(response, "price levels").data, input.side),
196
197
  };
197
198
  }
198
199
  /**
@@ -207,7 +208,7 @@ class MidnightApi {
207
208
  * @param params.request - Optional fetch options forwarded to this request.
208
209
  * @returns ABI-ready take objects mapped from the API response.
209
210
  * @throws {MidnightApiError} when the API returns a non-2xx response.
210
- * @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`.
211
+ * @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`.
211
212
  * @example
212
213
  * ```ts
213
214
  * import { MidnightApi } from "@morpho-org/midnight-sdk/api";
@@ -231,7 +232,7 @@ class MidnightApi {
231
232
  }),
232
233
  });
233
234
  return {
234
- data: (0, helpers_js_1.mapBoundTakeableOffers)(response.data, {
235
+ data: (0, helpers_js_1.mapBoundTakeableOffers)((0, helpers_js_1.requireResponseEnvelope)(response, "takeable offers").data, {
235
236
  marketId: input.marketId,
236
237
  side: input.side,
237
238
  }),
@@ -250,6 +251,7 @@ class MidnightApi {
250
251
  * @param params.slippage - Optional slippage percentage used to derive the guard. Mutually exclusive with `params.averageWorstPrice`.
251
252
  * @param params.taker - Account that will execute the take (the `taker` passed to Midnight `take`).
252
253
  * The API leaves out offers made by this account, since Midnight rejects self-takes.
254
+ * @param params.limit - Optional maximum number of offers the API walks to build the quote (1 to 10,000, API default 10,000).
253
255
  * @param params.settlementFee - Optional current WAD-scaled settlement fee used for local guard validation. Defaults to zero.
254
256
  * @param params.baseUrl - Optional Midnight API base URL override.
255
257
  * @param params.fetch - Optional fetch implementation override.
@@ -264,7 +266,7 @@ class MidnightApi {
264
266
  * @throws {InvalidMidnightApiQuoteTargetError} when the runtime input does not set exactly one of `units` or `assets`.
265
267
  * @throws {NegativeValueError} when `settlementFee` is negative.
266
268
  * @throws {MidnightApiError} when the API returns a non-2xx response.
267
- * @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.
269
+ * @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.
268
270
  * @throws {SettlementFeeExceedsPriceError} when a bid's settlement fee exceeds its offer price.
269
271
  * @example
270
272
  * ```ts
@@ -299,9 +301,15 @@ class MidnightApi {
299
301
  units: input.units,
300
302
  assets: input.assets,
301
303
  taker: input.taker,
304
+ limit: input.limit,
302
305
  },
303
306
  });
304
- const takeableOffers = (0, helpers_js_1.mapBoundTakeableOffers)(response.data.takeable_offers, {
307
+ const data = (0, helpers_js_1.requireObject)((0, helpers_js_1.requireResponseEnvelope)(response, "quote").data, "quote data");
308
+ const averageBestPrice = (0, helpers_js_1.requireBigIntString)(data.average_best_price, "quote average_best_price");
309
+ const responseAverageWorstPrice = (0, helpers_js_1.requireBigIntString)(data.average_worst_price, "quote average_worst_price");
310
+ const availableAssets = (0, helpers_js_1.requireBigIntString)(data.available_assets, "quote available_assets");
311
+ const availableUnits = (0, helpers_js_1.requireBigIntString)(data.available_units, "quote available_units");
312
+ const takeableOffers = (0, helpers_js_1.mapBoundTakeableOffers)(data.takeable_offers, {
305
313
  marketId: input.marketId,
306
314
  side: input.side,
307
315
  taker: input.taker,
@@ -309,7 +317,7 @@ class MidnightApi {
309
317
  const averageWorstPrice = "averageWorstPrice" in input && input.averageWorstPrice != null
310
318
  ? input.averageWorstPrice
311
319
  : "slippage" in input && input.slippage != null
312
- ? response.data.average_worst_price
320
+ ? responseAverageWorstPrice
313
321
  : undefined;
314
322
  const guard = averageWorstPrice == null ? undefined : BigInt(averageWorstPrice);
315
323
  if (guard != null) {
@@ -368,10 +376,10 @@ class MidnightApi {
368
376
  }
369
377
  return {
370
378
  data: {
371
- averageBestPrice: response.data.average_best_price,
372
- averageWorstPrice: guard?.toString() ?? response.data.average_worst_price,
373
- availableAssets: response.data.available_assets,
374
- availableUnits: response.data.available_units,
379
+ averageBestPrice,
380
+ averageWorstPrice: guard?.toString() ?? responseAverageWorstPrice,
381
+ availableAssets,
382
+ availableUnits,
375
383
  takeableOffers,
376
384
  },
377
385
  };
@@ -391,7 +399,7 @@ class MidnightApi {
391
399
  * @param params.request - Optional fetch options forwarded to this request.
392
400
  * @returns Paginated ABI-ready take objects mapped from the API response.
393
401
  * @throws {MidnightApiError} when the API returns a non-2xx response.
394
- * @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`.
402
+ * @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`.
395
403
  * @example
396
404
  * ```ts
397
405
  * import { MidnightApi } from "@morpho-org/midnight-sdk/api";
@@ -416,9 +424,10 @@ class MidnightApi {
416
424
  cursor: input.cursor,
417
425
  },
418
426
  });
427
+ const envelope = (0, helpers_js_1.requireResponseEnvelope)(response, "takeable offers");
419
428
  return {
420
- cursor: response.cursor,
421
- data: (0, helpers_js_1.mapBoundTakeableOffers)(response.data, {
429
+ cursor: (0, helpers_js_1.parseResponseCursor)(envelope.cursor, "takeable offers"),
430
+ data: (0, helpers_js_1.mapBoundTakeableOffers)(envelope.data, {
422
431
  maker: input.maker,
423
432
  marketIds: input.marketIds,
424
433
  groups: input.groups,
@@ -558,7 +567,7 @@ class MidnightApi {
558
567
  * @param params.cursor - Optional opaque pagination cursor from a previous response.
559
568
  * @returns Paginated books mapped to SDK camelCase fields, with each book's price levels sorted best first (asks ascending tick, bids descending tick).
560
569
  * @throws {MidnightApiError} when the API returns a non-2xx response.
561
- * @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.
570
+ * @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.
562
571
  * @example
563
572
  * ```ts
564
573
  * import { MidnightApi } from "@morpho-org/midnight-sdk/api";
@@ -583,7 +592,7 @@ class MidnightApi {
583
592
  * @param params.depth - Optional maximum levels returned per side.
584
593
  * @returns Book snapshot mapped to SDK camelCase fields, with price levels sorted best first (asks ascending tick, bids descending tick).
585
594
  * @throws {MidnightApiError} when the API returns a non-2xx response.
586
- * @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`.
595
+ * @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`.
587
596
  * @example
588
597
  * ```ts
589
598
  * import { MidnightApi } from "@morpho-org/midnight-sdk/api";
@@ -611,7 +620,7 @@ class MidnightApi {
611
620
  * @param params.depth - Optional maximum levels returned.
612
621
  * @returns Price levels mapped to SDK camelCase fields, sorted best first (asks ascending tick, bids descending tick).
613
622
  * @throws {MidnightApiError} when the API returns a non-2xx response.
614
- * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON.
623
+ * @throws {InvalidMidnightApiResponseError} when the API success response is not JSON or its envelope or price levels are malformed.
615
624
  * @example
616
625
  * ```ts
617
626
  * import { MidnightApi } from "@morpho-org/midnight-sdk/api";
@@ -639,7 +648,7 @@ class MidnightApi {
639
648
  * @param params.side - Book side to query.
640
649
  * @returns ABI-ready take objects mapped from the API response.
641
650
  * @throws {MidnightApiError} when the API returns a non-2xx response.
642
- * @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`.
651
+ * @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`.
643
652
  * @example
644
653
  * ```ts
645
654
  * import { MidnightApi } from "@morpho-org/midnight-sdk/api";
@@ -671,6 +680,7 @@ class MidnightApi {
671
680
  * @param params.slippage - Optional slippage percentage used to derive the guard. Mutually exclusive with `params.averageWorstPrice`.
672
681
  * @param params.taker - Account that will execute the take (the `taker` passed to Midnight `take`).
673
682
  * The API leaves out offers made by this account, since Midnight rejects self-takes.
683
+ * @param params.limit - Optional maximum number of offers the API walks to build the quote (1 to 10,000, API default 10,000).
674
684
  * @param params.settlementFee - Optional current WAD-scaled settlement fee used for local guard validation. Defaults to zero.
675
685
  * @returns Quote and ABI-ready take caps. `averageWorstPrice` equals the caller's guard when provided,
676
686
  * otherwise the API's guard. Offers are returned as the API sends them. An `asks` quote by
@@ -682,7 +692,7 @@ class MidnightApi {
682
692
  * @throws {InvalidMidnightApiQuoteTargetError} when the runtime input does not set exactly one of `units` or `assets`.
683
693
  * @throws {NegativeValueError} when `settlementFee` is negative.
684
694
  * @throws {MidnightApiError} when the API returns a non-2xx response.
685
- * @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.
695
+ * @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.
686
696
  * @throws {SettlementFeeExceedsPriceError} when a bid's settlement fee exceeds its offer price.
687
697
  * @example
688
698
  * ```ts
@@ -715,7 +725,7 @@ class MidnightApi {
715
725
  * @param params.cursor - Optional opaque pagination cursor from a previous response.
716
726
  * @returns Paginated ABI-ready take objects mapped from the API response.
717
727
  * @throws {MidnightApiError} when the API returns a non-2xx response.
718
- * @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`.
728
+ * @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`.
719
729
  * @example
720
730
  * ```ts
721
731
  * 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;
@@ -7,11 +7,16 @@ exports.mapBoundBooks = mapBoundBooks;
7
7
  exports.mapPriceLevels = mapPriceLevels;
8
8
  exports.mapBoundTakeableOffers = mapBoundTakeableOffers;
9
9
  exports.parseValidationResponse = parseValidationResponse;
10
+ exports.requireObject = requireObject;
11
+ exports.requireResponseEnvelope = requireResponseEnvelope;
12
+ exports.parseResponseCursor = parseResponseCursor;
13
+ exports.requireBigIntString = requireBigIntString;
10
14
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
11
15
  const viem_1 = require("viem");
12
16
  const errors_js_1 = require("../errors.js");
13
17
  const index_js_1 = require("../market/index.js");
14
- const index_js_2 = require("../offers/index.js");
18
+ const index_js_2 = require("../math/index.js");
19
+ const index_js_3 = require("../offers/index.js");
15
20
  const types_js_1 = require("./types.js");
16
21
  const version_generated_js_1 = require("./version.generated.js");
17
22
  const DEFAULT_MIDNIGHT_API_URL = new URL("/v0/midnight", morpho_ts_1.BLUE_API_BASE_URL);
@@ -100,6 +105,11 @@ function buildBookPath(params) {
100
105
  * the onchain `collateralIndex`.
101
106
  */
102
107
  function mapBookMarket(book) {
108
+ // Validate the response shape before reading its fields.
109
+ requireObject(book, "book");
110
+ if (typeof book.market_id !== "string") {
111
+ throw new errors_js_1.InvalidMidnightApiResponseError("Midnight API book market_id is not a string.");
112
+ }
103
113
  let derivedMarketId;
104
114
  let matchesAdvertisedId;
105
115
  try {
@@ -154,7 +164,7 @@ function mapBoundBookMarket(book, requestedMarketId) {
154
164
  }
155
165
  /** @internal Maps listed book markets, binding each verified id to requested filters when present. */
156
166
  function mapBoundBooks(books, context = {}) {
157
- return books.map((book) => {
167
+ return requireArray(books, "books").map((book) => {
158
168
  const market = mapBookMarket(book);
159
169
  if (context.marketIds != null &&
160
170
  context.marketIds.length > 0 &&
@@ -196,17 +206,28 @@ function mapCollateral(collateral) {
196
206
  }
197
207
  /** @internal Maps a price-level API payload to the SDK response shape. */
198
208
  function mapPriceLevel(level) {
209
+ // Validate the response shape before reading its fields.
210
+ requireObject(level, "price level");
211
+ if (typeof level.tick !== "number" || !Number.isSafeInteger(level.tick)) {
212
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API price level tick (${typeof level.tick}) is not a safe integer.`);
213
+ }
214
+ const price = requireBigIntString(level.price, "price level price");
215
+ const units = requireBigIntString(level.units, "price level units");
216
+ const assets = requireBigIntString(level.assets, "price level assets");
217
+ if (typeof level.count !== "number" || !Number.isSafeInteger(level.count)) {
218
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API price level count (${typeof level.count}) is not a safe integer.`);
219
+ }
199
220
  return {
200
221
  tick: level.tick,
201
- price: level.price,
202
- units: level.units,
203
- assets: level.assets,
222
+ price,
223
+ units,
224
+ assets,
204
225
  count: level.count,
205
226
  };
206
227
  }
207
228
  /** @internal Maps API price levels and sorts them best first: asks by ascending tick, bids by descending tick. */
208
229
  function mapPriceLevels(levels, side) {
209
- return levels
230
+ return requireArray(levels, "price levels")
210
231
  .map(mapPriceLevel)
211
232
  .sort((a, b) => (side === "asks" ? a.tick - b.tick : b.tick - a.tick));
212
233
  }
@@ -217,6 +238,26 @@ function mapPriceLevels(levels, side) {
217
238
  */
218
239
  function mapTakeableOffer(takeableOffer) {
219
240
  const offer = takeableOffer.offer;
241
+ // The filters after mapping call viem helpers that throw their own errors on non-address values.
242
+ for (const [field, value] of [
243
+ ["maker", offer.maker],
244
+ ["receiver_if_maker_is_seller", offer.receiver_if_maker_is_seller],
245
+ ]) {
246
+ if (typeof value !== "string" || !(0, viem_1.isAddress)(value, { strict: false })) {
247
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API takeable offer ${field} (${typeof value}) is not an address.`);
248
+ }
249
+ }
250
+ if (typeof offer.group !== "string" || !(0, viem_1.isHex)(offer.group)) {
251
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API takeable offer group (${typeof offer.group}) is not a hex string.`);
252
+ }
253
+ for (const [field, value] of [
254
+ ["buy", offer.buy],
255
+ ["reduce_only", offer.reduce_only],
256
+ ]) {
257
+ if (typeof value !== "boolean") {
258
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API takeable offer ${field} (${typeof value}) is not a boolean.`);
259
+ }
260
+ }
220
261
  return {
221
262
  marketId: takeableOffer.market_id,
222
263
  units: BigInt(takeableOffer.units),
@@ -242,7 +283,7 @@ function mapTakeableOffer(takeableOffer) {
242
283
  maker: offer.maker,
243
284
  start: BigInt(offer.start),
244
285
  expiry: BigInt(offer.expiry),
245
- tick: BigInt(offer.tick),
286
+ tick: index_js_2.TickLib.assertTickInRange(BigInt(offer.tick)),
246
287
  group: offer.group,
247
288
  callback: offer.callback,
248
289
  callbackData: offer.callback_data,
@@ -258,7 +299,13 @@ function mapTakeableOffer(takeableOffer) {
258
299
  }
259
300
  /** @internal Maps, validates offer caps and units, and best-price-sorts API takeable offers. */
260
301
  function mapBoundTakeableOffers(takeableOffers, context) {
261
- const mapped = takeableOffers.map((takeableOffer) => {
302
+ const mapped = requireArray(takeableOffers, "takeable offers").map((takeableOffer) => {
303
+ // Validate the response shape before reading its fields.
304
+ requireObject(takeableOffer, "takeable offer");
305
+ // Rejects malformed entries before the catch below interpolates their market_id.
306
+ if (typeof takeableOffer.market_id !== "string") {
307
+ throw new errors_js_1.InvalidMidnightApiResponseError("Midnight API takeable offer market_id is not a string.");
308
+ }
262
309
  let take;
263
310
  let matchesAdvertisedId;
264
311
  let embeddedMarketId;
@@ -282,8 +329,8 @@ function mapBoundTakeableOffers(takeableOffers, context) {
282
329
  }
283
330
  try {
284
331
  // Return values unused: called only to enforce the cap-shape and buy-receiver invariants.
285
- index_js_2.OfferUtils.validateOfferCaps({ maxUnits, maxAssets });
286
- index_js_2.OfferUtils.resolveReceiverIfMakerIsSeller({
332
+ index_js_3.OfferUtils.validateOfferCaps({ maxUnits, maxAssets });
333
+ index_js_3.OfferUtils.resolveReceiverIfMakerIsSeller({
287
334
  buy,
288
335
  maker,
289
336
  receiverIfMakerIsSeller,
@@ -389,6 +436,46 @@ function parseValidationResponse(response) {
389
436
  issues,
390
437
  };
391
438
  }
439
+ /** @internal Returns `value` when it is a non-null, non-array object. */
440
+ function requireObject(value, context) {
441
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
442
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API ${context} is malformed.`);
443
+ }
444
+ return value;
445
+ }
446
+ /** @internal Returns a Midnight API response envelope after checking it carries `data`. */
447
+ function requireResponseEnvelope(response, context) {
448
+ // Validate the response shape before reading its fields.
449
+ requireObject(response, `${context} response`);
450
+ if (response.data == null) {
451
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API ${context} response is missing "data".`);
452
+ }
453
+ return response;
454
+ }
455
+ /** @internal Parses a paginated response cursor, treating a missing cursor as the last page. */
456
+ function parseResponseCursor(cursor, context) {
457
+ if (cursor == null)
458
+ return null;
459
+ if (typeof cursor === "string")
460
+ return cursor;
461
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API ${context} cursor is malformed.`);
462
+ }
463
+ /** @internal Returns `value` when it is a decimal string of a uint256. */
464
+ function requireBigIntString(value, context) {
465
+ if (typeof value === "string" &&
466
+ value.length <= MAX_UINT256_DECIMAL_LENGTH &&
467
+ /^\d+$/.test(value) &&
468
+ BigInt(value) <= viem_1.maxUint256) {
469
+ return value;
470
+ }
471
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API ${context} (${typeof value}) is not a decimal uint256 string.`);
472
+ }
473
+ function requireArray(value, context) {
474
+ if (Array.isArray(value))
475
+ return value;
476
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API ${context} is malformed.`);
477
+ }
478
+ /** @internal Returns `value` when it is a plain object, else throws `InvalidMidnightApiResponseError`. */
392
479
  function requireRecord(value, context) {
393
480
  if (isRecord(value))
394
481
  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.3.0";
2
+ export declare const MIDNIGHT_SDK_VERSION = "2.4.0";
@@ -3,4 +3,4 @@
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.MIDNIGHT_SDK_VERSION = void 0;
5
5
  /** @internal Installed Midnight SDK package version. */
6
- exports.MIDNIGHT_SDK_VERSION = "2.3.0";
6
+ exports.MIDNIGHT_SDK_VERSION = "2.4.0";
@@ -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`.
@@ -457,6 +457,9 @@ class Offer {
457
457
  * continuous fee and settlement-fee buckets are available locally. Fetch the
458
458
  * current `consumed(maker, group)` value separately and pass it as input.
459
459
  *
460
+ * Returns `0n` when Midnight `take` rejects this offer regardless of the
461
+ * amount; see {@link OfferUtils.getConsumableUnits} for the mirrored checks.
462
+ *
460
463
  * @param params.consumed - Amount already consumed from this offer's group.
461
464
  * @param params.timestamp - Timestamp used to compute the market time to maturity.
462
465
  * @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.
@@ -891,6 +891,12 @@ var OfferUtils;
891
891
  * continuous fee and settlement-fee buckets are available locally. Fetch the
892
892
  * current `consumed(maker, group)` value separately and pass it as input.
893
893
  *
894
+ * Returns `0n` when Midnight `take` rejects the offer regardless of the
895
+ * amount: outside its `start`/`expiry` window, above its `continuousFeeCap`,
896
+ * on a tick off the market's tick spacing (the default spacing on an
897
+ * untouched market), or on a market whose loss factor is maxed out. Taker-dependent checks (`SelfTake`, ratification) and the
898
+ * seller's post-maturity debt check are not mirrored.
899
+ *
894
900
  * @param params.offer - Offer to inspect. Its market must be hydrated.
895
901
  * @param params.consumed - Amount already consumed from the offer group.
896
902
  * @param params.timestamp - Timestamp used to compute market time to maturity.
@@ -987,6 +993,14 @@ var OfferUtils;
987
993
  return 0n;
988
994
  if (continuousFeeCap < BigInt(market.continuousFee))
989
995
  return 0n;
996
+ if (market.lossFactor >= viem_1.maxUint128)
997
+ return 0n;
998
+ // A zero spacing marks an untouched market, which `take` creates with its default spacing.
999
+ const tickSpacing = market.tickSpacing === 0
1000
+ ? constants_js_1.DEFAULT_TICK_SPACING
1001
+ : BigInt(market.tickSpacing);
1002
+ if (BigInt(offer.tick) % tickSpacing !== 0n)
1003
+ return 0n;
990
1004
  const settlementFee = market.getSettlementFee(market.timeToMaturity(timestamp));
991
1005
  // Validates the settlement fee against the offer price for both cap modes.
992
1006
  const { sellerPrice, buyerPrice } = index_js_2.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;
@@ -144,8 +144,21 @@ exports.Position = Position;
144
144
  */
145
145
  class AccrualPosition extends Position {
146
146
  _market;
147
+ /**
148
+ * @throws {InvalidMarketParameterError} when `position` carries a `marketId` that differs from `market.id`.
149
+ */
147
150
  constructor(position, market) {
148
151
  const _market = Market_js_1.Market.from(market);
152
+ const carriedMarketId = "marketId" in position ? position.marketId : undefined;
153
+ if (carriedMarketId !== undefined &&
154
+ (typeof carriedMarketId !== "string" ||
155
+ carriedMarketId.toLowerCase() !== _market.id.toLowerCase())) {
156
+ throw new errors_js_1.InvalidMarketParameterError({
157
+ parameter: "marketId",
158
+ value: carriedMarketId,
159
+ instruction: "Pair the position with the market it was read from.",
160
+ });
161
+ }
149
162
  super({ ...position, marketId: _market.id });
150
163
  this._market = _market;
151
164
  }