@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
@@ -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
  /**
@@ -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
  /**
@@ -339,8 +339,9 @@ export var Payload;
339
339
  });
340
340
  }
341
341
  catch (error) {
342
- if (error instanceof PayloadDecodeError)
342
+ if (error instanceof PayloadDecodeError) {
343
343
  throw error;
344
+ }
344
345
  if (error instanceof Error) {
345
346
  throw new PayloadDecodeError(`invalid offer bytes: ${error.message}`, error);
346
347
  }
@@ -359,8 +360,9 @@ export var Payload;
359
360
  }
360
361
  }
361
362
  function assertApiValidOfferStruct(offer) {
362
- if (isEmptyOfferStruct(offer))
363
+ if (isEmptyOfferStruct(offer)) {
363
364
  return;
365
+ }
364
366
  assertCollateralParams(offer);
365
367
  assertSafeTimestamp("market.maturity", offer.market.maturity);
366
368
  assertMaturityAt15Utc(offer.market.maturity);
@@ -451,20 +453,23 @@ export var Payload;
451
453
  }
452
454
  }
453
455
  function resolveMaxItems(maxItems) {
454
- if (maxItems === undefined)
456
+ if (maxItems === undefined) {
455
457
  return undefined;
458
+ }
456
459
  if (!Number.isInteger(maxItems) || maxItems < 1) {
457
460
  throw new PayloadDecodeError(`maxItems must be a positive integer: got ${maxItems}`);
458
461
  }
459
462
  return maxItems;
460
463
  }
461
464
  function assertNonEmptyItemCount(count) {
462
- if (count === 0)
465
+ if (count === 0) {
463
466
  throw new PayloadDecodeError("items payload is empty");
467
+ }
464
468
  }
465
469
  function assertCallerItemCountLimit(count, maxItems) {
466
- if (maxItems === undefined)
470
+ if (maxItems === undefined) {
467
471
  return;
472
+ }
468
473
  if (count > maxItems) {
469
474
  throw new PayloadDecodeError(`items payload exceeds ${maxItems} items`);
470
475
  }
@@ -487,8 +492,9 @@ export var Payload;
487
492
  return compressed;
488
493
  }
489
494
  async function decompressItemsPayload(compressed) {
490
- if (compressed.length === 0)
495
+ if (compressed.length === 0) {
491
496
  throw new PayloadDecodeError("decompression failed");
497
+ }
492
498
  if (compressed.length > Payload.MAX_COMPRESSED_ITEMS_BYTES) {
493
499
  throw new PayloadDecodeError(`compressed items exceed ${Payload.MAX_COMPRESSED_ITEMS_BYTES} bytes`);
494
500
  }
@@ -500,8 +506,9 @@ export var Payload;
500
506
  try {
501
507
  while (true) {
502
508
  const { done, value } = await reader.read();
503
- if (done)
509
+ if (done) {
504
510
  break;
511
+ }
505
512
  totalLength += value.length;
506
513
  if (totalLength > Payload.MAX_DECOMPRESSED_ITEMS_BYTES) {
507
514
  await reader.cancel();
@@ -511,8 +518,9 @@ export var Payload;
511
518
  }
512
519
  }
513
520
  catch (error) {
514
- if (error instanceof PayloadDecodeError)
521
+ if (error instanceof PayloadDecodeError) {
515
522
  throw error;
523
+ }
516
524
  throw new PayloadDecodeError("decompression failed", error instanceof Error ? error : undefined);
517
525
  }
518
526
  const result = new Uint8Array(totalLength);
@@ -535,8 +543,9 @@ export var Payload;
535
543
  if (decoded.length < ABI_ARRAY_HEAD_BYTES) {
536
544
  throw new PayloadDecodeError("items payload truncated before ABI array head");
537
545
  }
538
- if (maxItems === undefined)
546
+ if (maxItems === undefined) {
539
547
  return;
548
+ }
540
549
  for (let i = 32; i < ABI_LENGTH_LOW_OFFSET; i++) {
541
550
  if (decoded[i] !== 0) {
542
551
  throw new PayloadDecodeError(`items payload exceeds ${maxItems} items`);
@@ -9,6 +9,7 @@ import { GroupUtils } from "./GroupUtils.js";
9
9
  import { EMPTY_OFFER_STRUCT, isEmptyOfferStruct, isZeroAddress, } from "./offerStructInternal.js";
10
10
  import { assertRatifierV1Address, assertRatifierV1Taker, assignRatifierV1Groups, buildRatifierV1Descriptor, resolveRatifierV1Tree, } from "./ratifierV1Internal.js";
11
11
  import { TreeUtils } from "./TreeUtils.js";
12
+ import { requireTreeItem } from "./treeMathInternal.js";
12
13
  const priceRatifierV1DataAbi = [
13
14
  { name: "root", type: "bytes32" },
14
15
  { name: "leafIndex", type: "uint256" },
@@ -237,7 +238,7 @@ export var PriceRatifierV1;
237
238
  const assignedOffers = assignRatifierV1Groups(normalized, groupId);
238
239
  const offers = [];
239
240
  const structs = normalized.map(({ allowedTaker }, index) => {
240
- const offer = assignedOffers[index];
241
+ const offer = requireTreeItem(assignedOffers, index);
241
242
  offers.push(offer);
242
243
  return { offer: OfferUtils.toStruct({ offer }), allowedTaker };
243
244
  });
@@ -427,7 +428,7 @@ export var PriceRatifierV1;
427
428
  function ratifierData(params) {
428
429
  const tree = resolveRatifierV1Tree(params.tree, treeHelpers);
429
430
  const proof = TreeUtils.buildProof({ tree, leafIndex: params.leafIndex });
430
- const entry = tree.entries[Number(proof.leafIndex)];
431
+ const entry = requireTreeItem(tree.entries, Number(proof.leafIndex));
431
432
  return encodeRatifierData({
432
433
  root: proof.root,
433
434
  leafIndex: proof.leafIndex,
@@ -467,8 +468,8 @@ export var PriceRatifierV1;
467
468
  count: tree.offers.length,
468
469
  });
469
470
  return tree.offers.map((offer, leafIndex) => {
470
- const entry = tree.entries[leafIndex];
471
- const proof = proofs[leafIndex];
471
+ const entry = requireTreeItem(tree.entries, leafIndex);
472
+ const proof = requireTreeItem(proofs, leafIndex);
472
473
  return {
473
474
  offer,
474
475
  ratifierData: encodeRatifierData({
@@ -10,6 +10,7 @@ import { GroupUtils } from "./GroupUtils.js";
10
10
  import { EMPTY_OFFER_STRUCT, isEmptyOfferStruct, isZeroAddress, } from "./offerStructInternal.js";
11
11
  import { assertRatifierV1Address, assertRatifierV1Taker, assignRatifierV1Groups, buildRatifierV1Descriptor, resolveRatifierV1Tree, } from "./ratifierV1Internal.js";
12
12
  import { TreeUtils } from "./TreeUtils.js";
13
+ import { requireTreeItem } from "./treeMathInternal.js";
13
14
  const rateRatifierV1DataAbi = [
14
15
  { name: "root", type: "bytes32" },
15
16
  { name: "leafIndex", type: "uint256" },
@@ -164,8 +165,9 @@ export var RateRatifierV1;
164
165
  */
