@aztec/cli-wallet 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 (49) hide show
  1. package/dest/bin/index.js +1 -1
  2. package/dest/cmds/check_tx.js +13 -12
  3. package/dest/cmds/create_account.d.ts +4 -2
  4. package/dest/cmds/create_account.d.ts.map +1 -1
  5. package/dest/cmds/create_account.js +26 -10
  6. package/dest/cmds/deploy.d.ts +3 -3
  7. package/dest/cmds/deploy.d.ts.map +1 -1
  8. package/dest/cmds/deploy.js +23 -21
  9. package/dest/cmds/deploy_account.js +4 -7
  10. package/dest/cmds/import_test_accounts.d.ts +1 -1
  11. package/dest/cmds/import_test_accounts.d.ts.map +1 -1
  12. package/dest/cmds/import_test_accounts.js +2 -1
  13. package/dest/cmds/index.d.ts +1 -1
  14. package/dest/cmds/index.d.ts.map +1 -1
  15. package/dest/cmds/index.js +10 -9
  16. package/dest/cmds/send.js +3 -6
  17. package/dest/cmds/simulate.d.ts +1 -1
  18. package/dest/cmds/simulate.d.ts.map +1 -1
  19. package/dest/cmds/simulate.js +2 -1
  20. package/dest/storage/wallet_db.d.ts +7 -4
  21. package/dest/storage/wallet_db.d.ts.map +1 -1
  22. package/dest/storage/wallet_db.js +15 -1
  23. package/dest/utils/constants.d.ts +2 -2
  24. package/dest/utils/constants.d.ts.map +1 -1
  25. package/dest/utils/constants.js +1 -0
  26. package/dest/utils/options/fees.d.ts +2 -1
  27. package/dest/utils/options/fees.d.ts.map +1 -1
  28. package/dest/utils/options/fees.js +26 -3
  29. package/dest/utils/options/options.d.ts +2 -2
  30. package/dest/utils/options/options.d.ts.map +1 -1
  31. package/dest/utils/options/options.js +5 -5
  32. package/dest/utils/wallet.d.ts +28 -5
  33. package/dest/utils/wallet.d.ts.map +1 -1
  34. package/dest/utils/wallet.js +132 -75
  35. package/package.json +16 -15
  36. package/src/bin/index.ts +1 -1
  37. package/src/cmds/check_tx.ts +14 -13
  38. package/src/cmds/create_account.ts +27 -15
  39. package/src/cmds/deploy.ts +22 -23
  40. package/src/cmds/deploy_account.ts +4 -4
  41. package/src/cmds/import_test_accounts.ts +12 -1
  42. package/src/cmds/index.ts +14 -11
  43. package/src/cmds/send.ts +3 -3
  44. package/src/cmds/simulate.ts +2 -1
  45. package/src/storage/wallet_db.ts +24 -2
  46. package/src/utils/constants.ts +7 -1
  47. package/src/utils/options/fees.ts +28 -4
  48. package/src/utils/options/options.ts +5 -5
  49. package/src/utils/wallet.ts +171 -92
@@ -1,39 +1,46 @@
1
- import { EcdsaRAccountContract, EcdsaRSSHAccountContract } from '@aztec/accounts/ecdsa';
2
- import { SchnorrAccountContract } from '@aztec/accounts/schnorr';
3
- import { StubEcdsaAccountContractArtifact, createStubEcdsaAccount } from '@aztec/accounts/stub/ecdsa';
4
- import { StubSchnorrAccountContractArtifact, createStubSchnorrAccount } from '@aztec/accounts/stub/schnorr';
1
+ import { EcdsaKAccountContract, EcdsaRAccountContract, EcdsaRSSHAccountContract } from '@aztec/accounts/ecdsa';
2
+ import { StubEcdsaAccountContractArtifact, createStubEcdsaAccount } from '@aztec/accounts/ecdsa/stub';
3
+ import { SchnorrAccountContract, SchnorrInitializerlessAccountContract } from '@aztec/accounts/schnorr';
4
+ import { StubSchnorrAccountContractArtifact, createStubSchnorrAccount } from '@aztec/accounts/schnorr/stub';
5
5
  import { getIdentities } from '@aztec/accounts/utils';
