@aztec/ethereum 0.0.1-commit.343b43af6 → 0.0.1-commit.350e0a4d

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 (139) hide show
  1. package/dest/client.d.ts +25 -3
  2. package/dest/client.d.ts.map +1 -1
  3. package/dest/client.js +60 -8
  4. package/dest/config.d.ts +27 -8
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +59 -12
  7. package/dest/contracts/chain_state_override.d.ts +78 -0
  8. package/dest/contracts/chain_state_override.d.ts.map +1 -0
  9. package/dest/contracts/chain_state_override.js +137 -0
  10. package/dest/contracts/empire_base.d.ts +1 -3
  11. package/dest/contracts/empire_base.d.ts.map +1 -1
  12. package/dest/contracts/fee_asset_price_oracle.d.ts +6 -2
  13. package/dest/contracts/fee_asset_price_oracle.d.ts.map +1 -1
  14. package/dest/contracts/fee_asset_price_oracle.js +11 -6
  15. package/dest/contracts/governance.d.ts +108 -33
  16. package/dest/contracts/governance.d.ts.map +1 -1
  17. package/dest/contracts/governance.js +193 -12
  18. package/dest/contracts/governance_proposer.d.ts +33 -3
  19. package/dest/contracts/governance_proposer.d.ts.map +1 -1
  20. package/dest/contracts/governance_proposer.js +51 -9
  21. package/dest/contracts/gse.d.ts +4 -2
  22. package/dest/contracts/gse.d.ts.map +1 -1
  23. package/dest/contracts/gse.js +2 -2
  24. package/dest/contracts/inbox.d.ts +3 -3
  25. package/dest/contracts/inbox.d.ts.map +1 -1
  26. package/dest/contracts/inbox.js +12 -7
  27. package/dest/contracts/index.d.ts +3 -3
  28. package/dest/contracts/index.d.ts.map +1 -1
  29. package/dest/contracts/index.js +2 -2
  30. package/dest/contracts/multicall.d.ts +130 -13
  31. package/dest/contracts/multicall.d.ts.map +1 -1
  32. package/dest/contracts/multicall.js +203 -94
  33. package/dest/contracts/outbox.d.ts +27 -4
  34. package/dest/contracts/outbox.d.ts.map +1 -1
  35. package/dest/contracts/outbox.js +34 -7
  36. package/dest/contracts/rollup.d.ts +5411 -26
  37. package/dest/contracts/rollup.d.ts.map +1 -1
  38. package/dest/contracts/rollup.js +380 -68
  39. package/dest/contracts/{tally_slashing_proposer.d.ts → slashing_proposer.d.ts} +3 -4
  40. package/dest/contracts/slashing_proposer.d.ts.map +1 -0
  41. package/dest/contracts/{tally_slashing_proposer.js → slashing_proposer.js} +13 -15
  42. package/dest/deploy_aztec_l1_contracts.d.ts +18 -10
  43. package/dest/deploy_aztec_l1_contracts.d.ts.map +1 -1
  44. package/dest/deploy_aztec_l1_contracts.js +17 -13
  45. package/dest/l1_artifacts.d.ts +14941 -16273
  46. package/dest/l1_artifacts.d.ts.map +1 -1
  47. package/dest/l1_artifacts.js +9 -24
  48. package/dest/l1_contract_addresses.d.ts +61 -65
  49. package/dest/l1_contract_addresses.d.ts.map +1 -1
  50. package/dest/l1_contract_addresses.js +101 -82
  51. package/dest/l1_reader.d.ts +5 -5
  52. package/dest/l1_reader.d.ts.map +1 -1
  53. package/dest/l1_reader.js +9 -7
  54. package/dest/l1_tx_utils/config.js +3 -3
  55. package/dest/l1_tx_utils/l1_fee_analyzer.d.ts +23 -4
  56. package/dest/l1_tx_utils/l1_fee_analyzer.d.ts.map +1 -1
  57. package/dest/l1_tx_utils/l1_fee_analyzer.js +65 -3
  58. package/dest/l1_tx_utils/l1_tx_utils.d.ts +9 -1
  59. package/dest/l1_tx_utils/l1_tx_utils.d.ts.map +1 -1
  60. package/dest/l1_tx_utils/l1_tx_utils.js +138 -57
  61. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts +1 -1
  62. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts.map +1 -1
  63. package/dest/l1_tx_utils/readonly_l1_tx_utils.js +2 -1
  64. package/dest/l1_tx_utils/tx_delayer.d.ts +5 -3
  65. package/dest/l1_tx_utils/tx_delayer.d.ts.map +1 -1
  66. package/dest/l1_tx_utils/tx_delayer.js +7 -5
  67. package/dest/l1_tx_utils/types.d.ts +27 -1
  68. package/dest/l1_tx_utils/types.d.ts.map +1 -1
  69. package/dest/l1_tx_utils/types.js +10 -0
  70. package/dest/publisher_manager.d.ts +34 -8
  71. package/dest/publisher_manager.d.ts.map +1 -1
  72. package/dest/publisher_manager.js +119 -8
  73. package/dest/queries.d.ts +13 -2
  74. package/dest/queries.d.ts.map +1 -1
  75. package/dest/queries.js +69 -4
  76. package/dest/test/blob_kzg_warmup.d.ts +19 -0
  77. package/dest/test/blob_kzg_warmup.d.ts.map +1 -0
  78. package/dest/test/blob_kzg_warmup.js +64 -0
  79. package/dest/test/chain_monitor.d.ts +55 -4
  80. package/dest/test/chain_monitor.d.ts.map +1 -1
  81. package/dest/test/chain_monitor.js +104 -3
  82. package/dest/test/eth_cheat_codes.d.ts +37 -6
  83. package/dest/test/eth_cheat_codes.d.ts.map +1 -1
  84. package/dest/test/eth_cheat_codes.js +89 -41
  85. package/dest/test/index.d.ts +2 -1
  86. package/dest/test/index.d.ts.map +1 -1
  87. package/dest/test/index.js +1 -0
  88. package/dest/test/rollup_cheat_codes.d.ts +60 -3
  89. package/dest/test/rollup_cheat_codes.d.ts.map +1 -1
  90. package/dest/test/rollup_cheat_codes.js +86 -7
  91. package/dest/test/start_anvil.d.ts +8 -1
  92. package/dest/test/start_anvil.d.ts.map +1 -1
  93. package/dest/test/start_anvil.js +16 -2
  94. package/dest/utils.d.ts +9 -2
  95. package/dest/utils.d.ts.map +1 -1
  96. package/dest/utils.js +34 -6
  97. package/package.json +6 -7
  98. package/src/client.ts +66 -2
  99. package/src/config.ts +82 -16
  100. package/src/contracts/chain_state_override.ts +200 -0
  101. package/src/contracts/empire_base.ts +0 -2
  102. package/src/contracts/fee_asset_price_oracle.ts +10 -5
  103. package/src/contracts/governance.ts +266 -9
  104. package/src/contracts/governance_proposer.ts +52 -5
  105. package/src/contracts/gse.ts +7 -2
  106. package/src/contracts/inbox.ts +13 -5
  107. package/src/contracts/index.ts +2 -2
  108. package/src/contracts/multicall.ts +247 -106
  109. package/src/contracts/outbox.ts +42 -8
  110. package/src/contracts/rollup.ts +415 -69
  111. package/src/contracts/{tally_slashing_proposer.ts → slashing_proposer.ts} +14 -16
  112. package/src/deploy_aztec_l1_contracts.ts +16 -14
  113. package/src/l1_artifacts.ts +12 -35
  114. package/src/l1_contract_addresses.ts +120 -94
  115. package/src/l1_reader.ts +17 -10
  116. package/src/l1_tx_utils/config.ts +3 -3
  117. package/src/l1_tx_utils/l1_fee_analyzer.ts +75 -3
  118. package/src/l1_tx_utils/l1_tx_utils.ts +122 -48
  119. package/src/l1_tx_utils/readonly_l1_tx_utils.ts +2 -1
  120. package/src/l1_tx_utils/tx_delayer.ts +16 -7
  121. package/src/l1_tx_utils/types.ts +32 -0
  122. package/src/publisher_manager.ts +143 -12
  123. package/src/queries.ts +76 -4
  124. package/src/test/blob_kzg_warmup.ts +65 -0
  125. package/src/test/chain_monitor.ts +148 -3
  126. package/src/test/eth_cheat_codes.ts +82 -45
  127. package/src/test/index.ts +1 -0
  128. package/src/test/rollup_cheat_codes.ts +115 -6
  129. package/src/test/start_anvil.ts +25 -2
  130. package/src/utils.ts +30 -6
  131. package/dest/contracts/empire_slashing_proposer.d.ts +0 -69
  132. package/dest/contracts/empire_slashing_proposer.d.ts.map +0 -1
  133. package/dest/contracts/empire_slashing_proposer.js +0 -216
  134. package/dest/contracts/tally_slashing_proposer.d.ts.map +0 -1
  135. package/dest/generated/l1-contracts-defaults.d.ts +0 -30
  136. package/dest/generated/l1-contracts-defaults.d.ts.map +0 -1
  137. package/dest/generated/l1-contracts-defaults.js +0 -30
  138. package/src/contracts/empire_slashing_proposer.ts +0 -265
  139. package/src/generated/l1-contracts-defaults.ts +0 -32
