@morpho-org/midnight-sdk 2.7.0-next.1 → 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 (51) hide show
  1. package/lib/cjs/api/MidnightApi.js +63 -52
  2. package/lib/cjs/api/helpers.js +30 -17
  3. package/lib/cjs/fetch/Position.js +2 -1
  4. package/lib/cjs/fetch/Ratifier.js +4 -5
  5. package/lib/cjs/market/Market.js +2 -1
  6. package/lib/cjs/market/MarketUtils.js +16 -14
  7. package/lib/cjs/math/TakeAmountsLib.js +8 -4
  8. package/lib/cjs/math/TickLib.js +12 -6
  9. package/lib/cjs/offers/OfferChainUtils.js +35 -26
  10. package/lib/cjs/offers/OfferUtils.js +17 -10
  11. package/lib/cjs/position/Position.js +2 -1
  12. package/lib/cjs/signatures/EcrecoverRatifier.js +22 -17
  13. package/lib/cjs/signatures/Group.js +4 -2
  14. package/lib/cjs/signatures/Payload.js +18 -9
  15. package/lib/cjs/signatures/PriceRatifierV1.js +5 -4
  16. package/lib/cjs/signatures/RateRatifierV1.js +19 -11
  17. package/lib/cjs/signatures/Ratifier.js +4 -4
  18. package/lib/cjs/signatures/SetterRatifier.js +2 -1
  19. package/lib/cjs/signatures/Tree.js +8 -4
  20. package/lib/cjs/signatures/TreeUtils.js +16 -13
  21. package/lib/cjs/signatures/ratifierV1Internal.js +34 -24
  22. package/lib/cjs/signatures/treeMathInternal.d.ts +2 -0
  23. package/lib/cjs/signatures/treeMathInternal.js +10 -0
  24. package/lib/cjs/version.d.ts +1 -1
  25. package/lib/cjs/version.js +1 -1
  26. package/lib/esm/api/MidnightApi.js +63 -52
  27. package/lib/esm/api/helpers.js +30 -17
  28. package/lib/esm/fetch/Position.js +2 -1
  29. package/lib/esm/fetch/Ratifier.js +4 -5
  30. package/lib/esm/market/Market.js +2 -1
  31. package/lib/esm/market/MarketUtils.js +16 -14
  32. package/lib/esm/math/TakeAmountsLib.js +8 -4
  33. package/lib/esm/math/TickLib.js +12 -6
  34. package/lib/esm/offers/OfferChainUtils.js +35 -26
  35. package/lib/esm/offers/OfferUtils.js +17 -10
  36. package/lib/esm/position/Position.js +2 -1
  37. package/lib/esm/signatures/EcrecoverRatifier.js +22 -17
  38. package/lib/esm/signatures/Group.js +4 -2
  39. package/lib/esm/signatures/Payload.js +18 -9
  40. package/lib/esm/signatures/PriceRatifierV1.js +5 -4
  41. package/lib/esm/signatures/RateRatifierV1.js +19 -11
  42. package/lib/esm/signatures/Ratifier.js +5 -5
  43. package/lib/esm/signatures/SetterRatifier.js +2 -1
  44. package/lib/esm/signatures/Tree.js +8 -4
  45. package/lib/esm/signatures/TreeUtils.js +17 -14
  46. package/lib/esm/signatures/ratifierV1Internal.js +35 -25
  47. package/lib/esm/signatures/treeMathInternal.d.ts +2 -0
  48. package/lib/esm/signatures/treeMathInternal.js +9 -0
  49. package/lib/esm/version.d.ts +1 -1
  50. package/lib/esm/version.js +1 -1
  51. package/package.json +13 -13
@@ -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) {
@@ -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
  }
@@ -69,8 +69,9 @@ var MarketUtils;
69
69
  function compareCollateralTokens(a, b) {
70
70
  const tokenA = a.token.toLowerCase();
71
71
  const tokenB = b.token.toLowerCase();
72
- if (tokenA === tokenB)
72
+ if (tokenA === tokenB) {
73
73
  return 0;
74
+ }
74
75
  return tokenA < tokenB ? -1 : 1;
75
76
  }
76
77
  MarketUtils.compareCollateralTokens = compareCollateralTokens;
