@morpho-org/midnight-sdk 2.4.0-next.0 → 2.5.0-next.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.
- package/lib/cjs/abis.d.ts +382 -0
- package/lib/cjs/abis.js +488 -1
- package/lib/cjs/api/MidnightApi.d.ts +14 -12
- package/lib/cjs/api/MidnightApi.js +35 -25
- package/lib/cjs/api/helpers.d.ts +10 -0
- package/lib/cjs/api/helpers.js +97 -10
- package/lib/cjs/api/types.d.ts +5 -0
- package/lib/cjs/api/version.generated.d.ts +1 -1
- package/lib/cjs/api/version.generated.js +1 -1
- package/lib/cjs/offers/Offer.d.ts +3 -0
- package/lib/cjs/offers/Offer.js +3 -0
- package/lib/cjs/offers/OfferUtils.d.ts +6 -0
- package/lib/cjs/offers/OfferUtils.js +14 -0
- package/lib/cjs/position/Position.d.ts +3 -0
- package/lib/cjs/position/Position.js +13 -0
- package/lib/esm/abis.d.ts +382 -0
- package/lib/esm/abis.js +487 -0
- package/lib/esm/api/MidnightApi.d.ts +14 -12
- package/lib/esm/api/MidnightApi.js +36 -26
- package/lib/esm/api/helpers.d.ts +10 -0
- package/lib/esm/api/helpers.js +91 -8
- package/lib/esm/api/types.d.ts +5 -0
- package/lib/esm/api/version.generated.d.ts +1 -1
- package/lib/esm/api/version.generated.js +1 -1
- package/lib/esm/offers/Offer.d.ts +3 -0
- package/lib/esm/offers/Offer.js +3 -0
- package/lib/esm/offers/OfferUtils.d.ts +6 -0
- package/lib/esm/offers/OfferUtils.js +15 -1
- package/lib/esm/position/Position.d.ts +3 -0
- package/lib/esm/position/Position.js +14 -1
- 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:
|
|
109
|
-
data: mapBoundBooks(
|
|
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
|
|
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
|
-
?
|
|
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
|
|
368
|
-
averageWorstPrice: guard?.toString() ??
|
|
369
|
-
availableAssets
|
|
370
|
-
availableUnits
|
|
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:
|
|
417
|
-
data: mapBoundTakeableOffers(
|
|
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";
|
package/lib/esm/api/helpers.d.ts
CHANGED
|
@@ -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;
|
package/lib/esm/api/helpers.js
CHANGED
|
@@ -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
|
|
193
|
-
units
|
|
194
|
-
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;
|
package/lib/esm/api/types.d.ts
CHANGED
|
@@ -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.
|
|
2
|
+
export declare const MIDNIGHT_SDK_VERSION = "2.5.0-next.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`.
|
package/lib/esm/offers/Offer.js
CHANGED
|
@@ -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;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { _try, MathLib } from "@morpho-org/morpho-ts";
|
|
2
|
-
import { UnknownCollateralIndexError } from "../errors.js";
|
|
2
|
+
import { InvalidMarketParameterError, UnknownCollateralIndexError, } from "../errors.js";
|
|
3
3
|
import { Market } from "../market/Market.js";
|
|
4
4
|
import { PositionUtils } from "./PositionUtils.js";
|
|
5
5
|
/**
|
|
@@ -140,8 +140,21 @@ export class Position {
|
|
|
140
140
|
*/
|
|
141
141
|
export class AccrualPosition extends Position {
|
|
142
142
|
_market;
|
|
143
|
+
/**
|
|
144
|
+
* @throws {InvalidMarketParameterError} when `position` carries a `marketId` that differs from `market.id`.
|
|
145
|
+
*/
|
|
143
146
|
constructor(position, market) {
|
|
144
147
|
const _market = Market.from(market);
|
|
148
|
+
const carriedMarketId = "marketId" in position ? position.marketId : undefined;
|
|
149
|
+
if (carriedMarketId !== undefined &&
|
|
150
|
+
(typeof carriedMarketId !== "string" ||
|
|
151
|
+
carriedMarketId.toLowerCase() !== _market.id.toLowerCase())) {
|
|
152
|
+
throw new InvalidMarketParameterError({
|
|
153
|
+
parameter: "marketId",
|
|
154
|
+
value: carriedMarketId,
|
|
155
|
+
instruction: "Pair the position with the market it was read from.",
|
|
156
|
+
});
|
|
157
|
+
}
|
|
145
158
|
super({ ...position, marketId: _market.id });
|
|
146
159
|
this._market = _market;
|
|
147
160
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@morpho-org/midnight-sdk",
|
|
3
3
|
"description": "Viem-based package for Morpho Midnight that exports protocol utilities, fetch helpers, and Midnight API utilities under a dedicated API subpath.",
|
|
4
|
-
"version": "2.
|
|
4
|
+
"version": "2.5.0-next.0",
|
|
5
5
|
"author": "Morpho Association <contact@morpho.org>",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
@@ -41,12 +41,12 @@
|
|
|
41
41
|
"MIGRATION-v1-to-v2.md"
|
|
42
42
|
],
|
|
43
43
|
"peerDependencies": {
|
|
44
|
-
"@morpho-org/morpho-ts": "^4.
|
|
44
|
+
"@morpho-org/morpho-ts": "^4.3.0-0",
|
|
45
45
|
"viem": "^2.0.0"
|
|
46
46
|
},
|
|
47
47
|
"devDependencies": {
|
|
48
|
-
"@morpho-org/morpho-ts": "^4.
|
|
49
|
-
"@morpho-org/test": "^2.13.0-next.
|
|
48
|
+
"@morpho-org/morpho-ts": "^4.3.0-next.0",
|
|
49
|
+
"@morpho-org/test": "^2.13.0-next.1",
|
|
50
50
|
"fast-check": "^4.9.0",
|
|
51
51
|
"typescript": "7.0.2",
|
|
52
52
|
"viem": "^2.55.10",
|