@@ -376,25 +376,20 @@ import { Buffer32 } from '@aztec/foundation/buffer';
376
376
  import { Fr } from '@aztec/foundation/curves/bn254';
377
377
  import { memoize } from '@aztec/foundation/decorators';
378
378
  import { EthAddress } from '@aztec/foundation/eth-address';
379
+ import { createLogger } from '@aztec/foundation/log';
379
380
  import { makeBackoff, retry } from '@aztec/foundation/retry';
381
+ import { getErrorCause } from '@aztec/foundation/types';
380
382
  import { EscapeHatchAbi } from '@aztec/l1-artifacts/EscapeHatchAbi';
381
383
  import { RollupAbi } from '@aztec/l1-artifacts/RollupAbi';
382
384
  import { RollupStorage } from '@aztec/l1-artifacts/RollupStorage';
383
385
  import chunk from 'lodash.chunk';
384
- import { encodeFunctionData, getContract, hexToBigInt, keccak256 } from 'viem';
386
+ import { ContractFunctionRevertedError, RpcRequestError, decodeErrorResult, encodeAbiParameters, encodeFunctionData, getContract, hexToBigInt, keccak256 } from 'viem';
385
387
  import { getPublicClient } from '../client.js';
386
388
  import { formatViemError } from '../utils.js';
387
- import { EmpireSlashingProposerContract } from './empire_slashing_proposer.js';
388
389
  import { GSEContract } from './gse.js';
389
390
  import { SlasherContract } from './slasher_contract.js';
