@aztec/ethereum 0.0.0-test.1 → 0.0.1-commit.21caa21

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 (232) hide show
  1. package/dest/account.d.ts +2 -0
  2. package/dest/account.d.ts.map +1 -0
  3. package/dest/account.js +4 -0
  4. package/dest/chain.d.ts +1 -1
  5. package/dest/client.d.ts +6 -4
  6. package/dest/client.d.ts.map +1 -1
  7. package/dest/client.js +16 -2
  8. package/dest/config.d.ts +111 -17
  9. package/dest/config.d.ts.map +1 -1
  10. package/dest/config.js +462 -22
  11. package/dest/constants.d.ts +1 -1
  12. package/dest/contracts/empire_base.d.ts +24 -8
  13. package/dest/contracts/empire_base.d.ts.map +1 -1
  14. package/dest/contracts/empire_base.js +75 -2
  15. package/dest/contracts/empire_slashing_proposer.d.ts +66 -0
  16. package/dest/contracts/empire_slashing_proposer.d.ts.map +1 -0
  17. package/dest/contracts/empire_slashing_proposer.js +200 -0
  18. package/dest/contracts/errors.d.ts +7 -0
  19. package/dest/contracts/errors.d.ts.map +1 -0
  20. package/dest/contracts/errors.js +12 -0
  21. package/dest/contracts/fee_asset_handler.d.ts +19 -0
  22. package/dest/contracts/fee_asset_handler.d.ts.map +1 -0
  23. package/dest/contracts/fee_asset_handler.js +57 -0
  24. package/dest/contracts/fee_juice.d.ts +6 -7
  25. package/dest/contracts/fee_juice.d.ts.map +1 -1
  26. package/dest/contracts/fee_juice.js +27 -20
  27. package/dest/contracts/governance.d.ts +43 -32
  28. package/dest/contracts/governance.d.ts.map +1 -1
  29. package/dest/contracts/governance.js +87 -84
  30. package/dest/contracts/governance_proposer.d.ts +16 -13
  31. package/dest/contracts/governance_proposer.d.ts.map +1 -1
  32. package/dest/contracts/governance_proposer.js +37 -17
  33. package/dest/contracts/gse.d.ts +32 -0
  34. package/dest/contracts/gse.d.ts.map +1 -0
  35. package/dest/contracts/gse.js +72 -0
  36. package/dest/contracts/inbox.d.ts +26 -0
  37. package/dest/contracts/inbox.d.ts.map +1 -0
  38. package/dest/contracts/inbox.js +45 -0
  39. package/dest/contracts/index.d.ts +9 -3
  40. package/dest/contracts/index.d.ts.map +1 -1
  41. package/dest/contracts/index.js +8 -2
  42. package/dest/contracts/multicall.d.ts +21 -0
  43. package/dest/contracts/multicall.d.ts.map +1 -0
  44. package/dest/contracts/multicall.js +156 -0
  45. package/dest/contracts/registry.d.ts +10 -5
  46. package/dest/contracts/registry.d.ts.map +1 -1
  47. package/dest/contracts/registry.js +44 -16
  48. package/dest/contracts/rollup.d.ts +204 -40
  49. package/dest/contracts/rollup.d.ts.map +1 -1
  50. package/dest/contracts/rollup.js +529 -79
  51. package/dest/contracts/slasher_contract.d.ts +44 -0
  52. package/dest/contracts/slasher_contract.d.ts.map +1 -0
  53. package/dest/contracts/slasher_contract.js +75 -0
  54. package/dest/contracts/tally_slashing_proposer.d.ts +139 -0
  55. package/dest/contracts/tally_slashing_proposer.d.ts.map +1 -0
  56. package/dest/contracts/tally_slashing_proposer.js +313 -0
  57. package/dest/contracts/utils.d.ts +3 -0
  58. package/dest/contracts/utils.d.ts.map +1 -0
  59. package/dest/contracts/utils.js +11 -0
  60. package/dest/deploy_l1_contracts.d.ts +577 -21114
  61. package/dest/deploy_l1_contracts.d.ts.map +1 -1
  62. package/dest/deploy_l1_contracts.js +1225 -421
  63. package/dest/eth-signer/eth-signer.d.ts +21 -0
  64. package/dest/eth-signer/eth-signer.d.ts.map +1 -0
  65. package/dest/eth-signer/eth-signer.js +5 -0
  66. package/dest/eth-signer/index.d.ts +2 -0
  67. package/dest/eth-signer/index.d.ts.map +1 -0
  68. package/dest/eth-signer/index.js +1 -0
  69. package/dest/index.d.ts +7 -3
  70. package/dest/index.d.ts.map +1 -1
  71. package/dest/index.js +6 -2
  72. package/dest/l1_artifacts.d.ts +77344 -0
  73. package/dest/l1_artifacts.d.ts.map +1 -0
  74. package/dest/l1_artifacts.js +166 -0
  75. package/dest/l1_contract_addresses.d.ts +24 -4
  76. package/dest/l1_contract_addresses.d.ts.map +1 -1
  77. package/dest/l1_contract_addresses.js +22 -18
  78. package/dest/l1_reader.d.ts +2 -2
  79. package/dest/l1_reader.d.ts.map +1 -1
  80. package/dest/l1_reader.js +8 -8
  81. package/dest/l1_tx_utils/config.d.ts +59 -0
  82. package/dest/l1_tx_utils/config.d.ts.map +1 -0
  83. package/dest/l1_tx_utils/config.js +82 -0
  84. package/dest/l1_tx_utils/constants.d.ts +6 -0
  85. package/dest/l1_tx_utils/constants.d.ts.map +1 -0
  86. package/dest/l1_tx_utils/constants.js +14 -0
  87. package/dest/l1_tx_utils/factory.d.ts +24 -0
  88. package/dest/l1_tx_utils/factory.d.ts.map +1 -0
  89. package/dest/l1_tx_utils/factory.js +12 -0
  90. package/dest/l1_tx_utils/index.d.ts +10 -0
  91. package/dest/l1_tx_utils/index.d.ts.map +1 -0
  92. package/dest/l1_tx_utils/index.js +10 -0
  93. package/dest/l1_tx_utils/interfaces.d.ts +76 -0
  94. package/dest/l1_tx_utils/interfaces.d.ts.map +1 -0
  95. package/dest/l1_tx_utils/interfaces.js +4 -0
  96. package/dest/l1_tx_utils/l1_tx_utils.d.ts +94 -0
  97. package/dest/l1_tx_utils/l1_tx_utils.d.ts.map +1 -0
  98. package/dest/l1_tx_utils/l1_tx_utils.js +610 -0
  99. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.d.ts +26 -0
  100. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.d.ts.map +1 -0
  101. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.js +26 -0
  102. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts +94 -0
  103. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts.map +1 -0
  104. package/dest/l1_tx_utils/readonly_l1_tx_utils.js +430 -0
  105. package/dest/l1_tx_utils/signer.d.ts +4 -0
  106. package/dest/l1_tx_utils/signer.d.ts.map +1 -0
  107. package/dest/l1_tx_utils/signer.js +16 -0
  108. package/dest/l1_tx_utils/types.d.ts +67 -0
  109. package/dest/l1_tx_utils/types.d.ts.map +1 -0
  110. package/dest/l1_tx_utils/types.js +26 -0
  111. package/dest/l1_tx_utils/utils.d.ts +4 -0
  112. package/dest/l1_tx_utils/utils.d.ts.map +1 -0
  113. package/dest/l1_tx_utils/utils.js +14 -0
  114. package/dest/l1_types.d.ts +6 -0
  115. package/dest/l1_types.d.ts.map +1 -0
  116. package/dest/l1_types.js +1 -0
  117. package/dest/publisher_manager.d.ts +15 -0
  118. package/dest/publisher_manager.d.ts.map +1 -0
  119. package/dest/publisher_manager.js +88 -0
  120. package/dest/queries.d.ts +4 -2
  121. package/dest/queries.d.ts.map +1 -1
  122. package/dest/queries.js +53 -12
  123. package/dest/test/chain_monitor.d.ts +73 -0
  124. package/dest/test/chain_monitor.d.ts.map +1 -0
  125. package/dest/test/chain_monitor.js +215 -0
  126. package/dest/test/delayed_tx_utils.d.ts +8 -3
  127. package/dest/test/delayed_tx_utils.d.ts.map +1 -1
  128. package/dest/test/delayed_tx_utils.js +13 -6
  129. package/dest/test/eth_cheat_codes.d.ts +217 -0
  130. package/dest/test/eth_cheat_codes.d.ts.map +1 -0
  131. package/dest/test/eth_cheat_codes.js +558 -0
  132. package/dest/test/eth_cheat_codes_with_state.d.ts +2 -2
  133. package/dest/test/eth_cheat_codes_with_state.d.ts.map +1 -1
  134. package/dest/test/eth_cheat_codes_with_state.js +1 -1
  135. package/dest/test/index.d.ts +4 -1
  136. package/dest/test/index.d.ts.map +1 -1
  137. package/dest/test/index.js +3 -0
  138. package/dest/test/rollup_cheat_codes.d.ts +87 -0
  139. package/dest/test/rollup_cheat_codes.d.ts.map +1 -0
  140. package/dest/test/rollup_cheat_codes.js +266 -0
  141. package/dest/test/start_anvil.d.ts +7 -1
  142. package/dest/test/start_anvil.d.ts.map +1 -1
  143. package/dest/test/start_anvil.js +16 -7
  144. package/dest/test/tx_delayer.d.ts +18 -7
  145. package/dest/test/tx_delayer.d.ts.map +1 -1
  146. package/dest/test/tx_delayer.js +95 -19
  147. package/dest/test/upgrade_utils.d.ts +6 -5
  148. package/dest/test/upgrade_utils.d.ts.map +1 -1
  149. package/dest/test/upgrade_utils.js +23 -16
  150. package/dest/types.d.ts +7 -8
  151. package/dest/types.d.ts.map +1 -1
  152. package/dest/types.js +3 -1
  153. package/dest/utils.d.ts +2 -1
  154. package/dest/utils.d.ts.map +1 -1
  155. package/dest/utils.js +43 -88
  156. package/dest/zkPassportVerifierAddress.d.ts +15 -0
  157. package/dest/zkPassportVerifierAddress.d.ts.map +1 -0
  158. package/dest/zkPassportVerifierAddress.js +11 -0
  159. package/package.json +28 -19
  160. package/src/account.ts +5 -0
  161. package/src/client.ts +42 -4
  162. package/src/config.ts +592 -31
  163. package/src/contracts/empire_base.ts +77 -7
  164. package/src/contracts/empire_slashing_proposer.ts +265 -0
  165. package/src/contracts/errors.ts +13 -0
  166. package/src/contracts/fee_asset_handler.ts +63 -0
  167. package/src/contracts/fee_juice.ts +29 -15
  168. package/src/contracts/governance.ts +80 -77
  169. package/src/contracts/governance_proposer.ts +66 -24
  170. package/src/contracts/gse.ts +88 -0
  171. package/src/contracts/inbox.ts +63 -0
  172. package/src/contracts/index.ts +8 -2
  173. package/src/contracts/multicall.ts +155 -0
  174. package/src/contracts/registry.ts +51 -26
  175. package/src/contracts/rollup.ts +596 -74
  176. package/src/contracts/slasher_contract.ts +89 -0
  177. package/src/contracts/tally_slashing_proposer.ts +316 -0
  178. package/src/contracts/utils.ts +14 -0
  179. package/src/deploy_l1_contracts.ts +1459 -538
  180. package/src/eth-signer/eth-signer.ts +25 -0
  181. package/src/eth-signer/index.ts +1 -0
  182. package/src/index.ts +6 -2
  183. package/src/l1_artifacts.ts +254 -0
  184. package/src/l1_contract_addresses.ts +32 -19
  185. package/src/l1_reader.ts +9 -9
  186. package/src/l1_tx_utils/README.md +177 -0
  187. package/src/l1_tx_utils/config.ts +143 -0
  188. package/src/l1_tx_utils/constants.ts +18 -0
  189. package/src/l1_tx_utils/factory.ts +64 -0
  190. package/src/l1_tx_utils/index.ts +12 -0
  191. package/src/l1_tx_utils/interfaces.ts +86 -0
  192. package/src/l1_tx_utils/l1_tx_utils.ts +718 -0
  193. package/src/l1_tx_utils/l1_tx_utils_with_blobs.ts +77 -0
  194. package/src/l1_tx_utils/readonly_l1_tx_utils.ts +558 -0
  195. package/src/l1_tx_utils/signer.ts +28 -0
  196. package/src/l1_tx_utils/types.ts +85 -0
  197. package/src/l1_tx_utils/utils.ts +16 -0
  198. package/src/l1_types.ts +6 -0
  199. package/src/publisher_manager.ts +106 -0
  200. package/src/queries.ts +73 -15
  201. package/src/test/chain_monitor.ts +243 -0
  202. package/src/test/delayed_tx_utils.ts +34 -6
  203. package/src/test/eth_cheat_codes.ts +588 -0
  204. package/src/test/eth_cheat_codes_with_state.ts +1 -1
  205. package/src/test/index.ts +3 -0
  206. package/src/test/rollup_cheat_codes.ts +307 -0
  207. package/src/test/start_anvil.ts +22 -5
  208. package/src/test/tx_delayer.ts +127 -26
  209. package/src/test/upgrade_utils.ts +30 -21
  210. package/src/types.ts +10 -8
  211. package/src/utils.ts +49 -90
  212. package/src/zkPassportVerifierAddress.ts +15 -0
  213. package/dest/contracts/forwarder.d.ts +0 -24
  214. package/dest/contracts/forwarder.d.ts.map +0 -1
  215. package/dest/contracts/forwarder.js +0 -101
  216. package/dest/contracts/slashing_proposer.d.ts +0 -21
  217. package/dest/contracts/slashing_proposer.d.ts.map +0 -1
  218. package/dest/contracts/slashing_proposer.js +0 -47
  219. package/dest/eth_cheat_codes.d.ts +0 -147
  220. package/dest/eth_cheat_codes.d.ts.map +0 -1
  221. package/dest/eth_cheat_codes.js +0 -303
  222. package/dest/l1_tx_utils.d.ts +0 -192
  223. package/dest/l1_tx_utils.d.ts.map +0 -1
  224. package/dest/l1_tx_utils.js +0 -641
  225. package/dest/l1_tx_utils_with_blobs.d.ts +0 -12
  226. package/dest/l1_tx_utils_with_blobs.d.ts.map +0 -1
  227. package/dest/l1_tx_utils_with_blobs.js +0 -64
  228. package/src/contracts/forwarder.ts +0 -132
  229. package/src/contracts/slashing_proposer.ts +0 -51
  230. package/src/eth_cheat_codes.ts +0 -314
  231. package/src/l1_tx_utils.ts +0 -847
  232. package/src/l1_tx_utils_with_blobs.ts +0 -86