165
166
  function memberHash(leaf) {
166
167
  const rate = BigInt(leaf.rate);
167
- if (rate < 0n)
168
+ if (rate < 0n) {
168
169
  throw new InvalidRateRatifierV1RateError(rate);
170
+ }
169
171
  return hashLeaf({
170
172
  offer: OfferUtils.toStruct({ offer: leaf.offer, group: zeroHash }),
171
173
  rate,
@@ -264,18 +266,20 @@ export var RateRatifierV1;
264
266
  function buildDescriptor(leaves) {
265
267
  const normalized = leaves.map((leaf) => {
266
268
  const rate = BigInt(leaf.rate);
267
- if (rate < 0n)
269
+ if (rate < 0n) {
268
270
  throw new InvalidRateRatifierV1RateError(rate);
271
+ }
269
272
  const allowedTaker = leaf.allowedTaker ?? zeroAddress;
270
273
  const input = Offer.from(leaf.offer);
271
- if (input.tick < RateRatifierV1.MIN_TICK)
274
+ if (input.tick < RateRatifierV1.MIN_TICK) {
272
275
  throw new InvalidRateRatifierV1TickError(input.tick, RateRatifierV1.MIN_TICK);
276
+ }
273
277
  return { offer: input, rate, allowedTaker };
274
278
  });
275
279
  const assignedOffers = assignRatifierV1Groups(normalized, groupId);
276
280
  const offers = [];
277
281
  const structs = normalized.map(({ rate, allowedTaker }, index) => {
278
- const offer = assignedOffers[index];
282
+ const offer = requireTreeItem(assignedOffers, index);
279
283
  offers.push(offer);
280
284
  return { offer: OfferUtils.toStruct({ offer }), rate, allowedTaker };
281
285
  });
@@ -305,10 +309,12 @@ export var RateRatifierV1;
305
309
  isPadding: isPaddingEntry,
306
310
  ratifierOf: (leafStruct) => leafStruct.offer.ratifier,
307
311
  validateEntry: (entry) => {
308
- if (entry.rate < 0n)
312
+ if (entry.rate < 0n) {
309
313
  throw new InvalidRateRatifierV1RateError(entry.rate);
310
- if (entry.offer.tick < RateRatifierV1.MIN_TICK)
314
+ }
315
+ if (entry.offer.tick < RateRatifierV1.MIN_TICK) {
311
316
  throw new InvalidRateRatifierV1TickError(entry.offer.tick, RateRatifierV1.MIN_TICK);
317
+ }
312
318
  },
313
319
  label: "RateRatifierV1",
314
320
  type: "rateV1",
@@ -491,7 +497,7 @@ export var RateRatifierV1;
491
497
  function ratifierData(params) {
492
498
  const tree = resolveRatifierV1Tree(params.tree, treeHelpers);
493
499
  const proof = TreeUtils.buildProof({ tree, leafIndex: params.leafIndex });
494
- const entry = tree.entries[Number(proof.leafIndex)];
500
+ const entry = requireTreeItem(tree.entries, Number(proof.leafIndex));
495
501
  return encodeRatifierData({
496
502
  root: proof.root,
497
503
  leafIndex: proof.leafIndex,
@@ -534,8 +540,8 @@ export var RateRatifierV1;
534
540
  count: tree.offers.length,
535
541
  });
536
542
  return tree.offers.map((offer, leafIndex) => {
537
- const entry = tree.entries[leafIndex];
538
- const proof = proofs[leafIndex];
543
+ const entry = requireTreeItem(tree.entries, leafIndex);
544
+ const proof = requireTreeItem(proofs, leafIndex);
539
545
  return {
540
546
  offer,
541
547
  ratifierData: encodeRatifierData({
@@ -578,8 +584,9 @@ export var RateRatifierV1;
578
584
  */
579
585
  function priceBound(params) {
580
586
  const rate = BigInt(params.rate);
581
- if (rate < 0n)
587
+ if (rate < 0n) {
582
588
  throw new InvalidRateRatifierV1RateError(rate);
589
+ }
583
590
  const timeToMaturity = BigInt(params.timeToMaturity);
584
591
  if (timeToMaturity < 0n) {
585
592
  throw new InvalidRateRatifierV1TimeError(timeToMaturity, "timeToMaturity");
@@ -648,8 +655,9 @@ export var RateRatifierV1;
648
655
  });
649
656
  }
650
657
  catch (error) {
651
- if (error instanceof RateRatifierV1BoundOverflowError)
658
+ if (error instanceof RateRatifierV1BoundOverflowError) {
652
659
  return false;
660
+ }
653
661
  throw error;
654
662
  }
655
663
  const offerPrice = TickLib.tickToPrice(params.offer.tick);
@@ -3,7 +3,7 @@ import { InvalidTreeError, InvalidTreeHeightError } from "../errors.js";
3
3
  import { OfferUtils } from "../offers/index.js";
4
4
  import { isEmptyOfferStruct } from "./offerStructInternal.js";
5
5
  import { TreeUtils } from "./TreeUtils.js";
6
- import { nextPowerOfTwo } from "./treeMathInternal.js";
6
+ import { nextPowerOfTwo, requireTreeItem } from "./treeMathInternal.js";
7
7
  function isTreeLike(tree) {
8
8
  return (!Array.isArray(tree) &&
9
9
  "offers" in tree &&
@@ -28,13 +28,13 @@ function normalizeTree(tree) {
28
28
  const computedLeaves = tree.paddedOffers.map(OfferUtils.hashStruct);
29
29
  const seen = new Set();
30
30
  for (const [index, offer] of tree.offers.entries()) {
31
- if (isEmptyOfferStruct(tree.paddedOffers[index], {
31
+ if (isEmptyOfferStruct(requireTreeItem(tree.paddedOffers, index), {
32
32
  allowDefaultGroup: true,
33
33
  })) {
34
34
  throw new InvalidTreeError("Visible offers must not contain tree padding.");
35
35
  }
36
36
  const hash = OfferUtils.hashStruct(OfferUtils.toStruct({ offer }));
37
- if (hash.toLowerCase() !== computedLeaves[index].toLowerCase() ||
37
+ if (hash.toLowerCase() !== computedLeaves[index]?.toLowerCase() ||
38
38
  seen.has(hash.toLowerCase())) {
39
39
  throw new InvalidTreeError("Visible offers do not match the tree leaves.");
40
40
  }
@@ -45,14 +45,14 @@ function normalizeTree(tree) {
45
45
  .some((offer) => !isEmptyOfferStruct(offer, { allowDefaultGroup: true }))) {
46
46
  throw new InvalidTreeError("Tree padding contains offers hidden from the visible offer list.");
47
47
  }
48
- if (computedLeaves.some((leaf, index) => leaf.toLowerCase() !== tree.leaves[index].toLowerCase())) {
48
+ if (computedLeaves.some((leaf, index) => leaf.toLowerCase() !== tree.leaves[index]?.toLowerCase())) {
49
49
  throw new InvalidTreeError("Tree leaves do not match its padded offers.");
50
50
  }
51
51
  let level = computedLeaves;
52
52
  while (level.length > 1) {
53
53
  const next = [];
54
54
  for (let index = 0; index < level.length; index += 2) {
55
- next.push(TreeUtils.hashNode(level[index], level[index + 1]));
55
+ next.push(TreeUtils.hashNode(requireTreeItem(level, index), requireTreeItem(level, index + 1)));
56
56
  }
57
57
  level = next;
58
58
  }
@@ -5,6 +5,7 @@ import { Offer } from "../offers/index.js";
5
5
  import { Ratifier } from "./Ratifier.js";
6
6
  import { parseStandardRatifierTree } from "./standardRatifierInternal.js";
7
7
  import { TreeUtils } from "./TreeUtils.js";
8
+ import { requireTreeItem } from "./treeMathInternal.js";
8
9
  const setterRatifierDataAbi = [
9
10
  { name: "root", type: "bytes32" },
10
11
  { name: "leafIndex", type: "uint256" },
@@ -249,7 +250,7 @@ export var SetterRatifierUtils;
249
250
  });
250
251
  return tree.offers.map((offer, leafIndex) => ({
251
252
  offer,
252
- ratifierData: encodeRatifierData(proofs[leafIndex]),
253
+ ratifierData: encodeRatifierData(requireTreeItem(proofs, leafIndex)),
253
254
  }));
254
255
  }
255
256
  SetterRatifierUtils.ratify = ratify;
@@ -73,8 +73,9 @@ export class Tree {
73
73
  this.height = descriptor.height;
74
74
  }
75
75
  static from(tree) {
76
- if (tree instanceof Tree)
76
+ if (tree instanceof Tree) {
77
77
  return tree;
78
+ }
78
79
  // Portable snapshots resume through descriptor validation instead of rebuilding.
79
80
  if (!Array.isArray(tree) &&
80
81
  "entries" in tree &&
@@ -84,8 +85,9 @@ export class Tree {
84
85
  ? Tree.fromDescriptor(tree)
85
86
  : Tree.fromDescriptor(tree);
86
87
  }
87
- if ("type" in tree && tree.type != null)
88
+ if ("type" in tree && tree.type != null) {
88
89
  return Tree.create(tree);
90
+ }
89
91
  return Tree.create(Array.isArray(tree) ? tree : [tree]);
90
92
  }
91
93
  static create(params) {
@@ -172,10 +174,12 @@ export class Tree {
172
174
  ? OfferUtils.toStruct({ offer })
173
175
  : offer),
174
176
  };
175
- if (descriptor.type === "ecrecover")
177
+ if (descriptor.type === "ecrecover") {
176
178
  return new Tree("ecrecover", normalized);
177
- if (descriptor.type === "setter")
179
+ }
180
+ if (descriptor.type === "setter") {
178
181
  return new Tree("setter", normalized);
182
+ }
179
183
  return new Tree(undefined, normalized);
180
184
  }
181
185
  default: