@aztec/ethereum 0.0.1-commit.3fd054f6 → 0.0.1-commit.431c48d

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 (144) hide show
  1. package/dest/client.d.ts +19 -3
  2. package/dest/client.d.ts.map +1 -1
  3. package/dest/client.js +52 -3
  4. package/dest/config.d.ts +15 -6
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +29 -9
  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 +135 -35
  16. package/dest/contracts/governance.d.ts.map +1 -1
  17. package/dest/contracts/governance.js +226 -15
  18. package/dest/contracts/governance_proposer.d.ts +33 -4
  19. package/dest/contracts/governance_proposer.d.ts.map +1 -1
  20. package/dest/contracts/governance_proposer.js +52 -13
  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 +79 -13
  31. package/dest/contracts/multicall.d.ts.map +1 -1
  32. package/dest/contracts/multicall.js +117 -95
  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 +5418 -28
  37. package/dest/contracts/rollup.d.ts.map +1 -1
  38. package/dest/contracts/rollup.js +389 -95
  39. package/dest/contracts/slashing_proposer.d.ts +171 -0
  40. package/dest/contracts/slashing_proposer.d.ts.map +1 -0
  41. package/dest/contracts/slashing_proposer.js +753 -0
  42. package/dest/contracts/watch_event.d.ts +36 -0
  43. package/dest/contracts/watch_event.d.ts.map +1 -0
  44. package/dest/contracts/watch_event.js +66 -0
  45. package/dest/deploy_aztec_l1_contracts.d.ts +4 -7
  46. package/dest/deploy_aztec_l1_contracts.d.ts.map +1 -1
  47. package/dest/deploy_aztec_l1_contracts.js +15 -8
  48. package/dest/foundry_binary.d.ts +13 -0
  49. package/dest/foundry_binary.d.ts.map +1 -0
  50. package/dest/foundry_binary.js +52 -0
  51. package/dest/generated/l1-contracts-defaults.d.ts +2 -2
  52. package/dest/generated/l1-contracts-defaults.js +2 -2
  53. package/dest/l1_artifacts.d.ts +14941 -16273
  54. package/dest/l1_artifacts.d.ts.map +1 -1
  55. package/dest/l1_artifacts.js +9 -24
  56. package/dest/l1_contract_addresses.d.ts +61 -65
  57. package/dest/l1_contract_addresses.d.ts.map +1 -1
  58. package/dest/l1_contract_addresses.js +101 -82
  59. package/dest/l1_reader.d.ts +3 -5
  60. package/dest/l1_reader.d.ts.map +1 -1
  61. package/dest/l1_reader.js +3 -6
  62. package/dest/l1_tx_utils/config.js +3 -3
  63. package/dest/l1_tx_utils/l1_tx_utils.d.ts +9 -1
  64. package/dest/l1_tx_utils/l1_tx_utils.d.ts.map +1 -1
  65. package/dest/l1_tx_utils/l1_tx_utils.js +115 -54
  66. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts +1 -1
  67. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts.map +1 -1
  68. package/dest/l1_tx_utils/readonly_l1_tx_utils.js +49 -19
  69. package/dest/l1_tx_utils/tx_delayer.d.ts +5 -3
  70. package/dest/l1_tx_utils/tx_delayer.d.ts.map +1 -1
  71. package/dest/l1_tx_utils/tx_delayer.js +7 -5
  72. package/dest/publisher_manager.d.ts +18 -6
  73. package/dest/publisher_manager.d.ts.map +1 -1
  74. package/dest/publisher_manager.js +44 -7
  75. package/dest/queries.d.ts +13 -2
  76. package/dest/queries.d.ts.map +1 -1
  77. package/dest/queries.js +62 -3
  78. package/dest/test/blob_kzg_warmup.d.ts +19 -0
  79. package/dest/test/blob_kzg_warmup.d.ts.map +1 -0
  80. package/dest/test/blob_kzg_warmup.js +64 -0
  81. package/dest/test/chain_monitor.d.ts +34 -2
  82. package/dest/test/chain_monitor.d.ts.map +1 -1
  83. package/dest/test/chain_monitor.js +76 -6
  84. package/dest/test/eth_cheat_codes.d.ts +26 -3
  85. package/dest/test/eth_cheat_codes.d.ts.map +1 -1
  86. package/dest/test/eth_cheat_codes.js +61 -40
  87. package/dest/test/index.d.ts +2 -1
  88. package/dest/test/index.d.ts.map +1 -1
  89. package/dest/test/index.js +1 -0
  90. package/dest/test/recording_rpc_server.d.ts +18 -0
  91. package/dest/test/recording_rpc_server.d.ts.map +1 -0
  92. package/dest/test/recording_rpc_server.js +68 -0
  93. package/dest/test/rollup_cheat_codes.d.ts +60 -3
  94. package/dest/test/rollup_cheat_codes.d.ts.map +1 -1
  95. package/dest/test/rollup_cheat_codes.js +86 -7
  96. package/dest/test/start_anvil.d.ts +1 -1
  97. package/dest/test/start_anvil.d.ts.map +1 -1
  98. package/dest/test/start_anvil.js +41 -5
  99. package/dest/utils.d.ts +9 -2
  100. package/dest/utils.d.ts.map +1 -1
  101. package/dest/utils.js +45 -14
  102. package/package.json +6 -6
  103. package/src/client.ts +63 -1
  104. package/src/config.ts +44 -13
  105. package/src/contracts/chain_state_override.ts +200 -0
  106. package/src/contracts/empire_base.ts +0 -2
  107. package/src/contracts/fee_asset_price_oracle.ts +10 -5
  108. package/src/contracts/governance.ts +310 -10
  109. package/src/contracts/governance_proposer.ts +56 -13
  110. package/src/contracts/gse.ts +7 -2
  111. package/src/contracts/inbox.ts +13 -5
  112. package/src/contracts/index.ts +2 -2
  113. package/src/contracts/multicall.ts +179 -105
  114. package/src/contracts/outbox.ts +42 -8
  115. package/src/contracts/rollup.ts +429 -86
  116. package/src/contracts/{tally_slashing_proposer.ts → slashing_proposer.ts} +119 -45
  117. package/src/contracts/watch_event.ts +110 -0
  118. package/src/deploy_aztec_l1_contracts.ts +19 -10
  119. package/src/foundry_binary.ts +57 -0
  120. package/src/generated/l1-contracts-defaults.ts +2 -2
  121. package/src/l1_artifacts.ts +12 -35
  122. package/src/l1_contract_addresses.ts +120 -94
  123. package/src/l1_reader.ts +4 -9
  124. package/src/l1_tx_utils/config.ts +3 -3
  125. package/src/l1_tx_utils/l1_tx_utils.ts +107 -50
  126. package/src/l1_tx_utils/readonly_l1_tx_utils.ts +49 -13
  127. package/src/l1_tx_utils/tx_delayer.ts +16 -7
  128. package/src/publisher_manager.ts +54 -18
  129. package/src/queries.ts +70 -4
  130. package/src/test/blob_kzg_warmup.ts +65 -0
  131. package/src/test/chain_monitor.ts +93 -5
  132. package/src/test/eth_cheat_codes.ts +57 -43
  133. package/src/test/index.ts +1 -0
  134. package/src/test/recording_rpc_server.ts +69 -0
  135. package/src/test/rollup_cheat_codes.ts +115 -6
  136. package/src/test/start_anvil.ts +38 -6
  137. package/src/utils.ts +41 -17
  138. package/dest/contracts/empire_slashing_proposer.d.ts +0 -69
  139. package/dest/contracts/empire_slashing_proposer.d.ts.map +0 -1
  140. package/dest/contracts/empire_slashing_proposer.js +0 -216
  141. package/dest/contracts/tally_slashing_proposer.d.ts +0 -140
  142. package/dest/contracts/tally_slashing_proposer.d.ts.map +0 -1
  143. package/dest/contracts/tally_slashing_proposer.js +0 -320
  144. package/src/contracts/empire_slashing_proposer.ts +0 -265
