@morpho-org/midnight-sdk 2.7.0 → 2.8.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.
Files changed (57) hide show
  1. package/lib/cjs/api/MidnightApi.js +63 -52
  2. package/lib/cjs/api/helpers.js +30 -17
  3. package/lib/cjs/errors.d.ts +13 -27
  4. package/lib/cjs/errors.js +8 -39
  5. package/lib/cjs/fetch/Position.js +2 -1
  6. package/lib/cjs/fetch/Ratifier.js +4 -5
  7. package/lib/cjs/market/Market.js +2 -1
  8. package/lib/cjs/market/MarketUtils.js +17 -17
  9. package/lib/cjs/math/TakeAmountsLib.js +8 -4
  10. package/lib/cjs/math/TickLib.js +12 -6
  11. package/lib/cjs/offers/OfferChainUtils.js +35 -26
  12. package/lib/cjs/offers/OfferUtils.js +17 -10
  13. package/lib/cjs/position/Position.js +2 -1
  14. package/lib/cjs/position/PositionUtils.js +11 -35
  15. package/lib/cjs/signatures/EcrecoverRatifier.js +22 -17
  16. package/lib/cjs/signatures/Group.js +4 -2
  17. package/lib/cjs/signatures/Payload.js +18 -9
  18. package/lib/cjs/signatures/PriceRatifierV1.js +5 -4
  19. package/lib/cjs/signatures/RateRatifierV1.js +19 -11
  20. package/lib/cjs/signatures/Ratifier.js +4 -4
  21. package/lib/cjs/signatures/SetterRatifier.js +2 -1
  22. package/lib/cjs/signatures/Tree.js +8 -4
  23. package/lib/cjs/signatures/TreeUtils.js +16 -13
  24. package/lib/cjs/signatures/ratifierV1Internal.js +34 -24
  25. package/lib/cjs/signatures/treeMathInternal.d.ts +2 -0
  26. package/lib/cjs/signatures/treeMathInternal.js +10 -0
  27. package/lib/cjs/version.d.ts +1 -1
  28. package/lib/cjs/version.js +1 -1
  29. package/lib/esm/api/MidnightApi.js +63 -52
  30. package/lib/esm/api/helpers.js +30 -17
  31. package/lib/esm/errors.d.ts +13 -27
  32. package/lib/esm/errors.js +8 -36
  33. package/lib/esm/fetch/Position.js +2 -1
  34. package/lib/esm/fetch/Ratifier.js +4 -5
  35. package/lib/esm/market/Market.js +2 -1
  36. package/lib/esm/market/MarketUtils.js +19 -19
  37. package/lib/esm/math/TakeAmountsLib.js +8 -4
  38. package/lib/esm/math/TickLib.js +12 -6
  39. package/lib/esm/offers/OfferChainUtils.js +35 -26
  40. package/lib/esm/offers/OfferUtils.js +17 -10
  41. package/lib/esm/position/Position.js +2 -1
  42. package/lib/esm/position/PositionUtils.js +12 -36
  43. package/lib/esm/signatures/EcrecoverRatifier.js +22 -17
  44. package/lib/esm/signatures/Group.js +4 -2
  45. package/lib/esm/signatures/Payload.js +18 -9
  46. package/lib/esm/signatures/PriceRatifierV1.js +5 -4
  47. package/lib/esm/signatures/RateRatifierV1.js +19 -11
  48. package/lib/esm/signatures/Ratifier.js +5 -5
  49. package/lib/esm/signatures/SetterRatifier.js +2 -1
  50. package/lib/esm/signatures/Tree.js +8 -4
  51. package/lib/esm/signatures/TreeUtils.js +17 -14
  52. package/lib/esm/signatures/ratifierV1Internal.js +35 -25
  53. package/lib/esm/signatures/treeMathInternal.d.ts +2 -0
  54. package/lib/esm/signatures/treeMathInternal.js +9 -0
  55. package/lib/esm/version.d.ts +1 -1
  56. package/lib/esm/version.js +1 -1
  57. package/package.json +4 -4
@@ -6,6 +6,56 @@ const errors_js_1 = require("../errors.js");
6
6
  const index_js_1 = require("../math/index.js");
7
7
  const Payload_js_1 = require("../signatures/Payload.js");
8
8
  const helpers_js_1 = require("./helpers.js");