@@ -0,0 +1,307 @@
1
+ import { RollupContract, type ViemPublicClient } from '@aztec/ethereum';
2
+ import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
3
+ import { EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
4
+ import { EthAddress } from '@aztec/foundation/eth-address';
5
+ import { createLogger } from '@aztec/foundation/log';
6
+ import type { DateProvider } from '@aztec/foundation/timer';
7
+ import { RollupAbi } from '@aztec/l1-artifacts/RollupAbi';
8
+
9
+ import {
10
+ type GetContractReturnType,
11
+ type Hex,
12
+ createPublicClient,
13
+ fallback,
14
+ getContract,
15
+ hexToBigInt,
16
+ http,
17
+ } from 'viem';
18
+
19
+ import { EthCheatCodes } from './eth_cheat_codes.js';
20
+
21
+ /** Cheat codes for the L1 rollup contract. */
22
+ export class RollupCheatCodes {
23
+ private client: ViemPublicClient;
24
+ private rollup: GetContractReturnType<typeof RollupAbi, ViemPublicClient>;
25
+
26
+ private logger = createLogger('aztecjs:cheat_codes');
27
+
28
+ constructor(
29
+ private ethCheatCodes: EthCheatCodes,
30
+ addresses: Pick<L1ContractAddresses, 'rollupAddress'>,
31
+ ) {
32
+ this.client = createPublicClient({
33
+ chain: ethCheatCodes.chain,
34
+ transport: fallback(ethCheatCodes.rpcUrls.map(url => http(url))),
35
+ });
36
+ this.rollup = getContract({
37
+ abi: RollupAbi,
38
+ address: addresses.rollupAddress.toString(),
39
+ client: this.client,
40
+ });
41
+ }
42
+
43
+ static create(
44
+ rpcUrls: string[],
45
+ addresses: Pick<L1ContractAddresses, 'rollupAddress'>,
46
+ dateProvider: DateProvider,
47
+ ): RollupCheatCodes {
48
+ const ethCheatCodes = new EthCheatCodes(rpcUrls, dateProvider);
49
+ return new RollupCheatCodes(ethCheatCodes, addresses);
50
+ }
51
+
52
+ /** Returns the current slot */
53
+ public async getSlot(): Promise<SlotNumber> {
54
+ const ts = BigInt((await this.client.getBlock()).timestamp);
55
+ return SlotNumber.fromBigInt(await this.rollup.read.getSlotAt([ts]));
56
+ }
57
+
58
+ /** Returns the current epoch */
59
+ public async getEpoch(): Promise<EpochNumber> {
60
+ const slotNumber = await this.getSlot();
61
+ return EpochNumber.fromBigInt(await this.rollup.read.getEpochAtSlot([BigInt(slotNumber)]));
62
+ }
63
+
64
+ /**
65
+ * Returns the pending and proven chain tips
66
+ * @returns The pending and proven chain tips
67
+ */
68
+ public async getTips(): Promise<{
69
+ /** The pending chain tip */ pending: bigint;
70
+ /** The proven chain tip */ proven: bigint;
71
+ }> {
72
+ return await this.rollup.read.getTips();
73
+ }
74
+
75
+ /**
76
+ * Logs the current state of the rollup contract.
77
+ */
78
+ public async debugRollup() {
79
+ const rollup = new RollupContract(this.client, this.rollup.address);
80
+ const pendingNum = await rollup.getCheckpointNumber();
81
+ const provenNum = await rollup.getProvenCheckpointNumber();
82
+ const validators = await rollup.getAttesters();
83
+ const committee = await rollup.getCurrentEpochCommittee();
84
+ const archive = await rollup.archive();
85
+ const slot = await this.getSlot();
86
+ const epochNum = await rollup.getEpochNumberForSlotNumber(slot);
87
+
88
+ this.logger.info(`Pending checkpoint num: ${pendingNum}`);
89
+ this.logger.info(`Proven checkpoint num: ${provenNum}`);
90
+ this.logger.info(`Validators: ${validators.map(v => v.toString()).join(', ')}`);
91
+ this.logger.info(`Committee: ${committee?.map(v => v.toString()).join(', ')}`);
92
+ this.logger.info(`Archive: ${archive}`);
93
+ this.logger.info(`Epoch num: ${epochNum}`);
94
+ this.logger.info(`Slot: ${slot}`);
95
+ }
96
+
97
+ /** Fetches the epoch and slot duration config from the rollup contract */
98
+ public async getConfig(): Promise<{
99
+ /** Epoch duration */ epochDuration: bigint;
100
+ /** Slot duration */ slotDuration: number;
101
+ }> {
102
+ const [epochDuration, slotDuration] = await Promise.all([
103
+ this.rollup.read.getEpochDuration(),
104
+ this.rollup.read.getSlotDuration(),
105
+ ]);
106
+ return { epochDuration, slotDuration: Number(slotDuration) };
107
+ }
108
+
109
+ /**
110
+ * Advances time to the beginning of the given epoch
111
+ * @param epoch - The epoch to advance to
112
+ * @param opts - Options
113
+ */
114
+ public async advanceToEpoch(
115
+ epoch: EpochNumber,
116
+ opts: {
117
+ /** Offset in seconds */
118
+ offset?: number;
119
+ } = {},
120
+ ) {
121
+ const { epochDuration: slotsInEpoch } = await this.getConfig();
122
+ const slotNumber = SlotNumber(epoch * Number(slotsInEpoch));
123
+ const timestamp = (await this.rollup.read.getTimestampForSlot([BigInt(slotNumber)])) + BigInt(opts.offset ?? 0);
124
+ try {
125
+ await this.ethCheatCodes.warp(Number(timestamp), { ...opts, silent: true, resetBlockInterval: true });
126
+ this.logger.warn(`Warped to epoch ${epoch}`);
127
+ } catch (err) {
128
+ this.logger.warn(`Warp to epoch ${epoch} failed: ${err}`);
129
+ }
130
+ return timestamp;
131
+ }
132
+
133
+ /** Warps time in L1 until the next epoch */
134
+ public async advanceToNextEpoch() {
135
+ const slot = await this.getSlot();
136
+ const { epochDuration, slotDuration } = await this.getConfig();
137
+ const slotsUntilNextEpoch = epochDuration - (BigInt(slot) % epochDuration) + 1n;
138
+ const timeToNextEpoch = slotsUntilNextEpoch * BigInt(slotDuration);
139
+ const l1Timestamp = BigInt((await this.client.getBlock()).timestamp);
140
+ await this.ethCheatCodes.warp(Number(l1Timestamp + timeToNextEpoch), {
141
+ silent: true,
142
+ resetBlockInterval: true,
143
+ });
144
+ this.logger.warn(`Advanced to next epoch`);
145
+ }
146
+
147
+ /** Warps time in L1 until the beginning of the next slot. */
148
+ public async advanceToNextSlot() {
149
+ const currentSlot = await this.getSlot();
150
+ const nextSlot = SlotNumber(currentSlot + 1);
151
+ const timestamp = await this.rollup.read.getTimestampForSlot([BigInt(nextSlot)]);
152
+ await this.ethCheatCodes.warp(Number(timestamp), { silent: true, resetBlockInterval: true });
153
+ this.logger.warn(`Advanced to slot ${nextSlot}`);
154
+ return [timestamp, nextSlot];
155
+ }
156
+
157
+ /**
158
+ * Warps time in L1 equivalent to however many slots.
159
+ * @param howMany - The number of slots to advance.
160
+ */
161
+ public async advanceSlots(howMany: number) {
162
+ const l1Timestamp = (await this.client.getBlock()).timestamp;
163
+ const slotDuration = Number(await this.rollup.read.getSlotDuration());
164
+ const timeToWarp = BigInt(howMany) * BigInt(slotDuration);
165
+ await this.ethCheatCodes.warp(l1Timestamp + timeToWarp, { silent: true, resetBlockInterval: true });
166
+ const [slot, epoch] = await Promise.all([this.getSlot(), this.getEpoch()]);
167
+ this.logger.warn(`Advanced ${howMany} slots up to slot ${slot} in epoch ${epoch}`);
168
+ }
169
+
170
+ /**
171
+ * Marks the specified checkpoint (or latest if none) as proven
172
+ * @param maybeCheckpointNumber - The checkpoint number to mark as proven (defaults to latest pending)
173
+ */
174
+ public markAsProven(maybeCheckpointNumber?: number | bigint) {
175
+ return this.ethCheatCodes.execWithPausedAnvil(async () => {
176
+ const tipsBefore = await this.getTips();
177
+ const { pending, proven } = tipsBefore;
178
+
179
+ let checkpointNumber = maybeCheckpointNumber;
180
+ if (checkpointNumber === undefined || checkpointNumber > pending) {
181
+ checkpointNumber = pending;
182
+ }
183
+ if (checkpointNumber <= proven) {
184
+ this.logger.debug(`Checkpoint ${checkpointNumber} is already proven`);
185
+ return;
186
+ }
187
+
188
+ // @note @LHerskind this is heavily dependent on the storage layout and size of values
189
+ // The rollupStore is a struct and if the size of elements or the struct changes, this can break
190
+ const provenCheckpointNumberSlot = hexToBigInt(RollupContract.stfStorageSlot);
191
+
192
+ // Need to pack it as a single 32 byte word
193
+ const newValue = (BigInt(tipsBefore.pending) << 128n) | BigInt(checkpointNumber);
194
+ await this.ethCheatCodes.store(EthAddress.fromString(this.rollup.address), provenCheckpointNumberSlot, newValue);
195
+
196
+ const tipsAfter = await this.getTips();
197
+ if (tipsAfter.pending < tipsAfter.proven) {
198
+ throw new Error('Overwrote pending tip to a checkpoint in the past');
199
+ }
200
+
201
+ this.logger.info(
202
+ `Proven tip moved: ${tipsBefore.proven} -> ${tipsAfter.proven}. Pending tip: ${tipsAfter.pending}.`,
203
+ );
204
+ });
205
+ }
206
+
207
+ /**
208
+ * Overrides the inProgress field of the Inbox contract state
209
+ * @param howMuch - How many checkpoints to move it forward
210
+ */
211
+ public advanceInboxInProgress(howMuch: number | bigint): Promise<bigint> {
212
+ return this.ethCheatCodes.execWithPausedAnvil(async () => {
213
+ // Storage slot 2 contains the InboxState struct
214
+ const inboxStateSlot = 2n;
215
+
216
+ // Get inbox and its current state values
217
+ const inboxAddress = await this.rollup.read.getInbox();
218
+ const currentStateValue = await this.ethCheatCodes.load(EthAddress.fromString(inboxAddress), inboxStateSlot);
219
+
220
+ // Extract current values from the packed storage slot
221
+ // Storage layout: rollingHash (128 bits) | totalMessagesInserted (64 bits) | inProgress (64 bits)
222
+ const currentRollingHash = currentStateValue & ((1n << 128n) - 1n);
223
+ const currentTotalMessages = (currentStateValue >> 128n) & ((1n << 64n) - 1n);
224
+ const currentInProgress = currentStateValue >> 192n;
225
+ const newInProgress = currentInProgress + BigInt(howMuch);
226
+
227
+ // Pack new values: rollingHash (low 128 bits) | totalMessages (middle 64 bits) | inProgress (high 64 bits)
228
+ const newValue = (BigInt(newInProgress) << 192n) | (currentTotalMessages << 128n) | currentRollingHash;
229
+
230
+ await this.ethCheatCodes.store(EthAddress.fromString(inboxAddress), inboxStateSlot, newValue, {
231
+ silent: true,
232
+ });
233
+
234
+ this.logger.warn(`Inbox inProgress advanced from ${currentInProgress} to ${newInProgress}`, {
235
+ inbox: inboxAddress,
236
+ oldValue: '0x' + currentStateValue.toString(16),
237
+ newValue: '0x' + newValue.toString(16),
238
+ rollingHash: currentRollingHash,
239
+ totalMessages: currentTotalMessages,
240
+ oldInProgress: currentInProgress,
241
+ newInProgress,
242
+ });
243
+
244
+ return newInProgress;
245
+ });
246
+ }
247
+
248
+ /**
249
+ * Executes an action impersonated as the owner of the Rollup contract.
250
+ * @param action - The action to execute
251
+ */
252
+ public async asOwner(
253
+ action: (owner: Hex, rollup: GetContractReturnType<typeof RollupAbi, ViemPublicClient>) => Promise<void>,
254
+ ) {
255
+ const owner = await this.rollup.read.owner();
256
+ await this.ethCheatCodes.startImpersonating(owner);
257
+ await action(owner, this.rollup);
258
+ await this.ethCheatCodes.stopImpersonating(owner);
259
+ }
260
+
261
+ /**
262
+ * Sets up the epoch.
263
+ */
264
+ public async setupEpoch() {
265
+ // Doesn't need to be done as owner, but the functionality is here...
266
+ await this.asOwner(async (account, rollup) => {
267
+ const hash = await rollup.write.setupEpoch({ account });
268
+ await this.client.waitForTransactionReceipt({ hash });
269
+ this.logger.warn(`Setup epoch`);
270
+ });
271
+ }
272
+
273
+ /** Directly calls the L1 gas fee oracle. */
274
+ public async updateL1GasFeeOracle() {
275
+ await this.asOwner(async (account, rollup) => {
276
+ const hash = await rollup.write.updateL1GasFeeOracle({ account, chain: this.client.chain });
277
+ await this.client.waitForTransactionReceipt({ hash });
278
+ this.logger.warn(`Updated L1 gas fee oracle`);
279
+ });
280
+ }
281
+
282
+ /**
283
+ * Bumps proving cost per mana.
284
+ * @param bumper - Callback to calculate the new proving cost per mana based on current value.
285
+ */
286
+ public async bumpProvingCostPerMana(bumper: (before: bigint) => bigint) {
287
+ const currentCost = await this.rollup.read.getProvingCostPerManaInEth();
288
+ const newCost = bumper(currentCost);
289
+ await this.setProvingCostPerMana(newCost);
290
+ }
291
+
292
+ /**
293
+ * Directly updates proving cost per mana.
294
+ * @param ethValue - The new proving cost per mana in ETH
295
+ */
296
+ public async setProvingCostPerMana(ethValue: bigint) {
297
+ await this.asOwner(async (account, rollup) => {
298
+ const hash = await rollup.write.setProvingCostPerMana([ethValue], {
299
+ account,
300
+ chain: this.client.chain,
301
+ gasLimit: 1000000n,
302
+ });
303
+ await this.client.waitForTransactionReceipt({ hash });
304
+ this.logger.warn(`Updated proving cost per mana to ${ethValue}`);
305
+ });
306
+ }
307
+ }
@@ -1,3 +1,4 @@
1
+ import { createLogger } from '@aztec/foundation/log';
1
2
  import { makeBackoff, retry } from '@aztec/foundation/retry';
2
3
  import { fileURLToPath } from '@aztec/foundation/url';
3
4
 
@@ -9,10 +10,17 @@ import { dirname, resolve } from 'path';
9
10
  */
10
11
  export async function startAnvil(
11
12
  opts: {
13
+ port?: number;
12
14
  l1BlockTime?: number;
15
+ log?: boolean;
16
+ captureMethodCalls?: boolean;
17
+ accounts?: number;
18
+ chainId?: number;
13
19
  } = {},
14
- ): Promise<{ anvil: Anvil; rpcUrl: string; stop: () => Promise<void> }> {
20
+ ): Promise<{ anvil: Anvil; methodCalls?: string[]; rpcUrl: string; stop: () => Promise<void> }> {
15
21
  const anvilBinary = resolve(dirname(fileURLToPath(import.meta.url)), '../../', 'scripts/anvil_kill_wrapper.sh');
22
+ const logger = opts.log ? createLogger('ethereum:anvil') : undefined;
23
+ const methodCalls = opts.captureMethodCalls ? ([] as string[]) : undefined;
16
24
 
17
25
  let port: number | undefined;
18
26
 
@@ -22,19 +30,28 @@ export async function startAnvil(
22
30
  async () => {
23
31
  const anvil = createAnvil({
24
32
  anvilBinary,
25
- port: 0,
33
+ host: '127.0.0.1',
34
+ port: opts.port ?? 8545,
26
35
  blockTime: opts.l1BlockTime,
27
36
  stopTimeout: 1000,
37
+ accounts: opts.accounts ?? 20,
38
+ gasLimit: 45_000_000n,
39
+ chainId: opts.chainId ?? 31337,
28
40
  });
29
41
 
30
42
  // Listen to the anvil output to get the port.
31
43
  const removeHandler = anvil.on('message', (message: string) => {
44
+ logger?.debug(message.trim());
45
+
46
+ methodCalls?.push(...(message.match(/eth_[^\s]+/g) || []));
32
47
  if (port === undefined && message.includes('Listening on')) {
33
48
  port = parseInt(message.match(/Listening on ([^:]+):(\d+)/)![2]);
34
49
  }
35
50
  });
36
51
  await anvil.start();
37
- removeHandler();
52
+ if (!logger && !opts.captureMethodCalls) {
53
+ removeHandler();
54
+ }
38
55
 
39
56
  return anvil;
40
57
  },
@@ -47,6 +64,6 @@ export async function startAnvil(
47
64
  }
48
65
 
49
66
  // Monkeypatch the anvil instance to include the actually assigned port
50
- Object.defineProperty(anvil, 'port', { value: port, writable: false });
51
- return { anvil, stop: () => anvil.stop(), rpcUrl: `http://127.0.0.1:${port}` };
67
+ // Object.defineProperty(anvil, 'port', { value: port, writable: false });
68
+ return { anvil, methodCalls, stop: () => anvil.stop(), rpcUrl: `http://127.0.0.1:${port}` };
52
69
  }
@@ -1,21 +1,29 @@
1
1
  import { omit } from '@aztec/foundation/collection';
2
2
  import { type Logger, createLogger } from '@aztec/foundation/log';
3
3
  import { retryUntil } from '@aztec/foundation/retry';
4
+ import type { DateProvider } from '@aztec/foundation/timer';
4
5
 
5
6
  import { inspect } from 'util';
6
7
  import {
7
8
  type Client,
8
9
  type Hex,
9
10
  type PublicClient,
11
+ type TransactionSerializableEIP4844,
10
12
  keccak256,
11
13
  parseTransaction,
12
14
  publicActions,
15
+ serializeTransaction,
13
16
  walletActions,
14
17
  } from 'viem';
15
18
 
16
- import type { ViemWalletClient } from '../types.js';
19
+ import { type ViemClient, isExtendedClient } from '../types.js';
17
20
 
18
- export function waitUntilBlock<T extends Client>(client: T, blockNumber: number | bigint, logger?: Logger) {
21
+ export function waitUntilBlock<T extends Client>(
22
+ client: T,
23
+ blockNumber: number | bigint,
24
+ logger?: Logger,
25
+ timeout?: number,
26
+ ) {
19
27
  const publicClient =
20
28
  'getBlockNumber' in client && typeof client.getBlockNumber === 'function'
21
29
  ? (client as unknown as PublicClient)
@@ -28,12 +36,17 @@ export function waitUntilBlock<T extends Client>(client: T, blockNumber: number
28
36
  return currentBlockNumber >= BigInt(blockNumber);
29
37
  },
30
38
  `Wait until L1 block ${blockNumber}`,
31
- 120,
39
+ timeout ?? 120,
32
40
  0.1,
33
41
  );
34
42
  }
35
43
 
36
- export function waitUntilL1Timestamp<T extends Client>(client: T, timestamp: number | bigint, logger?: Logger) {
44
+ export function waitUntilL1Timestamp<T extends Client>(
45
+ client: T,
46
+ timestamp: number | bigint,
47
+ logger?: Logger,
48
+ timeout?: number,
49
+ ) {
37
50
  const publicClient =
38
51
  'getBlockNumber' in client && typeof client.getBlockNumber === 'function'
39
52
  ? (client as unknown as PublicClient)
@@ -53,31 +66,51 @@ export function waitUntilL1Timestamp<T extends Client>(client: T, timestamp: num
53
66
  return currentTs >= BigInt(timestamp);
54
67
  },
55
68
  `Wait until L1 timestamp ${timestamp}`,
56
- 120,
69
+ timeout ?? 120,
57
70
  0.1,
58
71
  );
59
72
  }
60
73
 
61
74
  export interface Delayer {
62
- /** Returns the list of all txs (not just the delayed ones) sent through the attached client. */
63
- getTxs(): Hex[];
75
+ /** Returns the hashes of all effectively sent txs. */
76
+ getSentTxHashes(): Hex[];
77
+ /** Returns the raw hex for all cancelled txs. */
78
+ getCancelledTxs(): Hex[];
64
79
  /** Delays the next tx to be sent so it lands on the given L1 block number. */
65
80
  pauseNextTxUntilBlock(l1BlockNumber: number | bigint | undefined): void;
66
81
  /** Delays the next tx to be sent so it lands on the given timestamp. */
67
82
  pauseNextTxUntilTimestamp(l1Timestamp: number | bigint | undefined): void;
83
+ /** Delays the next tx to be sent indefinitely. */
84
+ cancelNextTx(): void;
85
+ /**
86
+ * Sets max inclusion time into slot. If more than this many seconds have passed
87
+ * since the last L1 block was mined, then any tx will not be mined in the current
88
+ * L1 slot but will be deferred for the next one.
89
+ */
90
+ setMaxInclusionTimeIntoSlot(seconds: number | bigint | undefined): void;
68
91
  }
69
92
 
70
93
  class DelayerImpl implements Delayer {
71
- constructor(opts: { ethereumSlotDuration: bigint | number }) {
94
+ private logger = createLogger('ethereum:tx_delayer');
95
+ constructor(
96
+ public dateProvider: DateProvider,
97
+ opts: { ethereumSlotDuration: bigint | number },
98
+ ) {
72
99
  this.ethereumSlotDuration = BigInt(opts.ethereumSlotDuration);
73
100
  }
74
101
 
102
+ public maxInclusionTimeIntoSlot: number | undefined = undefined;
75
103
  public ethereumSlotDuration: bigint;
76
- public nextWait: { l1Timestamp: bigint } | { l1BlockNumber: bigint } | undefined = undefined;
77
- public txs: Hex[] = [];
104
+ public nextWait: { l1Timestamp: bigint } | { l1BlockNumber: bigint } | { indefinitely: true } | undefined = undefined;
105
+ public sentTxHashes: Hex[] = [];
106
+ public cancelledTxs: Hex[] = [];
107
+
108
+ getSentTxHashes() {
109
+ return this.sentTxHashes;
110
+ }
78
111
 
79
- getTxs() {
80
- return this.txs;
112
+ getCancelledTxs(): Hex[] {
113
+ return this.cancelledTxs;
81
114
  }
82
115
 
83
116
  pauseNextTxUntilBlock(l1BlockNumber: number | bigint) {
@@ -87,6 +120,14 @@ class DelayerImpl implements Delayer {
87
120
  pauseNextTxUntilTimestamp(l1Timestamp: number | bigint) {
88
121
  this.nextWait = { l1Timestamp: BigInt(l1Timestamp) };
89
122
  }
123
+
124
+ cancelNextTx() {
125
+ this.nextWait = { indefinitely: true };
126
+ }
127
+
128
+ setMaxInclusionTimeIntoSlot(seconds: number | undefined) {
129
+ this.maxInclusionTimeIntoSlot = seconds;
130
+ }
90
131
  }
91
132
 
92
133
  /**
@@ -94,12 +135,17 @@ class DelayerImpl implements Delayer {
94
135
  * The delayer can be used to hold off the next tx to be sent until a given block number.
95
136
  * TODO(#10824): This doesn't play along well with blob txs for some reason.
96
137
  */
97
- export function withDelayer<T extends ViemWalletClient>(
138
+ export function withDelayer<T extends ViemClient>(
98
139
  client: T,
140
+ dateProvider: DateProvider,
99
141
  opts: { ethereumSlotDuration: bigint | number },
100
142
  ): { client: T; delayer: Delayer } {
143
+ if (!isExtendedClient(client)) {
144
+ throw new Error('withDelayer has to be instantiated with a wallet viem client.');
145
+ }
101
146
  const logger = createLogger('ethereum:tx_delayer');
102
- const delayer = new DelayerImpl(opts);
147
+ const delayer = new DelayerImpl(dateProvider, opts);
148
+
103
149
  const extended = client
104
150
  // Tweak sendRawTransaction so it uses the delay defined in the delayer.
105
151
  // Note that this will only work with local accounts (ie accounts for which we have the private key).
@@ -107,28 +153,68 @@ export function withDelayer<T extends ViemWalletClient>(
107
153
  // but we do not use them in our codebase at all.
108
154
  .extend(client => ({
109
155
  async sendRawTransaction(...args) {
156
+ let wait: Promise<unknown> | undefined;
157
+ let txHash: Hex | undefined;
158
+
159
+ const { serializedTransaction } = args[0];
160
+ const publicClient = client as unknown as PublicClient;
161
+
110
162
  if (delayer.nextWait !== undefined) {
163
+ // Check if we have been instructed to delay the next tx.
111
164
  const waitUntil = delayer.nextWait;
112
165
  delayer.nextWait = undefined;
113
166
 
114
- const publicClient = client as unknown as PublicClient;
115
- const wait =
167
+ // Compute the tx hash manually so we emulate sendRawTransaction response
168
+ txHash = computeTxHash(serializedTransaction);
169
+
170
+ // Cancel tx outright if instructed
171
+ if ('indefinitely' in waitUntil && waitUntil.indefinitely) {
172
+ logger.info(`Cancelling tx ${txHash}`);
173
+ delayer.cancelledTxs.push(serializedTransaction);
174
+ return Promise.resolve(txHash);
175
+ }
176
+
177
+ // Or wait until the desired block number or timestamp
178
+ wait =
116
179
  'l1BlockNumber' in waitUntil
117
180
  ? waitUntilBlock(publicClient, waitUntil.l1BlockNumber - 1n, logger)
118
- : waitUntilL1Timestamp(publicClient, waitUntil.l1Timestamp - delayer.ethereumSlotDuration, logger);
181
+ : 'l1Timestamp' in waitUntil
182
+ ? waitUntilL1Timestamp(publicClient, waitUntil.l1Timestamp - delayer.ethereumSlotDuration, logger)
183
+ : undefined;
119
184
 
120
- // Compute the tx hash manually so we emulate sendRawTransaction response
121
- const { serializedTransaction } = args[0];
122
- const txHash = keccak256(serializedTransaction);
123
185
  logger.info(`Delaying tx ${txHash} until ${inspect(waitUntil)}`, {
124
186
  argsLen: args.length,
125
187
  ...omit(parseTransaction(serializedTransaction), 'data', 'sidecars'),
126
188
  });
189
+ } else if (delayer.maxInclusionTimeIntoSlot !== undefined) {
190
+ // Check if we need to delay txs sent too close to the end of the slot.
191
+ const currentBlock = await publicClient.getBlock({ includeTransactions: false });
192
+ const { timestamp: lastBlockTimestamp, number } = currentBlock;
193
+ const now = delayer.dateProvider.now();
194
+
195
+ txHash = computeTxHash(serializedTransaction);
196
+ const logData = {
197
+ ...omit(parseTransaction(serializedTransaction), 'data', 'sidecars'),
198
+ lastBlockTimestamp,
199
+ now,
200
+ maxInclusionTimeIntoSlot: delayer.maxInclusionTimeIntoSlot,
201
+ };
202
+
203
+ if (now / 1000 - Number(lastBlockTimestamp) > delayer.maxInclusionTimeIntoSlot) {
204
+ // If the last block was mined more than `maxInclusionTimeIntoSlot` seconds ago, then we cannot include
205
+ // any txs in the current slot, so we delay the tx until the next slot.
206
+ logger.info(`Delaying inclusion of tx ${txHash} until the next slot since it was sent too late`, logData);
207
+ wait = waitUntilBlock(publicClient, number + 1n, logger);
208
+ } else {
209
+ logger.debug(`Immediately sending tx ${txHash} as it was received early enough in the slot`, logData);
210
+ }
211
+ }
127
212
 
213
+ if (wait !== undefined) {
128
214
  // Do not await here so we can return the tx hash immediately as if it had been sent on the spot.
129
215
  // Instead, delay it so it lands on the desired block number or timestamp, assuming anvil will
130
216
  // mine it immediately.
131
- void wait
217
+ void wait!
132
218
  .then(async () => {
133
219
  const clientTxHash = await client.sendRawTransaction(...args);
134
220
  if (clientTxHash !== txHash) {
@@ -137,16 +223,15 @@ export function withDelayer<T extends ViemWalletClient>(
137
223
  computedTxHash: txHash,
138
224
  });
139
225
  }
140
- logger.info(`Sent previously delayed tx ${clientTxHash} to land on ${inspect(waitUntil)}`);
141
- delayer.txs.push(clientTxHash);
226
+ logger.info(`Sent previously delayed tx ${clientTxHash}`);
227
+ delayer.sentTxHashes.push(clientTxHash);
142
228
  })
143
229
  .catch(err => logger.error(`Error sending tx after delay`, err));
144
-
145
- return Promise.resolve(txHash);
230
+ return Promise.resolve(txHash!);
146
231
  } else {
147
232
  const txHash = await client.sendRawTransaction(...args);
148
233
  logger.verbose(`Sent tx immediately ${txHash}`);
149
- delayer.txs.push(txHash);
234
+ delayer.sentTxHashes.push(txHash);
150
235
  return txHash;
151
236
  }
152
237
  },
@@ -161,3 +246,19 @@ export function withDelayer<T extends ViemWalletClient>(
161
246
 
162
247
  return { client: extended, delayer };
163
248
  }
249
+
250
+ /**
251
+ * Compute the tx hash given the serialized tx. Note that if this is a blob tx, we need to
252
+ * exclude the blobs, commitments, and proofs from the hash.
253
+ */
254
+ function computeTxHash(serializedTransaction: Hex) {
255
+ if (serializedTransaction.startsWith('0x03')) {
256
+ const parsed = parseTransaction(serializedTransaction);
257
+ if (parsed.blobs || parsed.sidecars) {
258
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
259
+ const { blobs, sidecars, ...rest } = parsed;
260
+ return keccak256(serializeTransaction({ type: 'eip4844', ...rest } as TransactionSerializableEIP4844));
261
+ }
262
+ }
263
+ return keccak256(serializedTransaction);
264
+ }