@@ -4,6 +4,7 @@ import type { ViemPublicClient } from '@aztec/ethereum/types';
4
4
  import { CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
5
5
  import { EthAddress } from '@aztec/foundation/eth-address';
6
6
  import { createLogger } from '@aztec/foundation/log';
7
+ import { retryUntil } from '@aztec/foundation/retry';
7
8
  import type { DateProvider } from '@aztec/foundation/timer';
8
9
  import { RollupAbi } from '@aztec/l1-artifacts/RollupAbi';
9
10
 
@@ -15,6 +16,7 @@ import {
15
16
  getContract,
16
17
  hexToBigInt,
17
18
  http,
19
+ keccak256,
18
20
  } from 'viem';
19
21
 
20
22
  import { EthCheatCodes } from './eth_cheat_codes.js';
@@ -53,7 +55,17 @@ export class RollupCheatCodes {
53
55
  /** Returns the current slot */
54
56
  public async getSlot(): Promise<SlotNumber> {
55
57
  const ts = BigInt((await this.client.getBlock()).timestamp);
56
- return SlotNumber.fromBigInt(await this.rollup.read.getSlotAt([ts]));
58
+ return this.getSlotAt(ts);
59
+ }
60
+
61
+ /** Returns the slot number at a given timestamp. */
62
+ public async getSlotAt(timestamp: bigint): Promise<SlotNumber> {
63
+ return SlotNumber.fromBigInt(await this.rollup.read.getSlotAt([timestamp]));
64
+ }
65
+
66
+ /** Returns the timestamp for the start of a given slot. */
67
+ public async getTimestampForSlot(slot: SlotNumber): Promise<bigint> {
68
+ return await this.rollup.read.getTimestampForSlot([BigInt(slot)]);
57
69
  }
58
70
 
59
71
  /** Returns the number of seconds until the start of the given slot based on L1 block timestamp. */
@@ -168,6 +180,21 @@ export class RollupCheatCodes {
168
180
  return [timestamp, nextSlot];
169
181
  }
170
182
 
183
+ /**
184
+ * Warps L1 time to the start of an explicit absolute slot. Unlike `advanceSlots(N)` which is
185
+ * relative to the current L1 timestamp at call time and therefore races with real-time
186
+ * progression between query and warp, this lands at the slot regardless of latency.
187
+ *
188
+ * Throws if the requested slot is in the past relative to current L1 time (anvil cannot
189
+ * rewind).
190
+ */
191
+ public async advanceToSlot(slot: SlotNumber) {
192
+ const timestamp = await this.rollup.read.getTimestampForSlot([BigInt(slot)]);
193
+ await this.ethCheatCodes.warp(Number(timestamp), { silent: true, resetBlockInterval: true });
194
+ this.logger.warn(`Advanced to slot ${slot}`, { timestamp });
195
+ return timestamp;
196
+ }
197
+
171
198
  /**
172
199
  * Warps time in L1 equivalent to however many slots.
173
200
  * @param howMany - The number of slots to advance.
@@ -218,6 +245,56 @@ export class RollupCheatCodes {
218
245
  });
219
246
  }
220
247
 
248
+ /**
249
+ * Polls the rollup until its current epoch reaches `epoch`. Unlike {@link advanceToEpoch} this does
250
+ * not warp the L1 clock; it only waits for the chain to reach `epoch` through external activity.
251
+ */
252
+ public async waitForEpoch(epoch: EpochNumber, opts: { timeout?: number; interval?: number } = {}): Promise<void> {
253
+ await retryUntil(
254
+ async () => (await this.getEpoch()) >= epoch || undefined,
255
+ `rollup epoch >= ${epoch}`,
256
+ opts.timeout ?? 60,
257
+ opts.interval ?? 1,
258
+ );
259
+ }
260
+
261
+ /**
262
+ * Polls the rollup until its current slot reaches `slot`. Unlike {@link advanceToSlot} this does not
263
+ * warp the L1 clock; it only waits for the chain to reach `slot` through external activity.
264
+ */
265
+ public async waitForSlot(slot: SlotNumber, opts: { timeout?: number; interval?: number } = {}): Promise<void> {
266
+ await retryUntil(
267
+ async () => (await this.getSlot()) >= slot || undefined,
268
+ `rollup slot >= ${slot}`,
269
+ opts.timeout ?? 60,
270
+ opts.interval ?? 1,
271
+ );
272
+ }
273
+
274
+ /**
275
+ * Polls the rollup until its pending checkpoint settles below `checkpoint` on a freshly mined, non-zero
276
+ * checkpoint, and returns that new pending checkpoint number. Reads the L1 rollup contract directly
277
+ * rather than a node, since a rollback lands on L1 first.
278
+ *
279
+ * A prune can momentarily drop the pending checkpoint to 0 before the post-deadline propose mines its
280
+ * replacement, so a caller detecting a rollback wants the new lower checkpoint, not that transient
281
+ * empty state — hence the non-zero guard.
282
+ */
283
+ public async waitForCheckpointBelow(
284
+ checkpoint: CheckpointNumber,
285
+ opts: { timeout?: number; interval?: number } = {},
286
+ ): Promise<CheckpointNumber> {
287
+ return await retryUntil(
288
+ async () => {
289
+ const { pending } = await this.getTips();
290
+ return pending > 0 && pending < checkpoint ? pending : undefined;
291
+ },
292
+ `rollup checkpoint in (0, ${checkpoint})`,
293
+ opts.timeout ?? 60,
294
+ opts.interval ?? 1,
295
+ );
296
+ }
297
+
221
298
  /**
222
299
  * Overrides the inProgress field of the Inbox contract state
223
300
  * @param howMuch - How many checkpoints to move it forward
@@ -259,12 +336,14 @@ export class RollupCheatCodes {
259
336
  });
260
337
  }
261
338
 
262
- public insertOutbox(epoch: EpochNumber, outHash: bigint) {
339
+ public insertOutbox(epoch: EpochNumber, numCheckpointsInEpoch: number, outHash: bigint) {
263
340
  return this.ethCheatCodes.execWithPausedAnvil(async () => {
264
341
  const outboxAddress = await this.rollup.read.getOutbox();
265
- const epochRootSlot = OutboxContract.getEpochRootStorageSlot(epoch);
342
+ const epochRootSlot = OutboxContract.getEpochRootStorageSlot(epoch, numCheckpointsInEpoch);
266
343
  await this.ethCheatCodes.store(EthAddress.fromString(outboxAddress), epochRootSlot, outHash);
267
- this.logger.warn(`Advanced outbox to epoch ${epoch} with out hash ${outHash}`);
344
+ this.logger.warn(
345
+ `Advanced outbox to epoch ${epoch} numCheckpointsInEpoch ${numCheckpointsInEpoch} with out hash ${outHash}`,
346
+ );
268
347
  });
269
348
  }
270
349
 
@@ -313,7 +392,8 @@ export class RollupCheatCodes {
313
392
  }
314
393
 
315
394
  /**
316
- * Directly updates proving cost per mana.
395
+ * Directly updates proving cost per mana. Throws if the on-chain tx reverts
396
+ * (e.g. rate-limit cooldown, step cap, or floor) instead of silently succeeding.
317
397
  * @param ethValue - The new proving cost per mana in ETH
318
398
  */
319
399
  public async setProvingCostPerMana(ethValue: bigint) {
@@ -323,8 +403,37 @@ export class RollupCheatCodes {
323
403
  chain: this.client.chain,
324
404
  gasLimit: 1000000n,
325
405
  });
326
- await this.client.waitForTransactionReceipt({ hash });
406
+ const receipt = await this.client.waitForTransactionReceipt({ hash });
407
+ if (receipt.status !== 'success') {
408
+ throw new Error(
409
+ `setProvingCostPerMana(${ethValue}) reverted on L1 (tx ${hash}). ` +
410
+ `Likely FeeLib rate-limit (30-day cooldown or 1.5x step cap); ` +
411
+ `use clearProvingCostCooldown() between successive updates.`,
412
+ );
413
+ }
327
414
  this.logger.warn(`Updated proving cost per mana to ${ethValue}`);
328
415
  });
