@aztec/ethereum 4.0.0-nightly.20250907 → 4.0.0-nightly.20260107

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 (226) hide show
  1. package/dest/account.d.ts +1 -1
  2. package/dest/chain.d.ts +1 -1
  3. package/dest/client.d.ts +2 -2
  4. package/dest/client.d.ts.map +1 -1
  5. package/dest/client.js +6 -2
  6. package/dest/config.d.ts +18 -46
  7. package/dest/config.d.ts.map +1 -1
  8. package/dest/config.js +40 -285
  9. package/dest/constants.d.ts +1 -1
  10. package/dest/contracts/empire_base.d.ts +8 -6
  11. package/dest/contracts/empire_base.d.ts.map +1 -1
  12. package/dest/contracts/empire_base.js +1 -1
  13. package/dest/contracts/empire_slashing_proposer.d.ts +8 -6
  14. package/dest/contracts/empire_slashing_proposer.d.ts.map +1 -1
  15. package/dest/contracts/empire_slashing_proposer.js +18 -3
  16. package/dest/contracts/errors.d.ts +1 -1
  17. package/dest/contracts/errors.d.ts.map +1 -1
  18. package/dest/contracts/fee_asset_handler.d.ts +4 -4
  19. package/dest/contracts/fee_asset_handler.d.ts.map +1 -1
  20. package/dest/contracts/fee_juice.d.ts +1 -1
  21. package/dest/contracts/fee_juice.d.ts.map +1 -1
  22. package/dest/contracts/governance.d.ts +16 -16
  23. package/dest/contracts/governance.d.ts.map +1 -1
  24. package/dest/contracts/governance.js +7 -3
  25. package/dest/contracts/governance_proposer.d.ts +7 -6
  26. package/dest/contracts/governance_proposer.d.ts.map +1 -1
  27. package/dest/contracts/governance_proposer.js +400 -12
  28. package/dest/contracts/gse.d.ts +1 -1
  29. package/dest/contracts/gse.d.ts.map +1 -1
  30. package/dest/contracts/inbox.d.ts +7 -3
  31. package/dest/contracts/inbox.d.ts.map +1 -1
  32. package/dest/contracts/inbox.js +4 -0
  33. package/dest/contracts/index.d.ts +1 -1
  34. package/dest/contracts/multicall.d.ts +5 -7
  35. package/dest/contracts/multicall.d.ts.map +1 -1
  36. package/dest/contracts/multicall.js +6 -4
  37. package/dest/contracts/registry.d.ts +1 -1
  38. package/dest/contracts/registry.d.ts.map +1 -1
  39. package/dest/contracts/rollup.d.ts +168 -117
  40. package/dest/contracts/rollup.d.ts.map +1 -1
  41. package/dest/contracts/rollup.js +712 -241
  42. package/dest/contracts/slasher_contract.d.ts +11 -1
  43. package/dest/contracts/slasher_contract.d.ts.map +1 -1
  44. package/dest/contracts/slasher_contract.js +18 -0
  45. package/dest/contracts/tally_slashing_proposer.d.ts +15 -7
  46. package/dest/contracts/tally_slashing_proposer.d.ts.map +1 -1
  47. package/dest/contracts/tally_slashing_proposer.js +15 -5
  48. package/dest/contracts/utils.d.ts +1 -1
  49. package/dest/deploy_aztec_l1_contracts.d.ts +247 -0
  50. package/dest/deploy_aztec_l1_contracts.d.ts.map +1 -0
  51. package/dest/deploy_aztec_l1_contracts.js +336 -0
  52. package/dest/deploy_l1_contract.d.ts +68 -0
  53. package/dest/deploy_l1_contract.d.ts.map +1 -0
  54. package/dest/deploy_l1_contract.js +312 -0
  55. package/dest/eth-signer/eth-signer.d.ts +1 -1
  56. package/dest/eth-signer/index.d.ts +1 -1
  57. package/dest/forwarder_proxy.d.ts +32 -0
  58. package/dest/forwarder_proxy.d.ts.map +1 -0
  59. package/dest/forwarder_proxy.js +93 -0
  60. package/dest/l1_artifacts.d.ts +17698 -6245
  61. package/dest/l1_artifacts.d.ts.map +1 -1
  62. package/dest/l1_artifacts.js +10 -5
  63. package/dest/l1_contract_addresses.d.ts +8 -4
  64. package/dest/l1_contract_addresses.d.ts.map +1 -1
  65. package/dest/l1_contract_addresses.js +5 -4
  66. package/dest/l1_reader.d.ts +4 -2
  67. package/dest/l1_reader.d.ts.map +1 -1
  68. package/dest/l1_reader.js +7 -1
  69. package/dest/l1_tx_utils/config.d.ts +59 -0
  70. package/dest/l1_tx_utils/config.d.ts.map +1 -0
  71. package/dest/l1_tx_utils/config.js +96 -0
  72. package/dest/l1_tx_utils/constants.d.ts +12 -0
  73. package/dest/l1_tx_utils/constants.d.ts.map +1 -0
  74. package/dest/l1_tx_utils/constants.js +39 -0
  75. package/dest/l1_tx_utils/factory.d.ts +24 -0
  76. package/dest/l1_tx_utils/factory.d.ts.map +1 -0
  77. package/dest/l1_tx_utils/factory.js +12 -0
  78. package/dest/l1_tx_utils/fee-strategies/index.d.ts +10 -0
  79. package/dest/l1_tx_utils/fee-strategies/index.d.ts.map +1 -0
  80. package/dest/l1_tx_utils/fee-strategies/index.js +12 -0
  81. package/dest/l1_tx_utils/fee-strategies/p75_competitive.d.ts +8 -0
  82. package/dest/l1_tx_utils/fee-strategies/p75_competitive.d.ts.map +1 -0
  83. package/dest/l1_tx_utils/fee-strategies/p75_competitive.js +129 -0
  84. package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.d.ts +23 -0
  85. package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.d.ts.map +1 -0
  86. package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.js +191 -0
  87. package/dest/l1_tx_utils/fee-strategies/types.d.ts +51 -0
  88. package/dest/l1_tx_utils/fee-strategies/types.d.ts.map +1 -0
  89. package/dest/l1_tx_utils/fee-strategies/types.js +3 -0
  90. package/dest/l1_tx_utils/forwarder_l1_tx_utils.d.ts +41 -0
  91. package/dest/l1_tx_utils/forwarder_l1_tx_utils.d.ts.map +1 -0
  92. package/dest/l1_tx_utils/forwarder_l1_tx_utils.js +48 -0
  93. package/dest/l1_tx_utils/index-blobs.d.ts +3 -0
  94. package/dest/l1_tx_utils/index-blobs.d.ts.map +1 -0
  95. package/dest/l1_tx_utils/index-blobs.js +2 -0
  96. package/dest/l1_tx_utils/index.d.ts +12 -0
  97. package/dest/l1_tx_utils/index.d.ts.map +1 -0
  98. package/dest/l1_tx_utils/index.js +12 -0
  99. package/dest/l1_tx_utils/interfaces.d.ts +76 -0
  100. package/dest/l1_tx_utils/interfaces.d.ts.map +1 -0
  101. package/dest/l1_tx_utils/interfaces.js +4 -0
  102. package/dest/l1_tx_utils/l1_fee_analyzer.d.ts +233 -0
  103. package/dest/l1_tx_utils/l1_fee_analyzer.d.ts.map +1 -0
  104. package/dest/l1_tx_utils/l1_fee_analyzer.js +506 -0
  105. package/dest/l1_tx_utils/l1_tx_utils.d.ts +94 -0
  106. package/dest/l1_tx_utils/l1_tx_utils.d.ts.map +1 -0
  107. package/dest/l1_tx_utils/l1_tx_utils.js +623 -0
  108. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.d.ts +26 -0
  109. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.d.ts.map +1 -0
  110. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.js +26 -0
  111. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts +83 -0
  112. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts.map +1 -0
  113. package/dest/l1_tx_utils/readonly_l1_tx_utils.js +323 -0
  114. package/dest/l1_tx_utils/signer.d.ts +4 -0
  115. package/dest/l1_tx_utils/signer.d.ts.map +1 -0
  116. package/dest/l1_tx_utils/signer.js +16 -0
  117. package/dest/l1_tx_utils/types.d.ts +67 -0
  118. package/dest/l1_tx_utils/types.d.ts.map +1 -0
  119. package/dest/l1_tx_utils/types.js +26 -0
  120. package/dest/l1_tx_utils/utils.d.ts +4 -0
  121. package/dest/l1_tx_utils/utils.d.ts.map +1 -0
  122. package/dest/l1_tx_utils/utils.js +14 -0
  123. package/dest/l1_types.d.ts +1 -1
  124. package/dest/publisher_manager.d.ts +8 -3
  125. package/dest/publisher_manager.d.ts.map +1 -1
  126. package/dest/publisher_manager.js +36 -8
  127. package/dest/queries.d.ts +1 -1
  128. package/dest/queries.d.ts.map +1 -1
  129. package/dest/queries.js +20 -14
  130. package/dest/test/chain_monitor.d.ts +29 -22
  131. package/dest/test/chain_monitor.d.ts.map +1 -1
  132. package/dest/test/chain_monitor.js +81 -38
  133. package/dest/test/delayed_tx_utils.d.ts +3 -3
  134. package/dest/test/delayed_tx_utils.d.ts.map +1 -1
  135. package/dest/test/delayed_tx_utils.js +2 -2
  136. package/dest/test/eth_cheat_codes.d.ts +36 -14
  137. package/dest/test/eth_cheat_codes.d.ts.map +1 -1
  138. package/dest/test/eth_cheat_codes.js +126 -31
  139. package/dest/test/eth_cheat_codes_with_state.d.ts +1 -1
  140. package/dest/test/eth_cheat_codes_with_state.d.ts.map +1 -1
  141. package/dest/test/index.d.ts +1 -1
  142. package/dest/test/rollup_cheat_codes.d.ts +23 -20
  143. package/dest/test/rollup_cheat_codes.d.ts.map +1 -1
  144. package/dest/test/rollup_cheat_codes.js +82 -43
  145. package/dest/test/start_anvil.d.ts +4 -1
  146. package/dest/test/start_anvil.d.ts.map +1 -1
  147. package/dest/test/start_anvil.js +2 -1
  148. package/dest/test/tx_delayer.d.ts +1 -1
  149. package/dest/test/tx_delayer.d.ts.map +1 -1
  150. package/dest/test/tx_delayer.js +4 -3
  151. package/dest/test/upgrade_utils.d.ts +1 -1
  152. package/dest/test/upgrade_utils.d.ts.map +1 -1
  153. package/dest/test/upgrade_utils.js +3 -2
  154. package/dest/types.d.ts +57 -2
  155. package/dest/types.d.ts.map +1 -1
  156. package/dest/utils.d.ts +15 -3
  157. package/dest/utils.d.ts.map +1 -1
  158. package/dest/utils.js +28 -161
  159. package/dest/zkPassportVerifierAddress.d.ts +1 -1
  160. package/dest/zkPassportVerifierAddress.js +1 -1
  161. package/package.json +33 -14
  162. package/src/client.ts +3 -3
  163. package/src/config.ts +49 -358
  164. package/src/contracts/empire_base.ts +7 -6
  165. package/src/contracts/empire_slashing_proposer.ts +23 -8
  166. package/src/contracts/fee_asset_handler.ts +1 -1
  167. package/src/contracts/governance.ts +3 -3
  168. package/src/contracts/governance_proposer.ts +19 -9
  169. package/src/contracts/inbox.ts +7 -2
  170. package/src/contracts/multicall.ts +12 -10
  171. package/src/contracts/rollup.ts +373 -235
  172. package/src/contracts/slasher_contract.ts +22 -0
  173. package/src/contracts/tally_slashing_proposer.ts +21 -9
  174. package/src/deploy_aztec_l1_contracts.ts +557 -0
  175. package/src/deploy_l1_contract.ts +362 -0
  176. package/src/forwarder_proxy.ts +108 -0
  177. package/src/l1_artifacts.ts +14 -6
  178. package/src/l1_contract_addresses.ts +24 -20
  179. package/src/l1_reader.ts +10 -2
  180. package/src/l1_tx_utils/README.md +177 -0
  181. package/src/l1_tx_utils/config.ts +161 -0
  182. package/src/l1_tx_utils/constants.ts +29 -0
  183. package/src/l1_tx_utils/factory.ts +64 -0
  184. package/src/l1_tx_utils/fee-strategies/index.ts +22 -0
  185. package/src/l1_tx_utils/fee-strategies/p75_competitive.ts +163 -0
  186. package/src/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.ts +245 -0
  187. package/src/l1_tx_utils/fee-strategies/types.ts +56 -0
  188. package/src/l1_tx_utils/forwarder_l1_tx_utils.ts +119 -0
  189. package/src/l1_tx_utils/index-blobs.ts +2 -0
  190. package/src/l1_tx_utils/index.ts +14 -0
  191. package/src/l1_tx_utils/interfaces.ts +86 -0
  192. package/src/l1_tx_utils/l1_fee_analyzer.ts +803 -0
  193. package/src/l1_tx_utils/l1_tx_utils.ts +738 -0
  194. package/src/l1_tx_utils/l1_tx_utils_with_blobs.ts +77 -0
  195. package/src/l1_tx_utils/readonly_l1_tx_utils.ts +419 -0
  196. package/src/l1_tx_utils/signer.ts +28 -0
  197. package/src/l1_tx_utils/types.ts +85 -0
  198. package/src/l1_tx_utils/utils.ts +16 -0
  199. package/src/publisher_manager.ts +51 -9
  200. package/src/queries.ts +24 -10
  201. package/src/test/chain_monitor.ts +102 -44
  202. package/src/test/delayed_tx_utils.ts +2 -2
  203. package/src/test/eth_cheat_codes.ts +150 -31
  204. package/src/test/rollup_cheat_codes.ts +95 -53
  205. package/src/test/start_anvil.ts +4 -0
  206. package/src/test/tx_delayer.ts +5 -3
  207. package/src/test/upgrade_utils.ts +3 -2
  208. package/src/types.ts +62 -0
  209. package/src/utils.ts +41 -184
  210. package/src/zkPassportVerifierAddress.ts +1 -1
  211. package/dest/deploy_l1_contracts.d.ts +0 -211
  212. package/dest/deploy_l1_contracts.d.ts.map +0 -1
  213. package/dest/deploy_l1_contracts.js +0 -1267
  214. package/dest/index.d.ts +0 -18
  215. package/dest/index.d.ts.map +0 -1
  216. package/dest/index.js +0 -17
  217. package/dest/l1_tx_utils.d.ts +0 -250
  218. package/dest/l1_tx_utils.d.ts.map +0 -1
  219. package/dest/l1_tx_utils.js +0 -826
  220. package/dest/l1_tx_utils_with_blobs.d.ts +0 -19
  221. package/dest/l1_tx_utils_with_blobs.d.ts.map +0 -1
  222. package/dest/l1_tx_utils_with_blobs.js +0 -85
  223. package/src/deploy_l1_contracts.ts +0 -1596
  224. package/src/index.ts +0 -17
  225. package/src/l1_tx_utils.ts +0 -1105
  226. package/src/l1_tx_utils_with_blobs.ts +0 -144
