@aztec/cli 0.0.1-commit.a89ec08 → 0.0.1-commit.aa0c64f

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 (75) hide show
  1. package/dest/cmds/aztec_node/block_number.js +1 -1
  2. package/dest/cmds/aztec_node/get_logs.d.ts +30 -4
  3. package/dest/cmds/aztec_node/get_logs.d.ts.map +1 -1
  4. package/dest/cmds/aztec_node/get_logs.js +39 -29
  5. package/dest/cmds/aztec_node/get_node_info.d.ts +1 -1
  6. package/dest/cmds/aztec_node/get_node_info.d.ts.map +1 -1
  7. package/dest/cmds/aztec_node/get_node_info.js +0 -2
  8. package/dest/cmds/aztec_node/index.d.ts +1 -1
  9. package/dest/cmds/aztec_node/index.d.ts.map +1 -1
  10. package/dest/cmds/aztec_node/index.js +13 -3
  11. package/dest/cmds/infrastructure/setup_l2_contract.d.ts +1 -1
  12. package/dest/cmds/infrastructure/setup_l2_contract.d.ts.map +1 -1
  13. package/dest/cmds/infrastructure/setup_l2_contract.js +10 -6
  14. package/dest/cmds/l1/deploy_l1_contracts_cmd.d.ts +1 -1
  15. package/dest/cmds/l1/deploy_l1_contracts_cmd.d.ts.map +1 -1
  16. package/dest/cmds/l1/deploy_l1_contracts_cmd.js +0 -1
  17. package/dest/cmds/l1/deploy_new_rollup.d.ts +1 -1
  18. package/dest/cmds/l1/deploy_new_rollup.d.ts.map +1 -1
  19. package/dest/cmds/l1/deploy_new_rollup.js +2 -4
  20. package/dest/cmds/l1/update_l1_validators.d.ts +1 -1
  21. package/dest/cmds/l1/update_l1_validators.d.ts.map +1 -1
  22. package/dest/cmds/l1/update_l1_validators.js +0 -1
  23. package/dest/cmds/validator_keys/eth_json_v3_worker.d.ts +2 -0
  24. package/dest/cmds/validator_keys/eth_json_v3_worker.d.ts.map +1 -0
  25. package/dest/cmds/validator_keys/eth_json_v3_worker.js +27 -0
  26. package/dest/cmds/validator_keys/index.d.ts +1 -1
  27. package/dest/cmds/validator_keys/index.d.ts.map +1 -1
  28. package/dest/cmds/validator_keys/index.js +7 -6
  29. package/dest/cmds/validator_keys/new.d.ts +7 -1
  30. package/dest/cmds/validator_keys/new.d.ts.map +1 -1
  31. package/dest/cmds/validator_keys/new.js +98 -12
  32. package/dest/cmds/validator_keys/set_funding_account.d.ts +14 -0
  33. package/dest/cmds/validator_keys/set_funding_account.d.ts.map +1 -0
  34. package/dest/cmds/validator_keys/set_funding_account.js +37 -0
  35. package/dest/cmds/validator_keys/shared.d.ts +15 -2
  36. package/dest/cmds/validator_keys/shared.d.ts.map +1 -1
  37. package/dest/cmds/validator_keys/shared.js +100 -23
  38. package/dest/cmds/validator_keys/utils.d.ts +12 -2
  39. package/dest/cmds/validator_keys/utils.d.ts.map +1 -1
  40. package/dest/cmds/validator_keys/utils.js +34 -0
  41. package/dest/config/chain_l2_config.d.ts +7 -2
  42. package/dest/config/chain_l2_config.d.ts.map +1 -1
  43. package/dest/config/chain_l2_config.js +17 -2
  44. package/dest/config/generated/networks.d.ts +63 -45
  45. package/dest/config/generated/networks.d.ts.map +1 -1
  46. package/dest/config/generated/networks.js +62 -44
  47. package/dest/utils/aztec.d.ts +1 -2
  48. package/dest/utils/aztec.d.ts.map +1 -1
  49. package/dest/utils/aztec.js +2 -3
  50. package/dest/utils/commands.d.ts +20 -11
  51. package/dest/utils/commands.d.ts.map +1 -1
  52. package/dest/utils/commands.js +29 -18
  53. package/dest/utils/inspect.d.ts +1 -1
  54. package/dest/utils/inspect.d.ts.map +1 -1
  55. package/dest/utils/inspect.js +11 -11
  56. package/package.json +30 -30
  57. package/src/cmds/aztec_node/block_number.ts +1 -1
  58. package/src/cmds/aztec_node/get_logs.ts +70 -38
  59. package/src/cmds/aztec_node/get_node_info.ts +0 -2
  60. package/src/cmds/aztec_node/index.ts +13 -8
  61. package/src/cmds/infrastructure/setup_l2_contract.ts +9 -5
  62. package/src/cmds/l1/deploy_l1_contracts_cmd.ts +0 -1
  63. package/src/cmds/l1/deploy_new_rollup.ts +1 -3
  64. package/src/cmds/l1/update_l1_validators.ts +0 -1
  65. package/src/cmds/validator_keys/eth_json_v3_worker.ts +30 -0
  66. package/src/cmds/validator_keys/index.ts +48 -8
  67. package/src/cmds/validator_keys/new.ts +129 -9
  68. package/src/cmds/validator_keys/set_funding_account.ts +55 -0
  69. package/src/cmds/validator_keys/shared.ts +123 -35
  70. package/src/cmds/validator_keys/utils.ts +44 -1
  71. package/src/config/chain_l2_config.ts +17 -2
  72. package/src/config/generated/networks.ts +62 -44
  73. package/src/utils/aztec.ts +12 -18
  74. package/src/utils/commands.ts +36 -22
  75. package/src/utils/inspect.ts +7 -8