329
416
  }
417
+
418
+ /**
419
+ * Resets the 30-day proving-cost update cooldown enforced by FeeLib.updateProvingCostPerMana
420
+ * by zeroing `FeeStore.provingCostLastUpdate` directly in contract storage. Use between
421
+ * successive setProvingCostPerMana / bumpProvingCostPerMana calls so the later update can
422
+ * land instead of reverting. Does not touch L1 time, so PXE/tx-expiration state stays intact.
423
+ *
424
+ * @note This is tightly coupled to the `FeeStore` layout in
425
+ * l1-contracts/src/core/libraries/rollup/FeeLib.sol:
426
+ * slot + 0: CompressedFeeConfig config (uint256)
427
+ * slot + 1: L1GasOracleValues l1GasOracleValues (14+14+4 bytes, packed)
428
+ * slot + 2: uint64 provingCostLastUpdate (only member — zeroing the slot is safe)
429
+ * If the struct layout changes, update the offset below.
430
+ */
431
+ public async clearProvingCostCooldown() {
432
+ const feeStoreBaseSlot = hexToBigInt(keccak256(Buffer.from('aztec.fee.storage', 'utf-8')));
433
+ const provingCostLastUpdateSlot = feeStoreBaseSlot + 2n;
434
+ await this.ethCheatCodes.store(EthAddress.fromString(this.rollup.address), provingCostLastUpdateSlot, 0n, {
435
+ silent: true,
436
+ });
437
+ this.logger.warn(`Cleared proving-cost update cooldown`);
438
+ }
330
439
  }
