@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
package/lib/esm/errors.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { InvalidPositionAccrualStateError as SharedInvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError as SharedInvalidPositionAccrualTimestampError, InvalidPositionLossFactorError as SharedInvalidPositionLossFactorError, } from "@morpho-org/morpho-ts";
1
2
  /**
2
3
  * Thrown when a Midnight offer group violates protocol-level group mechanics.
3
4
  *
@@ -81,54 +82,25 @@ export class SettlementFeeExceedsPriceError extends Error {
81
82
  this.name = "SettlementFeeExceedsPriceError";
82
83
  }
83
84
  }
85
+ // Temporary compatibility exception for these shared morpho-ts errors.
84
86
  /**
85
87
  * Thrown when a local position accrual is requested for an impossible timestamp.
86
88
  *
87
- * @example
88
- * ```ts
89
- * import { InvalidPositionAccrualTimestampError } from "@morpho-org/midnight-sdk";
90
- *
91
- * throw new InvalidPositionAccrualTimestampError(1n, 2n);
92
- * ```
89
+ * @deprecated Import `InvalidPositionAccrualTimestampError` from `@morpho-org/morpho-ts`. Removed in the next major.
93
90
  */
94
- export class InvalidPositionAccrualTimestampError extends Error {
95
- constructor(timestamp, lastAccrual) {
96
- super(`Position accrual timestamp "${timestamp}" is before last accrual "${lastAccrual}". Use a timestamp greater than or equal to last accrual.`);
97
- this.name = "InvalidPositionAccrualTimestampError";
98
- }
99
- }
91
+ export const InvalidPositionAccrualTimestampError = SharedInvalidPositionAccrualTimestampError;
100
92
  /**
101
93
  * Thrown when a local position accrual sees a market loss factor older than the position.
102
94
  *
103
- * @example
104
- * ```ts
105
- * import { InvalidPositionLossFactorError } from "@morpho-org/midnight-sdk";
106
- *
107
- * throw new InvalidPositionLossFactorError(1n, 2n);
108
- * ```
95
+ * @deprecated Import `InvalidPositionLossFactorError` from `@morpho-org/morpho-ts`. Removed in the next major.
109
96
  */
110
- export class InvalidPositionLossFactorError extends Error {
111
- constructor(marketLossFactor, positionLossFactor) {
112
- super(`Market loss factor "${marketLossFactor}" is below position loss factor "${positionLossFactor}". Fetch a consistent market and position at the same block.`);
113
- this.name = "InvalidPositionLossFactorError";
114
- }
115
- }
97
+ export const InvalidPositionLossFactorError = SharedInvalidPositionLossFactorError;
116
98
  /**
117
99
  * Thrown when local position accrual inputs violate Midnight accounting invariants.
118
100
  *
119
- * @example
120
- * ```ts
121
- * import { InvalidPositionAccrualStateError } from "@morpho-org/midnight-sdk";
122
- *
123
- * throw new InvalidPositionAccrualStateError("Pending fee exceeds credit.");
124
- * ```
101
+ * @deprecated Import `InvalidPositionAccrualStateError` from `@morpho-org/morpho-ts`. Removed in the next major.
125
102
  */
126
- export class InvalidPositionAccrualStateError extends Error {
127
- constructor(reason) {
128
- super(`Invalid Midnight position accrual state. ${reason}`);
129
- this.name = "InvalidPositionAccrualStateError";
130
- }
131
- }
103
+ export const InvalidPositionAccrualStateError = SharedInvalidPositionAccrualStateError;
132
104
  /**
133
105
  * Thrown when a market parameter cannot satisfy Midnight protocol rules.
134
106
  *
@@ -72,8 +72,9 @@ export async function fetchPosition(client, params) {
72
72
  });
73
73
  }
74
74
  catch (error) {
75
- if (params.deployless === "force")
75
+ if (params.deployless === "force") {
76
76
  throw error;
77
+ }
77
78
  // Fallback to direct reads if deployless execution is unavailable.
78
79
  }
79
80
  }
@@ -39,13 +39,12 @@ export async function fetchRatifierInfo(client, params) {
39
39
  const chainId = await resolveChainId(client);
40
40
  const ecrecoverRatifier = getChainAddress(chainId, "ecrecoverRatifier");
41
41
  const setterRatifier = getChainAddress(chainId, "setterRatifier");
42
+ const block = params.blockNumber == null
43
+ ? { blockTag: params.blockTag ?? undefined }
44
+ : { blockNumber: params.blockNumber };
42
45
  // eth_getCode is trusted; the returned ratifier is a suggestion the caller commits to on Offer.create. See THREAT_MODEL.md, RPC.
43
46
  const bytecode = await getBytecode(client, {
44
- ...(params.blockNumber != null
45
- ? { blockNumber: params.blockNumber }
46
- : params.blockTag != null
47
- ? { blockTag: params.blockTag }
48
- : {}),
47
+ ...block,
49
48
  address: params.maker,
50
49
  });
51
50
  return Ratifier.getRatifierInfo({
@@ -171,8 +171,9 @@ export class MarketParams {
171
171
  * ```
172
172
  */