6
6
  import { type Account, type AccountContract, NO_FROM } from '@aztec/aztec.js/account';
7
7
  import {
8
+ ContractFunctionInteraction,
8
9
  type InteractionFeeOptions,
9
- getContractInstanceFromInstantiationParams,
10
- getGasLimits,
10
+ getContractClassFromArtifact,
11
11
  } from '@aztec/aztec.js/contracts';
12
12
  import type { AztecNode } from '@aztec/aztec.js/node';
13
- import { AccountManager, type Aliased, type SimulateOptions } from '@aztec/aztec.js/wallet';
13
+ import { AccountManager, type Aliased } from '@aztec/aztec.js/wallet';
14
14
  import { TxSimulationResultWithAppOffset } from '@aztec/aztec.js/wallet';
15
15
  import type { DefaultAccountEntrypointOptions } from '@aztec/entrypoints/account';
16
16
  import { DefaultEntrypoint } from '@aztec/entrypoints/default';
17
17
  import { Fr } from '@aztec/foundation/curves/bn254';
18
+ import { GrumpkinScalar } from '@aztec/foundation/curves/grumpkin';
18
19
  import type { LogFn } from '@aztec/foundation/log';
19
20
  import type { NotesFilter } from '@aztec/pxe/client/lazy';
20
21
  import type { PXEConfig } from '@aztec/pxe/config';
21
22
  import type { PXE } from '@aztec/pxe/server';
22
23
  import { createPXE, getPXEConfig } from '@aztec/pxe/server';
24
+ import { getStandardAuthRegistry } from '@aztec/standard-contracts/auth-registry';
23
25
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
24
- import { deriveSigningKey } from '@aztec/stdlib/keys';
26
+ import type { Gas, GasUsed } from '@aztec/stdlib/gas';
25
27
  import { NoteDao } from '@aztec/stdlib/note';
26
28
  import type { SimulationOverrides, TxExecutionRequest, TxProvingResult } from '@aztec/stdlib/tx';
27
29
  import { ExecutionPayload, mergeExecutionPayloads } from '@aztec/stdlib/tx';
28
- import { BaseWallet, type SimulateViaEntrypointOptions } from '@aztec/wallet-sdk/base-wallet';
30
+ import { BaseWallet, type SimulateViaEntrypointOptions, getGasLimits } from '@aztec/wallet-sdk/base-wallet';
29
31
 
30
32
  import type { WalletDB } from '../storage/wallet_db.js';
31
33
  import type { AccountType } from './constants.js';
32
34
  import { extractECDSAPublicKeyFromBase64String } from './ecdsa.js';
33
- import { printGasEstimates } from './options/fees.js';
35
+
36
+ /** Padding the CLI wallet applies to simulated gas usage when deriving declared gas limits. */
37
+ const DEFAULT_ESTIMATED_GAS_PADDING = 0.1;
34
38
 