@@ -1,10 +1,10 @@
1
1
  import { createLogger } from '@aztec/foundation/log';
2
2
  import { makeBackoff, retry } from '@aztec/foundation/retry';
3
3
  import type { TestDateProvider } from '@aztec/foundation/timer';
4
- import { fileURLToPath } from '@aztec/foundation/url';
5
4
 
6
5
  import { type ChildProcess, spawn } from 'child_process';
7
- import { dirname, resolve } from 'path';
6
+
7
+ import { resolveFoundryBinary } from '../foundry_binary.js';
8
8
 
9
9
  /** Minimal interface matching the @viem/anvil Anvil shape used by callers. */
10
10
  export interface Anvil {
@@ -14,6 +14,30 @@ export interface Anvil {
14
14
  stop(): Promise<void>;
15
15
  }
16
16
 
17
+ // Watchdog wrapper: instead of spawning anvil directly, we spawn a small bash supervisor that runs
18
+ // anvil as a background child and polls its own parent (this node process). If the parent dies for
19
+ // ANY reason — including SIGKILL / crash / OOM, where node's own exit handlers never run — the poll
20
+ // loop ends and the EXIT trap reaps anvil. The script is inlined (rather than shipped as a `.sh`) so
21
+ // it works from the published npm tarball too, and the resolved anvil binary is passed via
22
+ // `$ANVIL_BIN` so it works without `anvil` on PATH.
23
+ //
24
+ // `$@` is the anvil argv; `bash -c <script> bash <...args>` puts the args in `$@` and `$0` = 'bash'.
25
+ //
26
+ // The EXIT trap reaps anvil; INT/TERM just `exit` (which fires the EXIT trap) so a signal terminates
27
+ // the supervisor promptly instead of being swallowed — a trapped TERM does NOT terminate the shell,
28
+ // so trapping the kill directly on TERM would leave the poll loop running and the caller's teardown
29
+ // hanging until its SIGKILL escalation. `sleep & wait` makes the poll interruptible, so INT/TERM are
30
+ // handled immediately rather than after the current `sleep` returns.
31
+ const ANVIL_WATCHDOG = `
32
+ set -u
33
+ parent=$PPID
34
+ "$ANVIL_BIN" "$@" &
35
+ anvil_pid=$!
36
+ trap 'kill "$anvil_pid" 2>/dev/null' EXIT
37
+ trap 'exit 0' INT TERM
38
+ while kill -0 "$parent" 2>/dev/null; do sleep 1 & wait $!; done
39
+ `;
40
+
17
41
  /**
18
42
  * Ensures there's a running Anvil instance and returns the RPC URL.
19
43
  */
@@ -42,7 +66,7 @@ export async function startAnvil(
42
66
  dateProvider?: TestDateProvider;
43
67
  } = {},
44
68
  ): Promise<{ anvil: Anvil; methodCalls?: string[]; rpcUrl: string; stop: () => Promise<void> }> {
45
- const anvilBinary = resolve(dirname(fileURLToPath(import.meta.url)), '../../', 'scripts/anvil_kill_wrapper.sh');
69
+ const anvilBinary = resolveFoundryBinary('anvil');
46
70
  const logger = opts.log ? createLogger('ethereum:anvil') : undefined;
47
71
  const methodCalls = opts.captureMethodCalls ? ([] as string[]) : undefined;
48
72
 
@@ -50,6 +74,9 @@ export async function startAnvil(
50
74
 
51
75
  const anvil = await retry(
52
76
  async () => {
77
+ // `--port 0` lets anvil bind an OS-assigned ephemeral port; the actual port is read back from
78
+ // its "Listening on host:port" stdout below, so independent suites can spawn their own anvil
79
+ // in parallel without fighting over a fixed port.
53
80
  const port = opts.port ?? (process.env.ANVIL_PORT ? parseInt(process.env.ANVIL_PORT) : 8545);
54
81
  const args: string[] = [
55
82
  '--host',
@@ -71,9 +98,11 @@ export async function startAnvil(
71
98
  }
72
99
  args.push('--slots-in-an-epoch', String(opts.slotsInAnEpoch ?? 1));
73
100
 
74
- const child = spawn(anvilBinary, args, {
101
+ // Spawn the watchdog (see ANVIL_WATCHDOG). It launches anvil with these args and reaps it if we
102
+ // die; `$0` is 'bash' and `$@` is the anvil argv.
103
+ const child = spawn('bash', ['-c', ANVIL_WATCHDOG, 'bash', ...args], {
75
104
  stdio: ['ignore', 'pipe', 'pipe'],
76
- env: { ...process.env, RAYON_NUM_THREADS: '1' },
105
+ env: { ...process.env, ANVIL_BIN: anvilBinary, RAYON_NUM_THREADS: '1' },
77
106
  });
78
107
 
79
108
  // Wait for "Listening on" or an early exit.
@@ -183,7 +212,10 @@ function syncDateProviderFromAnvilOutput(text: string, dateProvider: TestDatePro
183
212
  }
184
213
  }
185
214
 
186
- /** Send SIGTERM, wait up to 5 s, then SIGKILL. All timers are always cleared. */
215
+ /**
216
+ * Send SIGTERM to the watchdog, wait up to 5 s, then SIGKILL. The watchdog's trap forwards the
217
+ * signal to anvil, so terminating it tears down anvil too. All timers are always cleared.
218
+ */
187
219
  function killChild(child: ChildProcess): Promise<void> {
188
220
  return new Promise<void>(resolve => {
189
221
  if (child.exitCode !== null || child.killed) {
package/src/utils.ts CHANGED
@@ -27,8 +27,8 @@ export interface L2Claim {
27
27
  export class FormattedViemError extends Error {
28
28
  metaMessages?: any[];
29
29
 
30
- constructor(message: string, metaMessages?: any[]) {
31
- super(message);
30
+ constructor(message: string, metaMessages?: any[], options?: ErrorOptions) {
31
+ super(message, options);
32
32
  this.name = 'FormattedViemError';
33
33
  this.metaMessages = metaMessages;
34
34
  }
@@ -197,6 +197,8 @@ export function formatViemError(error: any, abi: Abi = ErrorsAbi): FormattedViem
197
197
  return error;
198
198
  }
199
199
 
200
+ const originalError = error;
201
+
200
202
  // First try to decode as a custom error using the ABI
201
203
  try {
202
204
  const data = getNestedErrorData(error);
@@ -207,7 +209,9 @@ export function formatViemError(error: any, abi: Abi = ErrorsAbi): FormattedViem
207
209
  data: data as Hex,
208
210
  });
209
211
  if (decoded) {
210
- return new FormattedViemError(`${decoded.errorName}(${decoded.args?.join(', ') ?? ''})`, error?.metaMessages);
212
+ return new FormattedViemError(`${decoded.errorName}(${decoded.args?.join(', ') ?? ''})`, error?.metaMessages, {
213
+ cause: originalError,
214
+ });
211
215
  }
212
216
  }
213
217
 
@@ -224,33 +228,35 @@ export function formatViemError(error: any, abi: Abi = ErrorsAbi): FormattedViem
224
228
  revertError.metaMessages && revertError.metaMessages?.length > 1
225
229
  ? revertError.metaMessages[1].trimStart()
226
230
  : '';
227
- return new FormattedViemError(`${errorName}${args}`, error?.metaMessages);
231
+ return new FormattedViemError(`${errorName}${args}`, error?.metaMessages, { cause: originalError });
228
232
  }
229
233
  }
230
234
  } catch {
231
235
  // If decoding fails, we fall back to the original formatting
232
236
  }
233
237
 
234
- // Strip ABI from the error object before formatting
238
+ // Strip ABI from the error object before formatting. We clone first to avoid mutating the
239
+ // caller's error, but structuredClone throws DataCloneError on values it cannot clone (e.g.
240
+ // viem RPC errors carrying function-valued request context). If cloning fails, fall back to
241
+ // formatting the original error untouched rather than letting the clone failure mask it.
235
242
  if (error && typeof error === 'object') {
236
- // Create a clone to avoid modifying the original
237
- const errorClone = structuredClone(error);
238
-
239
- // Helper function to recursively remove ABI properties
240
-
241
- // Strip ABIs from the clone
242
- stripAbis(errorClone);
243
-
244
- // Use the cleaned clone for further processing
245
- error = errorClone;
243
+ try {
244
+ const errorClone = structuredClone(error);
245
+ stripAbis(errorClone);
246
+ error = errorClone;
247
+ } catch {
248
+ // Leave `error` as the original; we skip stripAbis to avoid mutating the caller's object.
249
+ }
246
250
  }
247
251
 
248
252
  // If it's a regular Error instance, return it with its message
249
253
  if (error instanceof Error) {
250
- return new FormattedViemError(truncateErrorMessage(error.message), (error as any)?.metaMessages);
254
+ return new FormattedViemError(truncateErrorMessage(error.message), (error as any)?.metaMessages, {
255
+ cause: originalError,
256
+ });
251
257
  }
252
258
 
253
- return new FormattedViemError(truncateErrorMessage(String(error)));
259
+ return new FormattedViemError(truncateErrorMessage(String(error)), undefined, { cause: originalError });
254
260
  }
255
261
 
256
262
  function stripAbis(obj: any) {
@@ -276,6 +282,24 @@ function stripAbis(obj: any) {
276
282
  });
277
283
  }
278
284
 
285
+ /**
286
+ * Best-effort decode of a raw revert payload (`0x...`) against an ABI.
287
+ * Returns a human-readable `ErrorName(arg1, arg2, ...)` string, or `undefined` if the selector
288
+ * is unknown or the payload is empty. Use to surface decoded error names alongside the raw
289
+ * payload in log lines for operators.
290
+ */
291
+ export function tryDecodeRevertReason(data: Hex | undefined, abi: Abi): string | undefined {
292
+ if (!data || data === '0x') {
293
+ return undefined;
294
+ }
295
+ try {
296
+ const decoded = decodeErrorResult({ abi, data });
297
+ return `${decoded.errorName}(${decoded.args?.join(', ') ?? ''})`;
298
+ } catch {
299
+ return undefined;
300
+ }
301
+ }
302
+
279
303
  export function tryGetCustomErrorName(err: any) {
280
304
  try {
281
305
  // See https://viem.sh/docs/contract/simulateContract#handling-custom-errors
@@ -1,69 +0,0 @@
1
- import { SlotNumber } from '@aztec/foundation/branded-types';
2
- import { EthAddress } from '@aztec/foundation/eth-address';
3
- import EventEmitter from 'events';
4
- import { type Hex, type Log, type TypedDataDefinition } from 'viem';
5
- import type { L1TxRequest, L1TxUtils } from '../l1_tx_utils/index.js';
6
- import type { ViemClient } from '../types.js';
7
- import { type IEmpireBase } from './empire_base.js';
8
- export declare class ProposalAlreadyExecutedError extends Error {
9
- constructor(round: bigint);
10
- }
11
- export declare class EmpireSlashingProposerContract extends EventEmitter implements IEmpireBase {
12
- readonly client: ViemClient;
13
- private readonly logger;
14
- private readonly proposer;
15
- readonly type: "empire";
16
- constructor(client: ViemClient, address: Hex | EthAddress);
17
- get address(): EthAddress;
18
- getQuorumSize(): Promise<bigint>;
19
- getRoundSize(): Promise<bigint>;
20
- getLifetimeInRounds(): Promise<bigint>;
21
- getExecutionDelayInRounds(): Promise<bigint>;
22
- getCurrentRound(): Promise<bigint>;
23
- computeRound(slot: SlotNumber): Promise<bigint>;
24
- getInstance(): Promise<`0x${string}`>;
25
- getRoundInfo(rollupAddress: Hex, round: bigint): Promise<{
26
- lastSignalSlot: SlotNumber;
27
- payloadWithMostSignals: Hex;
28
- quorumReached: boolean;
29
- executed: boolean;
30
- }>;
31
- getPayloadSignals(rollupAddress: Hex, round: bigint, payload: Hex): Promise<bigint>;
32
- createSignalRequest(payload: Hex): L1TxRequest;
33
- createSignalRequestWithSignature(payload: Hex, slot: SlotNumber, chainId: number, signerAddress: Hex, signer: (msg: TypedDataDefinition) => Promise<Hex>): Promise<L1TxRequest>;
34
- /** Checks if a payload was ever submitted to governance via submitRoundWinner. */
35
- hasPayloadBeenProposed(payload: Hex, fromBlock: bigint): Promise<boolean>;
36
- listenToSubmittablePayloads(callback: (args: {
37
- payload: `0x${string}`;
38
- round: bigint;
39
- }) => unknown): import("viem").WatchContractEventReturnType;
40
- listenToPayloadSubmitted(callback: (args: {
41
- round: bigint;
42
- payload: `0x${string}`;
43
- }) => unknown): import("viem").WatchContractEventReturnType;
44
- listenToSignalCasted(callback: (args: {
45
- round: bigint;
46
- payload: `0x${string}`;
47
- signaler: `0x${string}`;
48
- }) => unknown): import("viem").WatchContractEventReturnType;
49
- /** Creates an L1TxRequest to submit the round winner for the given round. */
50
- buildExecuteRoundRequest(round: bigint): L1TxRequest;
51
- /** Tries to extract a PayloadSubmitted event from the given logs. */
52
- tryExtractPayloadSubmittedEvent(logs: Log[]): {
53
- eventName: "PayloadSubmitted";
54
- args: {
55
- payload: `0x${string}`;
56
- round: bigint;
57
- };
58
- } | undefined;
59
- /**
60
- * Wait for a round to be reached.
61
- *
62
- * @param round - The round to wait for.
63
- * @param pollingIntervalSeconds - The interval in seconds to poll for the round.
64
- * @returns True if the round was reached, false otherwise.
65
- */
66
- waitForRound(round: bigint, pollingIntervalSeconds?: number): Promise<boolean>;
67
- executeRound(txUtils: L1TxUtils, round: bigint | number): ReturnType<typeof txUtils.sendAndMonitorTransaction>;
68
- }
69
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW1waXJlX3NsYXNoaW5nX3Byb3Bvc2VyLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvY29udHJhY3RzL2VtcGlyZV9zbGFzaGluZ19wcm9wb3Nlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEVBQUUsVUFBVSxFQUFFLE1BQU0saUNBQWlDLENBQUM7QUFDN0QsT0FBTyxFQUFFLFVBQVUsRUFBRSxNQUFNLCtCQUErQixDQUFDO0FBSzNELE9BQU8sWUFBWSxNQUFNLFFBQVEsQ0FBQztBQUNsQyxPQUFPLEVBRUwsS0FBSyxHQUFHLEVBQ1IsS0FBSyxHQUFHLEVBQ1IsS0FBSyxtQkFBbUIsRUFHekIsTUFBTSxNQUFNLENBQUM7QUFFZCxPQUFPLEtBQUssRUFBRSxXQUFXLEVBQUUsU0FBUyxFQUFFLE1BQU0seUJBQXlCLENBQUM7QUFDdEUsT0FBTyxLQUFLLEVBQUUsVUFBVSxFQUFFLE1BQU0sYUFBYSxDQUFDO0FBRTlDLE9BQU8sRUFBRSxLQUFLLFdBQVcsRUFBOEQsTUFBTSxrQkFBa0IsQ0FBQztBQUVoSCxxQkFBYSw0QkFBNkIsU0FBUSxLQUFLO0lBQ3JELFlBQVksS0FB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MAAM,EAAE,CAAA;KAAE,KAAK,OAAO,+CAcrG;IAEM,oBAAoB,CACzB,QAAQ,EAAE,CAAC,IAAI,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,KAAK,MAAM,EAAE,CAAC;QAAC,QAAQ,EAAE,KAAK,MAAM,EAAE,CAAA;KAAE,KAAK,OAAO,+CAehG;IAED,6EAA6E;IACtE,wBAAwB,CAAC,KAAK,EAAE,MAAM,GAAG,WAAW,CAU1D;IAED,qEAAqE;IAC9D,+BAA+B,CAAC,IAAI,EAAE,GAAG,EAAE;;;;;;kBAEjD;IAED;;;;;;OAMG;IACI,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,sBAAsB,GAAE,MAAU,GAAG,OAAO,CAAC,OAAO,CAAC,CAavF;IAEY,YAAY,CACvB,OAAO,EAAE,SAAS,EAClB,KAAK,EAAE,MAAM,GAAG,MAAM,GACrB,UAAU,CAAC,OAAO,OAAO,CAAC,yBAAyB,CAAC,CAmCtD;CACF"}
@@ -1,216 +0,0 @@
1
- import { SlotNumber } from '@aztec/foundation/branded-types';
2
- import { EthAddress } from '@aztec/foundation/eth-address';
3
- import { createLogger } from '@aztec/foundation/log';
4
- import { retryUntil } from '@aztec/foundation/retry';
5
- import { EmpireSlashingProposerAbi } from '@aztec/l1-artifacts/EmpireSlashingProposerAbi';
6
- import EventEmitter from 'events';
7
- import { encodeFunctionData, getContract } from 'viem';
8
- import { FormattedViemError, tryExtractEvent } from '../utils.js';
9
- import { encodeSignal, encodeSignalWithSignature, signSignalWithSig } from './empire_base.js';
10
- export class ProposalAlreadyExecutedError extends Error {
11
- constructor(round){
12
- super(`Proposal already executed: ${round}`);
13
- }
14
- }
15
- export class EmpireSlashingProposerContract extends EventEmitter {
16
- client;
17
- logger;
18
- proposer;
19
- type;
20
- constructor(client, address){
21
- super(), this.client = client, this.logger = createLogger('ethereum:contracts:empire_slashing_proposer'), this.type = 'empire';
22
- this.proposer = getContract({
23
- address: typeof address === 'string' ? address : address.toString(),
24
- abi: EmpireSlashingProposerAbi,
25
- client
26
- });
27
- }
28
- get address() {
29
- return EthAddress.fromString(this.proposer.address);
30
- }
31
- getQuorumSize() {
32
- return this.proposer.read.QUORUM_SIZE();
33
- }
34
- getRoundSize() {
35
- return this.proposer.read.ROUND_SIZE();
36
- }
37
- getLifetimeInRounds() {
38
- return this.proposer.read.LIFETIME_IN_ROUNDS();
39
- }
40
- getExecutionDelayInRounds() {
41
- return this.proposer.read.EXECUTION_DELAY_IN_ROUNDS();
42
- }
43
- getCurrentRound() {
44
- return this.proposer.read.getCurrentRound();
45
- }
46
- computeRound(slot) {
47
- return this.proposer.read.computeRound([
48
- BigInt(slot)
49
- ]);
50
- }
51
- getInstance() {
52
- return this.proposer.read.getInstance();
53
- }
54
- async getRoundInfo(rollupAddress, round) {
55
- const result = await this.proposer.read.getRoundData([
56
- rollupAddress,
57
- round
58
- ]);
59
- const [signalCount, quorum] = await Promise.all([
60
- this.proposer.read.signalCount([
61
- rollupAddress,
62
- round,
63
- result.payloadWithMostSignals
64
- ]),
65
- this.getQuorumSize()
66
- ]);
67
- return {
68
- lastSignalSlot: SlotNumber.fromBigInt(result.lastSignalSlot),
69
- payloadWithMostSignals: result.payloadWithMostSignals,
70
- quorumReached: signalCount >= quorum,
71
- executed: result.executed
72
- };
73
- }
74
- getPayloadSignals(rollupAddress, round, payload) {
75
- return this.proposer.read.signalCount([
76
- rollupAddress,
77
- round,
78
- payload
79
- ]);
80
- }
81
- createSignalRequest(payload) {
82
- return {
83
- to: this.address.toString(),
84
- abi: EmpireSlashingProposerAbi,
85
- data: encodeSignal(payload)
86
- };
87
- }
88
- async createSignalRequestWithSignature(payload, slot, chainId, signerAddress, signer) {
89
- const signature = await signSignalWithSig(signer, payload, slot, await this.getInstance(), this.address.toString(), chainId);
90
- return {
91
- to: this.address.toString(),
92
- abi: EmpireSlashingProposerAbi,
93
- data: encodeSignalWithSignature(payload, signature)
94
- };
95
- }
96
- /** Checks if a payload was ever submitted to governance via submitRoundWinner. */ async hasPayloadBeenProposed(payload, fromBlock) {
97
- const events = await this.proposer.getEvents.PayloadSubmitted({
98
- payload
99
- }, {
100
- fromBlock,
101
- strict: true
102
- });
103
- return events.length > 0;
104
- }
105
- listenToSubmittablePayloads(callback) {
106
- return this.proposer.watchEvent.PayloadSubmittable({}, {
107
- strict: true,
108
- onLogs: (logs)=>{
109
- for (const log of logs){
110
- const { payload, round } = log.args;
111
- if (payload && round) {
112
- callback({
113
- payload,
114
- round
115
- });
116
- }
117
- }
118
- }
119
- });
120
- }
121
- listenToPayloadSubmitted(callback) {
122
- return this.proposer.watchEvent.PayloadSubmitted({}, {
123
- onLogs: (logs)=>{
124
- for (const log of logs){
125
- const { payload, round } = log.args;
126
- if (round && payload) {
127
- callback({
128
- round,
129
- payload
130
- });
131
- }
132
- }
133
- }
134
- });
135
- }
136
- listenToSignalCasted(callback) {
137
- return this.proposer.watchEvent.SignalCast({}, {
138
- onLogs: (logs)=>{
139
- for (const log of logs){
140
- const { round, payload, signaler } = log.args;
141
- if (round && payload && signaler) {
142
- callback({
143
- round,
144
- payload,
145
- signaler
146
- });
147
- }
148
- }
149
- }
150
- });
151
- }
152
- /** Creates an L1TxRequest to submit the round winner for the given round. */ buildExecuteRoundRequest(round) {
153
- return {
154
- to: this.address.toString(),
155
- abi: EmpireSlashingProposerAbi,
156
- data: encodeFunctionData({
157
- abi: EmpireSlashingProposerAbi,
158
- functionName: 'submitRoundWinner',
159
- args: [
160
- round
161
- ]
162
- })
163
- };
164
- }
165
- /** Tries to extract a PayloadSubmitted event from the given logs. */ tryExtractPayloadSubmittedEvent(logs) {
166
- return tryExtractEvent(logs, this.address.toString(), EmpireSlashingProposerAbi, 'PayloadSubmitted');
167
- }
168
- /**
169
- * Wait for a round to be reached.
170
- *
171
- * @param round - The round to wait for.
172
- * @param pollingIntervalSeconds - The interval in seconds to poll for the round.
173
- * @returns True if the round was reached, false otherwise.
174
- */ waitForRound(round, pollingIntervalSeconds = 1) {
175
- return retryUntil(async ()=>{
176
- const currentRound = await this.proposer.read.getCurrentRound().catch((e)=>{
177
- this.logger.error('Error getting current round', e);
178
- return undefined;
179
- });
180
- return currentRound !== undefined && currentRound >= round;
181
- }, `Waiting for round ${round} to be reached`, 0, pollingIntervalSeconds).catch(()=>false);
182
- }
183
- async executeRound(txUtils, round) {
184
- if (typeof round === 'number') {
185
- round = BigInt(round);
186
- }
187
- const request = this.buildExecuteRoundRequest(round);
188
- const response = await txUtils.sendAndMonitorTransaction(request, {
189
- // Gas estimation is way off for this, likely because we are creating the contract/selector to call
190
- // for the actual slashing dynamically.
191
- gasLimitBufferPercentage: 50
192
- }).catch((err)=>{
193
- if (err instanceof FormattedViemError && err.message.includes('ProposalAlreadyExecuted')) {
194
- throw new ProposalAlreadyExecutedError(round);
195
- }
196
- throw err;
197
- });
198
- if (response.receipt.status === 'reverted') {
199
- const args = {
200
- abi: EmpireSlashingProposerAbi,
201
- functionName: 'submitRoundWinner',
202
- args: [
203
- round
204
- ],
205
- address: this.address.toString()
206
- };
207
- const error = await txUtils.tryGetErrorFromRevertedTx(request.data, args, undefined, []);
208
- if (error?.includes('ProposalAlreadyExecuted')) {
209
- throw new ProposalAlreadyExecutedError(round);
210
- }
211
- const errorMessage = `Failed to execute round ${round}, TxHash: ${response.receipt.transactionHash}, Error: ${error ?? 'Unknown error'}`;
212
- throw new Error(errorMessage);
213
- }
214
- return response;
215
- }
216
- }