@aztec/epoch-cache 0.0.1-commit.5daedc8 → 0.0.1-commit.6201a7b05

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