@@ -263,20 +264,21 @@ var MarketUtils;
263
264
  function getSettlementFee(params) {
264
265
  const timeToMaturity = BigInt(params.timeToMaturity);
265
266
  (0, morpho_ts_1.assertNonNegative)("timeToMaturity", timeToMaturity);
266
- const lastIndex = constants_js_1.SETTLEMENT_FEE_BREAKPOINTS.length - 1;
267
- const lastBreakpoint = constants_js_1.SETTLEMENT_FEE_BREAKPOINTS[lastIndex];
268
- if (timeToMaturity >= lastBreakpoint) {
269
- 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;
270
280
  }
271
- const upperIndex = constants_js_1.SETTLEMENT_FEE_BREAKPOINTS.findIndex((breakpoint) => timeToMaturity < breakpoint);
272
- const lowerIndex = upperIndex - 1;
273
- const start = constants_js_1.SETTLEMENT_FEE_BREAKPOINTS[lowerIndex];
274
- const end = constants_js_1.SETTLEMENT_FEE_BREAKPOINTS[upperIndex];
275
- const feeLower = BigInt(params.settlementFeeCbps[lowerIndex]) * constants_js_1.CBP;
276
- const feeUpper = BigInt(params.settlementFeeCbps[upperIndex]) * constants_js_1.CBP;
277
- return ((feeLower * (end - timeToMaturity) +
278
- feeUpper * (timeToMaturity - start)) /
279
- (end - start));
281
+ return BigInt(params.settlementFeeCbps[lowerIndex]) * constants_js_1.CBP;
280
282
  }
281
283
  MarketUtils.getSettlementFee = getSettlementFee;
282
284
  /**
@@ -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;
@@ -151,8 +151,9 @@ var OfferChainUtils;
151
151
  const tauStop = Number(maturityTimestamp - chainEndTimestamp) / SECONDS_PER_YEAR;
152
152
  const lowerRate = params.targetRate * (1 - FAVORABLE_RATE_DRIFT);
153
153
  /* v8 ignore next: positive finite targetRate validation keeps lowerRate positive for practical JS numbers. */
154
- if (lowerRate <= 0)
154
+ if (lowerRate <= 0) {
155
155
  return [];
156
+ }
156
157
  const legs = [];
157
158
  let tauTop = tauInitial;
158
159
  let iteration = 0;
@@ -169,17 +170,21 @@ var OfferChainUtils;
169
170
  priceInput = (0, viem_1.parseUnits)(price.toFixed(18), 18);
170
171
  }
171
172
  const rawTick = index_js_1.TickLib.priceToTick(priceInput, 1n) - 1n;
172
- if (rawTick < 0n || rawTick > constants_js_1.MAX_TICK)
173
+ if (rawTick < 0n || rawTick > constants_js_1.MAX_TICK) {
173
174
  break;
175
+ }
174
176
  const tick = floorTickToSpacing(rawTick, tickSpacing);
175
- if (legs.at(-1)?.tick === tick)
177
+ if (legs.at(-1)?.tick === tick) {
176
178
  break;
179
+ }
177
180
  const tauMax = rateTau(tick, lowerRate);
178
181
  const tauMin = rateTau(tick, params.targetRate);
179
- if (tauMin >= tauTop)
182
+ if (tauMin >= tauTop) {
180
183
  break;
181
- if (tauMin < tauStop)
184
+ }
185
+ if (tauMin < tauStop) {
182
186
  break;
187
+ }
183
188
  const startTimestamp = maturityTimestamp -
184
189
  BigInt(Math.round(Math.min(tauMax, tauTop) * SECONDS_PER_YEAR));
185
190
  const expiryTimestamp = maturityTimestamp - BigInt(Math.round(tauMin * SECONDS_PER_YEAR));
@@ -305,41 +310,33 @@ var OfferChainUtils;
305
310
  : maxAlignedTick;
306
311
  const tauCeiling = rateTau(ceilingTick, upperRate);
307
312
  let tauBottom = Math.max(tauStop, tauCeiling);
308
- if (tauBottom >= tauInitial)
313
+ if (tauBottom >= tauInitial) {
309
314
  return [];
315
+ }
310
316
  const tauLegs = [];
311
317
  let iteration = 0;