390
- import { TallySlashingProposerContract } from './tally_slashing_proposer.js';
391
+ import { SlashingProposerContract } from './slashing_proposer.js';
391
392
  import { checkBlockTag } from './utils.js';
392
- export var SlashingProposerType = /*#__PURE__*/ function(SlashingProposerType) {
393
- SlashingProposerType[SlashingProposerType["None"] = 0] = "None";
394
- SlashingProposerType[SlashingProposerType["Tally"] = 1] = "Tally";
395
- SlashingProposerType[SlashingProposerType["Empire"] = 2] = "Empire";
396
- return SlashingProposerType;
397
- }({});
398
393
  /**
399
394
  * Status of a validator/attester in the staking system.
400
395
  * Matches the Status enum in StakingLib.sol
@@ -405,6 +400,37 @@ export var SlashingProposerType = /*#__PURE__*/ function(SlashingProposerType) {
405
400
  AttesterStatus[AttesterStatus["EXITING"] = 3] = "EXITING";
406
401
  return AttesterStatus;
407
402
  }({});
403
+ /** Field offsets within the CompressedTempCheckpointLog struct in Solidity storage. */ export var TempCheckpointLogField = /*#__PURE__*/ function(TempCheckpointLogField) {
404
+ TempCheckpointLogField[TempCheckpointLogField["HeaderHash"] = 0] = "HeaderHash";
405
+ TempCheckpointLogField[TempCheckpointLogField["BlobCommitmentsHash"] = 1] = "BlobCommitmentsHash";
406
+ TempCheckpointLogField[TempCheckpointLogField["OutHash"] = 2] = "OutHash";
407
+ TempCheckpointLogField[TempCheckpointLogField["AttestationsHash"] = 3] = "AttestationsHash";
408
+ TempCheckpointLogField[TempCheckpointLogField["PayloadDigest"] = 4] = "PayloadDigest";
409
+ TempCheckpointLogField[TempCheckpointLogField["SlotNumber"] = 5] = "SlotNumber";
410
+ TempCheckpointLogField[TempCheckpointLogField["FeeHeader"] = 6] = "FeeHeader";
411
+ return TempCheckpointLogField;
412
+ }({});
413
+ const INSUFFICIENT_VALIDATOR_SET_SIZE_ERROR = 'ValidatorSelection__InsufficientValidatorSetSize';
414
+ function isValidatorSelectionError(err, errorName) {
415
+ return getErrorCause(err, ContractFunctionRevertedError)?.data?.errorName === errorName || decodeRpcRequestErrorName(err) === errorName;
416
+ }
417
+ function decodeRpcRequestErrorName(err) {
418
+ const data = getErrorCause(err, RpcRequestError)?.data;
419
+ if (!isHexString(data)) {
420
+ return undefined;
421
+ }
422
+ try {
423
+ return decodeErrorResult({
424
+ abi: RollupAbi,
425
+ data
426
+ }).errorName;
427
+ } catch {
428
+ return undefined;
429
+ }
430
+ }
431
+ function isHexString(value) {
432
+ return typeof value === 'string' && value.startsWith('0x');
433
+ }
408
434
  export class RollupContract {
409
435
  client;
410
436
  static{
@@ -499,6 +525,16 @@ export class RollupContract {
499
525
  2,
500
526
  "getGenesisArchiveTreeRoot"
501
527
  ],
528
+ [
529
+ memoize,
530
+ 2,
531
+ "getVkTreeRoot"
532
+ ],
533
+ [
534
+ memoize,
535
+ 2,
536
+ "getProtocolContractsHash"
537
+ ],
502
538
  [
503
539
  memoize,
504
540
  2,
@@ -507,6 +543,7 @@ export class RollupContract {
507
543
  ], []));
508
544
  }
509
545
  rollup;
546
+ logger;
510
547
  static cachedStfStorageSlot;
511
548
  cachedEscapeHatch;
512
549
  static get checkBlobStorageSlot() {
@@ -525,12 +562,12 @@ export class RollupContract {
525
562
  }
526
563
  static getFromConfig(config) {
527
564
  const client = getPublicClient(config);
528
- const address = config.l1Contracts.rollupAddress.toString();
565
+ const address = config.rollupAddress.toString();
529
566
  return new RollupContract(client, address);
530
567
  }
531
568
  constructor(client, address){
532
569
  this.client = client;
533
- _initProto(this);
570
+ this.logger = (_initProto(this), createLogger('ethereum:rollup'));
534
571
  if (address instanceof EthAddress) {
535
572
  address = address.toString();
536
573
  }
@@ -555,34 +592,10 @@ export class RollupContract {
555
592
  return undefined;
556
593
  }
557
594
  const proposerAddress = await slasher.getProposer();
558
- const proposerAbi = [
559
- {
560
- type: 'function',
561
- name: 'SLASHING_PROPOSER_TYPE',
562
- inputs: [],
563
- outputs: [
564
- {
565
- name: '',
566
- type: 'uint8',
567
- internalType: 'enum SlasherFlavor'
568
- }
569
- ],
570
- stateMutability: 'view'
571
- }
572
- ];
573
- const proposer = getContract({
574
- address: proposerAddress.toString(),
575
- abi: proposerAbi,
576
- client: this.client
577
- });
578
- const proposerType = await proposer.read.SLASHING_PROPOSER_TYPE();
579
- if (proposerType === 1..valueOf()) {
580
- return new TallySlashingProposerContract(this.client, proposerAddress);
581
- } else if (proposerType === 2..valueOf()) {
582
- return new EmpireSlashingProposerContract(this.client, proposerAddress);
583
- } else {
584
- throw new Error(`Unknown slashing proposer type: ${proposerType}`);
595
+ if (proposerAddress.isZero()) {
596
+ return undefined;
585
597
  }
598
+ return new SlashingProposerContract(this.client, proposerAddress);
586
599
  }
587
600
  getL1StartBlock() {
588
601
  return this.rollup.read.L1_BLOCK_AT_GENESIS();
@@ -640,6 +653,22 @@ export class RollupContract {
640
653
  0n
641
654
  ]));
642
655
  }