173
173
  static from(market) {
174
- if ("params" in market)
174
+ if ("params" in market) {
175
175
  return MarketParams.from(market.params);
176
+ }
176
177
  return market instanceof MarketParams ? market : new MarketParams(market);
177
178
  }
178
179
  }
@@ -1,9 +1,8 @@
1
- import { assertNonNegative, MathLib, } from "@morpho-org/morpho-ts";
2
- import { concat, encodeAbiParameters, encodePacked, keccak256, } from "viem";
1
+ import { assertNonNegative, MathLib, MidnightMarketLib, } from "@morpho-org/morpho-ts";
2
+ import { concat, encodeAbiParameters, keccak256 } from "viem";
3
3
  import { CBP, COLLATERAL_PARAMS_TYPEHASH, MARKET_TYPEHASH, SETTLEMENT_FEE_BREAKPOINTS, } from "../constants.js";
4
4
  import { InvalidMarketParameterError, UnknownCollateralIndexError, } from "../errors.js";
5
5
  import { MarketParams, } from "./Market.js";
6
- const SSTORE2_PREFIX = "0x600b380380600b5f395ff3";
7
6
  const collateralParamsHashParams = [
8
7
  { name: "typehash", type: "bytes32" },
9
8
  { name: "token", type: "address" },
@@ -67,8 +66,9 @@ export var MarketUtils;
67
66
  function compareCollateralTokens(a, b) {
68
67
  const tokenA = a.token.toLowerCase();
69
68
  const tokenB = b.token.toLowerCase();
70
- if (tokenA === tokenB)
69
+ if (tokenA === tokenB) {
71
70
  return 0;
71
+ }
72
72
  return tokenA < tokenB ? -1 : 1;
73
73
  }
74
74
  MarketUtils.compareCollateralTokens = compareCollateralTokens;
@@ -261,20 +261,21 @@ export var MarketUtils;
261
261
  function getSettlementFee(params) {
262
262
  const timeToMaturity = BigInt(params.timeToMaturity);
263
263
  assertNonNegative("timeToMaturity", timeToMaturity);
264
- const lastIndex = SETTLEMENT_FEE_BREAKPOINTS.length - 1;
265
- const lastBreakpoint = SETTLEMENT_FEE_BREAKPOINTS[lastIndex];
266
- if (timeToMaturity >= lastBreakpoint) {
267
- return BigInt(params.settlementFeeCbps[lastIndex]) * CBP;
264
+ const upperBucketIndices = [1, 2, 3, 4, 5, 6];
265
+ let lowerIndex = 0;
266
+ for (const upperIndex of upperBucketIndices) {
267
+ const end = SETTLEMENT_FEE_BREAKPOINTS[upperIndex];
268
+ if (timeToMaturity < end) {
269
+ const start = SETTLEMENT_FEE_BREAKPOINTS[lowerIndex];
270
+ const feeLower = BigInt(params.settlementFeeCbps[lowerIndex]) * CBP;
271
+ const feeUpper = BigInt(params.settlementFeeCbps[upperIndex]) * CBP;
272
+ return ((feeLower * (end - timeToMaturity) +
273
+ feeUpper * (timeToMaturity - start)) /
274
+ (end - start));
275
+ }
276
+ lowerIndex = upperIndex;
268
277
  }
269
- const upperIndex = SETTLEMENT_FEE_BREAKPOINTS.findIndex((breakpoint) => timeToMaturity < breakpoint);
270
- const lowerIndex = upperIndex - 1;
271
- const start = SETTLEMENT_FEE_BREAKPOINTS[lowerIndex];
272
- const end = SETTLEMENT_FEE_BREAKPOINTS[upperIndex];
273
- const feeLower = BigInt(params.settlementFeeCbps[lowerIndex]) * CBP;
274
- const feeUpper = BigInt(params.settlementFeeCbps[upperIndex]) * CBP;
275
- return ((feeLower * (end - timeToMaturity) +
276
- feeUpper * (timeToMaturity - start)) /
277
- (end - start));
278
+ return BigInt(params.settlementFeeCbps[lowerIndex]) * CBP;
278
279
  }
279
280
  MarketUtils.getSettlementFee = getSettlementFee;
280
281
  /**
@@ -369,8 +370,7 @@ export var MarketUtils;
369
370
  function toId(market) {
370
371
  const marketParams = MarketParams.from(market);
371
372
  const encodedMarket = encodeAbiParameters([marketParamsAbiParameter], [toStruct(marketParams)]);
372
- const creationHash = keccak256(concat([SSTORE2_PREFIX, encodedMarket]));
373
- return keccak256(encodePacked(["uint8", "address", "uint256", "bytes32"], [255, marketParams.midnight, 0n, creationHash]));
373
+ return MidnightMarketLib.id(marketParams.midnight, encodedMarket);
374
374
  }
375
375
  MarketUtils.toId = toId;
376
376
  })(MarketUtils || (MarketUtils = {}));
@@ -87,10 +87,12 @@ export var TakeAmountsLib;
87
87
  const targetBuyerAssets = BigInt(params.targetBuyerAssets);
88
88
  assertNonNegative("targetBuyerAssets", targetBuyerAssets);
89
89
  const { buyerPrice } = prices({ offer: params.offer, settlementFee });
90
- if (buyerPrice === 0n)
90
+ if (buyerPrice === 0n) {
91
91
  throw new DivisionByZeroError("buyerPrice");
92
- if (buyerPrice > MathLib.WAD)
92
+ }
93
+ if (buyerPrice > MathLib.WAD) {
93
94
  throw new PriceGreaterThanOneError(buyerPrice);
95
+ }
94
96
  return MathLib.mulDiv(targetBuyerAssets, MathLib.WAD, buyerPrice, params.offer.buy ? "Up" : "Down");
95
97
  }
96
98
  TakeAmountsLib.buyerAssetsToUnits = buyerAssetsToUnits;
@@ -130,8 +132,9 @@ export var TakeAmountsLib;
130
132
  const targetSellerAssets = BigInt(params.targetSellerAssets);
131
133
  assertNonNegative("targetSellerAssets", targetSellerAssets);
132
134
  const { sellerPrice } = prices({ offer: params.offer, settlementFee });
133
- if (sellerPrice === 0n)
135
+ if (sellerPrice === 0n) {
134
136
  throw new DivisionByZeroError("sellerPrice");
137
+ }
135
138
  return MathLib.mulDiv(targetSellerAssets, MathLib.WAD, sellerPrice, params.offer.buy ? "Up" : "Down");
136
139
  }
137
140
  TakeAmountsLib.sellerAssetsToUnits = sellerAssetsToUnits;
@@ -160,8 +163,9 @@ export var TakeAmountsLib;
160
163
  const price = BigInt(params.price);
161
164
  assertNonNegative("assets", assets);
162
165
  assertNonNegative("price", price);
163
- if (price === 0n)
166
+ if (price === 0n) {
164
167
  throw new DivisionByZeroError("price");
168
+ }
165
169
  return MathLib.mulDiv(assets, MathLib.WAD, price, params.rounding);
166
170
  }
167
171
  TakeAmountsLib.toUnits = toUnits;
@@ -79,8 +79,9 @@ export var TickLib;
79
79
  TickLib.assertTickInRange = (tick) => {
80
80
  const tickValue = BigInt(tick);
81
81
  assertNonNegative("tick", tickValue);
82
- if (tickValue > MAX_TICK)
82
+ if (tickValue > MAX_TICK) {
83
83
  throw new TickOutOfRangeError(tickValue, MAX_TICK);
84
+ }
84
85
  return tickValue;
85
86
  };
86
87
  /**
@@ -97,8 +98,9 @@ export var TickLib;
97
98
  * ```
98
99
  */
99
100
  TickLib.wExp = (x) => {
100
- if (x < 0n)
101
+ if (x < 0n) {
101
102
  return 1000000000000000000000000000000000000n / TickLib.wExp(-x);
103
+ }
102
104
  const q = (x + TickLib.EXP_OFFSET) / TickLib.LN_2;
103
105
  const r = x - q * TickLib.LN_2;
104
106
  const secondTerm = (r * r) / (2n * MathLib.WAD);
@@ -149,8 +151,9 @@ export var TickLib;
149
151
  const priceValue = BigInt(price);
150
152
  const spacingValue = BigInt(spacing);
151
153
  assertNonNegative("price", priceValue);
152
- if (priceValue > MathLib.WAD)
154
+ if (priceValue > MathLib.WAD) {
153
155
  throw new PriceGreaterThanOneError(priceValue);
156
+ }
154
157
  if (spacingValue <= 0n || MAX_TICK % spacingValue !== 0n) {
155
158
  throw new InvalidTickSpacingError(spacingValue);
156
159
  }
@@ -158,10 +161,12 @@ export var TickLib;
158
161
  let high = MAX_TICK;
159
162
  while (low !== high) {
160
163
  const mid = (low + high) / 2n;
161
- if (tickToPrice(mid) < priceValue)
164
+ if (tickToPrice(mid) < priceValue) {
162
165
  low = mid + 1n;
163
- else
166
+ }
167
+ else {
164
168
  high = mid;
169
+ }
165
170
  }
166
171
  return ((low + spacingValue - 1n) / spacingValue) * spacingValue;
167
172
  }
@@ -231,8 +236,9 @@ export var TickLib;
231
236
  */
232
237
  function tickToRate(tick) {
233
238
  const price = tickToPrice(tick);
234
- if (price === 0n)
239
+ if (price === 0n) {
235
240
  throw new DivisionByZeroError("price");
241
+ }
236
242
  return MathLib.mulDiv(MathLib.WAD, MathLib.WAD, price, "Up") - MathLib.WAD;
237
243
  }
238
244
  TickLib.tickToRate = tickToRate;
@@ -148,8 +148,9 @@ export var OfferChainUtils;
148
148
  const tauStop = Number(maturityTimestamp - chainEndTimestamp) / SECONDS_PER_YEAR;
149
149
  const lowerRate = params.targetRate * (1 - FAVORABLE_RATE_DRIFT);
150
150
  /* v8 ignore next: positive finite targetRate validation keeps lowerRate positive for practical JS numbers. */
151
- if (lowerRate <= 0)
151
+ if (lowerRate <= 0) {
152
152
  return [];
153
+ }
153
154
  const legs = [];
154
155
  let tauTop = tauInitial;
155
156
  let iteration = 0;
@@ -166,17 +167,21 @@ export var OfferChainUtils;
166
167
  priceInput = parseUnits(price.toFixed(18), 18);
167
168
  }
168
169
  const rawTick = TickLib.priceToTick(priceInput, 1n) - 1n;
169
- if (rawTick < 0n || rawTick > MAX_TICK)
170
+ if (rawTick < 0n || rawTick > MAX_TICK) {
170
171
  break;
172
+ }
171
173
  const tick = floorTickToSpacing(rawTick, tickSpacing);
172
- if (legs.at(-1)?.tick === tick)
174
+ if (legs.at(-1)?.tick === tick) {
173
175
  break;
176
+ }
174
177
  const tauMax = rateTau(tick, lowerRate);
175
178
  const tauMin = rateTau(tick, params.targetRate);
176
- if (tauMin >= tauTop)
179
+ if (tauMin >= tauTop) {
177
180
  break;
178
- if (tauMin < tauStop)
181
+ }
182
+ if (tauMin < tauStop) {
179
183
  break;
184
+ }
180
185
  const startTimestamp = maturityTimestamp -
181
186
  BigInt(Math.round(Math.min(tauMax, tauTop) * SECONDS_PER_YEAR));
182
187
  const expiryTimestamp = maturityTimestamp - BigInt(Math.round(tauMin * SECONDS_PER_YEAR));
@@ -302,41 +307,33 @@ export var OfferChainUtils;
302
307
  : maxAlignedTick;
303
308
  const tauCeiling = rateTau(ceilingTick, upperRate);
304
309
  let tauBottom = Math.max(tauStop, tauCeiling);
305
- if (tauBottom >= tauInitial)
310
+ if (tauBottom >= tauInitial) {
306
311
  return [];
312
+ }
307
313
  const tauLegs = [];
308
314
  let iteration = 0;
309
315
  for (; iteration < MAX_CHAIN_LEGS; iteration++) {
310
316
  const price = 1 / (1 + upperRate * tauBottom);
311
- let priceInput;
312
- if (!Number.isFinite(price) || price <= 0) {
313
- priceInput = 0n;
314
- }
315
- else {
316
- /* v8 ignore next: positive rates that survive the grid-floor check keep lend-chain prices below one. */
317
- if (price >= 1) {
318
- priceInput = MathLib.WAD;
319
- }
320
- else {
321
- priceInput = parseUnits(price.toFixed(18), 18);
322
- }
323
- }
324
- const rawTick = TickLib.priceToTick(priceInput, 1n);
317
+ const rawTick = TickLib.priceToTick(clampLendPrice(price), 1n);
325
318
  /* v8 ignore next: priceToTick returns in-range ticks; maxAlignedTick only tightens non-dividing spacing. */
326
- if (rawTick < 0n || rawTick > MAX_TICK || rawTick > maxAlignedTick)
319
+ if (rawTick < 0n || rawTick > MAX_TICK || rawTick > maxAlignedTick) {
327
320
  break;
321
+ }
328
322
  const alignedTick = ((rawTick + tickSpacing - 1n) / tickSpacing) * tickSpacing;
329
323
  /* v8 ignore next: non-dividing spacing boundary clamp is defensive; normal alignment is covered. */
330
324
  const tick = alignedTick < maxAlignedTick ? alignedTick : maxAlignedTick;
331
- if (tauLegs.at(-1)?.tick === tick)
325
+ if (tauLegs.at(-1)?.tick === tick) {
332
326
  break;
327
+ }
333
328
  const tauMax = rateTau(tick, params.targetRate);
334
329
  const tauMin = rateTau(tick, upperRate);
335
- if (tauMax <= tauBottom)
330
+ if (tauMax <= tauBottom) {
336
331
  break;
332
+ }
337
333
  tauLegs.push({ tick, tauMax, tauMin: Math.max(tauMin, tauBottom) });
338
- if (tauMax >= tauInitial)
334
+ if (tauMax >= tauInitial) {
339
335
  break;
336
+ }
340
337
  tauBottom = tauMax;
341
338
  }
342
339
  /* v8 ignore next: the monotonic tick walk exits before exhausting the finite tick range. */
@@ -348,8 +345,9 @@ export var OfferChainUtils;
348
345
  });