9
+ function computeQuoteFillByUnits({ side, settlementFee, takeableOffers }, units) {
10
+ let remainingUnits = units;
11
+ let filledUnits = 0n;
12
+ let filledAssets = 0n;
13
+ for (const take of takeableOffers) {
14
+ if (remainingUnits === 0n) {
15
+ break;
16
+ }
17
+ const { buyerPrice, sellerPrice } = index_js_1.TakeAmountsLib.prices({
18
+ offer: take.offer,
19
+ settlementFee,
20
+ });
21
+ const price = side === "asks" ? buyerPrice : sellerPrice;
22
+ const filled = take.units < remainingUnits ? take.units : remainingUnits;
23
+ filledUnits += filled;
24
+ filledAssets += morpho_ts_1.MathLib.mulDiv(filled, price, morpho_ts_1.MathLib.WAD, side === "asks" ? "Up" : "Down");
25
+ remainingUnits -= filled;
26
+ }
27
+ return { filledUnits, filledAssets };
28
+ }
29
+ function computeQuoteFillByAssets({ side, settlementFee, takeableOffers }, assets) {
30
+ let remainingAssets = assets;
31
+ let filledUnits = 0n;
32
+ let filledAssets = 0n;
33
+ for (const take of takeableOffers) {
34
+ if (remainingAssets === 0n) {
35
+ break;
36
+ }
37
+ const { buyerPrice, sellerPrice } = index_js_1.TakeAmountsLib.prices({
38
+ offer: take.offer,
39
+ settlementFee,
40
+ });
41
+ const makerPrice = side === "asks" ? sellerPrice : buyerPrice;
42
+ const settlementPrice = side === "asks" ? buyerPrice : sellerPrice;
43
+ const takeMakerAssets = side === "asks"
44
+ ? morpho_ts_1.MathLib.mulDivUp(take.units, makerPrice, morpho_ts_1.MathLib.WAD)
45
+ : morpho_ts_1.MathLib.mulDivDown(take.units, makerPrice, morpho_ts_1.MathLib.WAD);
46
+ const fillsEntireTake = takeMakerAssets <= remainingAssets;
47
+ const filled = fillsEntireTake
48
+ ? take.units
49
+ : morpho_ts_1.MathLib.mulDiv(remainingAssets, morpho_ts_1.MathLib.WAD, makerPrice, side === "asks" ? "Down" : "Up");
50
+ if (filled === 0n) {
51
+ continue;
52
+ }
53
+ filledUnits += filled;
54
+ filledAssets += morpho_ts_1.MathLib.mulDiv(filled, settlementPrice, morpho_ts_1.MathLib.WAD, side === "asks" ? "Up" : "Down");
55
+ remainingAssets = fillsEntireTake ? remainingAssets - takeMakerAssets : 0n;
56
+ }
57
+ return { filledUnits, filledAssets };
58
+ }
9
59
  var types_js_1 = require("./types.js");
10
60
  Object.defineProperty(exports, "MempoolPayloadValidationRule", { enumerable: true, get: function () { return types_js_1.MempoolPayloadValidationRule; } });
11
61
  /**
@@ -283,8 +333,9 @@ class MidnightApi {
283
333
  */