@@ -1,1596 +0,0 @@
1
- import { L1_TO_L2_MSG_SUBTREE_HEIGHT } from '@aztec/constants';
2
- import { SecretValue, getActiveNetworkName } from '@aztec/foundation/config';
3
- import { keccak256String } from '@aztec/foundation/crypto';
4
- import { EthAddress } from '@aztec/foundation/eth-address';
5
- import type { Fr } from '@aztec/foundation/fields';
6
- import { jsonStringify } from '@aztec/foundation/json-rpc';
7
- import { type Logger, createLogger } from '@aztec/foundation/log';
8
- import { DateProvider } from '@aztec/foundation/timer';
9
- import type { RollupAbi } from '@aztec/l1-artifacts/RollupAbi';
10
-
11
- import type { Abi, Narrow } from 'abitype';
12
- import { mkdir, writeFile } from 'fs/promises';
13
- import {
14
- type Chain,
15
- type ContractConstructorArgs,
16
- type HDAccount,
17
- type Hex,
18
- type PrivateKeyAccount,
19
- concatHex,
20
- encodeAbiParameters,
21
- encodeDeployData,
22
- encodeFunctionData,
23
- getAddress,
24
- getContract,
25
- getContractAddress,
26
- numberToHex,
27
- padHex,
28
- } from 'viem';
29
- import { foundry } from 'viem/chains';
30
-
31
- import { isAnvilTestChain } from './chain.js';
32
- import { createExtendedL1Client } from './client.js';
33
- import {
34
- type L1ContractsConfig,
35
- getEntryQueueConfig,
36
- getGSEConfiguration,
37
- getGovernanceConfiguration,
38
- getRewardBoostConfig,
39
- getRewardConfig,
40
- validateConfig,
41
- } from './config.js';
42
- import { GSEContract } from './contracts/gse.js';
43
- import { deployMulticall3 } from './contracts/multicall.js';
44
- import { RegistryContract } from './contracts/registry.js';
45
- import { RollupContract, SlashingProposerType } from './contracts/rollup.js';
46
- import {
47
- CoinIssuerArtifact,
48
- FeeAssetArtifact,
49
- FeeAssetHandlerArtifact,
50
- GSEArtifact,
51
- GovernanceArtifact,
52
- GovernanceProposerArtifact,
53
- MultiAdderArtifact,
54
- RegisterNewRollupVersionPayloadArtifact,
55
- RegistryArtifact,
56
- RollupArtifact,
57
- SlashFactoryArtifact,
58
- StakingAssetArtifact,
59
- StakingAssetHandlerArtifact,
60
- l1ArtifactsVerifiers,
61
- mockVerifiers,
62
- } from './l1_artifacts.js';
63
- import type { L1ContractAddresses } from './l1_contract_addresses.js';
64
- import {
65
- type GasPrice,
66
- type L1GasConfig,
67
- type L1TxRequest,
68
- L1TxUtils,
69
- type L1TxUtilsConfig,
70
- createL1TxUtilsFromViemWallet,
71
- getL1TxUtilsConfigEnvVars,
72
- } from './l1_tx_utils.js';
73
- import type { ExtendedViemWalletClient } from './types.js';
74
- import { formatViemError } from './utils.js';
75
- import { ZK_PASSPORT_DOMAIN, ZK_PASSPORT_SCOPE, ZK_PASSPORT_VERIFIER_ADDRESS } from './zkPassportVerifierAddress.js';
76
-
77
- export const DEPLOYER_ADDRESS: Hex = '0x4e59b44847b379578588920cA78FbF26c0B4956C';
78
-
79
- const networkName = getActiveNetworkName();
80
-
81
- export type Operator = {
82
- attester: EthAddress;
83
- withdrawer: EthAddress;
84
- bn254SecretKey: SecretValue<bigint>;
85
- };
86
-
87
- /**
88
- * Return type of the deployL1Contract function.
89
- */
90
- export type DeployL1ContractsReturnType = {
91
- /** Extended Wallet Client Type. */
92
- l1Client: ExtendedViemWalletClient;
93
- /** The currently deployed l1 contract addresses */
94
- l1ContractAddresses: L1ContractAddresses;
95
- /** Version of the current rollup contract. */
96
- rollupVersion: number;
97
- };
98
-
99
- export interface LinkReferences {
100
- [fileName: string]: {
101
- [contractName: string]: ReadonlyArray<{
102
- start: number;
103
- length: number;
104
- }>;
105
- };
106
- }
107
-
108
- export interface Libraries {
109
- linkReferences: LinkReferences;
110
- libraryCode: Record<string, ContractArtifacts>;
111
- }
112
-
113
- /**
114
- * Contract artifacts
115
- */
116
- export interface ContractArtifacts<TAbi extends Abi | readonly unknown[] = Abi> {
117
- /**
118
- * The contract name.
119
- */
120
- name: string;
121
- /**
122
- * The contract abi.
123
- */
124
- contractAbi: Narrow<TAbi>;
125
- /**
126
- * The contract bytecode
127
- */
128
- contractBytecode: Hex;
129
- /**
130
- * The contract libraries
131
- */
132
- libraries?: Libraries;
133
- }
134
-
135
- export type VerificationLibraryEntry = {
136
- file: string;
137
- contract: string;
138
- address: string;
139
- };
140
-
141
- export type VerificationRecord = {
142
- name: string;
143
- address: string;
144
- constructorArgsHex: Hex;
145
- libraries: VerificationLibraryEntry[];
146
- };
147
-
148
- export interface DeployL1ContractsArgs extends Omit<L1ContractsConfig, keyof L1TxUtilsConfig> {
149
- /** The vk tree root. */
150
- vkTreeRoot: Fr;
151
- /** The protocol contract tree root. */
152
- protocolContractTreeRoot: Fr;
153
- /** The genesis root of the archive tree. */
154
- genesisArchiveRoot: Fr;
155
- /** The salt for CREATE2 deployment. */
156
- salt: number | undefined;
157
- /** The initial validators for the rollup contract. */
158
- initialValidators?: Operator[];
159
- /** Configuration for the L1 tx utils module. */
160
- l1TxConfig?: Partial<L1TxUtilsConfig>;
161
- /** Enable fast mode for deployments (fire and forget transactions) */
162
- acceleratedTestDeployments?: boolean;
163
- /** The initial balance of the fee juice portal. This is the amount of fee juice that is prefunded to accounts */
164
- feeJuicePortalInitialBalance?: bigint;
165
- /** Whether to deploy the real verifier or the mock verifier */
166
- realVerifier: boolean;
167
- /** The zk passport args */
168
- zkPassportArgs?: ZKPassportArgs;
169
- }
170
-
171
- export interface ZKPassportArgs {
172
- /** Whether to use the mock zk passport verifier */
173
- mockZkPassportVerifier?: boolean;
174
- /** The domain of the zk passport (url) */
175
- zkPassportDomain?: string;
176
- /** The scope of the zk passport (personhood, etc) */
177
- zkPassportScope?: string;
178
- }
179
-
180
- export const deploySharedContracts = async (
181
- l1Client: ExtendedViemWalletClient,
182
- deployer: L1Deployer,
183
- args: DeployL1ContractsArgs,
184
- logger: Logger,
185
- ) => {
186
- logger.info(`Deploying shared contracts for network configration: ${networkName}`);
187
-
188
- const txHashes: Hex[] = [];
189
-
190
- const feeAssetAddress = await deployer.deploy(FeeAssetArtifact, ['FeeJuice', 'FEE', l1Client.account.address]);
191
- logger.verbose(`Deployed Fee Asset at ${feeAssetAddress}`);
192
-
193
- const stakingAssetAddress = await deployer.deploy(StakingAssetArtifact, ['Staking', 'STK', l1Client.account.address]);
194
- logger.verbose(`Deployed Staking Asset at ${stakingAssetAddress}`);
195
-
196
- const gseConfiguration = getGSEConfiguration(networkName);
197
-
198
- const gseAddress = await deployer.deploy(GSEArtifact, [
199
- l1Client.account.address,
200
- stakingAssetAddress.toString(),
201
- gseConfiguration.activationThreshold,
202
- gseConfiguration.ejectionThreshold,
203
- ]);
204
- logger.verbose(`Deployed GSE at ${gseAddress}`);
205
-
206
- const registryAddress = await deployer.deploy(RegistryArtifact, [
207
- l1Client.account.address,
208
- feeAssetAddress.toString(),
209
- ]);
210
- logger.verbose(`Deployed Registry at ${registryAddress}`);
211
-
212
- const governanceProposerAddress = await deployer.deploy(GovernanceProposerArtifact, [
213
- registryAddress.toString(),
214
- gseAddress.toString(),
215
- BigInt(args.governanceProposerQuorum ?? args.governanceProposerRoundSize / 2 + 1),
216
- BigInt(args.governanceProposerRoundSize),
217
- ]);
218
- logger.verbose(`Deployed GovernanceProposer at ${governanceProposerAddress}`);
219
-
220
- // @note @LHerskind the assets are expected to be the same at some point, but for better
221
- // configurability they are different for now.
222
- const governanceAddress = await deployer.deploy(GovernanceArtifact, [
223
- stakingAssetAddress.toString(),
224
- governanceProposerAddress.toString(),
225
- gseAddress.toString(),
226
- getGovernanceConfiguration(networkName),
227
- ]);
228
- logger.verbose(`Deployed Governance at ${governanceAddress}`);
229
-
230
- let needToSetGovernance = false;
231
-
232
- const existingCode = await l1Client.getCode({ address: gseAddress.toString() });
233
- if (!existingCode || existingCode === '0x') {
234
- needToSetGovernance = true;
235
- } else {
236
- const gseContract = getContract({
237
- address: getAddress(gseAddress.toString()),
238
- abi: GSEArtifact.contractAbi,
239
- client: l1Client,
240
- });
241
- const existingGovernance = await gseContract.read.getGovernance();
242
- if (EthAddress.fromString(existingGovernance).equals(EthAddress.ZERO)) {
243
- needToSetGovernance = true;
244
- }
245
- }
246
-
247
- if (needToSetGovernance) {
248
- const { txHash } = await deployer.sendTransaction(
249
- {
250
- to: gseAddress.toString(),
251
- data: encodeFunctionData({
252
- abi: GSEArtifact.contractAbi,
253
- functionName: 'setGovernance',
254
- args: [governanceAddress.toString()],
255
- }),
256
- },
257
- { gasLimit: 100_000n },
258
- );
259
-
260
- logger.verbose(`Set governance on GSE in ${txHash}`);
261
- txHashes.push(txHash);
262
- }
263
-
264
- const coinIssuerAddress = await deployer.deploy(CoinIssuerArtifact, [
265
- feeAssetAddress.toString(),
266
- 1_000_000n * 10n ** 18n, // @todo #8084
267
- l1Client.account.address,
268
- ]);
269
- logger.verbose(`Deployed CoinIssuer at ${coinIssuerAddress}`);
270
-
271
- logger.verbose(`Waiting for deployments to complete`);
272
- await deployer.waitForDeployments();
273
-
274
- // Registry ownership will be transferred to governance later, after rollup is added
275
-
276
- let feeAssetHandlerAddress: EthAddress | undefined = undefined;
277
- let stakingAssetHandlerAddress: EthAddress | undefined = undefined;
278
- let zkPassportVerifierAddress: EthAddress | undefined = undefined;
279
-
280
- // Only if not on mainnet will we deploy the handlers
281
- if (l1Client.chain.id !== 1) {
282
- /* -------------------------------------------------------------------------- */
283
- /* CHEAT CODES START HERE */
284
- /* -------------------------------------------------------------------------- */
285
-
286
- feeAssetHandlerAddress = await deployer.deploy(FeeAssetHandlerArtifact, [
287
- l1Client.account.address,
288
- feeAssetAddress.toString(),
289
- BigInt(1000n * 10n ** 18n),
290
- ]);
291
- logger.verbose(`Deployed FeeAssetHandler at ${feeAssetHandlerAddress}`);
292
-
293
- // Only if we are "fresh" will we be adding as a minter, otherwise above will simply get same address
294
- if (needToSetGovernance) {
295
- const { txHash } = await deployer.sendTransaction({
296
- to: feeAssetAddress.toString(),
297
- data: encodeFunctionData({
298
- abi: FeeAssetArtifact.contractAbi,
299
- functionName: 'addMinter',
300
- args: [feeAssetHandlerAddress.toString()],
301
- }),
302
- });
303
- logger.verbose(`Added fee asset handler ${feeAssetHandlerAddress} as minter on fee asset in ${txHash}`);
304
- txHashes.push(txHash);
305
- }
306
-
307
- // Only if on sepolia will we deploy the staking asset handler
308
- // Should not be deployed to devnet since it would cause caos with sequencers there etc.
309
- if ([11155111, foundry.id].includes(l1Client.chain.id)) {
310
- const AMIN = EthAddress.fromString('0x3b218d0F26d15B36C715cB06c949210a0d630637');
311
- zkPassportVerifierAddress = await getZkPassportVerifierAddress(deployer, args);
312
- const [domain, scope] = getZkPassportScopes(args);
313
-
314
- const stakingAssetHandlerDeployArgs = {
315
- owner: l1Client.account.address,
316
- stakingAsset: stakingAssetAddress.toString(),
317
- registry: registryAddress.toString(),
318
- withdrawer: AMIN.toString(),
319
- mintInterval: BigInt(60 * 60 * 24),
320
- depositsPerMint: BigInt(10),
321
- depositMerkleRoot: '0x0000000000000000000000000000000000000000000000000000000000000000',
322
- zkPassportVerifier: zkPassportVerifierAddress.toString(),
323
- unhinged: [AMIN.toString()], // isUnhinged,
324
- // Scopes
325
- domain: domain,
326
- scope: scope,
327
- // Skip checks
328
- skipBindCheck: args.zkPassportArgs?.mockZkPassportVerifier ?? false,
329
- skipMerkleCheck: true, // skip merkle check - needed for testing without generating proofs
330
- } as const;
331
-
332
- stakingAssetHandlerAddress = await deployer.deploy(StakingAssetHandlerArtifact, [stakingAssetHandlerDeployArgs]);
333
- logger.verbose(`Deployed StakingAssetHandler at ${stakingAssetHandlerAddress}`);
334
-
335
- const { txHash: stakingMinterTxHash } = await deployer.sendTransaction({
336
- to: stakingAssetAddress.toString(),
337
- data: encodeFunctionData({
338
- abi: StakingAssetArtifact.contractAbi,
339
- functionName: 'addMinter',
340
- args: [stakingAssetHandlerAddress.toString()],
341
- }),
342
- });
343
- logger.verbose(
344
- `Added staking asset handler ${stakingAssetHandlerAddress} as minter on staking asset in ${stakingMinterTxHash}`,
345
- );
346
- txHashes.push(stakingMinterTxHash);
347
- }
348
- }
349
-
350
- /* -------------------------------------------------------------------------- */
351
- /* CHEAT CODES END HERE */
352
- /* -------------------------------------------------------------------------- */
353
-
354
- logger.verbose(`Waiting for deployments to complete`);
355
- await deployer.waitForDeployments();
356
- await Promise.all(txHashes.map(txHash => l1Client.waitForTransactionReceipt({ hash: txHash })));
357
-
358
- logger.verbose(`Deployed shared contracts`);
359
-
360
- const registry = new RegistryContract(l1Client, registryAddress);
361
-
362
- /* -------------------------------------------------------------------------- */
363
- /* FUND REWARD DISTRIBUTOR START */
364
- /* -------------------------------------------------------------------------- */
365
-
366
- const rewardDistributorAddress = await registry.getRewardDistributor();
367
-
368
- const blockReward = getRewardConfig(networkName).blockReward;
369
-
370
- const funding = blockReward * 200000n;
371
- const { txHash: fundRewardDistributorTxHash } = await deployer.sendTransaction({
372
- to: feeAssetAddress.toString(),
373
- data: encodeFunctionData({
374
- abi: FeeAssetArtifact.contractAbi,
375
- functionName: 'mint',
376
- args: [rewardDistributorAddress.toString(), funding],
377
- }),
378
- });
379
-
380
- logger.verbose(`Funded reward distributor with ${funding} fee asset in ${fundRewardDistributorTxHash}`);
381
-
382
- /* -------------------------------------------------------------------------- */
383
- /* FUND REWARD DISTRIBUTOR STOP */
384
- /* -------------------------------------------------------------------------- */
385
-
386
- return {
387
- feeAssetAddress,
388
- feeAssetHandlerAddress,
389
- stakingAssetAddress,
390
- stakingAssetHandlerAddress,
391
- zkPassportVerifierAddress,
392
- registryAddress,
393
- gseAddress,
394
- governanceAddress,
395
- governanceProposerAddress,
396
- coinIssuerAddress,
397
- rewardDistributorAddress: await registry.getRewardDistributor(),
398
- };
399
- };
400
-
401
- const getZkPassportVerifierAddress = async (deployer: L1Deployer, args: DeployL1ContractsArgs): Promise<EthAddress> => {
402
- if (args.zkPassportArgs?.mockZkPassportVerifier) {
403
- return await deployer.deploy(mockVerifiers.mockZkPassportVerifier);
404
- }
405
- return ZK_PASSPORT_VERIFIER_ADDRESS;
406
- };
407
-
408
- /**
409
- * Get the zk passport scopes - default to testnet values if not provided
410
- * @param args - The deployment arguments
411
- * @returns The zk passport scopes
412
- */
413
- const getZkPassportScopes = (args: DeployL1ContractsArgs): [string, string] => {
414
- const domain = args.zkPassportArgs?.zkPassportDomain ?? ZK_PASSPORT_DOMAIN;
415
- const scope = args.zkPassportArgs?.zkPassportScope ?? ZK_PASSPORT_SCOPE;
416
- return [domain, scope];
417
- };
418
-
419
- /**
420
- * Deploys a new rollup, using the existing canonical version to derive certain values (addresses of assets etc).
421
- * @param clients - The L1 clients.
422
- * @param args - The deployment arguments.
423
- * @param registryAddress - The address of the registry.
424
- * @param logger - The logger.
425
- * @param txUtilsConfig - The L1 tx utils config.
426
- */
427
- export const deployRollupForUpgrade = async (
428
- extendedClient: ExtendedViemWalletClient,
429
- args: Omit<
430
- DeployL1ContractsArgs,
431
- 'governanceProposerQuorum' | 'governanceProposerRoundSize' | 'ejectionThreshold' | 'activationThreshold'
432
- >,
433
- registryAddress: EthAddress,
434
- logger: Logger,
435
- txUtilsConfig: L1TxUtilsConfig,
436
- ) => {
437
- const deployer = new L1Deployer(
438
- extendedClient,
439
- args.salt,
440
- undefined,
441
- args.acceleratedTestDeployments,
442
- logger,
443
- txUtilsConfig,
444
- );
445
-
446
- const addresses = await RegistryContract.collectAddresses(extendedClient, registryAddress, 'canonical');
447
-
448
- const { rollup, slashFactoryAddress } = await deployRollup(extendedClient, deployer, args, addresses, logger);
449
-
450
- await deployer.waitForDeployments();
451
-
452
- return { rollup, slashFactoryAddress };
453
- };
454
-
455
- export const deploySlashFactory = async (deployer: L1Deployer, rollupAddress: Hex, logger: Logger) => {
456
- const slashFactoryAddress = await deployer.deploy(SlashFactoryArtifact, [rollupAddress]);
457
- logger.verbose(`Deployed SlashFactory at ${slashFactoryAddress}`);
458
- return slashFactoryAddress;
459
- };
460
-
461
- export const deployUpgradePayload = async (
462
- deployer: L1Deployer,
463
- addresses: Pick<L1ContractAddresses, 'registryAddress' | 'rollupAddress'>,
464
- ) => {
465
- const payloadAddress = await deployer.deploy(RegisterNewRollupVersionPayloadArtifact, [
466
- addresses.registryAddress.toString(),
467
- addresses.rollupAddress.toString(),
468
- ]);
469
-
470
- return payloadAddress;
471
- };
472
-
473
- function slasherFlavorToSolidityEnum(flavor: DeployL1ContractsArgs['slasherFlavor']): number {
474
- switch (flavor) {
475
- case 'none':
476
- return SlashingProposerType.None.valueOf();
477
- case 'tally':
478
- return SlashingProposerType.Tally.valueOf();
479
- case 'empire':
480
- return SlashingProposerType.Empire.valueOf();
481
- default: {
482
- const _: never = flavor;
483
- throw new Error(`Unexpected slasher flavor ${flavor}`);
484
- }
485
- }
486
- }
487
-
488
- /**
489
- * Deploys a new rollup contract, funds and initializes the fee juice portal, and initializes the validator set.
490
- */
491
- export const deployRollup = async (
492
- extendedClient: ExtendedViemWalletClient,
493
- deployer: L1Deployer,
494
- args: Omit<
495
- DeployL1ContractsArgs,
496
- 'governanceProposerQuorum' | 'governanceProposerRoundSize' | 'ejectionThreshold' | 'activationThreshold'
497
- >,
498
- addresses: Pick<
499
- L1ContractAddresses,
500
- | 'feeJuiceAddress'
501
- | 'registryAddress'
502
- | 'rewardDistributorAddress'
503
- | 'stakingAssetAddress'
504
- | 'gseAddress'
505
- | 'governanceAddress'
506
- >,
507
- logger: Logger,
508
- ) => {
509
- if (!addresses.gseAddress) {
510
- throw new Error('GSE address is required when deploying');
511
- }
512
-
513
- logger.info(`Deploying rollup using network configuration: ${networkName}`);
514
-
515
- const txHashes: Hex[] = [];
516
-
517
- let epochProofVerifier = EthAddress.ZERO;
518
-
519
- if (args.realVerifier) {
520
- epochProofVerifier = await deployer.deploy(l1ArtifactsVerifiers.honkVerifier);
521
- logger.verbose(`Rollup will use the real verifier at ${epochProofVerifier}`);
522
- } else {
523
- epochProofVerifier = await deployer.deploy(mockVerifiers.mockVerifier);
524
- logger.verbose(`Rollup will use the mock verifier at ${epochProofVerifier}`);
525
- }
526
-
527
- const rewardConfig = {
528
- ...getRewardConfig(networkName),
529
- rewardDistributor: addresses.rewardDistributorAddress.toString(),
530
- };
531
-
532
- const rollupConfigArgs: ContractConstructorArgs<typeof RollupAbi>[6] = {
533
- aztecSlotDuration: BigInt(args.aztecSlotDuration),
534
- aztecEpochDuration: BigInt(args.aztecEpochDuration),
535
- targetCommitteeSize: BigInt(args.aztecTargetCommitteeSize),
536
- aztecProofSubmissionEpochs: BigInt(args.aztecProofSubmissionEpochs),
537
- slashingQuorum: BigInt(args.slashingQuorum ?? (args.slashingRoundSizeInEpochs * args.aztecEpochDuration) / 2 + 1),
538
- slashingRoundSize: BigInt(args.slashingRoundSizeInEpochs * args.aztecEpochDuration),
539
- slashingLifetimeInRounds: BigInt(args.slashingLifetimeInRounds),
540
- slashingExecutionDelayInRounds: BigInt(args.slashingExecutionDelayInRounds),
541
- slashingVetoer: args.slashingVetoer.toString(),
542
- manaTarget: args.manaTarget,
543
- provingCostPerMana: args.provingCostPerMana,
544
- rewardConfig: rewardConfig,
545
- version: 0,
546
- rewardBoostConfig: getRewardBoostConfig(networkName),
547
- stakingQueueConfig: getEntryQueueConfig(networkName),
548
- exitDelaySeconds: BigInt(args.exitDelaySeconds),
549
- slasherFlavor: slasherFlavorToSolidityEnum(args.slasherFlavor),
550
- slashingOffsetInRounds: BigInt(args.slashingOffsetInRounds),
551
- slashAmounts: [args.slashAmountSmall, args.slashAmountMedium, args.slashAmountLarge],
552
- };
553
-
554
- const genesisStateArgs = {
555
- vkTreeRoot: args.vkTreeRoot.toString(),
556
- protocolContractTreeRoot: args.protocolContractTreeRoot.toString(),
557
- genesisArchiveRoot: args.genesisArchiveRoot.toString(),
558
- };
559
-
560
- // Until there is an actual chain-id for the version, we will just draw a random value.
561
- // TODO(https://linear.app/aztec-labs/issue/TMNT-139/version-at-deployment)
562
- rollupConfigArgs.version = Buffer.from(
563
- keccak256String(
564
- jsonStringify({
565
- rollupConfigArgs,
566
- genesisStateArgs,
567
- }),
568
- ),
569
- ).readUint32BE(0);
570
- logger.verbose(`Rollup config args`, rollupConfigArgs);
571
-
572
- const rollupArgs = [
573
- addresses.feeJuiceAddress.toString(),
574
- addresses.stakingAssetAddress.toString(),
575
- addresses.gseAddress.toString(),
576
- epochProofVerifier.toString(),
577
- extendedClient.account.address,
578
- genesisStateArgs,
579
- rollupConfigArgs,
580
- ] as const;
581
-
582
- const rollupAddress = await deployer.deploy(RollupArtifact, rollupArgs, { gasLimit: 15_000_000n });
583
- logger.verbose(`Deployed Rollup at ${rollupAddress}`, rollupConfigArgs);
584
-
585
- const rollupContract = new RollupContract(extendedClient, rollupAddress);
586
-
587
- await deployer.waitForDeployments();
588
- logger.verbose(`All core contracts have been deployed`);
589
-
590
- if (args.feeJuicePortalInitialBalance && args.feeJuicePortalInitialBalance > 0n) {
591
- const feeJuicePortalAddress = await rollupContract.getFeeJuicePortal();
592
-
593
- // In fast mode, use the L1TxUtils to send transactions with nonce management
594
- const { txHash: mintTxHash } = await deployer.sendTransaction({
595
- to: addresses.feeJuiceAddress.toString(),
596
- data: encodeFunctionData({
597
- abi: FeeAssetArtifact.contractAbi,
598
- functionName: 'mint',
599
- args: [feeJuicePortalAddress.toString(), args.feeJuicePortalInitialBalance],
600
- }),
601
- });
602
- logger.verbose(
603
- `Funding fee juice portal with ${args.feeJuicePortalInitialBalance} fee juice in ${mintTxHash} (accelerated test deployments)`,
604
- );
605
- txHashes.push(mintTxHash);
606
- }
607
-
608
- const slashFactoryAddress = await deployer.deploy(SlashFactoryArtifact, [rollupAddress.toString()]);
609
- logger.verbose(`Deployed SlashFactory at ${slashFactoryAddress}`);
610
-
611
- // We need to call a function on the registry to set the various contract addresses.
612
- const registryContract = getContract({
613
- address: getAddress(addresses.registryAddress.toString()),
614
- abi: RegistryArtifact.contractAbi,
615
- client: extendedClient,
616
- });
617
-
618
- // Only if we are the owner will we be sending these transactions
619
- if ((await registryContract.read.owner()) === getAddress(extendedClient.account.address)) {
620
- const version = await rollupContract.getVersion();
621
- try {
622
- const retrievedRollupAddress = await registryContract.read.getRollup([version]);
623
- logger.verbose(`Rollup ${retrievedRollupAddress} already exists in registry`);
624
- } catch {
625
- const { txHash: addRollupTxHash } = await deployer.sendTransaction({
626
- to: addresses.registryAddress.toString(),
627
- data: encodeFunctionData({
628
- abi: RegistryArtifact.contractAbi,
629
- functionName: 'addRollup',
630
- args: [getAddress(rollupContract.address)],
631
- }),
632
- });
633
- logger.verbose(
634
- `Adding rollup ${rollupContract.address} to registry ${addresses.registryAddress} in tx ${addRollupTxHash}`,
635
- );
636
-
637
- txHashes.push(addRollupTxHash);
638
- }
639
- } else {
640
- logger.verbose(`Not the owner of the registry, skipping rollup addition`);
641
- }
642
-
643
- // We need to call a function on the registry to set the various contract addresses.
644
- const gseContract = getContract({
645
- address: getAddress(addresses.gseAddress.toString()),
646
- abi: GSEArtifact.contractAbi,
647
- client: extendedClient,
648
- });
649
- if ((await gseContract.read.owner()) === getAddress(extendedClient.account.address)) {
650
- if (!(await gseContract.read.isRollupRegistered([rollupContract.address]))) {
651
- const { txHash: addRollupTxHash } = await deployer.sendTransaction({
652
- to: addresses.gseAddress.toString(),
653
- data: encodeFunctionData({
654
- abi: GSEArtifact.contractAbi,
655
- functionName: 'addRollup',
656
- args: [getAddress(rollupContract.address)],
657
- }),
658
- });
659
- logger.verbose(`Adding rollup ${rollupContract.address} to GSE ${addresses.gseAddress} in tx ${addRollupTxHash}`);
660
-
661
- // wait for this tx to land in case we have to register initialValidators
662
- await extendedClient.waitForTransactionReceipt({ hash: addRollupTxHash });
663
- } else {
664
- logger.verbose(`Rollup ${rollupContract.address} is already registered in GSE ${addresses.gseAddress}`);
665
- }
666
- } else {
667
- logger.verbose(`Not the owner of the gse, skipping rollup addition`);
668
- }
669
-
670
- if (args.initialValidators && (await gseContract.read.isRollupRegistered([rollupContract.address]))) {
671
- await addMultipleValidators(
672
- extendedClient,
673
- deployer,
674
- addresses.gseAddress.toString(),
675
- rollupAddress.toString(),
676
- addresses.stakingAssetAddress.toString(),
677
- args.initialValidators,
678
- args.acceleratedTestDeployments,
679
- logger,
680
- );
681
- }
682
-
683
- // If the owner is not the Governance contract, transfer ownership to the Governance contract
684
- logger.verbose(addresses.governanceAddress.toString());
685
- if (getAddress(await rollupContract.getOwner()) !== getAddress(addresses.governanceAddress.toString())) {
686
- // TODO(md): add send transaction to the deployer such that we do not need to manage tx hashes here
687
- const { txHash: transferOwnershipTxHash } = await deployer.sendTransaction({
688
- to: rollupContract.address,
689
- data: encodeFunctionData({
690
- abi: RegistryArtifact.contractAbi,
691
- functionName: 'transferOwnership',
692
- args: [getAddress(addresses.governanceAddress.toString())],
693
- }),
694
- });
695
- logger.verbose(
696
- `Transferring the ownership of the rollup contract at ${rollupContract.address} to the Governance ${addresses.governanceAddress} in tx ${transferOwnershipTxHash}`,
697
- );
698
- txHashes.push(transferOwnershipTxHash);
699
- }
700
-
701
- await deployer.waitForDeployments();
702
- await Promise.all(txHashes.map(txHash => extendedClient.waitForTransactionReceipt({ hash: txHash })));
703
- logger.verbose(`Rollup deployed`);
704
-
705
- return { rollup: rollupContract, slashFactoryAddress };
706
- };
707
-
708
- export const handoverToGovernance = async (
709
- extendedClient: ExtendedViemWalletClient,
710
- deployer: L1Deployer,
711
- registryAddress: EthAddress,
712
- gseAddress: EthAddress,
713
- coinIssuerAddress: EthAddress,
714
- feeAssetAddress: EthAddress,
715
- governanceAddress: EthAddress,
716
- logger: Logger,
717
- acceleratedTestDeployments: boolean | undefined,
718
- ) => {
719
- // We need to call a function on the registry to set the various contract addresses.
720
- const registryContract = getContract({
721
- address: getAddress(registryAddress.toString()),
722
- abi: RegistryArtifact.contractAbi,
723
- client: extendedClient,
724
- });
725
-
726
- const gseContract = getContract({
727
- address: getAddress(gseAddress.toString()),
728
- abi: GSEArtifact.contractAbi,
729
- client: extendedClient,
730
- });
731
-
732
- const coinIssuerContract = getContract({
733
- address: getAddress(coinIssuerAddress.toString()),
734
- abi: CoinIssuerArtifact.contractAbi,
735
- client: extendedClient,
736
- });
737
-
738
- const feeAsset = getContract({
739
- address: getAddress(feeAssetAddress.toString()),
740
- abi: FeeAssetArtifact.contractAbi,
741
- client: extendedClient,
742
- });
743
-
744
- const txHashes: Hex[] = [];
745
-
746
- // If the owner is not the Governance contract, transfer ownership to the Governance contract
747
- if (
748
- acceleratedTestDeployments ||
749
- (await registryContract.read.owner()) !== getAddress(governanceAddress.toString())
750
- ) {
751
- // TODO(md): add send transaction to the deployer such that we do not need to manage tx hashes here
752
- const { txHash: transferOwnershipTxHash } = await deployer.sendTransaction({
753
- to: registryAddress.toString(),
754
- data: encodeFunctionData({
755
- abi: RegistryArtifact.contractAbi,
756
- functionName: 'transferOwnership',
757
- args: [getAddress(governanceAddress.toString())],
758
- }),
759
- });
760
- logger.verbose(
761
- `Transferring the ownership of the registry contract at ${registryAddress} to the Governance ${governanceAddress} in tx ${transferOwnershipTxHash}`,
762
- );
763
- txHashes.push(transferOwnershipTxHash);
764
- }
765
-
766
- // If the owner is not the Governance contract, transfer ownership to the Governance contract
767
- if (acceleratedTestDeployments || (await gseContract.read.owner()) !== getAddress(governanceAddress.toString())) {
768
- // TODO(md): add send transaction to the deployer such that we do not need to manage tx hashes here
769
- const { txHash: transferOwnershipTxHash } = await deployer.sendTransaction({
770
- to: gseContract.address,
771
- data: encodeFunctionData({
772
- abi: GSEArtifact.contractAbi,
773
- functionName: 'transferOwnership',
774
- args: [getAddress(governanceAddress.toString())],
775
- }),
776
- });
777
- logger.verbose(
778
- `Transferring the ownership of the gse contract at ${gseAddress} to the Governance ${governanceAddress} in tx ${transferOwnershipTxHash}`,
779
- );
780
- txHashes.push(transferOwnershipTxHash);
781
- }
782
-
783
- if (acceleratedTestDeployments || (await feeAsset.read.owner()) !== coinIssuerAddress.toString()) {
784
- const { txHash } = await deployer.sendTransaction(
785
- {
786
- to: feeAssetAddress.toString(),
787
- data: encodeFunctionData({
788
- abi: FeeAssetArtifact.contractAbi,
789
- functionName: 'transferOwnership',
790
- args: [coinIssuerAddress.toString()],
791
- }),
792
- },
793
- { gasLimit: 500_000n },
794
- );
795
- logger.verbose(`Transfer ownership of fee asset to coin issuer ${coinIssuerAddress} in ${txHash}`);
796
- txHashes.push(txHash);
797
-
798
- const { txHash: acceptTokenOwnershipTxHash } = await deployer.sendTransaction(
799
- {
800
- to: coinIssuerAddress.toString(),
801
- data: encodeFunctionData({
802
- abi: CoinIssuerArtifact.contractAbi,
803
- functionName: 'acceptTokenOwnership',
804
- }),
805
- },
806
- { gasLimit: 500_000n },
807
- );
808
- logger.verbose(`Accept ownership of fee asset in ${acceptTokenOwnershipTxHash}`);
809
- txHashes.push(acceptTokenOwnershipTxHash);
810
- }
811
-
812
- // If the owner is not the Governance contract, transfer ownership to the Governance contract
813
- if (
814
- acceleratedTestDeployments ||
815
- (await coinIssuerContract.read.owner()) !== getAddress(governanceAddress.toString())
816
- ) {
817
- const { txHash: transferOwnershipTxHash } = await deployer.sendTransaction({
818
- to: coinIssuerContract.address,
819
- data: encodeFunctionData({
820
- abi: CoinIssuerArtifact.contractAbi,
821
- functionName: 'transferOwnership',
822
- args: [getAddress(governanceAddress.toString())],
823
- }),
824
- });
825
- logger.verbose(
826
- `Transferring the ownership of the coin issuer contract at ${coinIssuerAddress} to the Governance ${governanceAddress} in tx ${transferOwnershipTxHash}`,
827
- );
828
- txHashes.push(transferOwnershipTxHash);
829
- }
830
-
831
- // Wait for all actions to be mined
832
- await deployer.waitForDeployments();
833
- await Promise.all(txHashes.map(txHash => extendedClient.waitForTransactionReceipt({ hash: txHash })));
834
- };
835
-
836
- /*
837
- * Adds multiple validators to the rollup
838
- *
839
- * @param extendedClient - The L1 clients.
840
- * @param deployer - The L1 deployer.
841
- * @param rollupAddress - The address of the rollup.
842
- * @param stakingAssetAddress - The address of the staking asset.
843
- * @param validators - The validators to initialize.
844
- * @param acceleratedTestDeployments - Whether to use accelerated test deployments.
845
- * @param logger - The logger.
846
- */
847
- export const addMultipleValidators = async (
848
- extendedClient: ExtendedViemWalletClient,
849
- deployer: L1Deployer,
850
- gseAddress: Hex,
851
- rollupAddress: Hex,
852
- stakingAssetAddress: Hex,
853
- validators: Operator[],
854
- acceleratedTestDeployments: boolean | undefined,
855
- logger: Logger,
856
- ) => {
857
- const rollup = new RollupContract(extendedClient, rollupAddress);
858
- const activationThreshold = await rollup.getActivationThreshold();
859
- if (validators && validators.length > 0) {
860
- // Check if some of the initial validators are already registered, so we support idempotent deployments
861
- if (!acceleratedTestDeployments) {
862
- const enrichedValidators = await Promise.all(
863
- validators.map(async operator => ({
864
- operator,
865
- status: await rollup.getStatus(operator.attester),
866
- })),
867
- );
868
- const existingValidators = enrichedValidators.filter(v => v.status !== 0);
869
- if (existingValidators.length > 0) {
870
- logger.warn(
871
- `Validators ${existingValidators
872
- .map(v => v.operator.attester)
873
- .join(', ')} already exist. Skipping from initialization.`,
874
- );
875
- }
876
-
877
- validators = enrichedValidators.filter(v => v.status === 0).map(v => v.operator);
878
- }
879
-
880
- if (validators.length > 0) {
881
- const gseContract = new GSEContract(extendedClient, gseAddress);
882
- const multiAdder = await deployer.deploy(MultiAdderArtifact, [rollupAddress, deployer.client.account.address]);
883
-
884
- const makeValidatorTuples = async (validator: Operator) => {
885
- const registrationTuple = await gseContract.makeRegistrationTuple(validator.bn254SecretKey.getValue());
886
- return {
887
- attester: getAddress(validator.attester.toString()),
888
- withdrawer: getAddress(validator.withdrawer.toString()),
889
- ...registrationTuple,
890
- };
891
- };
892
-
893
- const validatorsTuples = await Promise.all(validators.map(makeValidatorTuples));
894
-
895
- // Mint tokens, approve them, use cheat code to initialize validator set without setting up the epoch.
896
- const stakeNeeded = activationThreshold * BigInt(validators.length);
897
-
898
- await deployer.l1TxUtils.sendAndMonitorTransaction({
899
- to: stakingAssetAddress,
900
- data: encodeFunctionData({
901
- abi: StakingAssetArtifact.contractAbi,
902
- functionName: 'mint',
903
- args: [multiAdder.toString(), stakeNeeded],
904
- }),
905
- });
906
-
907
- const entryQueueLengthBefore = await rollup.getEntryQueueLength();
908
- const validatorCountBefore = await rollup.getActiveAttesterCount();
909
-
910
- logger.info(`Adding ${validators.length} validators to the rollup`);
911
-
912
- // Adding to the queue and flushing need to be done in two transactions
913
- // if we are adding many validators.
914
- if (validatorsTuples.length > 10) {
915
- await deployer.l1TxUtils.sendAndMonitorTransaction(
916
- {
917
- to: multiAdder.toString(),
918
- data: encodeFunctionData({
919
- abi: MultiAdderArtifact.contractAbi,
920
- functionName: 'addValidators',
921
- args: [validatorsTuples, true],
922
- }),
923
- },
924
- {
925
- gasLimit: 40_000_000n,
926
- },
927
- );
928
-
929
- await deployer.l1TxUtils.sendAndMonitorTransaction(
930
- {
931
- to: rollupAddress,
932
- data: encodeFunctionData({
933
- abi: RollupArtifact.contractAbi,
934
- functionName: 'flushEntryQueue',
935
- args: [],
936
- }),
937
- },
938
- {
939
- gasLimit: 40_000_000n,
940
- },
941
- );
942
- } else {
943
- await deployer.l1TxUtils.sendAndMonitorTransaction(
944
- {
945
- to: multiAdder.toString(),
946
- data: encodeFunctionData({
947
- abi: MultiAdderArtifact.contractAbi,
948
- functionName: 'addValidators',
949
- args: [validatorsTuples, false],
950
- }),
951
- },
952
- {
953
- gasLimit: 45_000_000n,
954
- },
955
- );
956
- }
957
-
958
- const entryQueueLengthAfter = await rollup.getEntryQueueLength();
959
- const validatorCountAfter = await rollup.getActiveAttesterCount();
960
-
961
- if (
962
- entryQueueLengthAfter + validatorCountAfter <
963
- entryQueueLengthBefore + validatorCountBefore + BigInt(validators.length)
964
- ) {
965
- throw new Error(
966
- `Failed to add ${validators.length} validators. Active validators: ${validatorCountBefore} -> ${validatorCountAfter}. Queue: ${entryQueueLengthBefore} -> ${entryQueueLengthAfter}`,
967
- );
968
- }
969
-
970
- logger.info(
971
- `Added ${validators.length} validators. Active validators: ${validatorCountBefore} -> ${validatorCountAfter}. Queue: ${entryQueueLengthBefore} -> ${entryQueueLengthAfter}`,
972
- );
973
- }
974
- }
975
- };
976
-
977
- /**
978
- * Initialize the fee asset handler and make it a minter on the fee asset.
979
- * @note This function will only be used for testing purposes.
980
- *
981
- * @param extendedClient - The L1 clients.
982
- * @param deployer - The L1 deployer.
983
- * @param feeAssetAddress - The address of the fee asset.
984
- * @param logger - The logger.
985
- */
986
- // eslint-disable-next-line camelcase
987
- export const cheat_initializeFeeAssetHandler = async (
988
- extendedClient: ExtendedViemWalletClient,
989
- deployer: L1Deployer,
990
- feeAssetAddress: EthAddress,
991
- logger: Logger,
992
- ): Promise<{
993
- feeAssetHandlerAddress: EthAddress;
994
- txHash: Hex;
995
- }> => {
996
- const feeAssetHandlerAddress = await deployer.deploy(FeeAssetHandlerArtifact, [
997
- extendedClient.account.address,
998
- feeAssetAddress.toString(),
999
- BigInt(1e18),
1000
- ]);
1001
- logger.verbose(`Deployed FeeAssetHandler at ${feeAssetHandlerAddress}`);
1002
-
1003
- const { txHash } = await deployer.sendTransaction({
1004
- to: feeAssetAddress.toString(),
1005
- data: encodeFunctionData({
1006
- abi: FeeAssetArtifact.contractAbi,
1007
- functionName: 'addMinter',
1008
- args: [feeAssetHandlerAddress.toString()],
1009
- }),
1010
- });
1011
- logger.verbose(`Added fee asset handler ${feeAssetHandlerAddress} as minter on fee asset in ${txHash}`);
1012
- return { feeAssetHandlerAddress, txHash };
1013
- };
1014
-
1015
- /**
1016
- * Deploys the aztec L1 contracts; Rollup & (optionally) Decoder Helper.
1017
- * @param rpcUrls - List of URLs of the ETH RPC to use for deployment.
1018
- * @param account - Private Key or HD Account that will deploy the contracts.
1019
- * @param chain - The chain instance to deploy to.
1020
- * @param logger - A logger object.
1021
- * @param args - Arguments for initialization of L1 contracts
1022
- * @returns A list of ETH addresses of the deployed contracts.
1023
- */
1024
- export const deployL1Contracts = async (
1025
- rpcUrls: string[],
1026
- account: HDAccount | PrivateKeyAccount,
1027
- chain: Chain,
1028
- logger: Logger,
1029
- args: DeployL1ContractsArgs,
1030
- txUtilsConfig: L1TxUtilsConfig = getL1TxUtilsConfigEnvVars(),
1031
- createVerificationJson: string | false = false,
1032
- ): Promise<DeployL1ContractsReturnType> => {
1033
- logger.info(`Deploying L1 contracts with config: ${jsonStringify(args)}`);
1034
- validateConfig(args);
1035
-
1036
- const l1Client = createExtendedL1Client(rpcUrls, account, chain);
1037
-
1038
- // Deploy multicall3 if it does not exist in this network
1039
- await deployMulticall3(l1Client, logger);
1040
-
1041
- // We are assuming that you are running this on a local anvil node which have 1s block times
1042
- // To align better with actual deployment, we update the block interval to 12s
1043
-
1044
- const rpcCall = async (method: string, params: any[]) => {
1045
- logger.info(`Calling ${method} with params: ${JSON.stringify(params)}`);
1046
- return (await l1Client.transport.request({
1047
- method,
1048
- params,
1049
- })) as any;
1050
- };
1051
-
1052
- if (isAnvilTestChain(chain.id)) {
1053
- try {
1054
- await rpcCall('anvil_setBlockTimestampInterval', [args.ethereumSlotDuration]);
1055
- logger.warn(`Set block interval to ${args.ethereumSlotDuration}`);
1056
- } catch (e) {
1057
- logger.error(`Error setting block interval: ${e}`);
1058
- }
1059
- }
1060
-
1061
- logger.verbose(`Deploying contracts from ${account.address.toString()}`);
1062
-
1063
- const dateProvider = new DateProvider();
1064
- const deployer = new L1Deployer(
1065
- l1Client,
1066
- args.salt,
1067
- dateProvider,
1068
- args.acceleratedTestDeployments,
1069
- logger,
1070
- txUtilsConfig,
1071
- !!createVerificationJson,
1072
- );
1073
-
1074
- const {
1075
- feeAssetAddress,
1076
- feeAssetHandlerAddress,
1077
- stakingAssetAddress,
1078
- stakingAssetHandlerAddress,
1079
- registryAddress,
1080
- gseAddress,
1081
- governanceAddress,
1082
- rewardDistributorAddress,
1083
- zkPassportVerifierAddress,
1084
- coinIssuerAddress,
1085
- } = await deploySharedContracts(l1Client, deployer, args, logger);
1086
- const { rollup, slashFactoryAddress } = await deployRollup(
1087
- l1Client,
1088
- deployer,
1089
- args,
1090
- {
1091
- feeJuiceAddress: feeAssetAddress,
1092
- registryAddress,
1093
- gseAddress,
1094
- rewardDistributorAddress,
1095
- stakingAssetAddress,
1096
- governanceAddress,
1097
- },
1098
- logger,
1099
- );
1100
-
1101
- logger.verbose('Waiting for rollup and slash factory to be deployed');
1102
- await deployer.waitForDeployments();
1103
-
1104
- // Now that the rollup has been deployed and added to the registry, transfer ownership to governance
1105
- await handoverToGovernance(
1106
- l1Client,
1107
- deployer,
1108
- registryAddress,
1109
- gseAddress,
1110
- coinIssuerAddress,
1111
- feeAssetAddress,
1112
- governanceAddress,
1113
- logger,
1114
- args.acceleratedTestDeployments,
1115
- );
1116
-
1117
- logger.info(`Handing over to governance complete`);
1118
-
1119
- logger.verbose(`All transactions for L1 deployment have been mined`);
1120
- const l1Contracts = await RegistryContract.collectAddresses(l1Client, registryAddress, 'canonical');
1121
-
1122
- logger.info(`Aztec L1 contracts initialized`, l1Contracts);
1123
-
1124
- // Write verification data (constructor args + linked libraries) to file for later forge verify
1125
- if (createVerificationJson) {
1126
- try {
1127
- // Add Inbox / Outbox verification records (constructor args are created inside RollupCore)
1128
- const rollupAddr = l1Contracts.rollupAddress.toString();
1129
- const inboxAddr = l1Contracts.inboxAddress.toString();
1130
- const outboxAddr = l1Contracts.outboxAddress.toString();
1131
- const feeAsset = l1Contracts.feeJuiceAddress.toString();
1132
- const version = await rollup.getVersion();
1133
-
1134
- const inboxCtor = encodeAbiParameters(
1135
- [{ type: 'address' }, { type: 'address' }, { type: 'uint256' }, { type: 'uint256' }],
1136
- [rollupAddr, feeAsset, version, BigInt(L1_TO_L2_MSG_SUBTREE_HEIGHT)],
1137
- );
1138
-
1139
- const outboxCtor = encodeAbiParameters([{ type: 'address' }, { type: 'uint256' }], [rollupAddr, version]);
1140
-
1141
- deployer.verificationRecords.push(
1142
- { name: 'Inbox', address: inboxAddr, constructorArgsHex: inboxCtor, libraries: [] },
1143
- { name: 'Outbox', address: outboxAddr, constructorArgsHex: outboxCtor, libraries: [] },
1144
- );
1145
-
1146
- // Include Slasher and SlashingProposer (if deployed) in verification data
1147
- try {
1148
- const slasherAddrHex = await rollup.getSlasher();
1149
- const slasherAddr = EthAddress.fromString(slasherAddrHex);
1150
- if (!slasherAddr.isZero()) {
1151
- // Slasher constructor: (address _vetoer, address _governance)
1152
- const slasherCtor = encodeAbiParameters(
1153
- [{ type: 'address' }, { type: 'address' }],
1154
- [args.slashingVetoer.toString(), l1Client.account.address],
1155
- );
1156
- deployer.verificationRecords.push({
1157
- name: 'Slasher',
1158
- address: slasherAddr.toString(),
1159
- constructorArgsHex: slasherCtor,
1160
- libraries: [],
1161
- });
1162
-
1163
- // Proposer address is stored in Slasher.PROPOSER()
1164
- const proposerAddr = (await rollup.getSlashingProposerAddress()).toString();
1165
-
1166
- // Compute constructor args matching deployment path in RollupCore
1167
- const computedRoundSize = BigInt(args.slashingRoundSizeInEpochs * args.aztecEpochDuration);
1168
- const computedQuorum = BigInt(
1169
- args.slashingQuorum ?? (args.slashingRoundSizeInEpochs * args.aztecEpochDuration) / 2 + 1,
1170
- );
1171
- const lifetimeInRounds = BigInt(args.slashingLifetimeInRounds);
1172
- const executionDelayInRounds = BigInt(args.slashingExecutionDelayInRounds);
1173
-
1174
- if (args.slasherFlavor === 'tally') {
1175
- const slashAmounts: readonly [bigint, bigint, bigint] = [
1176
- args.slashAmountSmall,
1177
- args.slashAmountMedium,
1178
- args.slashAmountLarge,
1179
- ];
1180
- const committeeSize = BigInt(args.aztecTargetCommitteeSize);
1181
- const epochDuration = BigInt(args.aztecEpochDuration);
1182
- const slashOffsetInRounds = BigInt(args.slashingOffsetInRounds);
1183
-
1184
- const proposerCtor = encodeAbiParameters(
1185
- [
1186
- { type: 'address' },
1187
- { type: 'address' },
1188
- { type: 'uint256' },
1189
- { type: 'uint256' },
1190
- { type: 'uint256' },
1191
- { type: 'uint256' },
1192
- { type: 'uint256[3]' },
1193
- { type: 'uint256' },
1194
- { type: 'uint256' },
1195
- { type: 'uint256' },
1196
- ],
1197
- [
1198
- rollup.address,
1199
- slasherAddr.toString(),
1200
- computedQuorum,
1201
- computedRoundSize,
1202
- lifetimeInRounds,
1203
- executionDelayInRounds,
1204
- slashAmounts,
1205
- committeeSize,
1206
- epochDuration,
1207
- slashOffsetInRounds,
1208
- ],
1209
- );
1210
-
1211
- deployer.verificationRecords.push({
1212
- name: 'TallySlashingProposer',
1213
- address: proposerAddr,
1214
- constructorArgsHex: proposerCtor,
1215
- libraries: [],
1216
- });
1217
- } else if (args.slasherFlavor === 'empire') {
1218
- const proposerCtor = encodeAbiParameters(
1219
- [
1220
- { type: 'address' },
1221
- { type: 'address' },
1222
- { type: 'uint256' },
1223
- { type: 'uint256' },
1224
- { type: 'uint256' },
1225
- { type: 'uint256' },
1226
- ],
1227
- [
1228
- rollup.address,
1229
- slasherAddr.toString(),
1230
- computedQuorum,
1231
- computedRoundSize,
1232
- lifetimeInRounds,
1233
- executionDelayInRounds,
1234
- ],
1235
- );
1236
-
1237
- deployer.verificationRecords.push({
1238
- name: 'EmpireSlashingProposer',
1239
- address: proposerAddr,
1240
- constructorArgsHex: proposerCtor,
1241
- libraries: [],
1242
- });
1243
- }
1244
- }
1245
- } catch (e) {
1246
- logger.warn(`Failed to add Slasher/Proposer verification records: ${String(e)}`);
1247
- }
1248
- const date = new Date();
1249
- const formattedDate = date.toISOString().slice(2, 19).replace(/[-T:]/g, '');
1250
- // Ensure the verification output directory exists
1251
- await mkdir(createVerificationJson, { recursive: true });
1252
- const verificationOutputPath = `${createVerificationJson}/l1-verify-${chain.id}-${formattedDate.slice(0, 6)}-${formattedDate.slice(6)}.json`;
1253
- const verificationData = {
1254
- chainId: chain.id,
1255
- network: networkName,
1256
- records: deployer.verificationRecords,
1257
- };
1258
- await writeFile(verificationOutputPath, JSON.stringify(verificationData, null, 2));
1259
- logger.info(`Wrote L1 verification data to ${verificationOutputPath}`);
1260
- } catch (e) {
1261
- logger.warn(`Failed to write L1 verification data file: ${String(e)}`);
1262
- }
1263
- }
1264
-
1265
- if (isAnvilTestChain(chain.id)) {
1266
- // @note We make a time jump PAST the very first slot to not have to deal with the edge case of the first slot.
1267
- // The edge case being that the genesis block is already occupying slot 0, so we cannot have another block.
1268
- try {
1269
- // Need to get the time
1270
- const currentSlot = await rollup.getSlotNumber();
1271
-
1272
- if (BigInt(currentSlot) === 0n) {
1273
- const ts = Number(await rollup.getTimestampForSlot(1n));
1274
- await rpcCall('evm_setNextBlockTimestamp', [ts]);
1275
- await rpcCall('hardhat_mine', [1]);
1276
- const currentSlot = await rollup.getSlotNumber();
1277
-
1278
- if (BigInt(currentSlot) !== 1n) {
1279
- throw new Error(`Error jumping time: current slot is ${currentSlot}`);
1280
- }
1281
- logger.info(`Jumped to slot 1`);
1282
- }
1283
- } catch (e) {
1284
- throw new Error(`Error jumping time: ${e}`);
1285
- }
1286
- }
1287
-
1288
- return {
1289
- rollupVersion: Number(await rollup.getVersion()),
1290
- l1Client: l1Client,
1291
- l1ContractAddresses: {
1292
- ...l1Contracts,
1293
- slashFactoryAddress,
1294
- feeAssetHandlerAddress,
1295
- stakingAssetHandlerAddress,
1296
- zkPassportVerifierAddress,
1297
- coinIssuerAddress,
1298
- },
1299
- };
1300
- };
1301
-
1302
- export class L1Deployer {
1303
- private salt: Hex | undefined;
1304
- private txHashes: Hex[] = [];
1305
- public readonly l1TxUtils: L1TxUtils;
1306
- public readonly verificationRecords: VerificationRecord[] = [];
1307
-
1308
- constructor(
1309
- public readonly client: ExtendedViemWalletClient,
1310
- maybeSalt: number | undefined,
1311
- dateProvider: DateProvider = new DateProvider(),
1312
- private acceleratedTestDeployments: boolean = false,
1313
- private logger: Logger = createLogger('L1Deployer'),
1314
- private txUtilsConfig?: L1TxUtilsConfig,
1315
- private createVerificationJson: boolean = false,
1316
- ) {
1317
- this.salt = maybeSalt ? padHex(numberToHex(maybeSalt), { size: 32 }) : undefined;
1318
- this.l1TxUtils = createL1TxUtilsFromViemWallet(
1319
- this.client,
1320
- this.logger,
1321
- dateProvider,
1322
- this.txUtilsConfig,
1323
- this.acceleratedTestDeployments,
1324
- );
1325
- }
1326
-
1327
- async deploy<const TAbi extends Abi>(
1328
- params: ContractArtifacts<TAbi>,
1329
- args?: ContractConstructorArgs<TAbi>,
1330
- opts: { gasLimit?: bigint } = {},
1331
- ): Promise<EthAddress> {
1332
- this.logger.debug(`Deploying ${params.name} contract`, { args });
1333
- try {
1334
- const { txHash, address, deployedLibraries } = await deployL1Contract(
1335
- this.client,
1336
- params.contractAbi,
1337
- params.contractBytecode,
1338
- (args ?? []) as readonly unknown[],
1339
- {
1340
- salt: this.salt,
1341
- libraries: params.libraries,
1342
- logger: this.logger,
1343
- l1TxUtils: this.l1TxUtils,
1344
- acceleratedTestDeployments: this.acceleratedTestDeployments,
1345
- gasLimit: opts.gasLimit,
1346
- },
1347
- );
1348
- if (txHash) {
1349
- this.txHashes.push(txHash);
1350
- }
1351
- this.logger.debug(`Deployed ${params.name} at ${address}`, { args });
1352
-
1353
- if (this.createVerificationJson) {
1354
- // Encode constructor args for verification
1355
- let constructorArgsHex: Hex = '0x';
1356
- try {
1357
- const abiItem: any = (params.contractAbi as any[]).find((x: any) => x && x.type === 'constructor');
1358
- const inputDefs: any[] = abiItem && Array.isArray(abiItem.inputs) ? abiItem.inputs : [];
1359
- constructorArgsHex =
1360
- inputDefs.length > 0 ? (encodeAbiParameters(inputDefs as any, (args ?? []) as any) as Hex) : ('0x' as Hex);
1361
- } catch {
1362
- constructorArgsHex = '0x' as Hex;
1363
- }
1364
-
1365
- this.verificationRecords.push({
1366
- name: params.name,
1367
- address: address.toString(),
1368
- constructorArgsHex,
1369
- libraries: deployedLibraries ?? [],
1370
- });
1371
- }
1372
- return address;
1373
- } catch (error) {
1374
- throw new Error(`Failed to deploy ${params.name}`, { cause: formatViemError(error) });
1375
- }
1376
- }
1377
-
1378
- async waitForDeployments(): Promise<void> {
1379
- if (this.acceleratedTestDeployments) {
1380
- this.logger.info('Accelerated test deployments - skipping waiting for deployments');
1381
- return;
1382
- }
1383
- if (this.txHashes.length === 0) {
1384
- return;
1385
- }
1386
-
1387
- this.logger.verbose(`Waiting for ${this.txHashes.length} transactions to be mined`, { txHashes: this.txHashes });
1388
- const receipts = await Promise.all(
1389
- this.txHashes.map(txHash => this.client.waitForTransactionReceipt({ hash: txHash })),
1390
- );
1391
- const failed = receipts.filter(r => r.status !== 'success');
1392
- if (failed.length > 0) {
1393
- throw new Error(`Some deployment txs have failed: ${failed.map(f => f.transactionHash).join(', ')}`);
1394
- }
1395
- this.logger.info('All transactions mined successfully', { txHashes: this.txHashes });
1396
- }
1397
-
1398
- sendTransaction(
1399
- tx: L1TxRequest,
1400
- options?: L1GasConfig,
1401
- ): Promise<{ txHash: Hex; gasLimit: bigint; gasPrice: GasPrice }> {
1402
- return this.l1TxUtils.sendTransaction(tx, options);
1403
- }
1404
- }
1405
-
1406
- // docs:start:deployL1Contract
1407
- /**
1408
- * Helper function to deploy ETH contracts.
1409
- * @param walletClient - A viem WalletClient.
1410
- * @param publicClient - A viem PublicClient.
1411
- * @param abi - The ETH contract's ABI (as abitype's Abi).
1412
- * @param bytecode - The ETH contract's bytecode.
1413
- * @param args - Constructor arguments for the contract.
1414
- * @param salt - Optional salt for CREATE2 deployment (does not wait for deployment tx to be mined if set, does not send tx if contract already exists).
1415
- * @returns The ETH address the contract was deployed to.
1416
- */
1417
- export async function deployL1Contract(
1418
- extendedClient: ExtendedViemWalletClient,
1419
- abi: Narrow<Abi | readonly unknown[]>,
1420
- bytecode: Hex,
1421
- args: readonly unknown[] = [],
1422
- opts: {
1423
- salt?: Hex;
1424
- libraries?: Libraries;
1425
- logger?: Logger;
1426
- l1TxUtils?: L1TxUtils;
1427
- gasLimit?: bigint;
1428
- acceleratedTestDeployments?: boolean;
1429
- } = {},
1430
- ): Promise<{ address: EthAddress; txHash: Hex | undefined; deployedLibraries?: VerificationLibraryEntry[] }> {
1431
- let txHash: Hex | undefined = undefined;
1432
- let resultingAddress: Hex | null | undefined = undefined;
1433
- const deployedLibraries: VerificationLibraryEntry[] = [];
1434
-
1435
- const { salt: saltFromOpts, libraries, logger, gasLimit, acceleratedTestDeployments } = opts;
1436
- let { l1TxUtils } = opts;
1437
-
1438
- if (!l1TxUtils) {
1439
- const config = getL1TxUtilsConfigEnvVars();
1440
- l1TxUtils = createL1TxUtilsFromViemWallet(extendedClient, logger, undefined, config, acceleratedTestDeployments);
1441
- }
1442
-
1443
- if (libraries) {
1444
- // Note that this does NOT work well for linked libraries having linked libraries.
1445
-
1446
- // Verify that all link references have corresponding code
1447
- for (const linkRef in libraries.linkReferences) {
1448
- for (const contractName in libraries.linkReferences[linkRef]) {
1449
- if (!libraries.libraryCode[contractName]) {
1450
- throw new Error(`Missing library code for ${contractName}`);
1451
- }
1452
- }
1453
- }
1454
-
1455
- const replacements: Record<string, EthAddress> = {};
1456
- const libraryTxs: Hex[] = [];
1457
- for (const libraryName in libraries?.libraryCode) {
1458
- const lib = libraries.libraryCode[libraryName];
1459
- const { libraries: _libraries, ...optsWithoutLibraries } = opts;
1460
- const { address, txHash } = await deployL1Contract(
1461
- extendedClient,
1462
- lib.contractAbi,
1463
- lib.contractBytecode,
1464
- [],
1465
- optsWithoutLibraries,
1466
- );
1467
-
1468
- // Log deployed library name and address for easier verification/triage
1469
- logger?.verbose(`Linked library deployed`, { library: libraryName, address: address.toString(), txHash });
1470
-
1471
- if (txHash) {
1472
- libraryTxs.push(txHash);
1473
- }
1474
-
1475
- // Try to find the source file for this library from linkReferences
1476
- let fileNameForLibrary: string | undefined = undefined;
1477
- for (const fileName in libraries.linkReferences) {
1478
- if (libraries.linkReferences[fileName] && libraries.linkReferences[fileName][libraryName]) {
1479
- fileNameForLibrary = fileName;
1480
- break;
1481
- }
1482
- }
1483
- if (fileNameForLibrary) {
1484
- deployedLibraries.push({
1485
- file: fileNameForLibrary,
1486
- contract: libraryName,
1487
- address: address.toString(),
1488
- });
1489
- }
1490
-
1491
- for (const linkRef in libraries.linkReferences) {
1492
- for (const contractName in libraries.linkReferences[linkRef]) {
1493
- // If the library name matches the one we just deployed, we replace it.
1494
- if (contractName !== libraryName) {
1495
- continue;
1496
- }
1497
-
1498
- // We read the first instance to figure out what we are to replace.
1499
- const start = 2 + 2 * libraries.linkReferences[linkRef][contractName][0].start;
1500
- const length = 2 * libraries.linkReferences[linkRef][contractName][0].length;
1501
-
1502
- const toReplace = bytecode.slice(start, start + length);
1503
- replacements[toReplace] = address;
1504
- }
1505
- }
1506
- }
1507
-
1508
- const escapeRegExp = (s: string) => {
1509
- return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // Escape special characters
1510
- };
1511
-
1512
- for (const toReplace in replacements) {
1513
- const replacement = replacements[toReplace].toString().slice(2);
1514
- bytecode = bytecode.replace(new RegExp(escapeRegExp(toReplace), 'g'), replacement) as Hex;
1515
- }
1516
-
1517
- // Reth fails gas estimation if the deployed contract attempts to call a library that is not yet deployed,
1518
- // so we wait for all library deployments to be mined before deploying the contract.
1519
- // However, if we are in fast mode or using debugMaxGasLimit, we will skip simulation, so we can skip waiting.
1520
- if (libraryTxs.length > 0 && !acceleratedTestDeployments) {
1521
- logger?.verbose(`Awaiting for linked libraries to be deployed`);
1522
- await Promise.all(libraryTxs.map(txHash => extendedClient.waitForTransactionReceipt({ hash: txHash })));
1523
- } else {
1524
- logger?.verbose(
1525
- `Skipping waiting for linked libraries to be deployed ${
1526
- acceleratedTestDeployments ? '(accelerated test deployments)' : ''
1527
- }`,
1528
- );
1529
- }
1530
- }
1531
-
1532
- if (saltFromOpts) {
1533
- logger?.info(`Deploying contract with salt ${saltFromOpts}`);
1534
- const { address, paddedSalt: salt, calldata } = getExpectedAddress(abi, bytecode, args, saltFromOpts);
1535
- resultingAddress = address;
1536
- const existing = await extendedClient.getCode({ address: resultingAddress });
1537
- if (existing === undefined || existing === '0x') {
1538
- try {
1539
- await l1TxUtils.simulate({ to: DEPLOYER_ADDRESS, data: concatHex([salt, calldata]) }, { gasLimit });
1540
- } catch (err) {
1541
- logger?.error(`Failed to simulate deployment tx using universal deployer`, err);
1542
- await l1TxUtils.simulate({ to: null, data: encodeDeployData({ abi, bytecode, args }) });
1543
- }
1544
- const res = await l1TxUtils.sendTransaction(
1545
- { to: DEPLOYER_ADDRESS, data: concatHex([salt, calldata]) },
1546
- { gasLimit },
1547
- );
1548
- txHash = res.txHash;
1549
-
1550
- logger?.verbose(`Deployed contract with salt ${salt} to address ${resultingAddress} in tx ${txHash}.`);
1551
- } else {
1552
- logger?.verbose(`Skipping existing deployment of contract with salt ${salt} to address ${resultingAddress}`);
1553
- }
1554
- } else {
1555
- const deployData = encodeDeployData({ abi, bytecode, args });
1556
- const { receipt } = await l1TxUtils.sendAndMonitorTransaction({
1557
- to: null,
1558
- data: deployData,
1559
- });
1560
-
1561
- txHash = receipt.transactionHash;
1562
- resultingAddress = receipt.contractAddress;
1563
- if (!resultingAddress) {
1564
- throw new Error(
1565
- `No contract address found in receipt: ${JSON.stringify(receipt, (_, val) =>
1566
- typeof val === 'bigint' ? String(val) : val,
1567
- )}`,
1568
- );
1569
- }
1570
- }
1571
-
1572
- return { address: EthAddress.fromString(resultingAddress!), txHash, deployedLibraries };
1573
- }
1574
-
1575
- export function getExpectedAddress(
1576
- abi: Narrow<Abi | readonly unknown[]>,
1577
- bytecode: Hex,
1578
- args: readonly unknown[],
1579
- salt: Hex,
1580
- ) {
1581
- const paddedSalt = padHex(salt, { size: 32 });
1582
- const calldata = encodeDeployData({ abi, bytecode, args });
1583
- const address = getContractAddress({
1584
- from: DEPLOYER_ADDRESS,
1585
- salt: paddedSalt,
1586
- bytecode: calldata,
1587
- opcode: 'CREATE2',
1588
- });
1589
- return {
1590
- address,
1591
- paddedSalt,
1592
- calldata,
1593
- };
1594
- }
1595
-
1596
- // docs:end:deployL1Contract