@@ -29,7 +29,7 @@ export async function deployNewRollup(
29
29
  const initialFundedAccounts = initialAccounts.map(a => a.address).concat(sponsoredFPCAddress);
30
30
  const { genesisArchiveRoot, fundingNeeded } = await getGenesisValues(initialFundedAccounts);
31
31
 
32
- const { rollup, slashFactoryAddress } = await deployNewRollupContracts(
32
+ const { rollup } = await deployNewRollupContracts(
33
33
  registryAddress,
34
34
  rpcUrls,
35
35
  privateKey,
@@ -51,7 +51,6 @@ export async function deployNewRollup(
51
51
  initialFundedAccounts: initialFundedAccounts.map(a => a.toString()),
52
52
  initialValidators: initialValidators.map(a => a.attester.toString()),
53
53
  genesisArchiveRoot: genesisArchiveRoot.toString(),
54
- slashFactoryAddress: slashFactoryAddress.toString(),
55
54
  },
56
55
  null,
57
56
  2,
@@ -62,6 +61,5 @@ export async function deployNewRollup(
62
61
  log(`Initial funded accounts: ${initialFundedAccounts.map(a => a.toString()).join(', ')}`);
63
62
  log(`Initial validators: ${initialValidators.map(a => a.attester.toString()).join(', ')}`);
64
63
  log(`Genesis archive root: ${genesisArchiveRoot.toString()}`);
65
- log(`Slash Factory Address: ${slashFactoryAddress.toString()}`);
66
64
  }
67
65
  }
@@ -38,7 +38,6 @@ export interface LoggerArgs {
38
38
  export function generateL1Account() {
39
39
  const privateKey = generatePrivateKey();
40
40
  const account = privateKeyToAccount(privateKey);
41
- account.address;
42
41
  return {
43
42
  privateKey,
44
43
  address: account.address,
@@ -0,0 +1,30 @@
1
+ import { Wallet } from '@ethersproject/wallet';
2
+ import { parentPort, workerData } from 'worker_threads';
3
+
4
+ type EthJsonV3WorkerData = {
5
+ privateKeyHex: string;
6
+ password: string;
7
+ };
8
+
9
+ type SerializedError = {
10
+ message: string;
11
+ name?: string;
12
+ stack?: string;
13
+ };
14
+
15
+ function serializeError(error: unknown): SerializedError {
16
+ if (error instanceof Error) {
17
+ return { message: error.message, name: error.name, stack: error.stack };
18
+ }
19
+ return { message: String(error) };
20
+ }
21
+
22
+ void (async () => {
23
+ try {
24
+ const { privateKeyHex, password } = workerData as EthJsonV3WorkerData;
25
+ const json = await new Wallet(privateKeyHex).encrypt(password);
26
+ parentPort?.postMessage({ json });
27
+ } catch (error) {
28
+ parentPort?.postMessage({ error: serializeError(error) });
29
+ }
30
+ })();
@@ -1,6 +1,6 @@
1
1
  import type { LogFn } from '@aztec/foundation/log';
2
2
 
3
- import { Command } from 'commander';
3
+ import { Command, Option } from 'commander';
4
4
 
5
5
  import { parseAztecAddress, parseEthereumAddress, parseHex, parseOptionalInteger } from '../../utils/commands.js';
6
6
  import { defaultBlsPath } from './utils.js';
@@ -33,15 +33,31 @@ export function injectCommands(program: Command, log: LogFn) {
33
33
  'Coinbase ETH address to use when proposing. Defaults to attester address.',
34
34
  parseEthereumAddress,
35
35
  )
36
- // TODO: add funding account back in when implemented
37
- // .option('--funding-account <privateKey|address>', 'ETH private key (or address for remote signer setup) to fund publishers')
36
+ .option(
37
+ '--funding-account <privateKey|address>',
38
+ 'ETH funding account used to top up publisher EOAs. Provide a private key, or an address together with --remote-signer.',
39
+ )
38
40
  .option('--remote-signer <url>', 'Default remote signer URL for accounts in this file')
39
41
  .option('--ikm <hex>', 'Initial keying material for BLS (alternative to mnemonic)', value => parseHex(value, 32))
40
42
  .option('--bls-path <path>', `EIP-2334 path (default ${defaultBlsPath})`)
41
- .option(
42
- '--password <str>',
43
- 'Password for writing keystore files (ETH JSON V3 and BLS EIP-2335). Empty string allowed',
43
+ .addOption(
44
+ new Option('--password <str>', 'Shared password for writing ETH JSON V3 and BLS EIP-2335 keystore files').env(
45
+ 'AZTEC_KEYSTORE_PASSWORD',
46
+ ),
44
47
  )
48
+ .option('--password-file <path>', 'File containing the shared password for writing keystore files')
49
+ .addOption(
50
+ new Option('--eth-password <str>', 'Password for writing ETH JSON V3 keystore files').env(
51
+ 'AZTEC_ETH_KEYSTORE_PASSWORD',
52
+ ),
53
+ )
54
+ .option('--eth-password-file <path>', 'File containing the password for writing ETH JSON V3 keystore files')
55
+ .addOption(
56
+ new Option('--bls-password <str>', 'Password for writing BLS EIP-2335 keystore files').env(
57
+ 'AZTEC_BLS_KEYSTORE_PASSWORD',
58
+ ),
59
+ )
60
+ .option('--bls-password-file <path>', 'File containing the password for writing BLS EIP-2335 keystore files')
45
61
  .option('--encrypted-keystore-dir <dir>', 'Output directory for encrypted keystore file(s)')
46
62
  .option('--json', 'Echo resulting JSON to stdout')
47
63
  .option('--staker-output', 'Generate a single staker output JSON file with an array of validator entries')
@@ -85,8 +101,6 @@ export function injectCommands(program: Command, log: LogFn) {
85
101
  'Coinbase ETH address to use when proposing. Defaults to attester address.',
86
102
  parseEthereumAddress,
87
103
  )
88
- // TODO: add funding account back in when implemented
89
- // .option('--funding-account <privateKey|address>', 'ETH private key (or address for remote signer setup) to fund publishers')
90
104
  .option('--remote-signer <url>', 'Default remote signer URL for accounts in this file')
91
105
  .option('--ikm <hex>', 'Initial keying material for BLS (alternative to mnemonic)', value => parseHex(value, 32))
92
106
  .option('--bls-path <path>', `EIP-2334 path (default ${defaultBlsPath})`)
@@ -103,6 +117,32 @@ export function injectCommands(program: Command, log: LogFn) {
103
117
  await addValidatorKeys(existing, options, log);
104
118
  });
105
119
 
120
+ group
121
+ .command('set-funding-account')
122
+ .summary('Set the funding account of an existing keystore')
123
+ .description(
124
+ 'Sets the keystore-level ETH funding account used to top up publisher EOAs, replacing any existing one',
125
+ )
126
+ .argument('<existing>', 'Path to existing keystore JSON')
127
+ .argument(
128
+ '<privateKey|address>',
129
+ 'Funding account: a private key, or an address (needs --remote-signer unless the keystore already defines one)',
130
+ )
131
+ .option(
132
+ '--remote-signer <url>',
133
+ 'Remote signer URL for the funding account (required with an address unless the keystore already defines one)',
134
+ )
135
+ .option(
136
+ '--password <str>',
137
+ 'Password for writing the funding key as an encrypted ETH JSON V3 file. Empty string allowed',
138
+ )
139
+ .option('--encrypted-keystore-dir <dir>', 'Output directory for the encrypted funding key file')
140
+ .option('--json', 'Echo resulting JSON to stdout')
141
+ .action(async (existing: string, fundingAccount: string, options) => {
142
+ const { setFundingAccount } = await import('./set_funding_account.js');
143
+ await setFundingAccount(existing, fundingAccount, options, log);
144
+ });
145
+
106
146
  group
107
147
  .command('staker')
108
148
  .summary('Generate staking JSON from keystore')
@@ -6,15 +6,17 @@ import type { LogFn } from '@aztec/foundation/log';
6
6
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
7
7
 
8
8
  import { wordlist } from '@scure/bip39/wordlists/english.js';
9
- import { writeFile } from 'fs/promises';
9
+ import { readFile, writeFile } from 'fs/promises';
10
10
  import { basename, dirname, join } from 'path';
11
11
  import { createPublicClient, fallback, http } from 'viem';
12
- import { generateMnemonic, mnemonicToAccount } from 'viem/accounts';
12
+ import { generateMnemonic, mnemonicToAccount, privateKeyToAccount } from 'viem/accounts';
13
13
 
14
14
  import {
15
15
  buildValidatorEntries,
16
+ encryptFundingAccountToFile,
16
17
  logValidatorSummaries,
17
18
  maybePrintJson,
19
+ resolveFundingAccount,
18
20
  resolveKeystoreOutputPath,
19
21
  writeBlsBn254ToFile,
20
22
  writeEthJsonV3ToFile,
@@ -23,6 +25,7 @@ import {
23
25
  import { processAttesterAccounts } from './staker.js';
24
26
  import {
25
27
  validateBlsPathOptions,
28
+ validateFundingAccountOptions,
26
29
  validatePublisherOptions,
27
30
  validateRemoteSignerOptions,
28
31
  validateStakerOutputOptions,
@@ -42,10 +45,16 @@ export type NewValidatorKeystoreOptions = {
42
45
  ikm?: string;
43
46
  blsPath?: string;
44
47
  password?: string;
48
+ passwordFile?: string;
49
+ ethPassword?: string;
50
+ ethPasswordFile?: string;
51
+ blsPassword?: string;
52
+ blsPasswordFile?: string;
45
53
  encryptedKeystoreDir?: string;
46
54
  json?: boolean;
47
55
  feeRecipient: AztecAddress;
48
56
  coinbase?: EthAddress;
57
+ fundingAccount?: string;
49
58
  remoteSigner?: string;
50
59
  stakerOutput?: boolean;
51
60
  gseAddress?: EthAddress;
@@ -53,6 +62,86 @@ export type NewValidatorKeystoreOptions = {
53
62
  l1ChainId?: number;
54
63
  };
55
64
 
65
+ type PasswordSourceOptions = Pick<
66
+ NewValidatorKeystoreOptions,
67
+ 'password' | 'passwordFile' | 'ethPassword' | 'ethPasswordFile' | 'blsPassword' | 'blsPasswordFile'
68
+ >;
69
+
70
+ type PasswordSource = {
71
+ password?: string;
72
+ passwordFile?: string;
73
+ passwordOption: string;
74
+ passwordFileOption: string;
75
+ };
76
+
77
+ function validatePassword(password: string, source: string): string {
78
+ if (password.length === 0) {
79
+ throw new Error(`${source} cannot be empty`);
80
+ }
81
+ return password;
82
+ }
83
+
84
+ function stripOneTrailingNewline(password: string): string {
85
+ if (password.endsWith('\n')) {
86
+ password = password.slice(0, -1);
87
+ }
88
+ if (password.endsWith('\r')) {
89
+ password = password.slice(0, -1);
90
+ }
91
+ return password;
92
+ }
93
+
94
+ async function resolvePasswordSource(source: PasswordSource): Promise<string | undefined> {
95
+ if (source.password !== undefined && source.passwordFile !== undefined) {
96
+ throw new Error(`${source.passwordOption} and ${source.passwordFileOption} cannot be used together`);
97
+ }
98
+ if (source.password !== undefined) {
99
+ return validatePassword(source.password, source.passwordOption);
100
+ }
101
+ if (source.passwordFile !== undefined) {
102
+ if (source.passwordFile.length === 0) {
103
+ throw new Error(`${source.passwordFileOption} cannot be empty`);
104
+ }
105
+ const password = stripOneTrailingNewline(await readFile(source.passwordFile, 'utf-8'));
106
+ return validatePassword(password, source.passwordFileOption);
107
+ }
108
+
109
+ return undefined;
110
+ }
111
+
112
+ async function resolvePasswords(options: PasswordSourceOptions) {
113
+ const sharedPassword = await resolvePasswordSource({
114
+ password: options.password,
115
+ passwordFile: options.passwordFile,
116
+ passwordOption: '--password',
117
+ passwordFileOption: '--password-file',
118
+ });
119
+ const ethPassword =
120
+ (await resolvePasswordSource({
121
+ password: options.ethPassword,
122
+ passwordFile: options.ethPasswordFile,
123
+ passwordOption: '--eth-password',
124
+ passwordFileOption: '--eth-password-file',
125
+ })) ?? sharedPassword;
126
+ const blsPassword =
127
+ (await resolvePasswordSource({
128
+ password: options.blsPassword,
129
+ passwordFile: options.blsPasswordFile,
130
+ passwordOption: '--bls-password',
131
+ passwordFileOption: '--bls-password-file',
132
+ })) ?? sharedPassword;
133
+
134
+ if (ethPassword === undefined && blsPassword === undefined) {
135
+ return {};
136
+ }
137
+ if (ethPassword === undefined || blsPassword === undefined) {
138
+ throw new Error(
139
+ 'Both ETH and BLS passwords are required when writing encrypted keystores. Provide --password to use one password for both, or provide both --eth-password and --bls-password.',
140
+ );
141
+ }
142
+ return { ethPassword, blsPassword };
143
+ }
144
+
56
145
  export async function newValidatorKeystore(options: NewValidatorKeystoreOptions, log: LogFn) {
57
146
  // validate bls-path inputs before proceeding with key generation
58
147
  validateBlsPathOptions(options);
@@ -62,6 +151,8 @@ export async function newValidatorKeystore(options: NewValidatorKeystoreOptions,
62
151
  validatePublisherOptions(options);
63
152
  // validate remote signer options
64
153
  validateRemoteSignerOptions(options);
154
+ // validate funding account option
155
+ validateFundingAccountOptions(options);
65
156
 
66
157
  const {
67
158
  dataDir,
@@ -71,6 +162,7 @@ export async function newValidatorKeystore(options: NewValidatorKeystoreOptions,
71
162
  publishers,
72
163
  json,
73
164
  coinbase,
165
+ fundingAccount,
74
166
  accountIndex = 0,
75
167
  addressIndex = 0,
76
168
  feeRecipient,
@@ -78,7 +170,12 @@ export async function newValidatorKeystore(options: NewValidatorKeystoreOptions,
78
170
  blsPath,
79
171
  ikm,
80
172
  mnemonic: _mnemonic,
81
- password,
173
+ password: passwordOption,
174
+ passwordFile,
175
+ ethPassword: ethPasswordOption,
176
+ ethPasswordFile,
177
+ blsPassword: blsPasswordOption,
178
+ blsPasswordFile,
82
179
  encryptedKeystoreDir,
83
180
  stakerOutput,
84
181
  gseAddress,
@@ -86,9 +183,18 @@ export async function newValidatorKeystore(options: NewValidatorKeystoreOptions,
86
183
  l1ChainId,
87
184
  } = options;
88
185
 
186
+ const { ethPassword, blsPassword } = await resolvePasswords({
187
+ password: passwordOption,
188
+ passwordFile,
189
+ ethPassword: ethPasswordOption,
190
+ ethPasswordFile,
191
+ blsPassword: blsPasswordOption,
192
+ blsPasswordFile,
193
+ });
194
+ const shouldEncryptKeystores = ethPassword !== undefined && blsPassword !== undefined;
89
195
  const mnemonic = _mnemonic ?? generateMnemonic(wordlist);
90
196
 
91
- if (!_mnemonic && !json) {
197
+ if (!_mnemonic && !json && !shouldEncryptKeystores) {
92
198
  log('No mnemonic provided, generating new one...');
93
199
  log(`Using new mnemonic:`);
94
200
  log('');
@@ -114,17 +220,26 @@ export async function newValidatorKeystore(options: NewValidatorKeystoreOptions,
114
220
  remoteSigner,
115
221
  });
116
222
 
223
+ let resolvedFundingAccount = fundingAccount ? resolveFundingAccount(fundingAccount, remoteSigner) : undefined;
224
+
117
225
  // If password provided, write ETH JSON V3 and BLS BN254 keystores and replace plaintext
118
- if (password !== undefined) {
226
+ if (shouldEncryptKeystores) {
119
227
  const encryptedKeystoreOutDir =
120
228
  encryptedKeystoreDir && encryptedKeystoreDir.length > 0 ? encryptedKeystoreDir : keystoreOutDir;
121
- await writeEthJsonV3ToFile(validators, { outDir: encryptedKeystoreOutDir, password });
122
- await writeBlsBn254ToFile(validators, { outDir: encryptedKeystoreOutDir, password });
229
+ await writeEthJsonV3ToFile(validators, { outDir: encryptedKeystoreOutDir, password: ethPassword });
230
+ await writeBlsBn254ToFile(validators, { outDir: encryptedKeystoreOutDir, password: blsPassword });
231
+ if (resolvedFundingAccount) {
232
+ resolvedFundingAccount = await encryptFundingAccountToFile(resolvedFundingAccount, {
233
+ outDir: encryptedKeystoreOutDir,
234
+ password: ethPassword,
235
+ });
236
+ }
123
237
  }
124
238
 
125
239
  const keystore = {
126
240
  schemaVersion: 1,
127
241
  validators,
242
+ ...(resolvedFundingAccount ? { fundingAccount: resolvedFundingAccount } : {}),
128
243
  };
129
244
 
130
245
  await writeKeystoreFile(outputPath, keystore);
@@ -145,7 +260,7 @@ export async function newValidatorKeystore(options: NewValidatorKeystoreOptions,
145
260
  // Process each validator
146
261
  for (let i = 0; i < validators.length; i++) {
147
262
  const validator = validators[i];
148
- const outputs = await processAttesterAccounts(validator.attester, gse, password);
263
+ const outputs = await processAttesterAccounts(validator.attester, gse);
149
264
 
150
265
  // Collect all staker outputs
151
266
  for (let j = 0; j < outputs.length; j++) {
@@ -160,7 +275,7 @@ export async function newValidatorKeystore(options: NewValidatorKeystoreOptions,
160
275
  }
161
276
  }
162
277
 
163
- const outputData = !_mnemonic ? { ...keystore, generatedMnemonic: mnemonic } : keystore;
278
+ const outputData = !_mnemonic && !shouldEncryptKeystores ? { ...keystore, generatedMnemonic: mnemonic } : keystore;
164
279
 
165
280
  // Handle JSON output
166
281
  if (json) {
@@ -186,6 +301,11 @@ export async function newValidatorKeystore(options: NewValidatorKeystoreOptions,
186
301
  // print a concise summary of public keys (addresses and BLS pubkeys) if no --json options was selected
187
302
  if (!json) {
188
303
  logValidatorSummaries(log, summaries);
304
+ if (fundingAccount) {
305
+ const funderAddress =
306
+ fundingAccount.length === 66 ? privateKeyToAccount(fundingAccount as `0x${string}`).address : fundingAccount;
307
+ log(`funding account: ${funderAddress}`);
308
+ }
189
309
  }
190
310
 
191
311
  if (mnemonic && remoteSigner && !json) {
@@ -0,0 +1,55 @@
1
+ import type { LogFn } from '@aztec/foundation/log';
2
+ import { loadKeystoreFile } from '@aztec/node-keystore/loader';
3
+ import type { KeyStore } from '@aztec/node-keystore/types';
4
+
5
+ import { dirname } from 'path';
6
+ import { privateKeyToAccount } from 'viem/accounts';
7
+
8
+ import { encryptFundingAccountToFile, maybePrintJson, resolveFundingAccount, writeKeystoreFile } from './shared.js';
9
+ import { validateFundingAccountOptions } from './utils.js';
10
+
11
+ export type SetFundingAccountOptions = {
12
+ remoteSigner?: string;
13
+ password?: string;
14
+ encryptedKeystoreDir?: string;
15
+ json?: boolean;
16
+ };
17
+
18
+ /**
19
+ * Sets the top-level funding account of an existing keystore, replacing any previous one. The
20
+ * account may be a private key, or an address paired with a remote signer URL. With a password,
21
+ * a plaintext key is encrypted to an ETH JSON V3 file and stored as a { path, password } reference.
22
+ */
23
+ export async function setFundingAccount(
24
+ existing: string,
25
+ fundingAccount: string,
26
+ options: SetFundingAccountOptions,
27
+ log: LogFn,
28
+ ) {
29
+ const { remoteSigner, password, encryptedKeystoreDir, json } = options;
30
+
31
+ const keystore: KeyStore = loadKeystoreFile(existing);
32
+
33
+ const validated = { fundingAccount, remoteSigner };
34
+ validateFundingAccountOptions(validated, !!keystore.remoteSigner);
35
+
36
+ let resolved = resolveFundingAccount(validated.fundingAccount!, remoteSigner);
37
+ if (password !== undefined) {
38
+ const outDir = encryptedKeystoreDir && encryptedKeystoreDir.length > 0 ? encryptedKeystoreDir : dirname(existing);
39
+ resolved = await encryptFundingAccountToFile(resolved, { outDir, password });
40
+ }
41
+
42
+ if (keystore.fundingAccount) {
43
+ log('Replacing existing funding account in keystore');
44
+ }
45
+ keystore.fundingAccount = resolved;
46
+
47
+ await writeKeystoreFile(existing, keystore);
48
+
49
+ if (!json) {
50
+ const value = validated.fundingAccount!;
51
+ const funderAddress = value.length === 66 ? privateKeyToAccount(value as `0x${string}`).address : value;
52
+ log(`Set funding account ${funderAddress} in ${existing}`);
53
+ }
54
+ maybePrintJson(log, !!json, keystore as unknown as Record<string, any>);
55
+ }