284
334
  static async fetchBookQuote(params) {
285
335
  const input = params;
286
- if ((input.units == null) === (input.assets == null))
336
+ if ((input.units == null) === (input.assets == null)) {
287
337
  throw new errors_js_1.InvalidMidnightApiQuoteTargetError();
338
+ }
288
339
  const settlementFee = BigInt(input.settlementFee ?? 0n);
289
340
  (0, morpho_ts_1.assertNonNegative)("settlementFee", settlementFee);
290
341
  const response = await (0, helpers_js_1.requestMidnightApi)({
@@ -314,58 +365,18 @@ class MidnightApi {
314
365
  side: input.side,
315
366
  taker: input.taker,
316
367
  });
317
- const averageWorstPrice = "averageWorstPrice" in input && input.averageWorstPrice != null
318
- ? input.averageWorstPrice
319
- : "slippage" in input && input.slippage != null
320
- ? responseAverageWorstPrice
321
- : undefined;
322
- const guard = averageWorstPrice == null ? undefined : BigInt(averageWorstPrice);
368
+ let guard;
369
+ if ("averageWorstPrice" in input && input.averageWorstPrice != null) {
370
+ guard = BigInt(input.averageWorstPrice);
371
+ }
372
+ else if ("slippage" in input && input.slippage != null) {
373
+ guard = BigInt(responseAverageWorstPrice);
374
+ }
323
375
  if (guard != null) {
324
- let filledUnits = 0n;
325
- let filledAssets = 0n;
326
- if ("units" in input && input.units != null) {
327
- let remainingUnits = BigInt(input.units);
328
- for (const take of takeableOffers) {
329
- if (remainingUnits === 0n)
330
- break;
331
- const { buyerPrice, sellerPrice } = index_js_1.TakeAmountsLib.prices({
332
- offer: take.offer,
333
- settlementFee,
334
- });
335
- const price = input.side === "asks" ? buyerPrice : sellerPrice;
336
- const filled = take.units < remainingUnits ? take.units : remainingUnits;
337
- filledUnits += filled;
338
- filledAssets += morpho_ts_1.MathLib.mulDiv(filled, price, morpho_ts_1.MathLib.WAD, input.side === "asks" ? "Up" : "Down");
339
- remainingUnits -= filled;
340
- }
341
- }
342
- else {
343
- let remainingAssets = BigInt(input.assets);
344
- for (const take of takeableOffers) {
345
- if (remainingAssets === 0n)
346
- break;
347
- const { buyerPrice, sellerPrice } = index_js_1.TakeAmountsLib.prices({
348
- offer: take.offer,
349
- settlementFee,
350
- });
351
- const makerPrice = input.side === "asks" ? sellerPrice : buyerPrice;
352
- const settlementPrice = input.side === "asks" ? buyerPrice : sellerPrice;
353
- const takeMakerAssets = input.side === "asks"
354
- ? morpho_ts_1.MathLib.mulDivUp(take.units, makerPrice, morpho_ts_1.MathLib.WAD)
355
- : morpho_ts_1.MathLib.mulDivDown(take.units, makerPrice, morpho_ts_1.MathLib.WAD);
356
- const fillsEntireTake = takeMakerAssets <= remainingAssets;
357
- const filled = fillsEntireTake
358
- ? take.units
359
- : morpho_ts_1.MathLib.mulDiv(remainingAssets, morpho_ts_1.MathLib.WAD, makerPrice, input.side === "asks" ? "Down" : "Up");
360
- if (filled === 0n)
361
- continue;
362
- filledUnits += filled;
363
- filledAssets += morpho_ts_1.MathLib.mulDiv(filled, settlementPrice, morpho_ts_1.MathLib.WAD, input.side === "asks" ? "Up" : "Down");
364
- remainingAssets = fillsEntireTake
365
- ? remainingAssets - takeMakerAssets
366
- : 0n;
367
- }
368
- }
376
+ const settlement = { side: input.side, settlementFee, takeableOffers };
377
+ const { filledUnits, filledAssets } = "units" in input && input.units != null
378
+ ? computeQuoteFillByUnits(settlement, BigInt(input.units))
379
+ : computeQuoteFillByAssets(settlement, BigInt(input.assets));
369
380
  if (filledUnits > 0n) {
370
381
  const averagePrice = morpho_ts_1.MathLib.mulDiv(filledAssets, morpho_ts_1.MathLib.WAD, filledUnits, input.side === "asks" ? "Up" : "Down");
371
382
  const violatesGuard = input.side === "asks" ? averagePrice > guard : averagePrice < guard;
@@ -37,20 +37,24 @@ async function requestMidnightApi(params) {
37
37
  url.hash = "";
38
38
  if (params.query != null) {
39
39
  for (const [key, value] of Object.entries(params.query)) {
40
- if (value === undefined)
40
+ if (value === undefined) {
41
41
  continue;
42
- if (Array.isArray(value) && value.length === 0)
42
+ }
43
+ if (Array.isArray(value) && value.length === 0) {
43
44
  continue;
44
- url.searchParams.set(key, Array.isArray(value)
45
- ? value.map(String).join(",")
46
- : value instanceof Date
47
- ? value.toISOString()
48
- : String(value));
45
+ }
46
+ if (Array.isArray(value)) {
47
+ url.searchParams.set(key, value.map(String).join(","));
48
+ }
49
+ else {
50
+ url.searchParams.set(key, value instanceof Date ? value.toISOString() : String(value));
51
+ }
49
52
  }
50
53
  }
51
54
  const headers = new Headers(params.request?.headers);
52
- if (params.body !== undefined)
55
+ if (params.body !== undefined) {
53
56
  headers.set("Content-Type", "application/json");
57
+ }
54
58
  headers.set("sdk-version", version_js_1.version);
55
59
  const init = {
56
60
  ...params.request,
@@ -345,8 +349,9 @@ function mapBoundTakeableOffers(takeableOffers, context) {
345
349
  });
346
350
  }
347
351
  catch (cause) {
348
- if (!(cause instanceof errors_js_1.InvalidOfferParameterError))
352
+ if (!(cause instanceof errors_js_1.InvalidOfferParameterError)) {
349
353
  throw cause;
354
+ }
350
355
  throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API takeable offer for market_id "${take.marketId}" is not executable: ${cause.message}`, { cause });
351
356
  }
352
357
  if (maxUnits > 0n && take.units > maxUnits) {
@@ -383,13 +388,16 @@ function mapBoundTakeableOffers(takeableOffers, context) {
383
388
  }
384
389
  return take;
385
390
  });
386
- if (context.side == null)
391
+ if (context.side == null) {
387
392
  return mapped;
393
+ }
388
394
  return [...mapped].sort((a, b) => {
389
- if (a.offer.tick === b.offer.tick)
395
+ if (a.offer.tick === b.offer.tick) {
390
396
  return 0;
391
- if (context.side === "asks")
397
+ }
398
+ if (context.side === "asks") {
392
399
  return a.offer.tick < b.offer.tick ? -1 : 1;
400
+ }
393
401
  return a.offer.tick > b.offer.tick ? -1 : 1;
394
402
  });
395
403
  }
@@ -407,8 +415,9 @@ function parseValidationResponse(response) {
407
415
  throw new errors_js_1.InvalidMidnightApiResponseError('Midnight API validation issue is missing "rule".');
408
416
  }
409
417
  const details = record.details;
410
- if (details == null)
418
+ if (details == null) {
411
419
  return { rule };
420
+ }
412
421
  if (rule === types_js_1.MempoolPayloadValidationRule.MinOfferAssetsUsd &&
413
422
  isRecord(details)) {
414
423
  const loanToken = details.loan_token;
@@ -462,10 +471,12 @@ function requireResponseEnvelope(response, context) {
462
471
  }
463
472
  /** @internal Parses a paginated response cursor, treating a missing cursor as the last page. */
464
473
  function parseResponseCursor(cursor, context) {
465
- if (cursor == null)
474
+ if (cursor == null) {
466
475
  return null;
467
- if (typeof cursor === "string")
476
+ }
477
+ if (typeof cursor === "string") {
468
478
  return cursor;
479
+ }
469
480
  throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API ${context} cursor is malformed.`);
470
481
  }
471
482
  /** @internal Returns `value` when it is a decimal string of a uint256. */
@@ -479,14 +490,16 @@ function requireBigIntString(value, context) {
479
490
  throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API ${context} (${typeof value}) is not a decimal uint256 string.`);
480
491
  }
481
492
  function requireArray(value, context) {
482
- if (Array.isArray(value))
493
+ if (Array.isArray(value)) {
483
494
  return value;
495
+ }
484
496
  throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API ${context} is malformed.`);
485
497
  }
486
498
  /** @internal Returns `value` when it is a plain object, else throws `InvalidMidnightApiResponseError`. */
487
499
  function requireRecord(value, context) {
488
- if (isRecord(value))
500
+ if (isRecord(value)) {
489
501
  return value;
502
+ }
490
503
  throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API ${context} is malformed.`);
491
504
  }
492
505
  function isRecord(value) {
@@ -1,3 +1,4 @@
1
+ import { InvalidPositionAccrualStateError as SharedInvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError as SharedInvalidPositionAccrualTimestampError, InvalidPositionLossFactorError as SharedInvalidPositionLossFactorError } from "@morpho-org/morpho-ts";
1
2
  import type { Address } from "viem";
2
3
  import type { MempoolPayloadValidationIssue } from "./api/types.js";
3
4
  /**
@@ -70,42 +71,27 @@ export declare class SettlementFeeExceedsPriceError extends Error {
70
71
  /**
71
72
  * Thrown when a local position accrual is requested for an impossible timestamp.
72
73
  *
73
- * @example
74
- * ```ts
75
- * import { InvalidPositionAccrualTimestampError } from "@morpho-org/midnight-sdk";
76
- *
77
- * throw new InvalidPositionAccrualTimestampError(1n, 2n);
78
- * ```
74
+ * @deprecated Import `InvalidPositionAccrualTimestampError` from `@morpho-org/morpho-ts`. Removed in the next major.
79
75
  */
80
- export declare class InvalidPositionAccrualTimestampError extends Error {
81
- constructor(timestamp: bigint, lastAccrual: bigint);
82
- }
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;
83
79
  /**
84
80
  * Thrown when a local position accrual sees a market loss factor older than the position.
85
81
  *
86
- * @example
87
- * ```ts
88
- * import { InvalidPositionLossFactorError } from "@morpho-org/midnight-sdk";
89
- *
90
- * throw new InvalidPositionLossFactorError(1n, 2n);
91
- * ```
82
+ * @deprecated Import `InvalidPositionLossFactorError` from `@morpho-org/morpho-ts`. Removed in the next major.
92
83
  */
93
- export declare class InvalidPositionLossFactorError extends Error {
94
- constructor(marketLossFactor: bigint, positionLossFactor: bigint);
95
- }
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;
96
87
  /**
97
88
  * Thrown when local position accrual inputs violate Midnight accounting invariants.
98
89
  *
99
- * @example
100
- * ```ts
101
- * import { InvalidPositionAccrualStateError } from "@morpho-org/midnight-sdk";
102
- *
103
- * throw new InvalidPositionAccrualStateError("Pending fee exceeds credit.");
104
- * ```
90
+ * @deprecated Import `InvalidPositionAccrualStateError` from `@morpho-org/morpho-ts`. Removed in the next major.
105
91
  */
106
- export declare class InvalidPositionAccrualStateError extends Error {
107
- constructor(reason: string);
108
- }
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;
109
95
  /**
110
96
  * Thrown when a market parameter cannot satisfy Midnight protocol rules.
111
97
  *
package/lib/cjs/errors.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.InvalidMidnightApiQuoteTargetError = exports.InvalidMidnightApiResponseError = exports.MidnightApiError = exports.InvalidEcrecoverSignatureVError = exports.InvalidEcrecoverSignatureError = exports.InvalidTypedDataSignatureError = exports.MidnightMempoolValidationError = exports.ChainIdMismatchError = exports.RatifierV1TakerNotAllowedError = exports.InvalidRatifierV1AddressError = exports.InvalidRateRatifierV1TimeError = exports.InvalidRateRatifierV1TickError = exports.RateRatifierV1BoundOverflowError = exports.InvalidRateRatifierV1RateError = exports.InvalidTreeError = exports.InvalidTreeHeightError = exports.PayloadDecodeError = exports.InvalidOfferParameterError = exports.UnknownCollateralIndexError = exports.InvalidMarketParameterError = exports.InvalidPositionAccrualStateError = exports.InvalidPositionLossFactorError = exports.InvalidPositionAccrualTimestampError = exports.SettlementFeeExceedsPriceError = exports.InvalidTickSpacingError = exports.PriceGreaterThanOneError = exports.TickOutOfRangeError = exports.InvalidOfferGroupError = void 0;
4
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
4
5
  /**
5
6
  * Thrown when a Midnight offer group violates protocol-level group mechanics.
6
7
  *
@@ -89,57 +90,25 @@ class SettlementFeeExceedsPriceError extends Error {
89
90
  }
90
91
  }
91
92
  exports.SettlementFeeExceedsPriceError = SettlementFeeExceedsPriceError;
93
+ // Temporary compatibility exception for these shared morpho-ts errors.
92
94
  /**
93
95
  * Thrown when a local position accrual is requested for an impossible timestamp.
94
96
  *
95
- * @example
96
- * ```ts
97
- * import { InvalidPositionAccrualTimestampError } from "@morpho-org/midnight-sdk";
98
- *
99
- * throw new InvalidPositionAccrualTimestampError(1n, 2n);
100
- * ```
97
+ * @deprecated Import `InvalidPositionAccrualTimestampError` from `@morpho-org/morpho-ts`. Removed in the next major.
101
98
  */
102
- class InvalidPositionAccrualTimestampError extends Error {
103
- constructor(timestamp, lastAccrual) {
104
- super(`Position accrual timestamp "${timestamp}" is before last accrual "${lastAccrual}". Use a timestamp greater than or equal to last accrual.`);
105
- this.name = "InvalidPositionAccrualTimestampError";
106
- }
107
- }
108
- exports.InvalidPositionAccrualTimestampError = InvalidPositionAccrualTimestampError;
99
+ exports.InvalidPositionAccrualTimestampError = morpho_ts_1.InvalidPositionAccrualTimestampError;
109
100
  /**
110
101
  * Thrown when a local position accrual sees a market loss factor older than the position.
111
102
  *
112
- * @example
113
- * ```ts
114
- * import { InvalidPositionLossFactorError } from "@morpho-org/midnight-sdk";
115
- *
116
- * throw new InvalidPositionLossFactorError(1n, 2n);
117
- * ```
103
+ * @deprecated Import `InvalidPositionLossFactorError` from `@morpho-org/morpho-ts`. Removed in the next major.
118
104
  */
119
- class InvalidPositionLossFactorError extends Error {
120
- constructor(marketLossFactor, positionLossFactor) {
121
- super(`Market loss factor "${marketLossFactor}" is below position loss factor "${positionLossFactor}". Fetch a consistent market and position at the same block.`);
122
- this.name = "InvalidPositionLossFactorError";
123
- }
124
- }
125
- exports.InvalidPositionLossFactorError = InvalidPositionLossFactorError;
105
+ exports.InvalidPositionLossFactorError = morpho_ts_1.InvalidPositionLossFactorError;
126
106
  /**
127
107
  * Thrown when local position accrual inputs violate Midnight accounting invariants.
128
108
  *
129
- * @example
130
- * ```ts
131
- * import { InvalidPositionAccrualStateError } from "@morpho-org/midnight-sdk";
132
- *
133
- * throw new InvalidPositionAccrualStateError("Pending fee exceeds credit.");
134
- * ```
109
+ * @deprecated Import `InvalidPositionAccrualStateError` from `@morpho-org/morpho-ts`. Removed in the next major.
135
110
  */
136
- class InvalidPositionAccrualStateError extends Error {
137
- constructor(reason) {
138
- super(`Invalid Midnight position accrual state. ${reason}`);
139
- this.name = "InvalidPositionAccrualStateError";
140
- }
141
- }
142
- exports.InvalidPositionAccrualStateError = InvalidPositionAccrualStateError;
111
+ exports.InvalidPositionAccrualStateError = morpho_ts_1.InvalidPositionAccrualStateError;
143
112
  /**
144
113
  * Thrown when a market parameter cannot satisfy Midnight protocol rules.
145
114
  *
@@ -76,8 +76,9 @@ async function fetchPosition(client, params) {
76
76
  });
77
77
  }
78
78
  catch (error) {
79
- if (params.deployless === "force")
79
+ if (params.deployless === "force") {
80
80
  throw error;
81
+ }
81
82
  // Fallback to direct reads if deployless execution is unavailable.
82
83
  }
83
84
  }
@@ -42,13 +42,12 @@ async function fetchRatifierInfo(client, params) {
42
42
  const chainId = await (0, utils_js_1.resolveChainId)(client);
43
43
  const ecrecoverRatifier = (0, morpho_ts_1.getChainAddress)(chainId, "ecrecoverRatifier");
44
44
  const setterRatifier = (0, morpho_ts_1.getChainAddress)(chainId, "setterRatifier");
45
+ const block = params.blockNumber == null
46
+ ? { blockTag: params.blockTag ?? undefined }
47
+ : { blockNumber: params.blockNumber };
45
48
  // eth_getCode is trusted; the returned ratifier is a suggestion the caller commits to on Offer.create. See THREAT_MODEL.md, RPC.
46
49
  const bytecode = await (0, actions_1.getBytecode)(client, {
47
- ...(params.blockNumber != null
48
- ? { blockNumber: params.blockNumber }
49
- : params.blockTag != null
50
- ? { blockTag: params.blockTag }
51
- : {}),
50
+ ...block,
52
51
  address: params.maker,
53
52
  });
54
53
  return Ratifier_js_1.Ratifier.getRatifierInfo({
@@ -174,8 +174,9 @@ class MarketParams {
174
174
  * ```
175
175
  */
176
176
  static from(market) {
177
- if ("params" in market)
177
+ if ("params" in market) {
178
178
  return MarketParams.from(market.params);
179
+ }
179
180
  return market instanceof MarketParams ? market : new MarketParams(market);
180
181
  }
181
182
  }
@@ -6,7 +6,6 @@ const viem_1 = require("viem");
6
6
  const constants_js_1 = require("../constants.js");
7
7
  const errors_js_1 = require("../errors.js");
8
8
  const Market_js_1 = require("./Market.js");
9
- const SSTORE2_PREFIX = "0x600b380380600b5f395ff3";
10
9
  const collateralParamsHashParams = [
11
10
  { name: "typehash", type: "bytes32" },
12
11
  { name: "token", type: "address" },
@@ -70,8 +69,9 @@ var MarketUtils;
70
69
  function compareCollateralTokens(a, b) {
71
70
  const tokenA = a.token.toLowerCase();
72
71
  const tokenB = b.token.toLowerCase();
73
- if (tokenA === tokenB)
72
+ if (tokenA === tokenB) {
74
73
  return 0;
74
+ }
75
75
  return tokenA < tokenB ? -1 : 1;
76
76
  }
77
77
  MarketUtils.compareCollateralTokens = compareCollateralTokens;
@@ -264,20 +264,21 @@ var MarketUtils;
264
264
  function getSettlementFee(params) {
265
265
  const timeToMaturity = BigInt(params.timeToMaturity);
266
266
  (0, morpho_ts_1.assertNonNegative)("timeToMaturity", timeToMaturity);
267
- const lastIndex = constants_js_1.SETTLEMENT_FEE_BREAKPOINTS.length - 1;
268
- const lastBreakpoint = constants_js_1.SETTLEMENT_FEE_BREAKPOINTS[lastIndex];
269
- if (timeToMaturity >= lastBreakpoint) {
270
- return BigInt(params.settlementFeeCbps[lastIndex]) * constants_js_1.CBP;
267
+ const upperBucketIndices = [1, 2, 3, 4, 5, 6];
268
+ let lowerIndex = 0;
269
+ for (const upperIndex of upperBucketIndices) {
270
+ const end = constants_js_1.SETTLEMENT_FEE_BREAKPOINTS[upperIndex];
271
+ if (timeToMaturity < end) {
272
+ const start = constants_js_1.SETTLEMENT_FEE_BREAKPOINTS[lowerIndex];
273
+ const feeLower = BigInt(params.settlementFeeCbps[lowerIndex]) * constants_js_1.CBP;
274
+ const feeUpper = BigInt(params.settlementFeeCbps[upperIndex]) * constants_js_1.CBP;
275
+ return ((feeLower * (end - timeToMaturity) +
276
+ feeUpper * (timeToMaturity - start)) /
277
+ (end - start));
278
+ }
279
+ lowerIndex = upperIndex;
271
280
  }
272
- const upperIndex = constants_js_1.SETTLEMENT_FEE_BREAKPOINTS.findIndex((breakpoint) => timeToMaturity < breakpoint);
273
- const lowerIndex = upperIndex - 1;
274
- const start = constants_js_1.SETTLEMENT_FEE_BREAKPOINTS[lowerIndex];
275
- const end = constants_js_1.SETTLEMENT_FEE_BREAKPOINTS[upperIndex];
276
- const feeLower = BigInt(params.settlementFeeCbps[lowerIndex]) * constants_js_1.CBP;
277
- const feeUpper = BigInt(params.settlementFeeCbps[upperIndex]) * constants_js_1.CBP;
278
- return ((feeLower * (end - timeToMaturity) +
279
- feeUpper * (timeToMaturity - start)) /
280
- (end - start));
281
+ return BigInt(params.settlementFeeCbps[lowerIndex]) * constants_js_1.CBP;
281
282
  }
282
283
  MarketUtils.getSettlementFee = getSettlementFee;
283
284
  /**
@@ -372,8 +373,7 @@ var MarketUtils;
372
373
  function toId(market) {
373
374
  const marketParams = Market_js_1.MarketParams.from(market);
374
375
  const encodedMarket = (0, viem_1.encodeAbiParameters)([marketParamsAbiParameter], [toStruct(marketParams)]);
375
- const creationHash = (0, viem_1.keccak256)((0, viem_1.concat)([SSTORE2_PREFIX, encodedMarket]));
376
- return (0, viem_1.keccak256)((0, viem_1.encodePacked)(["uint8", "address", "uint256", "bytes32"], [255, marketParams.midnight, 0n, creationHash]));
376
+ return morpho_ts_1.MidnightMarketLib.id(marketParams.midnight, encodedMarket);
377
377
  }
378
378
  MarketUtils.toId = toId;
379
379
  })(MarketUtils || (exports.MarketUtils = MarketUtils = {}));
@@ -90,10 +90,12 @@ var TakeAmountsLib;
90
90
  const targetBuyerAssets = BigInt(params.targetBuyerAssets);
91
91
  (0, morpho_ts_1.assertNonNegative)("targetBuyerAssets", targetBuyerAssets);
92
92
  const { buyerPrice } = prices({ offer: params.offer, settlementFee });
93
- if (buyerPrice === 0n)
93
+ if (buyerPrice === 0n) {
94
94
  throw new morpho_ts_1.DivisionByZeroError("buyerPrice");
95
- if (buyerPrice > morpho_ts_1.MathLib.WAD)
95
+ }
96
+ if (buyerPrice > morpho_ts_1.MathLib.WAD) {
96
97
  throw new errors_js_1.PriceGreaterThanOneError(buyerPrice);
98
+ }
97
99
  return morpho_ts_1.MathLib.mulDiv(targetBuyerAssets, morpho_ts_1.MathLib.WAD, buyerPrice, params.offer.buy ? "Up" : "Down");
98
100
  }
99
101
  TakeAmountsLib.buyerAssetsToUnits = buyerAssetsToUnits;
@@ -133,8 +135,9 @@ var TakeAmountsLib;
133
135
  const targetSellerAssets = BigInt(params.targetSellerAssets);
134
136
  (0, morpho_ts_1.assertNonNegative)("targetSellerAssets", targetSellerAssets);
135
137
  const { sellerPrice } = prices({ offer: params.offer, settlementFee });
136
- if (sellerPrice === 0n)
138
+ if (sellerPrice === 0n) {
137
139
  throw new morpho_ts_1.DivisionByZeroError("sellerPrice");
140
+ }
138
141
  return morpho_ts_1.MathLib.mulDiv(targetSellerAssets, morpho_ts_1.MathLib.WAD, sellerPrice, params.offer.buy ? "Up" : "Down");
139
142
  }
140
143
  TakeAmountsLib.sellerAssetsToUnits = sellerAssetsToUnits;
@@ -163,8 +166,9 @@ var TakeAmountsLib;
163
166
  const price = BigInt(params.price);
164
167
  (0, morpho_ts_1.assertNonNegative)("assets", assets);
165
168
  (0, morpho_ts_1.assertNonNegative)("price", price);
166
- if (price === 0n)
169
+ if (price === 0n) {
167
170
  throw new morpho_ts_1.DivisionByZeroError("price");
171
+ }
168
172
  return morpho_ts_1.MathLib.mulDiv(assets, morpho_ts_1.MathLib.WAD, price, params.rounding);
169
173
  }
170
174
  TakeAmountsLib.toUnits = toUnits;
@@ -82,8 +82,9 @@ var TickLib;
82
82
  TickLib.assertTickInRange = (tick) => {
83
83
  const tickValue = BigInt(tick);
84
84
  (0, morpho_ts_1.assertNonNegative)("tick", tickValue);
85
- if (tickValue > constants_js_1.MAX_TICK)
85
+ if (tickValue > constants_js_1.MAX_TICK) {
86
86
  throw new errors_js_1.TickOutOfRangeError(tickValue, constants_js_1.MAX_TICK);
87
+ }
87
88
  return tickValue;
88
89
  };
89
90
  /**
@@ -100,8 +101,9 @@ var TickLib;
100
101
  * ```
101
102
  */
102
103
  TickLib.wExp = (x) => {
103
- if (x < 0n)
104
+ if (x < 0n) {
104
105
  return 1000000000000000000000000000000000000n / TickLib.wExp(-x);
106
+ }
105
107
  const q = (x + TickLib.EXP_OFFSET) / TickLib.LN_2;
106
108
  const r = x - q * TickLib.LN_2;
107
109
  const secondTerm = (r * r) / (2n * morpho_ts_1.MathLib.WAD);
@@ -152,8 +154,9 @@ var TickLib;
152
154
  const priceValue = BigInt(price);
153
155
  const spacingValue = BigInt(spacing);
154
156
  (0, morpho_ts_1.assertNonNegative)("price", priceValue);
155
- if (priceValue > morpho_ts_1.MathLib.WAD)
157
+ if (priceValue > morpho_ts_1.MathLib.WAD) {
156
158
  throw new errors_js_1.PriceGreaterThanOneError(priceValue);
159
+ }
157
160
  if (spacingValue <= 0n || constants_js_1.MAX_TICK % spacingValue !== 0n) {
158
161
  throw new errors_js_1.InvalidTickSpacingError(spacingValue);
159
162
  }
@@ -161,10 +164,12 @@ var TickLib;
161
164
  let high = constants_js_1.MAX_TICK;
162
165
  while (low !== high) {
163
166
  const mid = (low + high) / 2n;
164
- if (tickToPrice(mid) < priceValue)
167
+ if (tickToPrice(mid) < priceValue) {
165
168
  low = mid + 1n;
166
- else
169
+ }
170
+ else {
167
171
  high = mid;
172
+ }
168
173
  }
169
174
  return ((low + spacingValue - 1n) / spacingValue) * spacingValue;
170
175
  }
@@ -234,8 +239,9 @@ var TickLib;
234
239
  */
235
240
  function tickToRate(tick) {
236
241
  const price = tickToPrice(tick);
237
- if (price === 0n)
242
+ if (price === 0n) {
238
243
  throw new morpho_ts_1.DivisionByZeroError("price");
244
+ }
239
245
  return morpho_ts_1.MathLib.mulDiv(morpho_ts_1.MathLib.WAD, morpho_ts_1.MathLib.WAD, price, "Up") - morpho_ts_1.MathLib.WAD;
240
246
  }
241
247
  TickLib.tickToRate = tickToRate;