@aztec/epoch-cache 0.0.1-commit.ee80a48 → 0.0.1-commit.f103f88

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aztec/epoch-cache",
3
- "version": "0.0.1-commit.ee80a48",
3
+ "version": "0.0.1-commit.f103f88",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./dest/index.js",
@@ -26,11 +26,10 @@
26
26
  "../package.common.json"
27
27
  ],
28
28
  "dependencies": {
29
- "@aztec/ethereum": "0.0.1-commit.ee80a48",
30
- "@aztec/foundation": "0.0.1-commit.ee80a48",
31
- "@aztec/l1-artifacts": "0.0.1-commit.ee80a48",
32
- "@aztec/stdlib": "0.0.1-commit.ee80a48",
33
- "@viem/anvil": "^0.0.10",
29
+ "@aztec/ethereum": "0.0.1-commit.f103f88",
30
+ "@aztec/foundation": "0.0.1-commit.f103f88",
31
+ "@aztec/l1-artifacts": "0.0.1-commit.f103f88",
32
+ "@aztec/stdlib": "0.0.1-commit.f103f88",
34
33
  "dotenv": "^16.0.3",
35
34
  "get-port": "^7.1.0",
36
35
  "jest-mock-extended": "^4.0.0",
package/src/config.ts CHANGED
@@ -1,11 +1,17 @@
1
1
  import { type L1ContractsConfig, getL1ContractsConfigEnvVars } from '@aztec/ethereum/config';
2
2
  import { type L1ReaderConfig, getL1ReaderConfigFromEnv } from '@aztec/ethereum/l1-reader';
3
+ import { type PipelineConfig, getPipelineConfigEnvVars } from '@aztec/stdlib/config';
3
4
 
4
5
  export type EpochCacheConfig = Pick<
5
- L1ReaderConfig & L1ContractsConfig,
6
- 'l1RpcUrls' | 'l1ChainId' | 'viemPollingIntervalMS' | 'ethereumSlotDuration'
6
+ L1ReaderConfig & L1ContractsConfig & PipelineConfig,
7
+ | 'l1RpcUrls'
8
+ | 'l1ChainId'
9
+ | 'viemPollingIntervalMS'
10
+ | 'ethereumSlotDuration'
11
+ | 'l1HttpTimeoutMS'
12
+ | 'enableProposerPipelining'
7
13
  >;
8
14
 
9
15
  export function getEpochCacheConfigEnvVars(): EpochCacheConfig {
10
- return { ...getL1ReaderConfigFromEnv(), ...getL1ContractsConfigEnvVars() };
16
+ return { ...getL1ReaderConfigFromEnv(), ...getL1ContractsConfigEnvVars(), ...getPipelineConfigEnvVars() };
11
17
  }
@@ -1,4 +1,5 @@
1
1
  import { createEthereumChain } from '@aztec/ethereum/chain';
2
+ import { makeL1HttpTransport } from '@aztec/ethereum/client';
2
3
  import { NoCommitteeError, RollupContract } from '@aztec/ethereum/contracts';
3
4
  import { EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
4
5
  import { EthAddress } from '@aztec/foundation/eth-address';
@@ -8,19 +9,25 @@ import {
8
9
  type L1RollupConstants,
9
10
  getEpochAtSlot,
10
11
  getEpochNumberAtTimestamp,
12
+ getNextL1SlotTimestamp,
13
+ getSlotAtNextL1Block,
11
14
  getSlotAtTimestamp,
12
15
  getSlotRangeForEpoch,
16
+ getStartTimestampForEpoch,
13
17
  getTimestampForSlot,
14
- getTimestampRangeForEpoch,
15
18
  } from '@aztec/stdlib/epoch-helpers';
16
19
 
17
- import { createPublicClient, encodeAbiParameters, fallback, http, keccak256 } from 'viem';
20
+ import { createPublicClient, encodeAbiParameters, keccak256 } from 'viem';
18
21
 
19
22
  import { type EpochCacheConfig, getEpochCacheConfigEnvVars } from './config.js';
20
23
 
24
+ /** When proposer pipelining is enabled, the proposer builds one slot ahead. */
25
+ export const PROPOSER_PIPELINING_SLOT_OFFSET = 1;
26
+
27
+ /** Flat return type for compound epoch/slot getters. */
21
28
  export type EpochAndSlot = {
22
- epoch: EpochNumber;
23
29
  slot: SlotNumber;
30
+ epoch: EpochNumber;
24
31
  ts: bigint;
25
32
  };
26
33
 
@@ -34,17 +41,45 @@ export type EpochCommitteeInfo = {
34
41
 
35
42
  export type SlotTag = 'now' | 'next' | SlotNumber;
36
43
 
44
+ /** Minimal L1 block info used for cache provenance. */
45
+ type L1BlockInfo = { number: bigint; hash: `0x${string}`; timestamp: bigint };
46
+
47
+ /** Resolved cache entry with L1 provenance metadata. */
48
+ type CachedEpochEntry = {
49
+ data: EpochCommitteeInfo;
50
+ /** L1 block number at which the committee data was originally queried. */
51
+ lastQueryL1BlockNumber: bigint;
52
+ /** L1 block hash at which the committee data was originally queried. Used to detect reorgs. */
53
+ lastQueryL1BlockHash: `0x${string}`;
54
+ /** Latest L1 block timestamp at the time of the most recent refresh (full fetch or lightweight check). */
55
+ lastRefreshL1Timestamp: bigint;
56
+ /** Whether the epoch's sampling data falls within finalized L1 history. */
57
+ finalized: boolean;
58
+ };
59
+
37
60
  export interface EpochCacheInterface {
38
61
  getCommittee(slot: SlotTag | undefined): Promise<EpochCommitteeInfo>;
62
+ getSlotNow(): SlotNumber;
63
+ getTargetSlot(): SlotNumber;
64
+ getEpochNow(): EpochNumber;
65
+ getTargetEpoch(): EpochNumber;
39
66
  getEpochAndSlotNow(): EpochAndSlot & { nowMs: bigint };
40
- getEpochAndSlotInNextL1Slot(): EpochAndSlot & { now: bigint };
67
+ getEpochAndSlotInNextL1Slot(): EpochAndSlot & { nowSeconds: bigint };
68
+ /** Returns epoch/slot info for the next L1 slot with pipeline offset applied. */
69
+ getTargetEpochAndSlotInNextL1Slot(): EpochAndSlot & { nowSeconds: bigint };
70
+ isProposerPipeliningEnabled(): boolean;
71
+ pipeliningOffset(): number;
72
+ isEscapeHatchOpen(epoch: EpochNumber): Promise<boolean>;
73
+ isEscapeHatchOpenAtSlot(slot: SlotTag): Promise<boolean>;
41
74
  getProposerIndexEncoding(epoch: EpochNumber, slot: SlotNumber, seed: bigint): `0x${string}`;
42
75
  computeProposerIndex(slot: SlotNumber, epoch: EpochNumber, seed: bigint, size: bigint): bigint;
43
76
  getCurrentAndNextSlot(): { currentSlot: SlotNumber; nextSlot: SlotNumber };
77
+ getTargetAndNextSlot(): { targetSlot: SlotNumber; nextSlot: SlotNumber };
44
78
  getProposerAttesterAddressInSlot(slot: SlotNumber): Promise<EthAddress | undefined>;
45
79
  getRegisteredValidators(): Promise<EthAddress[]>;
46
80
  isInCommittee(slot: SlotTag, validator: EthAddress): Promise<boolean>;
47
81
  filterInCommittee(slot: SlotTag, validators: EthAddress[]): Promise<EthAddress[]>;
82
+ getL1Constants(): L1RollupConstants;
48
83
  }
49
84
 
50
85
  /**
@@ -57,12 +92,18 @@ export interface EpochCacheInterface {
57
92
  * Note: This class is very dependent on the system clock being in sync.
58
93
  */
59
94
  export class EpochCache implements EpochCacheInterface {
95
+ /**
96
+ * Single map holding both resolved entries and in-flight promises.
97
+ * A `Promise` value means a fetch is in progress; concurrent callers await it.
98
+ */
60
99
  // eslint-disable-next-line aztec-custom/no-non-primitive-in-collections
61
- protected cache: Map<EpochNumber, EpochCommitteeInfo> = new Map();
100
+ protected cache: Map<EpochNumber, CachedEpochEntry | Promise<CachedEpochEntry>> = new Map();
62
101
  private allValidators: Set<string> = new Set();
63
102
  private lastValidatorRefresh = 0;
64
103
  private readonly log: Logger = createLogger('epoch-cache');
65
104
 
105
+ protected enableProposerPipelining: boolean;
106
+
66
107
  constructor(
67
108
  private rollup: RollupContract,
68
109
  private readonly l1constants: L1RollupConstants & {
@@ -70,10 +111,12 @@ export class EpochCache implements EpochCacheInterface {
70
111
  lagInEpochsForRandao: number;
71
112
  },
72
113
  private readonly dateProvider: DateProvider = new DateProvider(),
73
- protected readonly config = { cacheSize: 12, validatorRefreshIntervalSeconds: 60 },
114
+ protected readonly config = { cacheSize: 12, validatorRefreshIntervalSeconds: 60, enableProposerPipelining: false },
74
115
  ) {
116
+ this.enableProposerPipelining = this.config.enableProposerPipelining;
75
117
  this.log.debug(`Initialized EpochCache`, {
76
118
  l1constants,
119
+ enableProposerPipelining: this.enableProposerPipelining,
77
120
  });
78
121
  }
79
122
 
@@ -92,7 +135,7 @@ export class EpochCache implements EpochCacheInterface {
92
135
  const chain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
93
136
  const publicClient = createPublicClient({
94
137
  chain: chain.chainInfo,
95
- transport: fallback(config.l1RpcUrls.map(url => http(url, { batch: false }))),
138
+ transport: makeL1HttpTransport(config.l1RpcUrls, { timeout: config.l1HttpTimeoutMS }),
96
139
  pollingInterval: config.viemPollingIntervalMS,
97
140
  });
98
141
  rollup = new RollupContract(publicClient, rollupOrAddress.toString());
@@ -106,6 +149,8 @@ export class EpochCache implements EpochCacheInterface {
106
149
  epochDuration,
107
150
  lagInEpochsForValidatorSet,
108
151
  lagInEpochsForRandao,
152
+ targetCommitteeSize,
153
+ rollupManaLimit,
109
154
  ] = await Promise.all([
110
155
  rollup.getL1StartBlock(),
111
156
  rollup.getL1GenesisTime(),
@@ -114,6 +159,8 @@ export class EpochCache implements EpochCacheInterface {
114
159
  rollup.getEpochDuration(),
115
160
  rollup.getLagInEpochsForValidatorSet(),
116
161
  rollup.getLagInEpochsForRandao(),
162
+ rollup.getTargetCommitteeSize(),
163
+ rollup.getManaLimit(),
117
164
  ] as const);
118
165
 
119
166
  const l1RollupConstants = {
@@ -125,43 +172,81 @@ export class EpochCache implements EpochCacheInterface {
125
172
  ethereumSlotDuration: config.ethereumSlotDuration,
126
173
  lagInEpochsForValidatorSet: Number(lagInEpochsForValidatorSet),
127
174
  lagInEpochsForRandao: Number(lagInEpochsForRandao),
175
+ targetCommitteeSize: Number(targetCommitteeSize),
176
+ rollupManaLimit: Number(rollupManaLimit),
128
177
  };
129
178
 
130
- return new EpochCache(rollup, l1RollupConstants, deps.dateProvider);
179
+ return new EpochCache(rollup, l1RollupConstants, deps.dateProvider, {
180
+ cacheSize: 12,
181
+ validatorRefreshIntervalSeconds: 60,
182
+ enableProposerPipelining: config.enableProposerPipelining,
183
+ });
131
184
  }
132
185
 
133
186
  public getL1Constants(): L1RollupConstants {
134
187
  return this.l1constants;
135
188
  }
136
189
 
190
+ public isProposerPipeliningEnabled(): boolean {
191
+ return this.enableProposerPipelining;
192
+ }
193
+
194
+ public pipeliningOffset(): number {
195
+ return this.enableProposerPipelining ? PROPOSER_PIPELINING_SLOT_OFFSET : 0;
196
+ }
197
+
198
+ public getSlotNow(): SlotNumber {
199
+ return this.getEpochAndSlotNow().slot;
200
+ }
201
+
202
+ public getTargetSlot(): SlotNumber {
203
+ const slotNow = this.getSlotNow();
204
+ const offset = this.isProposerPipeliningEnabled() ? PROPOSER_PIPELINING_SLOT_OFFSET : 0;
205
+ return SlotNumber(slotNow + offset);
206
+ }
207
+
208
+ public getEpochNow(): EpochNumber {
209
+ return this.getEpochAndSlotNow().epoch;
210
+ }
211
+
212
+ public getTargetEpoch(): EpochNumber {
213
+ return getEpochAtSlot(this.getTargetSlot(), this.l1constants);
214
+ }
215
+
137
216
  public getEpochAndSlotNow(): EpochAndSlot & { nowMs: bigint } {
138
217
  const nowMs = BigInt(this.dateProvider.now());
139
218
  const nowSeconds = nowMs / 1000n;
140
219
  return { ...this.getEpochAndSlotAtTimestamp(nowSeconds), nowMs };
141
220
  }
142
221
 
143
- public nowInSeconds(): bigint {
144
- return BigInt(Math.floor(this.dateProvider.now() / 1000));
222
+ private getEpochAndSlotAtSlot(slot: SlotNumber): EpochAndSlot {
223
+ return this.getEpochAndSlotAtTimestamp(getTimestampForSlot(slot, this.l1constants));
145
224
  }
146
225
 
147
- private getEpochAndSlotAtSlot(slot: SlotNumber): EpochAndSlot {
148
- const epoch = getEpochAtSlot(slot, this.l1constants);
149
- const ts = getTimestampRangeForEpoch(epoch, this.l1constants)[0];
150
- return { epoch, ts, slot };
226
+ public getEpochAndSlotInNextL1Slot(): EpochAndSlot & { nowSeconds: bigint } {
227
+ const nowSeconds = this.dateProvider.nowInSeconds();
228
+ const nextSlotTs = getNextL1SlotTimestamp(nowSeconds, this.l1constants);
229
+ return { ...this.getEpochAndSlotAtTimestamp(nextSlotTs), nowSeconds: BigInt(nowSeconds) };
151
230
  }
152
231
 
153
- public getEpochAndSlotInNextL1Slot(): EpochAndSlot & { now: bigint } {
154
- const now = this.nowInSeconds();
155
- const nextSlotTs = now + BigInt(this.l1constants.ethereumSlotDuration);
156
- return { ...this.getEpochAndSlotAtTimestamp(nextSlotTs), now };
232
+ public getTargetEpochAndSlotInNextL1Slot(): EpochAndSlot & { nowSeconds: bigint } {
233
+ if (!this.isProposerPipeliningEnabled()) {
234
+ return this.getEpochAndSlotInNextL1Slot();
235
+ }
236
+
237
+ const result = this.getEpochAndSlotInNextL1Slot();
238
+ const offset = PROPOSER_PIPELINING_SLOT_OFFSET;
239
+ const targetSlot = SlotNumber(result.slot + offset);
240
+ return { ...result, slot: targetSlot, epoch: getEpochAtSlot(targetSlot, this.l1constants) };
157
241
  }
158
242
 
159
243
  private getEpochAndSlotAtTimestamp(ts: bigint): EpochAndSlot {
160
244
  const slot = getSlotAtTimestamp(ts, this.l1constants);
245
+ const epoch = getEpochNumberAtTimestamp(ts, this.l1constants);
161
246
  return {
162
- epoch: getEpochNumberAtTimestamp(ts, this.l1constants),
163
- ts: getTimestampForSlot(slot, this.l1constants),
164
247
  slot,
248
+ epoch,
249
+ ts: getTimestampForSlot(slot, this.l1constants),
165
250
  };
166
251
  }
167
252
 
@@ -170,17 +255,8 @@ export class EpochCache implements EpochCacheInterface {
170
255
  return this.getCommittee(startSlot);
171
256
  }
172
257
 
173
- /**
174
- * Returns whether the escape hatch is open for the given epoch.
175
- *
176
- * Uses the already-cached EpochCommitteeInfo when available. If not cached, it will fetch
177
- * the epoch committee info (which includes the escape hatch flag) and return it.
178
- */
258
+ /** Returns whether the escape hatch is open for the given epoch. */
179
259
  public async isEscapeHatchOpen(epoch: EpochNumber): Promise<boolean> {
180
- const cached = this.cache.get(epoch);
181
- if (cached) {
182
- return cached.isEscapeHatchOpen;
183
- }
184
260
  const info = await this.getCommitteeForEpoch(epoch);
185
261
  return info.isEscapeHatchOpen;
186
262
  }
@@ -194,7 +270,7 @@ export class EpochCache implements EpochCacheInterface {
194
270
  public async isEscapeHatchOpenAtSlot(slot: SlotTag = 'now'): Promise<boolean> {
195
271
  const epoch =
196
272
  slot === 'now'
197
- ? this.getEpochAndSlotNow().epoch
273
+ ? this.getEpochNow()
198
274
  : slot === 'next'
199
275
  ? this.getEpochAndSlotInNextL1Slot().epoch
200
276
  : getEpochAtSlot(slot, this.l1constants);
@@ -203,33 +279,52 @@ export class EpochCache implements EpochCacheInterface {
203
279
  }
204
280
 
205
281
  /**
206
- * Get the current validator set
207
- * @param nextSlot - If true, get the validator set for the next slot.
208
- * @returns The current validator set.
282
+ * Get the current validator set.
283
+ *
284
+ * Returns cached data if the entry is finalized or still fresh (queried less than one
285
+ * Ethereum slot ago). Stale non-finalized entries are re-queried, and concurrent callers
286
+ * coalesce on the same in-flight promise so the L1 query happens only once.
209
287
  */
210
288
  public async getCommittee(slot: SlotTag = 'now'): Promise<EpochCommitteeInfo> {
211
289
  const { epoch, ts } = this.getEpochAndTimestamp(slot);
212
290
 
213
- if (this.cache.has(epoch)) {
214
- return this.cache.get(epoch)!;
291
+ const cached = this.cache.get(epoch);
292
+
293
+ // In-flight promise: another caller is already fetching this epoch — just await it.
294
+ if (cached instanceof Promise) {
295
+ return (await cached).data;
215
296
  }
216
297
 
217
- const epochData = await this.computeCommittee({ epoch, ts });
218
- // If the committee size is 0 or undefined, then do not cache
219
- if (!epochData.committee || epochData.committee.length === 0) {
220
- return epochData;
298
+ // Resolved entry: return it if finalized or still fresh.
299
+ if (cached && (cached.finalized || !this.isStale(cached))) {
300
+ return cached.data;
221
301
  }
222
- this.cache.set(epoch, epochData);
223
302
 
224
- const toPurge = Array.from(this.cache.keys())
225
- .sort((a, b) => Number(b - a))
226
- .slice(this.config.cacheSize);
227
- toPurge.forEach(key => this.cache.delete(key));
303
+ // Stale non-finalized entry: do a lightweight refresh first (check block hash + finalized ts).
304
+ // Only fall back to a full re-fetch if the L1 block was reorged.
305
+ if (cached) {
306
+ const promise = this.refreshStaleEntry(cached, epoch, ts);
307
+ this.cache.set(epoch, promise);
308
+ try {
309
+ return (await promise).data;
310
+ } catch (err) {
311
+ this.cache.set(epoch, cached);
312
+ throw err;
313
+ }
314
+ }
228
315
 
229
- return epochData;
316
+ // No entry at all: full fetch.
317
+ const promise = this.fetchAndCache(epoch, ts);
318
+ this.cache.set(epoch, promise);
319
+ try {
320
+ return (await promise).data;
321
+ } catch (err) {
322
+ this.cache.delete(epoch);
323
+ throw err;
324
+ }
230
325
  }
231
326
 
232
- private getEpochAndTimestamp(slot: SlotTag = 'now') {
327
+ private getEpochAndTimestamp(slot: SlotTag = 'now'): { epoch: EpochNumber; ts: bigint } {
233
328
  if (slot === 'now') {
234
329
  return this.getEpochAndSlotNow();
235
330
  } else if (slot === 'next') {
@@ -239,22 +334,137 @@ export class EpochCache implements EpochCacheInterface {
239
334
  }
240
335
  }
241
336
 
242
- private async computeCommittee(when: { epoch: EpochNumber; ts: bigint }): Promise<EpochCommitteeInfo> {
243
- const { ts, epoch } = when;
244
- const [committee, seedBuffer, l1Timestamp, isEscapeHatchOpen] = await Promise.all([
337
+ /** Evicts oldest cache entries (resolved or in-flight) beyond cacheSize. */
338
+ private purgeCache(): void {
339
+ if (this.cache.size <= this.config.cacheSize) {
340
+ return;
341
+ }
342
+ const toPurge = Array.from(this.cache.keys())
343
+ .sort((a, b) => Number(b - a))
344
+ .slice(this.config.cacheSize);
345
+ toPurge.forEach(key => this.cache.delete(key));
346
+ }
347
+
348
+ /** Returns true if a non-finalized cache entry is older than one Ethereum slot. */
349
+ private isStale(entry: CachedEpochEntry): boolean {
350
+ const nowSeconds = BigInt(this.dateProvider.nowInSeconds());
351
+ return nowSeconds - entry.lastRefreshL1Timestamp >= BigInt(this.l1constants.ethereumSlotDuration);
352
+ }
353
+
354
+ /** Whether a cached epoch entry has been marked as finalized. Returns undefined if not cached or still in-flight. */
355
+ public isFinalized(epoch: EpochNumber): boolean | undefined {
356
+ const entry = this.cache.get(epoch);
357
+ if (!entry || entry instanceof Promise) {
358
+ return undefined;
359
+ }
360
+ return entry.finalized;
361
+ }
362
+
363
+ /** Returns the latest L1 timestamp stored in the cached entry. Undefined if not cached or in-flight. */
364
+ public getCachedLastRefreshL1Timestamp(epoch: EpochNumber): bigint | undefined {
365
+ const entry = this.cache.get(epoch);
366
+ if (!entry || entry instanceof Promise) {
367
+ return undefined;
368
+ }
369
+ return entry.lastRefreshL1Timestamp;
370
+ }
371
+
372
+ /** Computes the sampling timestamp for an epoch's committee data. */
373
+ private getSamplingTimestamp(epoch: EpochNumber): bigint {
374
+ const { lagInEpochsForRandao, epochDuration, slotDuration } = this.l1constants;
375
+ const epochStartTs = getStartTimestampForEpoch(epoch, this.l1constants);
376
+ return epochStartTs - BigInt(lagInEpochsForRandao) * BigInt(epochDuration) * BigInt(slotDuration);
377
+ }
378
+
379
+ /**
380
+ * Lightweight refresh for a stale non-finalized entry. Queries only the block hash at
381
+ * the original block number and the finalized block timestamp — avoids the expensive
382
+ * getCommitteeAt and getSampleSeedAt calls on the rollup contract.
383
+ *
384
+ * If the block hash still matches (no L1 reorg), we keep the existing data and just
385
+ * update the provenance timestamp. If the finalized block has caught up, we promote the
386
+ * entry to finalized. If there was a reorg (hash mismatch), we fall back to a full fetch.
387
+ */
388
+ private async refreshStaleEntry(stale: CachedEpochEntry, epoch: EpochNumber, ts: bigint): Promise<CachedEpochEntry> {
389
+ const [blockAtOriginal, l1FinalizedBlock, latestBlock] = await Promise.all([
390
+ this.rollup.client.getBlock({ blockNumber: stale.lastQueryL1BlockNumber, includeTransactions: false }),
391
+ this.rollup.client.getBlock({ blockTag: 'finalized', includeTransactions: false }),
392
+ this.rollup.client.getBlock({ includeTransactions: false }),
393
+ ]);
394
+
395
+ if (blockAtOriginal.hash === stale.lastQueryL1BlockHash) {
396
+ // No reorg: the data is still valid. Check if we can now mark it as finalized.
397
+ const samplingTs = this.getSamplingTimestamp(epoch);
398
+ const finalized =
399
+ !!(stale.data.committee && stale.data.committee.length > 0) && samplingTs <= l1FinalizedBlock.timestamp;
400
+
401
+ const refreshed: CachedEpochEntry = {
402
+ ...stale,
403
+ lastRefreshL1Timestamp: latestBlock.timestamp,
404
+ finalized,
405
+ };
406
+ this.cache.set(epoch, refreshed);
407
+ return refreshed;
408
+ }
409
+
410
+ // Reorg detected: block hash mismatch. Do a full re-fetch.
411
+ // Pass the already-fetched block timestamps to avoid redundant queries.
412
+ this.log.warn(`L1 reorg detected for epoch ${epoch}: block ${stale.lastQueryL1BlockNumber} hash changed`, {
413
+ epoch,
414
+ expectedHash: stale.lastQueryL1BlockHash,
415
+ actualHash: blockAtOriginal.hash,
416
+ });
417
+ return this.fetchAndCache(epoch, ts, { latestBlock, finalizedBlock: l1FinalizedBlock });
418
+ }
419
+
420
+ /**
421
+ * Fetches committee data from L1, determines finalization status, and stores in the cache.
422
+ *
423
+ * Uses `lagInEpochsForRandao` (the binding constraint, always <= lagInEpochsForValidatorSet)
424
+ * and computes the sampling timestamp from the epoch start to match the L1 contract's logic.
425
+ *
426
+ * When called from refreshStaleEntry after a reorg, the latest and finalized blocks are
427
+ * passed in to avoid redundant L1 queries.
428
+ */
429
+ private async fetchAndCache(
430
+ epoch: EpochNumber,
431
+ ts: bigint,
432
+ prefetched?: { latestBlock: L1BlockInfo; finalizedBlock: { timestamp: bigint } },
433
+ ): Promise<CachedEpochEntry> {
434
+ const [committee, seedBuffer, latestBlock, finalizedBlock, isEscapeHatchOpen] = await Promise.all([
245
435
  this.rollup.getCommitteeAt(ts),
246
436
  this.rollup.getSampleSeedAt(ts),
247
- this.rollup.client.getBlock({ includeTransactions: false }).then(b => b.timestamp),
437
+ prefetched?.latestBlock ?? this.rollup.client.getBlock({ includeTransactions: false }),
438
+ prefetched?.finalizedBlock ?? this.rollup.client.getBlock({ blockTag: 'finalized', includeTransactions: false }),
248
439
  this.rollup.isEscapeHatchOpen(epoch),
249
440
  ]);
250
- const { lagInEpochsForValidatorSet, epochDuration, slotDuration } = this.l1constants;
251
- const sub = BigInt(lagInEpochsForValidatorSet) * BigInt(epochDuration) * BigInt(slotDuration);
252
- if (ts - sub > l1Timestamp) {
441
+
442
+ const samplingTs = this.getSamplingTimestamp(epoch);
443
+
444
+ if (samplingTs > latestBlock.timestamp) {
253
445
  throw new Error(
254
- `Cannot query committee for future epoch ${epoch} with timestamp ${ts} (current L1 time is ${l1Timestamp}). Check your Ethereum node is synced.`,
446
+ `Cannot query committee for future epoch ${epoch}: ` +
447
+ `sampling timestamp ${samplingTs} is beyond latest L1 block at ${latestBlock.timestamp}. ` +
448
+ `Check your Ethereum node is synced.`,
255
449
  );
256
450
  }
257
- return { committee, seed: seedBuffer.toBigInt(), epoch, isEscapeHatchOpen };
451
+
452
+ // Empty committees are never marked finalized so they always get re-queried after TTL.
453
+ const hasCommittee = !!(committee && committee.length > 0);
454
+ const finalized = hasCommittee && samplingTs <= finalizedBlock.timestamp;
455
+ const data: EpochCommitteeInfo = { committee, seed: seedBuffer.toBigInt(), epoch, isEscapeHatchOpen };
456
+ const entry: CachedEpochEntry = {
457
+ data,
458
+ lastQueryL1BlockNumber: latestBlock.number!,
459
+ lastQueryL1BlockHash: latestBlock.hash!,
460
+ lastRefreshL1Timestamp: latestBlock.timestamp,
461
+ finalized,
462
+ };
463
+
464
+ this.cache.set(epoch, entry);
465
+ this.purgeCache();
466
+
467
+ return entry;
258
468
  }
259
469
 
260
470
  /**
@@ -279,17 +489,31 @@ export class EpochCache implements EpochCacheInterface {
279
489
  return BigInt(keccak256(this.getProposerIndexEncoding(epoch, slot, seed))) % size;
280
490
  }
281
491
 
282
- /** Returns the current and next L2 slot numbers. */
492
+ /** Returns the current and next L2 slot in next eth L1 Slot. */
283
493
  public getCurrentAndNextSlot(): { currentSlot: SlotNumber; nextSlot: SlotNumber } {
284
- const current = this.getEpochAndSlotNow();
494
+ const currentSlot = this.getSlotNow();
285
495
  const next = this.getEpochAndSlotInNextL1Slot();
286
496
 
287
497
  return {
288
- currentSlot: current.slot,
498
+ currentSlot,
289
499
  nextSlot: next.slot,
290
500
  };
291
501
  }
292
502
 
503
+ /** Returns the target and next L2 slot in the next L1 slot. */
504
+ public getTargetAndNextSlot(): { targetSlot: SlotNumber; nextSlot: SlotNumber } {
505
+ const nowSeconds = BigInt(this.dateProvider.nowInSeconds());
506
+ const offset = this.isProposerPipeliningEnabled() ? PROPOSER_PIPELINING_SLOT_OFFSET : 0;
507
+
508
+ const currentSlot = getSlotAtTimestamp(nowSeconds, this.l1constants);
509
+ const targetSlot = SlotNumber(currentSlot + offset);
510
+
511
+ const nextL2SlotOnL1 = getSlotAtNextL1Block(nowSeconds, this.l1constants);
512
+ const nextSlot = SlotNumber(nextL2SlotOnL1 + offset);
513
+
514
+ return { targetSlot, nextSlot };
515
+ }
516
+
293
517
  /**
294
518
  * Get the proposer attester address in the given L2 slot
295
519
  * @returns The proposer attester address. If the committee does not exist, we throw a NoCommitteeError.
@@ -368,10 +592,11 @@ export class EpochCache implements EpochCacheInterface {
368
592
  async getRegisteredValidators(): Promise<EthAddress[]> {
369
593
  const validatorRefreshIntervalMs = this.config.validatorRefreshIntervalSeconds * 1000;
370
594
  const validatorRefreshTime = this.lastValidatorRefresh + validatorRefreshIntervalMs;
371
- if (validatorRefreshTime < this.dateProvider.now()) {
372
- const currentSet = await this.rollup.getAttesters();
595
+ const now = this.dateProvider.now();
596
+ if (validatorRefreshTime < now) {
597
+ const currentSet = await this.rollup.getAttesters(BigInt(Math.floor(now / 1000)));
373
598
  this.allValidators = new Set(currentSet.map(v => v.toString()));
374
- this.lastValidatorRefresh = this.dateProvider.now();
599
+ this.lastValidatorRefresh = now;
375
600
  }
376
601
  return Array.from(this.allValidators.keys()).map(v => EthAddress.fromString(v));
377
602
  }