312
318
  for (; iteration < MAX_CHAIN_LEGS; iteration++) {
313
319
  const price = 1 / (1 + upperRate * tauBottom);
314
- let priceInput;
315
- if (!Number.isFinite(price) || price <= 0) {
316
- priceInput = 0n;
317
- }
318
- else {
319
- /* v8 ignore next: positive rates that survive the grid-floor check keep lend-chain prices below one. */
320
- if (price >= 1) {
321
- priceInput = morpho_ts_1.MathLib.WAD;
322
- }
323
- else {
324
- priceInput = (0, viem_1.parseUnits)(price.toFixed(18), 18);
325
- }
326
- }
327
- const rawTick = index_js_1.TickLib.priceToTick(priceInput, 1n);
320
+ const rawTick = index_js_1.TickLib.priceToTick(clampLendPrice(price), 1n);
328
321
  /* v8 ignore next: priceToTick returns in-range ticks; maxAlignedTick only tightens non-dividing spacing. */
329
- if (rawTick < 0n || rawTick > constants_js_1.MAX_TICK || rawTick > maxAlignedTick)
322
+ if (rawTick < 0n || rawTick > constants_js_1.MAX_TICK || rawTick > maxAlignedTick) {
330
323
  break;
324
+ }
331
325
  const alignedTick = ((rawTick + tickSpacing - 1n) / tickSpacing) * tickSpacing;
332
326
  /* v8 ignore next: non-dividing spacing boundary clamp is defensive; normal alignment is covered. */
333
327
  const tick = alignedTick < maxAlignedTick ? alignedTick : maxAlignedTick;
334
- if (tauLegs.at(-1)?.tick === tick)
328
+ if (tauLegs.at(-1)?.tick === tick) {
335
329
  break;
330
+ }
336
331
  const tauMax = rateTau(tick, params.targetRate);
337
332
  const tauMin = rateTau(tick, upperRate);
338
- if (tauMax <= tauBottom)
333
+ if (tauMax <= tauBottom) {
339
334
  break;
335
+ }
340
336
  tauLegs.push({ tick, tauMax, tauMin: Math.max(tauMin, tauBottom) });
341
- if (tauMax >= tauInitial)
337
+ if (tauMax >= tauInitial) {
342
338
  break;
339
+ }
343
340
  tauBottom = tauMax;
344
341
  }
345
342
  /* v8 ignore next: the monotonic tick walk exits before exhausting the finite tick range. */
@@ -351,8 +348,9 @@ var OfferChainUtils;
351
348
  });
352
349
  }
353
350
  const leftmostLeg = tauLegs.at(-1);
354
- if (leftmostLeg && leftmostLeg.tauMax < tauInitial)
351
+ if (leftmostLeg && leftmostLeg.tauMax < tauInitial) {
355
352
  return [];
353
+ }
356
354
  return tauLegs
357
355
  .reverse()