35
39
  export class CLIWallet extends BaseWallet {
36
40
  private accountCache = new Map<string, Account>();
41
+ // Stub class ids, populated on wallet startup
42
+ // to avoid redundant work per simulation
43
+ private stubClassIds = new Map<AccountType, Fr>();
37
44
 
38
45
  constructor(
39
46
  pxe: PXE,
@@ -53,7 +60,35 @@ export class CLIWallet extends BaseWallet {
53
60
  ): Promise<CLIWallet> {
54
61
  const pxeConfig = Object.assign(getPXEConfig(), overridePXEConfig);
55
62
  const pxe = await createPXE(node, pxeConfig);
56
- return new CLIWallet(pxe, node, log, db);
63
+ const wallet = new CLIWallet(pxe, node, log, db);
64
+ await wallet.initStubClasses();
65
+ await wallet.registerAuthRegistry();
66
+ return wallet;
67
+ }
68
+
69
+ private async registerAuthRegistry(): Promise<void> {
70
+ const { instance, artifact } = await getStandardAuthRegistry();
71
+ await this.pxe.registerContractClass(artifact);
72
+ await this.pxe.registerContract(instance);
73
+ }
74
+
75
+ /**
76
+ * Hashes and registers the stub class for every supported account type with PXE, populating
77
+ * stubClassIds. Called on wallet initialization.
78
+ */
79
+ private async initStubClasses(): Promise<void> {
80
+ const { id: schnorrClassId } = await getContractClassFromArtifact(StubSchnorrAccountContractArtifact);
81
+ await this.pxe.registerContractClass(StubSchnorrAccountContractArtifact);
82
+
83
+ // ecdsa stubs share the same class id
84
+ const { id: ecdsaClassId } = await getContractClassFromArtifact(StubEcdsaAccountContractArtifact);
85
+ await this.pxe.registerContractClass(StubEcdsaAccountContractArtifact);
86
+
87
+ this.stubClassIds.set('schnorr', schnorrClassId);
88
+ this.stubClassIds.set('schnorr_initializerless', schnorrClassId);
89
+ this.stubClassIds.set('ecdsasecp256k1', ecdsaClassId);
90
+ this.stubClassIds.set('ecdsasecp256r1', ecdsaClassId);
91
+ this.stubClassIds.set('ecdsasecp256r1ssh', ecdsaClassId);
57
92
  }
58
93
 
59
94
  override async getAccounts(): Promise<Aliased<AztecAddress>[]> {
@@ -61,11 +96,21 @@ export class CLIWallet extends BaseWallet {
61
96
  return Promise.resolve(
62
97
  accounts.map(({ key, value }) => {
63
98
  const alias = key.includes(':') ? key.slice(key.indexOf(':') + 1) : key;
64
- return { alias, item: AztecAddress.fromString(value) };
99
+ return { alias, item: AztecAddress.fromStringUnsafe(value) };
65
100
  }),
66
101
  );
67
102
  }
68
103
 
104
+ /**
105
+ * Derives suggested total and teardown gas limits from simulated gas usage, padded and clamped to the
106
+ * network's per-tx admission limits.
107
+ * @param gasUsed - The gas consumed during simulation (from a `simulate({ includeMetadata: true })` result).
108
+ */
109
+ async estimateGasLimits(gasUsed: GasUsed): Promise<{ gasLimits: Gas; teardownGasLimits: Gas }> {
110
+ const maxTxGasLimits = await this.getMaxTxGasLimits();
111
+ return getGasLimits(gasUsed, maxTxGasLimits, DEFAULT_ESTIMATED_GAS_PADDING);
112
+ }
113
+
69
114
  private async createCancellationTxExecutionRequest(
70
115
  from: AztecAddress,
71
116
  txNonce: Fr,
@@ -100,7 +145,10 @@ export class CLIWallet extends BaseWallet {
100
145
  increasedFee: InteractionFeeOptions,
101
146
  ): Promise<TxProvingResult> {
102
147
  const cancellationTxRequest = await this.createCancellationTxExecutionRequest(from, txNonce, increasedFee);
103
- return await this.pxe.proveTx(cancellationTxRequest, this.scopesFrom(from));
148
+ return await this.pxe.proveTx(cancellationTxRequest, {
149
+ scopes: this.scopesFrom(from, [], undefined),
150
+ senderForTags: from,
151
+ });
104
152
  }
105
153
 
106
154
  override async getAccountFromAddress(address: AztecAddress) {
@@ -108,7 +156,7 @@ export class CLIWallet extends BaseWallet {
108
156
  if (this.accountCache.has(address.toString())) {
109
157
  return this.accountCache.get(address.toString())!;
110
158
  } else {
111
- const accountManager = await this.createOrRetrieveAccount(address);
159
+ const accountManager = await this.retrieveAccount(address);
112
160
  account = await accountManager.getAccount();
113
161
  }
114
162
 
@@ -118,74 +166,115 @@ export class CLIWallet extends BaseWallet {
118
166
  return account;
119
167
  }
120
168
 
121
- private async createAccount(secret: Fr, salt: Fr, contract: AccountContract): Promise<AccountManager> {
122
- const accountManager = await AccountManager.create(this, secret, contract, salt);
123
-
124
- const instance = accountManager.getInstance();
125
- const artifact = await contract.getContractArtifact();
126
-
127
- await this.registerContract(instance, artifact, secret);
128
- this.accountCache.set(accountManager.address.toString(), await accountManager.getAccount());
129
- return accountManager;
130
- }
131
-
132
- async createOrRetrieveAccount(
133
- address?: AztecAddress,
134
- secretKey?: Fr,
135
- type: AccountType = 'schnorr',
136
- salt?: Fr,
169
+ /**
170
+ * Creates an account from freshly supplied keys. SSH accounts sign with a key held in the agent (resolved from
171
+ * `publicKey`), every other type is rooted on `signingKey`, with `secretKey` as its privacy secret.
172
+ */
173
+ async createAccount(
174
+ type: AccountType,
175
+ signingKey: GrumpkinScalar | undefined,
176
+ secretKey: Fr | undefined,
177
+ salt: Fr = Fr.ZERO,
137
178
  publicKey?: string,
138
179
  ): Promise<AccountManager> {
139
- let account;
140
-
141
- salt ??= Fr.ZERO;
180
+ const publicSigningKey =
181
+ type === 'ecdsasecp256r1ssh' ? await this.resolveSshPublicSigningKey(publicKey) : undefined;
182
+ return this.buildAccount(type, salt, signingKey, secretKey, publicSigningKey);
183
+ }
142
184
 
143
- if (this.db && address) {
144
- ({ type, secretKey, salt } = await this.db.retrieveAccount(address));
185
+ /**
186
+ * Retrieves a previously stored account by address, loading its keys, type and salt from the wallet database.
187
+ */
188
+ async retrieveAccount(address: AztecAddress): Promise<AccountManager> {
189
+ if (!this.db) {
190
+ throw new Error('Cannot retrieve an account without a wallet database');
145
191
  }
146
-
147
- if (!secretKey) {
148
- throw new Error('Cannot retrieve/create wallet without secret key');
192
+ const { type, signingKey, secretKey, salt } = await this.db.retrieveAccount(address);
193
+ if (type !== 'ecdsasecp256r1ssh' && !signingKey) {
194
+ throw new Error(
195
+ `Account ${address} has no stored signing key: it was created with an older version of aztec-wallet and is ` +
196
+ `incompatible with this one. Create a new account to continue.`,
197
+ );
149
198
  }
199
+ const publicSigningKey =
200
+ type === 'ecdsasecp256r1ssh' ? await this.db.retrieveAccountMetadata(address, 'publicSigningKey') : undefined;
201
+ return this.buildAccount(type, salt, signingKey, secretKey, publicSigningKey);
202
+ }
150
203
 
204
+ private async buildAccount(
205
+ type: AccountType,
206
+ salt: Fr,
207
+ signingKey: GrumpkinScalar | undefined,
208
+ secretKey: Fr | undefined,
209
+ publicSigningKey: Buffer | undefined,
210
+ ): Promise<AccountManager> {
151
211
  switch (type) {
152
- case 'schnorr': {
153
- account = await this.createAccount(secretKey, salt, new SchnorrAccountContract(deriveSigningKey(secretKey)));
154
- break;
155
- }
156
- case 'ecdsasecp256r1': {
157
- account = await this.createAccount(
158
- secretKey,
159
- salt,
160
- new EcdsaRAccountContract(deriveSigningKey(secretKey).toBuffer()),
161
- );
162
- break;
212
+ case 'schnorr':
213
+ case 'schnorr_initializerless':
214
+ case 'ecdsasecp256r1':
215
+ case 'ecdsasecp256k1': {
216
+ if (!signingKey || !secretKey) {
217
+ throw new Error('Cannot build account without signing key and secret key');
218
+ }
219
+ const contract =
220
+ type === 'schnorr'
221
+ ? new SchnorrAccountContract(signingKey)
222
+ : type === 'schnorr_initializerless'
223
+ ? new SchnorrInitializerlessAccountContract(signingKey)
224
+ : type === 'ecdsasecp256r1'
225
+ ? new EcdsaRAccountContract(signingKey.toBuffer())
226
+ : new EcdsaKAccountContract(signingKey.toBuffer());
227
+ return await this.materializeAccount(secretKey, salt, contract);
163
228
  }
164
229
  case 'ecdsasecp256r1ssh': {
165
- let publicSigningKey;
166
- if (this.db && address) {
167
- publicSigningKey = await this.db.retrieveAccountMetadata(address, 'publicSigningKey');
168
- } else if (publicKey) {
169
- const identities = await getIdentities();
170
- const foundIdentity = identities.find(
171
- identity => identity.type === 'ecdsa-sha2-nistp256' && identity.publicKey === publicKey,
172
- );
173
- if (!foundIdentity) {
174
- throw new Error(`Identity for public key ${publicKey} not found in the SSH agent`);
175
- }
176
- publicSigningKey = extractECDSAPublicKeyFromBase64String(foundIdentity.publicKey);
177
- } else {
178
- throw new Error('Public key must be provided for ECDSA SSH account');
230
+ if (!secretKey || !publicSigningKey) {
231
+ throw new Error('Cannot build SSH account without secret key and public signing key');
179
232
  }
180
- account = await this.createAccount(secretKey, salt, new EcdsaRSSHAccountContract(publicSigningKey));
181
- break;
233
+ return await this.materializeAccount(secretKey, salt, new EcdsaRSSHAccountContract(publicSigningKey));
182
234
  }
183
235
  default: {
184
236
  throw new Error(`Unsupported account type: ${type}`);
185
237
  }
186
238
  }
239
+ }
187
240
 
188
- return account;
241
+ private async resolveSshPublicSigningKey(publicKey: string | undefined): Promise<Buffer> {
242
+ if (!publicKey) {
243
+ throw new Error('Public key must be provided for ECDSA SSH account');
244
+ }
245
+ const identities = await getIdentities();
246
+ const foundIdentity = identities.find(
247
+ identity => identity.type === 'ecdsa-sha2-nistp256' && identity.publicKey === publicKey,
248
+ );
249
+ if (!foundIdentity) {
250
+ throw new Error(`Identity for public key ${publicKey} not found in the SSH agent`);
251
+ }
252
+ return extractECDSAPublicKeyFromBase64String(foundIdentity.publicKey);
253
+ }
254
+
255
+ private async materializeAccount(secret: Fr, salt: Fr, contract: AccountContract): Promise<AccountManager> {
256
+ const accountManager = await AccountManager.create(this, secret, contract, { salt });
257
+
258
+ const instance = accountManager.getInstance();
259
+ const artifact = await contract.getContractArtifact();
260
+
261
+ await this.registerContract(instance, artifact, secret);
262
+ this.accountCache.set(accountManager.address.toString(), await accountManager.getAccount());
263
+
264
+ // Initializerless accounts have no deployment tx; their address commits to the signing public key
265
+ // (via the contract's immutablesHash, resolved by AccountManager.create) and the constructor's
266
+ // storage writes are materialized locally via a simulated "store" call here.
267
+ if (contract instanceof SchnorrInitializerlessAccountContract) {
268
+ const constructorAbi = artifact.functions.find(f => f.name === 'constructor');
269
+ if (!constructorAbi) {
270
+ throw new Error('Could not create SchnorrInitializerlessAccount: constructor ABI not found');
271
+ }
272
+ const { x, y } = await contract.getSigningPublicKey();
273
+ const storeCall = new ContractFunctionInteraction(this, instance.address, constructorAbi, [x, y]);
274
+ await storeCall.simulate({ from: instance.address });
275
+ }
276
+
277
+ return accountManager;
189
278
  }
190
279
 
191
280
  /**
@@ -202,29 +291,18 @@ export class CLIWallet extends BaseWallet {
202
291
  throw new Error(`No contract instance found for address: ${originalAddress.address}`);
203
292
  }
204
293
  const { type } = await this.db!.retrieveAccount(address);
205
- const isSchnorr = type === 'schnorr';
206
- const artifact = isSchnorr ? StubSchnorrAccountContractArtifact : StubEcdsaAccountContractArtifact;
207
- const stubAccount = isSchnorr ? createStubSchnorrAccount(originalAddress) : createStubEcdsaAccount(originalAddress);
208
- const instance = await getContractInstanceFromInstantiationParams(artifact, { salt: Fr.random() });
209
- return { account: stubAccount, instance, artifact };
210
- }
211
-
212
- override async simulateTx(
213
- executionPayload: ExecutionPayload,
214
- opts: SimulateOptions,
215
- ): Promise<TxSimulationResultWithAppOffset> {
216
- const simulationResults = await super.simulateTx(executionPayload, opts);
217
-
218
- if (opts.fee?.estimateGas) {
219
- const feeOptions = await this.completeFeeOptions({
220
- from: opts.from,
221
- feePayer: executionPayload.feePayer,
222
- gasSettings: opts.fee?.gasSettings,
223
- });
224
- const limits = getGasLimits(simulationResults, opts.fee?.estimatedGasPadding);
225
- printGasEstimates(feeOptions, limits, this.userLog);
294
+ const stubAccount =
295
+ type === 'schnorr' || type === 'schnorr_initializerless'
296
+ ? createStubSchnorrAccount(originalAddress)
297
+ : createStubEcdsaAccount(originalAddress);
298
+ const stubClassId = this.stubClassIds.get(type);
299
+ if (!stubClassId) {
300
+ throw new Error(
301
+ `Stub class for account type '${type}' was not registered at wallet init. This is a bug — initStubClasses should cover every supported AccountType.`,
302
+ );
226
303
  }
227
- return simulationResults;
304
+ const instance = { ...contractInstance, currentContractClassId: stubClassId };
305
+ return { account: stubAccount, instance };
228
306
  }
229
307
 
230
308
  /**
@@ -235,8 +313,8 @@ export class CLIWallet extends BaseWallet {
235
313
  executionPayload: ExecutionPayload,
236
314
  opts: SimulateViaEntrypointOptions,
237
315
  ): Promise<TxSimulationResultWithAppOffset> {
238
- const { from, feeOptions, additionalScopes } = opts;
239
- const scopes = this.scopesFrom(from, additionalScopes);
316
+ const { from, feeOptions, additionalScopes, sendMessagesAs } = opts;
317
+ const scopes = this.scopesFrom(from, additionalScopes ?? [], sendMessagesAs);
240
318
  const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
241
319
  const finalExecutionPayload = feeExecutionPayload
242
320
  ? mergeExecutionPayloads([feeExecutionPayload, executionPayload])
@@ -249,9 +327,9 @@ export class CLIWallet extends BaseWallet {
249
327
  const entrypoint = new DefaultEntrypoint();
250
328
  txRequest = await entrypoint.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo);
251
329
  } else {
252
- const { account, instance, artifact } = await this.getFakeAccountDataFor(from);
330
+ const { account, instance } = await this.getFakeAccountDataFor(from);
253
331
  overrides = {
254
- contracts: { [from.toString()]: { instance, artifact } },
332
+ contracts: { [from.toString()]: { instance } },
255
333
  };
256
334
  const executionOptions: DefaultAccountEntrypointOptions = {
257
335
  txNonce: Fr.random(),
@@ -273,6 +351,7 @@ export class CLIWallet extends BaseWallet {
273
351
  skipTxValidation: true,
274
352
  overrides,
275
353
  scopes,
354
+ senderForTags: this.senderForTagsFrom(from, sendMessagesAs),
276
355
  });
277
356
  const appCallOffset = await this.computeAppCallOffset(from, feeOptions);
278
357
  return TxSimulationResultWithAppOffset.fromResultAndOffset(result, appCallOffset);