656
+ async getVkTreeRoot() {
657
+ const slot = BigInt(RollupContract.stfStorageSlot) + 3n;
658
+ const value = await this.client.getStorageAt({
659
+ address: this.address,
660
+ slot: `0x${slot.toString(16)}`
661
+ });
662
+ return Fr.fromString(value ?? '0x0');
663
+ }
664
+ async getProtocolContractsHash() {
665
+ const slot = BigInt(RollupContract.stfStorageSlot) + 4n;
666
+ const value = await this.client.getStorageAt({
667
+ address: this.address,
668
+ slot: `0x${slot.toString(16)}`
669
+ });
670
+ return Fr.fromString(value ?? '0x0');
671
+ }
643
672
  /**
644
673
  * Returns rollup constants used for epoch queries.
645
674
  * Return type is `L1RollupConstants` which is defined in stdlib,
@@ -707,7 +736,11 @@ export class RollupContract {
707
736
  BigInt(epoch)
708
737
  ]);
709
738
  return isOpen;
710
- } catch {
739
+ } catch (err) {
740
+ this.logger.warn('isEscapeHatchOpen failed (treating as closed); RPC or contract error may cause liveness risk', {
741
+ epoch: Number(epoch),
742
+ error: err
743
+ });
711
744
  return false;
712
745
  }
713
746
  }
@@ -723,8 +756,9 @@ export class RollupContract {
723
756
  async getOwner() {
724
757
  return EthAddress.fromString(await this.rollup.read.owner());
725
758
  }
726
- async getActiveAttesterCount() {
727
- return Number(await this.rollup.read.getActiveAttesterCount());
759
+ async getActiveAttesterCount(options) {
760
+ await checkBlockTag(options?.blockNumber, this.client);
761
+ return Number(await this.rollup.read.getActiveAttesterCount(options));
728
762
  }
729
763
  async getSlashingProposerAddress() {
730
764
  const slasher = await this.getSlasherContract();
@@ -736,25 +770,40 @@ export class RollupContract {
736
770
  getCheckpointReward() {
737
771
  return this.rollup.read.getCheckpointReward();
738
772
  }
739
- async getCheckpointNumber() {
740
- return CheckpointNumber.fromBigInt(await this.rollup.read.getPendingCheckpointNumber());
773
+ async getCheckpointNumber(options) {
774
+ await checkBlockTag(options?.blockNumber, this.client);
775
+ return CheckpointNumber.fromBigInt(await this.rollup.read.getPendingCheckpointNumber(options));
741
776
  }
742
777
  async getProvenCheckpointNumber(options) {
743
778
  await checkBlockTag(options?.blockNumber, this.client);
744
779
  return CheckpointNumber.fromBigInt(await this.rollup.read.getProvenCheckpointNumber(options));
745
780
  }
746
- async getSlotNumber() {
747
- return SlotNumber.fromBigInt(await this.rollup.read.getCurrentSlot());
781
+ async getSlotNumber(options) {
782
+ await checkBlockTag(options?.blockNumber, this.client);
783
+ return SlotNumber.fromBigInt(await this.rollup.read.getCurrentSlot(options));
748
784
  }
749
- async getL1FeesAt(timestamp) {
785
+ async getL1FeesAt(timestamp, options) {
786
+ await checkBlockTag(options?.blockNumber, this.client);
750
787
  const result = await this.rollup.read.getL1FeesAt([
751
788
  timestamp
752
- ]);
789
+ ], options);
753
790
  return {
754
791
  baseFee: result.baseFee,
755
792
  blobFee: result.blobFee
756
793
  };
757
794
  }
795
+ async getFeeHeader(checkpointNumber) {
796
+ const result = await this.rollup.read.getFeeHeader([
797
+ checkpointNumber
798
+ ]);
799
+ return {
800
+ excessMana: result.excessMana,
801
+ manaUsed: result.manaUsed,
802
+ ethPerFeeAsset: result.ethPerFeeAsset,
803
+ congestionCost: result.congestionCost,
804
+ proverCost: result.proverCost
805
+ };
806
+ }
758
807
  getEthPerFeeAsset() {
759
808
  return this.rollup.read.getEthPerFeeAsset();
760
809
  }
@@ -767,7 +816,7 @@ export class RollupContract {
767
816
  timestamp
768
817
  ]
769
818
  }).catch((e)=>{
770
- if (e instanceof Error && e.message.includes('ValidatorSelection__InsufficientValidatorSetSize')) {
819
+ if (isValidatorSelectionError(e, INSUFFICIENT_VALIDATOR_SET_SIZE_ERROR)) {
771
820
  return {
772
821
  result: undefined
773
822
  };
@@ -794,7 +843,7 @@ export class RollupContract {
794
843
  functionName: 'getCurrentEpochCommittee',
795
844
  args: []
796
845
  }).catch((e)=>{
797
- if (e instanceof Error && e.message.includes('ValidatorSelection__InsufficientValidatorSetSize')) {
846
+ if (isValidatorSelectionError(e, INSUFFICIENT_VALIDATOR_SET_SIZE_ERROR)) {
798
847
  return {
799
848
  result: undefined
800
849
  };
@@ -823,10 +872,11 @@ export class RollupContract {
823
872
  });
824
873
  return EthAddress.fromString(result);
825
874
  }
826
- async getCheckpoint(checkpointNumber) {
875
+ async getCheckpoint(checkpointNumber, options) {
876
+ await checkBlockTag(options?.blockNumber, this.client);
827
877
  const result = await this.rollup.read.getCheckpoint([
828
878
  BigInt(checkpointNumber)
829
- ]);
879
+ ], options);
830
880
  return {
831
881
  archive: Fr.fromString(result.archive),
832
882
  headerHash: Buffer32.fromString(result.headerHash),
@@ -856,6 +906,28 @@ export class RollupContract {
856
906
  0.5
857
907
  ]));
858
908
  }
909
+ /**
910
+ * Returns the effective pending checkpoint, accounting for potential prunes.
911
+ * When a prune can happen, the L1 contract uses the proven checkpoint instead of the pending one.
912
+ * This mirrors the behavior of getEffectivePendingCheckpointNumber in STFLib.sol.
913
+ * @param atTimestamp - The timestamp to evaluate pruneability at. Defaults to the current L1 block timestamp.
914
+ * @param options - Optional L1 block number to pin the queries to.
915
+ */ getEffectivePendingCheckpoint(atTimestamp, options) {
916
+ return retry(async ()=>{
917
+ const timestamp = atTimestamp ?? (await this.client.getBlock()).timestamp;
918
+ const canPrune = await this.canPruneAtTime(timestamp, options);
919
+ if (canPrune) {
920
+ const provenCheckpointNumber = await this.getProvenCheckpointNumber(options);
921
+ return await this.getCheckpoint(provenCheckpointNumber, options);
922
+ }
923
+ const pendingCheckpointNumber = await this.getCheckpointNumber(options);
924
+ return await this.getCheckpoint(pendingCheckpointNumber, options);
925
+ }, 'getting effective pending checkpoint', makeBackoff([
926
+ 0.5,
927
+ 0.5,
928
+ 0.5
929
+ ]));
930
+ }
859
931
  async getTips() {
860
932
  const { pending, proven } = await this.rollup.read.getTips();
861
933
  return {
@@ -940,9 +1012,8 @@ export class RollupContract {
940
1012
  * @return [slot, checkpointNumber, timeOfNextL1Slot] - If you can propose, the L2 slot number, checkpoint number and
941
1013
  * timestamp of the next L1 block
942
1014
  * @throws otherwise
943
- */ async canProposeAtNextEthBlock(archive, account, slotDuration, opts = {}) {
944
- const latestBlock = await this.client.getBlock();
945
- const timeOfNextL1Slot = latestBlock.timestamp + BigInt(slotDuration);
1015
+ */ async canProposeAt(archive, account, timestamp, stateOverride = []) {
1016
+ const timeOfNextL1Slot = timestamp;
946
1017
  const who = typeof account === 'string' ? account : account.address;
947
1018
  try {
948
1019
  const { result: [slot, checkpointNumber] } = await this.client.simulateContract({
@@ -955,7 +1026,7 @@ export class RollupContract {
955
1026
  who
956
1027
  ],
957
1028
  account,
958
- stateOverride: await this.makePendingCheckpointNumberOverride(opts.forcePendingCheckpointNumber)
1029
+ stateOverride
959
1030
  });
960
1031
  return {
961
1032
  slot: SlotNumber.fromBigInt(slot),
@@ -967,11 +1038,15 @@ export class RollupContract {
967
1038
  }
968
1039
  }
969
1040
  /**
970
- * Returns a state override that sets the pending checkpoint number to the specified value. Useful for simulations.
971
- * Requires querying the current state of the contract to get the current proven checkpoint number, as they are both
972
- * stored in the same slot. If the argument is undefined, it returns an empty override.
973
- */ async makePendingCheckpointNumberOverride(forcePendingCheckpointNumber) {
974
- if (forcePendingCheckpointNumber === undefined) {
1041
+ * Returns a state override that sets the pending and/or proven checkpoint numbers. Useful for simulations.
1042
+ * Both values share a single storage slot (pending in the upper 128 bits, proven in the lower 128 bits), so
1043
+ * a single combined override is emitted to avoid the second state-diff clobbering the first. The current live
1044
+ * value is read once to preserve any half not being overridden. Returns an empty override if neither is set.
1045
+ *
1046
+ * Throws if the resulting `proven > pending`, which would crash the simulation: `STFLib.canPruneAtTime` calls
1047
+ * `getEpochForCheckpoint(proven + 1)` whenever `pending != proven`, and that asserts `_n <= tips.pending`.
1048
+ */ async makeChainTipsOverride(override) {
1049
+ if (override.pending === undefined && override.proven === undefined) {
975
1050
  return [];
976
1051
  }
977
1052
  const slot = RollupContract.stfStorageSlot;
@@ -979,8 +1054,15 @@ export class RollupContract {
979
1054
  address: this.address,
980
1055
  slot
981
1056
  });
982
- const currentProvenCheckpointNumber = currentValue ? hexToBigInt(currentValue) & (1n << 128n) - 1n : 0n;
983
- const newValue = BigInt(forcePendingCheckpointNumber) << 128n | currentProvenCheckpointNumber;
1057
+ const currentRaw = currentValue ? hexToBigInt(currentValue) : 0n;
1058
+ const currentPending = currentRaw >> 128n;
1059
+ const currentProven = currentRaw & (1n << 128n) - 1n;
1060
+ const newPending = override.pending !== undefined ? BigInt(override.pending) : currentPending;
1061
+ const newProven = override.proven !== undefined ? BigInt(override.proven) : currentProven;
1062
+ if (newProven > newPending) {
1063
+ throw new Error(`Invalid chain tips override: proven (${newProven}) > pending (${newPending})`);
1064
+ }
1065
+ const newValue = newPending << 128n | newProven;
984
1066
  return [
985
1067
  {
986
1068
  address: this.address,
@@ -993,6 +1075,161 @@ export class RollupContract {
993
1075
  }
994
1076
  ];
995
1077
  }
1078
+ /**
1079
+ * Returns a state override that patches `tempCheckpointLogs[checkpointNumber]` with every field that
1080
+ * the L1 contract reads during `propose()` for the checkpoint that builds on top of it (proposer
1081
+ * pipelining simulation). Mirrors the writes done by `ProposeLib.addTempCheckpointLog`.
1082
+ *
1083
+ * `blobCommitmentsHash` and `attestationsHash` are intentionally not exposed here — the propose path
1084
+ * never asserts against them, so leaving them at storage zero is harmless.
1085
+ */ async makeTempCheckpointLogOverride(checkpointNumber, fields) {
1086
+ const constants = await this.getRollupConstants();
1087
+ const slotAt = (field)=>`0x${this.computeTempCheckpointLogStorageSlot(checkpointNumber, field, constants).toString(16).padStart(64, '0')}`;
1088
+ const word = (v)=>`0x${v.toString(16).padStart(64, '0')}`;
1089
+ const stateDiff = [];
1090
+ if (fields.headerHash) {
1091
+ stateDiff.push({
1092
+ slot: slotAt(0),
1093
+ value: fields.headerHash.toString()
1094
+ });
1095
+ }
1096
+ if (fields.outHash) {
1097
+ stateDiff.push({
1098
+ slot: slotAt(2),
1099
+ value: fields.outHash.toString()
1100
+ });
1101
+ }
1102
+ if (fields.payloadDigest) {
1103
+ stateDiff.push({
1104
+ slot: slotAt(4),
1105
+ value: fields.payloadDigest.toString()
1106
+ });
1107
+ }
1108
+ if (fields.slotNumber !== undefined) {
1109
+ // CompressedSlot is uint32 on L1 (SafeCast.toUint32 reverts on overflow). Match that behavior here
1110
+ // so a malformed override surfaces immediately rather than silently truncating into a wrong slot.
1111
+ const slotNumber = BigInt(fields.slotNumber);
1112
+ if (slotNumber < 0n || slotNumber > 0xffffffffn) {
1113
+ throw new Error(`slotNumber ${slotNumber} does not fit in uint32`);
1114
+ }
1115
+ stateDiff.push({
1116
+ slot: slotAt(5),
1117
+ value: word(slotNumber)
1118
+ });
1119
+ }
1120
+ if (fields.feeHeader) {
1121
+ stateDiff.push({
1122
+ slot: slotAt(6),
1123
+ value: word(RollupContract.compressFeeHeader(fields.feeHeader))
1124
+ });
1125
+ }
1126
+ if (stateDiff.length === 0) {
1127
+ return [];
1128
+ }
1129
+ return [
1130
+ {
1131
+ address: this.address,
1132
+ stateDiff
1133
+ }
1134
+ ];
1135
+ }
1136
+ /**
1137
+ * Returns a state override that sets archives[checkpointNumber] to the given archive value.
1138
+ * Used when simulating a canProposeAtTime call where the local archive differs from L1
1139
+ * (e.g. pipelining where the parent checkpoint hasn't landed on L1 yet).
1140
+ */ makeArchiveOverride(checkpointNumber, archive) {
1141
+ const archivesMappingBase = hexToBigInt(RollupContract.stfStorageSlot) + 1n;
1142
+ const archiveSlot = hexToBigInt(keccak256(encodeAbiParameters([
1143
+ {
1144
+ type: 'uint256'
1145
+ },
1146
+ {
1147
+ type: 'uint256'
1148
+ }
1149
+ ], [
1150
+ BigInt(checkpointNumber),
1151
+ archivesMappingBase
1152
+ ])));
1153
+ return [
1154
+ {
1155
+ address: this.address,
1156
+ stateDiff: [
1157
+ {
1158
+ slot: `0x${archiveSlot.toString(16).padStart(64, '0')}`,
1159
+ value: archive.toString()
1160
+ }
1161
+ ]
1162
+ }
1163
+ ];
1164
+ }
1165
+ /** Merges multiple StateOverride arrays, combining stateDiff entries for the same address. */ static mergeStateOverrides(...overrides) {
1166
+ const byAddress = new Map();
1167
+ for (const override of overrides){
1168
+ for (const entry of override){
1169
+ const key = entry.address.toLowerCase();
1170
+ const existing = byAddress.get(key);
1171
+ if (existing) {
1172
+ existing.stateDiff.push(...entry.stateDiff ?? []);
1173
+ if (entry.balance !== undefined) {
1174
+ existing.balance = entry.balance;
1175
+ }
1176
+ } else {
1177
+ byAddress.set(key, {
1178
+ address: entry.address,
1179
+ balance: entry.balance,
1180
+ stateDiff: [
1181
+ ...entry.stateDiff ?? []
1182
+ ]
1183
+ });
1184
+ }
1185
+ }
1186
+ }
1187
+ return [
1188
+ ...byAddress.values()
1189
+ ];
1190
+ }
1191
+ /** Compresses a FeeHeader into a uint256 matching FeeHeaderLib.compress() in FeeStructs.sol. */ static compressFeeHeader(feeHeader) {
1192
+ const MASK_48_BITS = (1n << 48n) - 1n;
1193
+ const MASK_64_BITS = (1n << 64n) - 1n;
1194
+ const MASK_63_BITS = (1n << 63n) - 1n;
1195
+ let value = BigInt(feeHeader.manaUsed) & (1n << 32n) - 1n; // bits [0:31]
1196
+ value |= (feeHeader.excessMana < MASK_48_BITS ? feeHeader.excessMana : MASK_48_BITS) << 32n; // bits [32:79]
1197
+ value |= (BigInt(feeHeader.ethPerFeeAsset) & MASK_48_BITS) << 80n; // bits [80:127]
1198
+ value |= (feeHeader.congestionCost < MASK_64_BITS ? feeHeader.congestionCost : MASK_64_BITS) << 128n; // bits [128:191]
1199
+ value |= (feeHeader.proverCost < MASK_63_BITS ? feeHeader.proverCost : MASK_63_BITS) << 192n; // bits [192:254]
1200
+ value |= 1n << 255n; // preheat flag
1201
+ return value;
1202
+ }
1203
+ /** Computes the fee header for a child checkpoint given parent fee header and child data.
1204
+ * Must stay in sync with Solidity FeeLib.sol (computeNewEthPerFeeAsset, clampedAdd). */ static computeChildFeeHeader(parentFeeHeader, childManaUsed, feeAssetPriceModifier, manaTarget) {
1205
+ const MIN_ETH_PER_FEE_ASSET = 100n;
1206
+ const MAX_ETH_PER_FEE_ASSET = 100_000_000_000_000n; // 1e14, matches FeeLib.sol
1207
+ // excessMana = clampedAdd(parent.excessMana + parent.manaUsed, -manaTarget)
1208
+ const sum = parentFeeHeader.excessMana + parentFeeHeader.manaUsed;
1209
+ const excessMana = sum > manaTarget ? sum - manaTarget : 0n;
1210
+ // ethPerFeeAsset = computeNewEthPerFeeAsset(max(parent.ethPerFeeAsset, MIN), modifier)
1211
+ const parentPrice = parentFeeHeader.ethPerFeeAsset > MIN_ETH_PER_FEE_ASSET ? parentFeeHeader.ethPerFeeAsset : MIN_ETH_PER_FEE_ASSET;
1212
+ let newPrice;
1213
+ if (feeAssetPriceModifier >= 0n) {
1214
+ newPrice = parentPrice * (10_000n + feeAssetPriceModifier) / 10_000n;
1215
+ } else {
1216
+ const absMod = -feeAssetPriceModifier;
1217
+ newPrice = parentPrice * (10_000n - absMod) / 10_000n;
1218
+ }
1219
+ if (newPrice < MIN_ETH_PER_FEE_ASSET) {
1220
+ newPrice = MIN_ETH_PER_FEE_ASSET;
1221
+ }
1222
+ if (newPrice > MAX_ETH_PER_FEE_ASSET) {
1223
+ newPrice = MAX_ETH_PER_FEE_ASSET;
1224
+ }
1225
+ return {
1226
+ excessMana,
1227
+ manaUsed: childManaUsed,
1228
+ ethPerFeeAsset: newPrice,
1229
+ congestionCost: 0n,
1230
+ proverCost: 0n
1231
+ };
1232
+ }
996
1233
  /** Creates a request to Rollup#invalidateBadAttestation to be simulated or sent */ buildInvalidateBadAttestationRequest(checkpointNumber, attestationsAndSigners, committee, invalidIndex) {
997
1234
  return {
998
1235
  to: this.address,
@@ -1034,11 +1271,25 @@ export class RollupContract {
1034
1271
  prover
1035
1272
  ]);
1036
1273
  }
1037
- getManaMinFeeAt(timestamp, inFeeAsset) {
1274
+ getManaMinFeeAt(timestamp, inFeeAsset, stateOverride) {
1038
1275
  return this.rollup.read.getManaMinFeeAt([
1039
1276
  timestamp,
1040
1277
  inFeeAsset
1278
+ ], {
1279
+ stateOverride
1280
+ });
1281
+ }
1282
+ async getManaMinFeeComponentsAt(timestamp, inFeeAsset) {
1283
+ const result = await this.rollup.read.getManaMinFeeComponentsAt([
1284
+ timestamp,
1285
+ inFeeAsset
1041
1286
  ]);
1287
+ return {
1288
+ sequencerCost: result.sequencerCost,
1289
+ proverCost: result.proverCost,
1290
+ congestionCost: result.congestionCost,
1291
+ congestionMultiplier: result.congestionMultiplier
1292
+ };
1042
1293
  }
1043
1294
  async getSlotAt(timestamp) {
1044
1295
  return SlotNumber.fromBigInt(await this.rollup.read.getSlotAt([
@@ -1089,15 +1340,24 @@ export class RollupContract {
1089
1340
  prover
1090
1341
  ]);
1091
1342
  }
1092
- async getAttesters() {
1093
- const attesterSize = await this.getActiveAttesterCount();
1343
+ async getAttesters(timestamp) {
1344
+ // Pin every read to a single L1 block so the attester count and the chunked index reads
1345
+ // observe a consistent set. Without this, the count and each chunk default to `latest` and
1346
+ // can straddle a block boundary (or reorg), yielding an inconsistent or truncated set.
1347
+ const block = await this.client.getBlock();
1348
+ const blockNumber = block.number ?? undefined;
1349
+ const ts = timestamp ?? block.timestamp;
1350
+ const attesterSize = await this.getActiveAttesterCount({
1351
+ blockNumber
1352
+ });
1094
1353
  const gse = new GSEContract(this.client, await this.getGSE());
1095
- const ts = (await this.client.getBlock()).timestamp;
1096
1354
  const indices = Array.from({
1097
1355
  length: attesterSize
1098
1356
  }, (_, i)=>BigInt(i));
1099
1357
  const chunks = chunk(indices, 1000);
1100
- const results = await Promise.all(chunks.map((chunk)=>gse.getAttestersFromIndicesAtTime(this.address, ts, chunk)));
1358
+ const results = await Promise.all(chunks.map((chunk)=>gse.getAttestersFromIndicesAtTime(this.address, ts, chunk, {
1359
+ blockNumber
1360
+ })));
1101
1361
  return results.flat().map((addr)=>EthAddress.fromString(addr));
1102
1362
  }
1103
1363
  async getAttesterView(address) {
@@ -1198,7 +1458,8 @@ export class RollupContract {
1198
1458
  const args = log.args;
1199
1459
  if (args.checkpointNumber !== undefined) {
1200
1460
  callback({
1201
- checkpointNumber: CheckpointNumber.fromBigInt(args.checkpointNumber)
1461
+ checkpointNumber: CheckpointNumber.fromBigInt(args.checkpointNumber),
1462
+ event: log
1202
1463
  });
1203
1464
  }
1204
1465
  }
@@ -1229,6 +1490,18 @@ export class RollupContract {
1229
1490
  }
1230
1491
  });
1231
1492
  }
1493
+ /**
1494
+ * Fetches OwnershipTransferred events emitted on the L1 block this rollup was deployed on.
1495
+ * The Rollup inherits from Ownable and emits this event in its constructor, so the event
1496
+ * is guaranteed to exist on `l1StartBlock` for any correctly deployed rollup. Used as a
1497
+ * probe to detect RPC nodes that prune historical logs.
1498
+ */ async getOwnershipTransferredEventsAtDeploy() {
1499
+ const l1StartBlock = await this.getL1StartBlock();
1500
+ return await this.rollup.getEvents.OwnershipTransferred({}, {
1501
+ fromBlock: l1StartBlock,
1502
+ toBlock: l1StartBlock
1503
+ });
1504
+ }
1232
1505
  /** Fetches CheckpointProposed events within the given block range. */ async getCheckpointProposedEvents(fromBlock, toBlock) {
1233
1506
  const logs = await this.rollup.getEvents.CheckpointProposed({}, {
1234
1507
  fromBlock,
@@ -1257,4 +1530,43 @@ export class RollupContract {
1257
1530
  }
1258
1531
  }));
1259
1532
  }
1533
+ /** Packs pending and proven checkpoint numbers into the chain tips storage format. */ static packChainTips(pendingCheckpointNumber, provenCheckpointNumber) {
1534
+ return pendingCheckpointNumber << 128n | provenCheckpointNumber & (1n << 128n) - 1n;
1535
+ }
1536
+ /** Storage slot for the chain tips (offset 0 within the STF storage struct). */ static get chainTipsStorageSlot() {
1537
+ return BigInt(RollupContract.stfStorageSlot);
1538
+ }
1539
+ /**
1540
+ * Computes the storage slot for a field within a tempCheckpointLog entry.
1541
+ * @param checkpointNumber - The checkpoint number
1542
+ * @param field - The field within the CompressedTempCheckpointLog struct
1543
+ */ async getTempCheckpointLogStorageSlot(checkpointNumber, field) {
1544
+ const [epochDuration, proofSubmissionEpochs] = await Promise.all([
1545
+ this.getEpochDuration(),
1546
+ this.getProofSubmissionEpochs()
1547
+ ]);
1548
+ return this.computeTempCheckpointLogStorageSlot(checkpointNumber, field, {
1549
+ epochDuration,
1550
+ proofSubmissionEpochs
1551
+ });
1552
+ }
1553
+ computeTempCheckpointLogStorageSlot(checkpointNumber, field, constants) {
1554
+ const fieldOffset = BigInt(field);
1555
+ const { epochDuration, proofSubmissionEpochs } = constants;
1556
+ const roundaboutSize = BigInt(epochDuration) * (BigInt(proofSubmissionEpochs) + 1n) + 1n;
1557
+ const tempCheckpointLogsBase = BigInt(RollupContract.stfStorageSlot) + 2n;
1558
+ const circularIndex = BigInt(checkpointNumber) % roundaboutSize;
1559
+ const entryBase = BigInt(keccak256(encodeAbiParameters([
1560
+ {
1561
+ type: 'uint256'
1562
+ },
1563
+ {
1564
+ type: 'uint256'
1565
+ }
1566
+ ], [
1567
+ circularIndex,
1568
+ tempCheckpointLogsBase
1569
+ ])));
1570
+ return entryBase + fieldOffset;
1571
+ }
1260
1572
  }