@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
@@ -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
  /**
@@ -2,7 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PositionUtils = void 0;
4
4
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
5
- const errors_js_1 = require("../errors.js");
6
5
  /**
7
6
  * Domain helpers for Midnight positions.
8
7
  *
@@ -135,40 +134,17 @@ var PositionUtils;
135
134
  */
136
135
  function accrueInterest(params) {
137
136
  const timestamp = BigInt(params.timestamp);
138
- const credit = BigInt(params.position.credit);
139
- const pendingFee = BigInt(params.position.pendingFee);
140
- const lastLossFactor = BigInt(params.position.lastLossFactor);
141
- const lastAccrual = BigInt(params.position.lastAccrual);
142
137
  const marketLossFactor = BigInt(params.market.lossFactor);
143
- if (timestamp < lastAccrual) {
144
- throw new errors_js_1.InvalidPositionAccrualTimestampError(timestamp, lastAccrual);
145
- }
146
- if (marketLossFactor < lastLossFactor) {
147
- throw new errors_js_1.InvalidPositionLossFactorError(marketLossFactor, lastLossFactor);
148
- }
149
- if (pendingFee > credit) {
150
- throw new errors_js_1.InvalidPositionAccrualStateError("Pending fee must be less than or equal to credit.");
151
- }
152
- const postSlashCredit = lastLossFactor < morpho_ts_1.MathLib.MAX_UINT_128
153
- ? morpho_ts_1.MathLib.mulDivDown(credit, morpho_ts_1.MathLib.MAX_UINT_128 - marketLossFactor, morpho_ts_1.MathLib.MAX_UINT_128 - lastLossFactor)
154
- : 0n;
155
- if (postSlashCredit > credit) {
156
- throw new errors_js_1.InvalidPositionAccrualStateError("Post-slash credit cannot exceed stored credit.");
157
- }
158
- const creditDecrease = credit - postSlashCredit;
159
- const pendingFeeDecrease = credit > 0n ? morpho_ts_1.MathLib.mulDivUp(pendingFee, creditDecrease, credit) : 0n;
160
- if (pendingFeeDecrease > pendingFee) {
161
- throw new errors_js_1.InvalidPositionAccrualStateError("Pending-fee decrease cannot exceed pending fee.");
162
- }
163
- const postSlashPendingFee = pendingFee - pendingFeeDecrease;
164
138
  const maturity = BigInt(params.market.params.maturity);
165
- const accrualEnd = timestamp < maturity ? timestamp : maturity;
166
- const accruedFee = lastAccrual < maturity
167
- ? morpho_ts_1.MathLib.mulDivDown(postSlashPendingFee, accrualEnd - lastAccrual, maturity - lastAccrual)
168
- : 0n;
169
- if (accruedFee > postSlashCredit || accruedFee > postSlashPendingFee) {
170
- throw new errors_js_1.InvalidPositionAccrualStateError("Accrued fee cannot exceed post-slash credit or pending fee.");
171
- }
139
+ const { credit, pendingFee, accruedFee } = morpho_ts_1.MidnightPositionLib.accrue({
140
+ credit: params.position.credit,
141
+ pendingFee: params.position.pendingFee,
142
+ lastLossFactor: params.position.lastLossFactor,
143
+ lastAccrual: params.position.lastAccrual,
144
+ marketLossFactor,
145
+ maturity,
146
+ timestamp,
147
+ });
172
148
  const collateral = params.position.collateral.map((assets) => BigInt(assets));
173
149
  const collateralParams = params.market.params.collateralParams.map((collateralParam) => ({
174
150
  token: collateralParam.token,
@@ -199,8 +175,8 @@ var PositionUtils;
199
175
  position: {
200
176
  user: params.position.user,
201
177
  marketId: params.position.marketId,
202
- credit: postSlashCredit - accruedFee,
203
- pendingFee: postSlashPendingFee - accruedFee,
178
+ credit,
179
+ pendingFee,
204
180
  lastLossFactor: marketLossFactor,
205
181
  lastAccrual: timestamp,
206
182
  debt: BigInt(params.position.debt),
@@ -12,6 +12,7 @@ const eip712_js_1 = require("./eip712.js");
12
12
  const Ratifier_js_1 = require("./Ratifier.js");
13
13
  const standardRatifierInternal_js_1 = require("./standardRatifierInternal.js");
14
14
  const TreeUtils_js_1 = require("./TreeUtils.js");
15
+ const treeMathInternal_js_1 = require("./treeMathInternal.js");
15
16
  const treeTypeHashes = [
16
17
  "0x270da1ebafc0f24637af3612fb8c3a1d828fcb56d3637c24e86dd006b12ca7f9",
17
18
  "0x828b9cdf8326a1cf234328e4d5229546a98fb72ef73624f5b6b31538e555b96c",
@@ -97,8 +98,9 @@ const typedDataTypes = {
97
98
  ],
98
99
  };
99
100
  const buildTreeValue = (offers) => {
100
- if (offers.length === 1)
101
- return offers[0];
101
+ if (offers.length === 1) {
102
+ return (0, treeMathInternal_js_1.requireTreeItem)(offers, 0);
103
+ }
102
104
  const mid = offers.length / 2;
103
105
  return [
104
106
  buildTreeValue(offers.slice(0, mid)),
@@ -106,10 +108,12 @@ const buildTreeValue = (offers) => {
106
108
  ];
107
109
  };
108
110
  function toCanonicalYParity(v) {
109
- if (v === 27)
111
+ if (v === 27) {
110
112
  return 0;
111
- if (v === 28)
113
+ }
114
+ if (v === 28) {
112
115
  return 1;
116
+ }
113
117
  throw new errors_js_1.InvalidEcrecoverSignatureVError(v);
114
118
  }
115
119
  /**
@@ -150,8 +154,9 @@ var EcrecoverRatifierUtils;
150
154
  */
151
155
  function treeTypeHash(height) {
152
156
  const typehash = treeTypeHashes[height];
153
- if (typehash == null)
157
+ if (typehash == null) {
154
158
  throw new errors_js_1.InvalidTreeHeightError(height);
159
+ }
155
160
  return typehash;
156
161
  }
157
162
  EcrecoverRatifierUtils.treeTypeHash = treeTypeHash;
@@ -507,7 +512,7 @@ var EcrecoverRatifierUtils;
507
512
  tree: params.tree,
508
513
  label: "Ecrecover",
509
514
  });
510
- const expectedChainId = index_js_1.MarketParams.from(tree.offers[0].market).chainId;
515
+ const expectedChainId = index_js_1.MarketParams.from((0, treeMathInternal_js_1.requireTreeItem)(tree.offers, 0).market).chainId;
511
516
  for (const offer of tree.offers.slice(1)) {
512
517
  const offerChainId = index_js_1.MarketParams.from(offer.market).chainId;
513
518
  if (offerChainId !== expectedChainId) {
@@ -567,7 +572,7 @@ var EcrecoverRatifierUtils;
567
572
  */
568
573
  function toSignature(signature) {
569
574
  if (typeof signature !== "string") {
570
- const v = signature.v != null ? Number(signature.v) : Number(signature.yParity);
575
+ const v = signature.v == null ? Number(signature.yParity) : Number(signature.v);
571
576
  return {
572
577
  v: v < 27 ? v + 27 : v,
573
578
  r: signature.r,
@@ -800,9 +805,16 @@ var EcrecoverRatifierUtils;
800
805
  label: "Ecrecover",
801
806
  });
802
807
  let signature;
803
- if (params.signature != null) {
808
+ if (params.signature == null) {
809
+ signature = toSignature(await sign({
810
+ tree,
811
+ client: params.client,
812
+ account: params.account,
813
+ }));
814
+ }
815
+ else {
804
816
  signature = toSignature(params.signature);
805
- const expectedChainId = index_js_1.MarketParams.from(tree.offers[0].market).chainId;
817
+ const expectedChainId = index_js_1.MarketParams.from((0, treeMathInternal_js_1.requireTreeItem)(tree.offers, 0).market).chainId;
806
818
  for (const offer of tree.offers.slice(1)) {
807
819
  const offerChainId = index_js_1.MarketParams.from(offer.market).chainId;
808
820
  if (offerChainId !== expectedChainId) {
@@ -831,13 +843,6 @@ var EcrecoverRatifierUtils;
831
843
  throw new errors_js_1.InvalidTypedDataSignatureError(signer);
832
844
  }
833
845
  }
834
- else {
835
- signature = toSignature(await sign({
836
- tree,
837
- client: params.client,
838
- account: params.account,
839
- }));
840
- }
841
846
  const proofs = TreeUtils_js_1.TreeUtils.buildProofs({
842
847
  tree,
843
848
  count: tree.offers.length,
@@ -846,7 +851,7 @@ var EcrecoverRatifierUtils;
846
851
  offer,
847
852
  ratifierData: encodeRatifierData({
848
853
  signature,
849
- ...proofs[leafIndex],
854
+ ...(0, treeMathInternal_js_1.requireTreeItem)(proofs, leafIndex),
850
855
  }),
851
856
  }));
852
857
  }
@@ -144,10 +144,12 @@ class Group {
144
144
  * ```
145
145
  */
146
146
  static from(entry) {
147
- if (entry instanceof Group)
147
+ if (entry instanceof Group) {
148
148
  return entry;
149
- if (GroupUtils_js_1.GroupUtils.isGroupInput(entry))
149
+ }
150
+ if (GroupUtils_js_1.GroupUtils.isGroupInput(entry)) {
150
151
  return new Group(entry.offers);
152
+ }
151
153
  return new Group([entry]);
152
154
  }
153
155
  /**
@@ -342,8 +342,9 @@ var Payload;
342
342
  });
343
343
  }
344
344
  catch (error) {
345
- if (error instanceof errors_js_1.PayloadDecodeError)
345
+ if (error instanceof errors_js_1.PayloadDecodeError) {
346
346
  throw error;
347
+ }
347
348
  if (error instanceof Error) {
348
349
  throw new errors_js_1.PayloadDecodeError(`invalid offer bytes: ${error.message}`, error);
349
350
  }
@@ -362,8 +363,9 @@ var Payload;
362
363
  }
363
364
  }
364
365
  function assertApiValidOfferStruct(offer) {
365
- if ((0, offerStructInternal_js_1.isEmptyOfferStruct)(offer))
366
+ if ((0, offerStructInternal_js_1.isEmptyOfferStruct)(offer)) {
366
367
  return;
368
+ }
367
369
  assertCollateralParams(offer);
368
370
  assertSafeTimestamp("market.maturity", offer.market.maturity);
369
371
  assertMaturityAt15Utc(offer.market.maturity);
@@ -454,20 +456,23 @@ var Payload;
454
456
  }
455
457
  }
456
458
  function resolveMaxItems(maxItems) {
457
- if (maxItems === undefined)
459
+ if (maxItems === undefined) {
458
460
  return undefined;
461
+ }
459
462
  if (!Number.isInteger(maxItems) || maxItems < 1) {
460
463
  throw new errors_js_1.PayloadDecodeError(`maxItems must be a positive integer: got ${maxItems}`);
461
464
  }
462
465
  return maxItems;
463
466
  }
464
467
  function assertNonEmptyItemCount(count) {
465
- if (count === 0)
468
+ if (count === 0) {
466
469
  throw new errors_js_1.PayloadDecodeError("items payload is empty");
470
+ }
467
471
  }
468
472
  function assertCallerItemCountLimit(count, maxItems) {
469
- if (maxItems === undefined)
473
+ if (maxItems === undefined) {
470
474
  return;
475
+ }
471
476
  if (count > maxItems) {
472
477
  throw new errors_js_1.PayloadDecodeError(`items payload exceeds ${maxItems} items`);
473
478
  }
@@ -490,8 +495,9 @@ var Payload;
490
495
  return compressed;
491
496
  }
492
497
  async function decompressItemsPayload(compressed) {
493
- if (compressed.length === 0)
498
+ if (compressed.length === 0) {
494
499
  throw new errors_js_1.PayloadDecodeError("decompression failed");
500
+ }
495
501
  if (compressed.length > Payload.MAX_COMPRESSED_ITEMS_BYTES) {
496
502
  throw new errors_js_1.PayloadDecodeError(`compressed items exceed ${Payload.MAX_COMPRESSED_ITEMS_BYTES} bytes`);
497
503
  }
@@ -503,8 +509,9 @@ var Payload;
503
509
  try {
504
510
  while (true) {
505
511
  const { done, value } = await reader.read();
506
- if (done)
512
+ if (done) {
507
513
  break;
514
+ }
508
515
  totalLength += value.length;
509
516
  if (totalLength > Payload.MAX_DECOMPRESSED_ITEMS_BYTES) {
510
517
  await reader.cancel();
@@ -514,8 +521,9 @@ var Payload;
514
521
  }
515
522
  }
516
523
  catch (error) {
517
- if (error instanceof errors_js_1.PayloadDecodeError)
524
+ if (error instanceof errors_js_1.PayloadDecodeError) {
518
525
  throw error;
526
+ }
519
527
  throw new errors_js_1.PayloadDecodeError("decompression failed", error instanceof Error ? error : undefined);
520
528
  }
521
529
  const result = new Uint8Array(totalLength);
@@ -538,8 +546,9 @@ var Payload;
538
546
  if (decoded.length < ABI_ARRAY_HEAD_BYTES) {
539
547
  throw new errors_js_1.PayloadDecodeError("items payload truncated before ABI array head");
540
548
  }
541
- if (maxItems === undefined)
549
+ if (maxItems === undefined) {
542
550
  return;
551
+ }
543
552
  for (let i = 32; i < ABI_LENGTH_LOW_OFFSET; i++) {
544
553
  if (decoded[i] !== 0) {
545
554
  throw new errors_js_1.PayloadDecodeError(`items payload exceeds ${maxItems} items`);
@@ -12,6 +12,7 @@ const GroupUtils_js_1 = require("./GroupUtils.js");
12
12
  const offerStructInternal_js_1 = require("./offerStructInternal.js");
13
13
  const ratifierV1Internal_js_1 = require("./ratifierV1Internal.js");
14
14
  const TreeUtils_js_1 = require("./TreeUtils.js");
15
+ const treeMathInternal_js_1 = require("./treeMathInternal.js");
15
16
  const priceRatifierV1DataAbi = [
16
17
  { name: "root", type: "bytes32" },
17
18
  { name: "leafIndex", type: "uint256" },
@@ -240,7 +241,7 @@ var PriceRatifierV1;
240
241
  const assignedOffers = (0, ratifierV1Internal_js_1.assignRatifierV1Groups)(normalized, groupId);
241
242
  const offers = [];
242
243
  const structs = normalized.map(({ allowedTaker }, index) => {
243
- const offer = assignedOffers[index];
244
+ const offer = (0, treeMathInternal_js_1.requireTreeItem)(assignedOffers, index);
244
245
  offers.push(offer);
245
246
  return { offer: index_js_2.OfferUtils.toStruct({ offer }), allowedTaker };
246
247
  });
@@ -430,7 +431,7 @@ var PriceRatifierV1;
430
431
  function ratifierData(params) {
431
432
  const tree = (0, ratifierV1Internal_js_1.resolveRatifierV1Tree)(params.tree, treeHelpers);
432
433
  const proof = TreeUtils_js_1.TreeUtils.buildProof({ tree, leafIndex: params.leafIndex });
433
- const entry = tree.entries[Number(proof.leafIndex)];
434
+ const entry = (0, treeMathInternal_js_1.requireTreeItem)(tree.entries, Number(proof.leafIndex));
434
435
  return encodeRatifierData({
435
436
  root: proof.root,
436
437
  leafIndex: proof.leafIndex,
@@ -470,8 +471,8 @@ var PriceRatifierV1;
470
471
  count: tree.offers.length,
471
472
  });
472
473
  return tree.offers.map((offer, leafIndex) => {
473
- const entry = tree.entries[leafIndex];
474
- const proof = proofs[leafIndex];
474
+ const entry = (0, treeMathInternal_js_1.requireTreeItem)(tree.entries, leafIndex);
475
+ const proof = (0, treeMathInternal_js_1.requireTreeItem)(proofs, leafIndex);
475
476
  return {
476
477
  offer,
477
478
  ratifierData: encodeRatifierData({
@@ -13,6 +13,7 @@ const GroupUtils_js_1 = require("./GroupUtils.js");
13
13
  const offerStructInternal_js_1 = require("./offerStructInternal.js");
14
14
  const ratifierV1Internal_js_1 = require("./ratifierV1Internal.js");
15
15
  const TreeUtils_js_1 = require("./TreeUtils.js");
16
+ const treeMathInternal_js_1 = require("./treeMathInternal.js");
16
17
  const rateRatifierV1DataAbi = [
17
18
  { name: "root", type: "bytes32" },
18
19
  { name: "leafIndex", type: "uint256" },
@@ -167,8 +168,9 @@ var RateRatifierV1;
167
168
  */
168
169
  function memberHash(leaf) {
169
170
  const rate = BigInt(leaf.rate);
170
- if (rate < 0n)
171
+ if (rate < 0n) {
171
172
  throw new errors_js_1.InvalidRateRatifierV1RateError(rate);
173
+ }
172
174
  return hashLeaf({
173
175
  offer: index_js_3.OfferUtils.toStruct({ offer: leaf.offer, group: viem_1.zeroHash }),
174
176
  rate,
@@ -267,18 +269,20 @@ var RateRatifierV1;
267
269
  function buildDescriptor(leaves) {
268
270
  const normalized = leaves.map((leaf) => {
269
271
  const rate = BigInt(leaf.rate);
270
- if (rate < 0n)
272
+ if (rate < 0n) {
271
273
  throw new errors_js_1.InvalidRateRatifierV1RateError(rate);
274
+ }
272
275
  const allowedTaker = leaf.allowedTaker ?? viem_1.zeroAddress;
273
276
  const input = index_js_3.Offer.from(leaf.offer);
274
- if (input.tick < RateRatifierV1.MIN_TICK)
277
+ if (input.tick < RateRatifierV1.MIN_TICK) {
275
278
  throw new errors_js_1.InvalidRateRatifierV1TickError(input.tick, RateRatifierV1.MIN_TICK);
279
+ }
276
280
  return { offer: input, rate, allowedTaker };
277
281
  });
278
282
  const assignedOffers = (0, ratifierV1Internal_js_1.assignRatifierV1Groups)(normalized, groupId);
279
283
  const offers = [];
280
284
  const structs = normalized.map(({ rate, allowedTaker }, index) => {
281
- const offer = assignedOffers[index];
285
+ const offer = (0, treeMathInternal_js_1.requireTreeItem)(assignedOffers, index);
282
286
  offers.push(offer);
283
287
  return { offer: index_js_3.OfferUtils.toStruct({ offer }), rate, allowedTaker };
284
288
  });
@@ -308,10 +312,12 @@ var RateRatifierV1;
308
312
  isPadding: isPaddingEntry,
309
313
  ratifierOf: (leafStruct) => leafStruct.offer.ratifier,
310
314
  validateEntry: (entry) => {
311
- if (entry.rate < 0n)
315
+ if (entry.rate < 0n) {
312
316
  throw new errors_js_1.InvalidRateRatifierV1RateError(entry.rate);
313
- if (entry.offer.tick < RateRatifierV1.MIN_TICK)
317
+ }
318
+ if (entry.offer.tick < RateRatifierV1.MIN_TICK) {
314
319
  throw new errors_js_1.InvalidRateRatifierV1TickError(entry.offer.tick, RateRatifierV1.MIN_TICK);
320
+ }
315
321
  },
316
322
  label: "RateRatifierV1",
317
323
  type: "rateV1",
@@ -494,7 +500,7 @@ var RateRatifierV1;
494
500
  function ratifierData(params) {
495
501
  const tree = (0, ratifierV1Internal_js_1.resolveRatifierV1Tree)(params.tree, treeHelpers);
496
502
  const proof = TreeUtils_js_1.TreeUtils.buildProof({ tree, leafIndex: params.leafIndex });
497
- const entry = tree.entries[Number(proof.leafIndex)];
503
+ const entry = (0, treeMathInternal_js_1.requireTreeItem)(tree.entries, Number(proof.leafIndex));
498
504
  return encodeRatifierData({
499
505
  root: proof.root,
500
506
  leafIndex: proof.leafIndex,
@@ -537,8 +543,8 @@ var RateRatifierV1;
537
543
  count: tree.offers.length,
538
544
  });
539
545
  return tree.offers.map((offer, leafIndex) => {
540
- const entry = tree.entries[leafIndex];
541
- const proof = proofs[leafIndex];
546
+ const entry = (0, treeMathInternal_js_1.requireTreeItem)(tree.entries, leafIndex);
547
+ const proof = (0, treeMathInternal_js_1.requireTreeItem)(proofs, leafIndex);
542
548
  return {
543
549
  offer,
544
550
  ratifierData: encodeRatifierData({
@@ -581,8 +587,9 @@ var RateRatifierV1;
581
587
  */
582
588
  function priceBound(params) {
583
589
  const rate = BigInt(params.rate);
584
- if (rate < 0n)
590
+ if (rate < 0n) {
585
591
  throw new errors_js_1.InvalidRateRatifierV1RateError(rate);
592
+ }
586
593
  const timeToMaturity = BigInt(params.timeToMaturity);
587
594
  if (timeToMaturity < 0n) {
588
595
  throw new errors_js_1.InvalidRateRatifierV1TimeError(timeToMaturity, "timeToMaturity");
@@ -651,8 +658,9 @@ var RateRatifierV1;
651
658
  });
652
659
  }
653
660
  catch (error) {
654
- if (error instanceof errors_js_1.RateRatifierV1BoundOverflowError)
661
+ if (error instanceof errors_js_1.RateRatifierV1BoundOverflowError) {
655
662
  return false;
663
+ }
656
664
  throw error;
657
665
  }
658
666
  const offerPrice = index_js_2.TickLib.tickToPrice(params.offer.tick);
@@ -31,13 +31,13 @@ function normalizeTree(tree) {
31
31
  const computedLeaves = tree.paddedOffers.map(index_js_1.OfferUtils.hashStruct);
32
32
  const seen = new Set();
33
33
  for (const [index, offer] of tree.offers.entries()) {
34
- if ((0, offerStructInternal_js_1.isEmptyOfferStruct)(tree.paddedOffers[index], {
34
+ if ((0, offerStructInternal_js_1.isEmptyOfferStruct)((0, treeMathInternal_js_1.requireTreeItem)(tree.paddedOffers, index), {
35
35
  allowDefaultGroup: true,
36
36
  })) {
37
37
  throw new errors_js_1.InvalidTreeError("Visible offers must not contain tree padding.");
38
38
  }
39
39
  const hash = index_js_1.OfferUtils.hashStruct(index_js_1.OfferUtils.toStruct({ offer }));
40
- if (hash.toLowerCase() !== computedLeaves[index].toLowerCase() ||
40
+ if (hash.toLowerCase() !== computedLeaves[index]?.toLowerCase() ||
41
41
  seen.has(hash.toLowerCase())) {
42
42
  throw new errors_js_1.InvalidTreeError("Visible offers do not match the tree leaves.");
43
43
  }
@@ -48,14 +48,14 @@ function normalizeTree(tree) {
48
48
  .some((offer) => !(0, offerStructInternal_js_1.isEmptyOfferStruct)(offer, { allowDefaultGroup: true }))) {
49
49
  throw new errors_js_1.InvalidTreeError("Tree padding contains offers hidden from the visible offer list.");
50
50
  }
51
- if (computedLeaves.some((leaf, index) => leaf.toLowerCase() !== tree.leaves[index].toLowerCase())) {
51
+ if (computedLeaves.some((leaf, index) => leaf.toLowerCase() !== tree.leaves[index]?.toLowerCase())) {
52
52
  throw new errors_js_1.InvalidTreeError("Tree leaves do not match its padded offers.");
53
53
  }
54
54
  let level = computedLeaves;
55
55
  while (level.length > 1) {
56
56
  const next = [];
57
57
  for (let index = 0; index < level.length; index += 2) {
58
- next.push(TreeUtils_js_1.TreeUtils.hashNode(level[index], level[index + 1]));
58
+ next.push(TreeUtils_js_1.TreeUtils.hashNode((0, treeMathInternal_js_1.requireTreeItem)(level, index), (0, treeMathInternal_js_1.requireTreeItem)(level, index + 1)));
59
59
  }
60
60
  level = next;
61
61
  }
@@ -8,6 +8,7 @@ const index_js_1 = require("../offers/index.js");
8
8
  const Ratifier_js_1 = require("./Ratifier.js");
9
9
  const standardRatifierInternal_js_1 = require("./standardRatifierInternal.js");
10
10
  const TreeUtils_js_1 = require("./TreeUtils.js");
11
+ const treeMathInternal_js_1 = require("./treeMathInternal.js");
11
12
  const setterRatifierDataAbi = [
12
13
  { name: "root", type: "bytes32" },
13
14
  { name: "leafIndex", type: "uint256" },
@@ -252,7 +253,7 @@ var SetterRatifierUtils;
252
253
  });
253
254
  return tree.offers.map((offer, leafIndex) => ({
254
255
  offer,
255
- ratifierData: encodeRatifierData(proofs[leafIndex]),
256
+ ratifierData: encodeRatifierData((0, treeMathInternal_js_1.requireTreeItem)(proofs, leafIndex)),
256
257
  }));
257
258
  }
258
259
  SetterRatifierUtils.ratify = ratify;