358
356
  .map((leg) => ({
@@ -438,11 +436,22 @@ function normalizeTimestamp(parameter, value) {
438
436
  }
439
437
  return normalized;
440
438
  }
439
+ function clampLendPrice(price) {
440
+ if (!Number.isFinite(price) || price <= 0) {
441
+ return 0n;
442
+ }
443
+ /* v8 ignore next: positive rates that survive the grid-floor check keep lend-chain prices below one. */
444
+ if (price >= 1) {
445
+ return morpho_ts_1.MathLib.WAD;
446
+ }
447
+ return (0, viem_1.parseUnits)(price.toFixed(18), 18);
448
+ }
441
449
  function rateTau(tick, rate) {
442
450
  const price = Number((0, viem_1.formatUnits)(index_js_1.TickLib.tickToPrice(tick), 18));
443
451
  /* v8 ignore next: builders pass positive rates and discount ticks; this guards direct internal misuse. */
444
- if (price <= 0 || price >= 1 || rate <= 0)
452
+ if (price <= 0 || price >= 1 || rate <= 0) {
445
453
  return 0;
454
+ }
446
455
  return (1 / price - 1) / rate;
447
456
  }
448
457
  function floorTickToSpacing(tick, spacing) {
@@ -695,11 +695,11 @@ var OfferUtils;
695
695
  */
696
696
  function validateOfferGroup(params) {
697
697
  const offerInputs = Array.from(params.offers);
698
- if (offerInputs.length === 0) {
698
+ const offers = offerInputs.map((offer) => Offer_js_1.Offer.from(offer));
699
+ const [first] = offers;
700
+ if (first === undefined) {
699
701
  throw new errors_js_1.InvalidOfferGroupError("Provide at least one offer in the group.");
700
702
  }
701
- const offers = offerInputs.map((offer) => Offer_js_1.Offer.from(offer));
702
- const first = offers[0];
703
703
  const expectedMaker = first.maker;
704
704
  const expectedBuy = first.buy;
705
705
  const expectedLoanToken = index_js_1.MarketParams.from(first.market).loanToken;
@@ -989,34 +989,41 @@ var OfferUtils;
989
989
  });
990
990
  }
991
991
  const market = index_js_1.Market.from(offer.market);
992
- if (timestamp < start || timestamp > expiry)
992
+ if (timestamp < start || timestamp > expiry) {
993
993
  return 0n;
994
- if (continuousFeeCap < BigInt(market.continuousFee))
994
+ }
995
+ if (continuousFeeCap < BigInt(market.continuousFee)) {
995
996
  return 0n;
996
- if (market.lossFactor >= viem_1.maxUint128)
997
+ }
998
+ if (market.lossFactor >= viem_1.maxUint128) {
997
999
  return 0n;
1000
+ }
998
1001
  // A zero spacing marks an untouched market, which `take` creates with its default spacing.
999
1002
  const tickSpacing = market.tickSpacing === 0
1000
1003
  ? constants_js_1.DEFAULT_TICK_SPACING
1001
1004
  : BigInt(market.tickSpacing);
1002
- if (BigInt(offer.tick) % tickSpacing !== 0n)
1005
+ if (BigInt(offer.tick) % tickSpacing !== 0n) {
1003
1006
  return 0n;
1007
+ }
1004
1008
  const settlementFee = market.getSettlementFee(market.timeToMaturity(timestamp));
1005
1009
  // Validates the settlement fee against the offer price for both cap modes.
1006
1010
  const { sellerPrice, buyerPrice } = index_js_2.TakeAmountsLib.prices({
1007
1011
  offer,
1008
1012
  settlementFee,
1009
1013
  });
1010
- if (maxUnits > 0n)
1014
+ if (maxUnits > 0n) {
1011
1015
  return morpho_ts_1.MathLib.zeroFloorSub(maxUnits, consumed);
1016
+ }
1012
1017
  const remainingAssets = morpho_ts_1.MathLib.zeroFloorSub(maxAssets, consumed);
1013
1018
  if (!offer.buy) {
1014
- if (sellerPrice === 0n)
1019
+ if (sellerPrice === 0n) {
1015
1020
  return morpho_ts_1.MathLib.MAX_UINT_256;
1021
+ }
1016
1022
  return morpho_ts_1.MathLib.mulDivDown(remainingAssets, morpho_ts_1.MathLib.WAD, sellerPrice);
1017
1023
  }
1018
- if (buyerPrice === 0n)
1024
+ if (buyerPrice === 0n) {
1019
1025
  return morpho_ts_1.MathLib.MAX_UINT_256;
1026
+ }
1020
1027
  return ((remainingAssets + 1n) * morpho_ts_1.MathLib.WAD - 1n) / buyerPrice;
1021
1028
  }
1022
1029
  OfferUtils.getConsumableUnits = getConsumableUnits;
@@ -289,8 +289,9 @@ class AccrualPosition extends Position {
289
289
  */
290
290
  getCollateralBalanceByIndex(index) {
291
291
  const normalizedIndex = BigInt(index);
292
- if ((0, morpho_ts_1._try)(() => this.market.getCollateralByIndex(normalizedIndex), errors_js_1.UnknownCollateralIndexError) == null)
292
+ if ((0, morpho_ts_1._try)(() => this.market.getCollateralByIndex(normalizedIndex), errors_js_1.UnknownCollateralIndexError) == null) {
293
293
  return undefined;
294
+ }
294
295
  return this.collateral[Number(normalizedIndex)] ?? 0n;
295
296
  }
296
297
  /**