@aztec/ethereum 0.0.1-commit.b655e406 → 0.0.1-commit.bf2612ae

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