349
346
  }
350
347
  const leftmostLeg = tauLegs.at(-1);
351
- if (leftmostLeg && leftmostLeg.tauMax < tauInitial)
348
+ if (leftmostLeg && leftmostLeg.tauMax < tauInitial) {
352
349
  return [];
350
+ }
353
351
  return tauLegs
354
352
  .reverse()
355
353
  .map((leg) => ({
@@ -435,11 +433,22 @@ function normalizeTimestamp(parameter, value) {
435
433
  }
436
434
  return normalized;
437
435
  }
436
+ function clampLendPrice(price) {
437
+ if (!Number.isFinite(price) || price <= 0) {
438
+ return 0n;
439
+ }
440
+ /* v8 ignore next: positive rates that survive the grid-floor check keep lend-chain prices below one. */
441
+ if (price >= 1) {
442
+ return MathLib.WAD;
443
+ }
444
+ return parseUnits(price.toFixed(18), 18);
445
+ }
438
446
  function rateTau(tick, rate) {
439
447
  const price = Number(formatUnits(TickLib.tickToPrice(tick), 18));
440
448
  /* v8 ignore next: builders pass positive rates and discount ticks; this guards direct internal misuse. */
441
- if (price <= 0 || price >= 1 || rate <= 0)
449
+ if (price <= 0 || price >= 1 || rate <= 0) {
442
450
  return 0;
451
+ }
443
452
  return (1 / price - 1) / rate;
444
453
  }
445
454
  function floorTickToSpacing(tick, spacing) {
@@ -692,11 +692,11 @@ export var OfferUtils;
692
692
  */
693
693
  function validateOfferGroup(params) {
694
694
  const offerInputs = Array.from(params.offers);
695
- if (offerInputs.length === 0) {
695
+ const offers = offerInputs.map((offer) => Offer.from(offer));
696
+ const [first] = offers;
697
+ if (first === undefined) {
696
698
  throw new InvalidOfferGroupError("Provide at least one offer in the group.");
697
699
  }
698
- const offers = offerInputs.map((offer) => Offer.from(offer));
699
- const first = offers[0];
700
700
  const expectedMaker = first.maker;
701
701
  const expectedBuy = first.buy;
702
702
  const expectedLoanToken = MarketParams.from(first.market).loanToken;
@@ -986,34 +986,41 @@ export var OfferUtils;
986
986
  });
987
987
  }
988
988
  const market = Market.from(offer.market);
989
- if (timestamp < start || timestamp > expiry)
989
+ if (timestamp < start || timestamp > expiry) {
990
990
  return 0n;
991
- if (continuousFeeCap < BigInt(market.continuousFee))
991
+ }
992
+ if (continuousFeeCap < BigInt(market.continuousFee)) {
992
993
  return 0n;
993
- if (market.lossFactor >= maxUint128)
994
+ }
995
+ if (market.lossFactor >= maxUint128) {
994
996
  return 0n;
997
+ }
995
998
  // A zero spacing marks an untouched market, which `take` creates with its default spacing.
996
999
  const tickSpacing = market.tickSpacing === 0
997
1000
  ? DEFAULT_TICK_SPACING
998
1001
  : BigInt(market.tickSpacing);
999
- if (BigInt(offer.tick) % tickSpacing !== 0n)
1002
+ if (BigInt(offer.tick) % tickSpacing !== 0n) {
1000
1003
  return 0n;
1004
+ }
1001
1005
  const settlementFee = market.getSettlementFee(market.timeToMaturity(timestamp));
1002
1006
  // Validates the settlement fee against the offer price for both cap modes.
1003
1007
  const { sellerPrice, buyerPrice } = TakeAmountsLib.prices({
1004
1008
  offer,
1005
1009
  settlementFee,
1006
1010
  });
1007
- if (maxUnits > 0n)
1011
+ if (maxUnits > 0n) {
1008
1012
  return MathLib.zeroFloorSub(maxUnits, consumed);
1013
+ }
1009
1014
  const remainingAssets = MathLib.zeroFloorSub(maxAssets, consumed);
1010
1015
  if (!offer.buy) {
1011
- if (sellerPrice === 0n)
1016
+ if (sellerPrice === 0n) {
1012
1017
  return MathLib.MAX_UINT_256;
1018
+ }
1013
1019
  return MathLib.mulDivDown(remainingAssets, MathLib.WAD, sellerPrice);
1014
1020
  }
1015
- if (buyerPrice === 0n)
1021
+ if (buyerPrice === 0n) {
1016
1022
  return MathLib.MAX_UINT_256;
1023
+ }
1017
1024
  return ((remainingAssets + 1n) * MathLib.WAD - 1n) / buyerPrice;
1018
1025
  }
1019
1026
  OfferUtils.getConsumableUnits = getConsumableUnits;
@@ -285,8 +285,9 @@ export class AccrualPosition extends Position {
285
285
  */
286
286
  getCollateralBalanceByIndex(index) {
287
287
  const normalizedIndex = BigInt(index);
288
- if (_try(() => this.market.getCollateralByIndex(normalizedIndex), UnknownCollateralIndexError) == null)
288
+ if (_try(() => this.market.getCollateralByIndex(normalizedIndex), UnknownCollateralIndexError) == null) {
289
289
  return undefined;
290
+ }
290
291
  return this.collateral[Number(normalizedIndex)] ?? 0n;
291
292
  }
292
293
  /**
@@ -1,5 +1,4 @@
1
- import { MathLib } from "@morpho-org/morpho-ts";
2
- import { InvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionLossFactorError, } from "../errors.js";
1
+ import { MathLib, MidnightPositionLib, } from "@morpho-org/morpho-ts";
3
2
  /**
4
3
  * Domain helpers for Midnight positions.
5
4
  *
@@ -132,40 +131,17 @@ export var PositionUtils;
132
131
  */
133
132
  function accrueInterest(params) {
134
133
  const timestamp = BigInt(params.timestamp);
135
- const credit = BigInt(params.position.credit);
136
- const pendingFee = BigInt(params.position.pendingFee);
137
- const lastLossFactor = BigInt(params.position.lastLossFactor);
138
- const lastAccrual = BigInt(params.position.lastAccrual);
139
134
  const marketLossFactor = BigInt(params.market.lossFactor);
140
- if (timestamp < lastAccrual) {
141
- throw new InvalidPositionAccrualTimestampError(timestamp, lastAccrual);
142
- }
143
- if (marketLossFactor < lastLossFactor) {
144
- throw new InvalidPositionLossFactorError(marketLossFactor, lastLossFactor);
145
- }
146
- if (pendingFee > credit) {
147
- throw new InvalidPositionAccrualStateError("Pending fee must be less than or equal to credit.");
148
- }
149
- const postSlashCredit = lastLossFactor < MathLib.MAX_UINT_128
150
- ? MathLib.mulDivDown(credit, MathLib.MAX_UINT_128 - marketLossFactor, MathLib.MAX_UINT_128 - lastLossFactor)
151
- : 0n;
152
- if (postSlashCredit > credit) {
153
- throw new InvalidPositionAccrualStateError("Post-slash credit cannot exceed stored credit.");
154
- }
155
- const creditDecrease = credit - postSlashCredit;
156
- const pendingFeeDecrease = credit > 0n ? MathLib.mulDivUp(pendingFee, creditDecrease, credit) : 0n;
157
- if (pendingFeeDecrease > pendingFee) {
158
- throw new InvalidPositionAccrualStateError("Pending-fee decrease cannot exceed pending fee.");
159
- }
160
- const postSlashPendingFee = pendingFee - pendingFeeDecrease;
161
135
  const maturity = BigInt(params.market.params.maturity);
162
- const accrualEnd = timestamp < maturity ? timestamp : maturity;
163
- const accruedFee = lastAccrual < maturity
164
- ? MathLib.mulDivDown(postSlashPendingFee, accrualEnd - lastAccrual, maturity - lastAccrual)
165
- : 0n;
166
- if (accruedFee > postSlashCredit || accruedFee > postSlashPendingFee) {
167
- throw new InvalidPositionAccrualStateError("Accrued fee cannot exceed post-slash credit or pending fee.");
168
- }
136
+ const { credit, pendingFee, accruedFee } = MidnightPositionLib.accrue({
137
+ credit: params.position.credit,
138
+ pendingFee: params.position.pendingFee,
139
+ lastLossFactor: params.position.lastLossFactor,
140
+ lastAccrual: params.position.lastAccrual,
141
+ marketLossFactor,
142
+ maturity,
143
+ timestamp,
144
+ });
169
145
  const collateral = params.position.collateral.map((assets) => BigInt(assets));
170
146
  const collateralParams = params.market.params.collateralParams.map((collateralParam) => ({
171
147
  token: collateralParam.token,
@@ -196,8 +172,8 @@ export var PositionUtils;
196
172
  position: {
197
173
  user: params.position.user,
198
174
  marketId: params.position.marketId,
199
- credit: postSlashCredit - accruedFee,
200
- pendingFee: postSlashPendingFee - accruedFee,
175
+ credit,
176
+ pendingFee,
201
177
  lastLossFactor: marketLossFactor,
202
178
  lastAccrual: timestamp,
203
179
  debt: BigInt(params.position.debt),
@@ -9,6 +9,7 @@ import { eip712Digest } from "./eip712.js";
9
9
  import { Ratifier } from "./Ratifier.js";
10
10
  import { parseStandardRatifierTree } from "./standardRatifierInternal.js";
11
11
  import { TreeUtils } from "./TreeUtils.js";
12
+ import { requireTreeItem } from "./treeMathInternal.js";
12
13
  const treeTypeHashes = [
13
14
  "0x270da1ebafc0f24637af3612fb8c3a1d828fcb56d3637c24e86dd006b12ca7f9",
14
15
  "0x828b9cdf8326a1cf234328e4d5229546a98fb72ef73624f5b6b31538e555b96c",
@@ -94,8 +95,9 @@ const typedDataTypes = {
94
95
  ],
95
96
  };
96
97
  const buildTreeValue = (offers) => {
97
- if (offers.length === 1)
98
- return offers[0];
98
+ if (offers.length === 1) {
99
+ return requireTreeItem(offers, 0);
100
+ }
99
101
  const mid = offers.length / 2;
100
102
  return [
101
103
  buildTreeValue(offers.slice(0, mid)),
@@ -103,10 +105,12 @@ const buildTreeValue = (offers) => {
103
105
  ];
104
106
  };
105
107
  function toCanonicalYParity(v) {
106
- if (v === 27)
108
+ if (v === 27) {
107
109
  return 0;
108
- if (v === 28)
110
+ }
111
+ if (v === 28) {
109
112
  return 1;
113
+ }
110
114
  throw new InvalidEcrecoverSignatureVError(v);
111
115
  }
112
116
  /**
@@ -147,8 +151,9 @@ export var EcrecoverRatifierUtils;
147
151
  */
148
152
  function treeTypeHash(height) {
149
153
  const typehash = treeTypeHashes[height];
150
- if (typehash == null)
154
+ if (typehash == null) {
151
155
  throw new InvalidTreeHeightError(height);
156
+ }
152
157
  return typehash;
153
158
  }
154
159
  EcrecoverRatifierUtils.treeTypeHash = treeTypeHash;
@@ -504,7 +509,7 @@ export var EcrecoverRatifierUtils;
504
509
  tree: params.tree,
505
510
  label: "Ecrecover",
506
511
  });
507
- const expectedChainId = MarketParams.from(tree.offers[0].market).chainId;
512
+ const expectedChainId = MarketParams.from(requireTreeItem(tree.offers, 0).market).chainId;
508
513
  for (const offer of tree.offers.slice(1)) {
509
514
  const offerChainId = MarketParams.from(offer.market).chainId;
510
515
  if (offerChainId !== expectedChainId) {
@@ -564,7 +569,7 @@ export var EcrecoverRatifierUtils;
564
569
  */
565
570
  function toSignature(signature) {
566
571
  if (typeof signature !== "string") {
567
- const v = signature.v != null ? Number(signature.v) : Number(signature.yParity);
572
+ const v = signature.v == null ? Number(signature.yParity) : Number(signature.v);
568
573
  return {
569
574
  v: v < 27 ? v + 27 : v,
570
575
  r: signature.r,
@@ -797,9 +802,16 @@ export var EcrecoverRatifierUtils;
797
802
  label: "Ecrecover",
798
803
  });
799
804
  let signature;
800
- if (params.signature != null) {
805
+ if (params.signature == null) {
806
+ signature = toSignature(await sign({
807
+ tree,
808
+ client: params.client,
809
+ account: params.account,
810
+ }));
811
+ }
812
+ else {
801
813
  signature = toSignature(params.signature);
802
- const expectedChainId = MarketParams.from(tree.offers[0].market).chainId;
814
+ const expectedChainId = MarketParams.from(requireTreeItem(tree.offers, 0).market).chainId;
803
815
  for (const offer of tree.offers.slice(1)) {
804
816
  const offerChainId = MarketParams.from(offer.market).chainId;
805
817
  if (offerChainId !== expectedChainId) {
@@ -828,13 +840,6 @@ export var EcrecoverRatifierUtils;
828
840
  throw new InvalidTypedDataSignatureError(signer);
829
841
  }
830
842
  }
831
- else {
832
- signature = toSignature(await sign({
833
- tree,
834
- client: params.client,
835
- account: params.account,
836
- }));
837
- }
838
843
  const proofs = TreeUtils.buildProofs({
839
844
  tree,
840
845
  count: tree.offers.length,
@@ -843,7 +848,7 @@ export var EcrecoverRatifierUtils;
843
848
  offer,
844
849
  ratifierData: encodeRatifierData({
845
850
  signature,
846
- ...proofs[leafIndex],
851
+ ...requireTreeItem(proofs, leafIndex),
847
852
  }),
848
853
  }));
849
854
  }
@@ -141,10 +141,12 @@ export class Group {
141
141
  * ```
142
142
  */
143
143
  static from(entry) {
144
- if (entry instanceof Group)
144
+ if (entry instanceof Group) {
145
145
  return entry;
146
- if (GroupUtils.isGroupInput(entry))
146
+ }
147
+ if (GroupUtils.isGroupInput(entry)) {
147
148
  return new Group(entry.offers);
149
+ }
148
150
  return new Group([entry]);
149
151
  }
150
152
  /**