@aztec/wallet-sdk 0.0.1-commit.c2595eba → 0.0.1-commit.c2eed6949

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.
@@ -1,18 +1,28 @@
1
- import type { Account } from '@aztec/aztec.js/account';
1
+ import type { Account, NoFrom } from '@aztec/aztec.js/account';
2
+ import { NO_FROM } from '@aztec/aztec.js/account';
2
3
  import type { CallIntent, IntentInnerHash } from '@aztec/aztec.js/authorization';
3
- import { type InteractionWaitOptions, NO_WAIT, type SendReturn } from '@aztec/aztec.js/contracts';
4
+ import {
5
+ type InteractionWaitOptions,
6
+ NO_WAIT,
7
+ type SendReturn,
8
+ extractOffchainOutput,
9
+ } from '@aztec/aztec.js/contracts';
4
10
  import type { FeePaymentMethod } from '@aztec/aztec.js/fee';
5
11
  import { waitForTx } from '@aztec/aztec.js/node';
6
- import type {
7
- Aliased,
8
- BatchResults,
9
- BatchedMethod,
10
- PrivateEvent,
11
- PrivateEventFilter,
12
- ProfileOptions,
13
- SendOptions,
14
- SimulateOptions,
15
- Wallet,
12
+ import {
13
+ type Aliased,
14
+ type AppCapabilities,
15
+ type BatchResults,
16
+ type BatchedMethod,
17
+ ContractInitializationStatus,
18
+ type ExecuteUtilityOptions,
19
+ type PrivateEvent,
20
+ type PrivateEventFilter,
21
+ type ProfileOptions,
22
+ type SendOptions,
23
+ type SimulateOptions,
24
+ type Wallet,
25
+ type WalletCapabilities,
16
26
  } from '@aztec/aztec.js/wallet';
17
27
  import {
18
28
  GAS_ESTIMATION_DA_GAS_LIMIT,
@@ -21,10 +31,12 @@ import {
21
31
  GAS_ESTIMATION_TEARDOWN_L2_GAS_LIMIT,
22
32
  } from '@aztec/constants';
23
33
  import { AccountFeePaymentMethodOptions, type DefaultAccountEntrypointOptions } from '@aztec/entrypoints/account';
34
+ import { DefaultEntrypoint } from '@aztec/entrypoints/default';
24
35
  import type { ChainInfo } from '@aztec/entrypoints/interfaces';
25
36
  import { Fr } from '@aztec/foundation/curves/bn254';
26
37
  import { createLogger } from '@aztec/foundation/log';
27
38
  import type { FieldsOf } from '@aztec/foundation/types';
39
+ import { type AccessScopes, displayDebugLogs } from '@aztec/pxe/client/lazy';
28
40
  import type { PXE, PackedPrivateEvent } from '@aztec/pxe/server';
29
41
  import {
30
42
  type ContractArtifact,
@@ -33,7 +45,7 @@ import {
33
45
  decodeFromAbi,
34
46
  } from '@aztec/stdlib/abi';
35
47
  import type { AuthWitness } from '@aztec/stdlib/auth-witness';
36
- import type { AztecAddress } from '@aztec/stdlib/aztec-address';
48
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
37
49
  import {
38
50
  type ContractInstanceWithAddress,
39
51
  computePartialAddress,
@@ -41,18 +53,24 @@ import {
41
53
  } from '@aztec/stdlib/contract';
42
54
  import { SimulationError } from '@aztec/stdlib/errors';
43
55
  import { Gas, GasSettings } from '@aztec/stdlib/gas';
44
- import { siloNullifier } from '@aztec/stdlib/hash';
56
+ import {
57
+ computeSiloedPrivateInitializationNullifier,
58
+ computeSiloedPublicInitializationNullifier,
59
+ } from '@aztec/stdlib/hash';
45
60
  import type { AztecNode } from '@aztec/stdlib/interfaces/client';
46
- import type {
47
- TxExecutionRequest,
48
- TxProfileResult,
61
+ import {
62
+ BlockHeader,
63
+ type TxExecutionRequest,
64
+ type TxProfileResult,
49
65
  TxSimulationResult,
50
- UtilitySimulationResult,
66
+ type UtilityExecutionResult,
51
67
  } from '@aztec/stdlib/tx';
52
68
  import { ExecutionPayload, mergeExecutionPayloads } from '@aztec/stdlib/tx';
53
69
 
54
70
  import { inspect } from 'util';
55
71
 
72
+ import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simulateViaNode } from './utils.js';
73
+
56
74
  /**
57
75
  * Options to configure fee payment for a transaction
58
76
  */
@@ -63,17 +81,25 @@ export type FeeOptions = {
63
81
  */
64
82
  walletFeePaymentMethod?: FeePaymentMethod;
65
83
  /** Configuration options for the account to properly handle the selected fee payment method */
66
- accountFeePaymentMethodOptions: AccountFeePaymentMethodOptions;
84
+ accountFeePaymentMethodOptions?: AccountFeePaymentMethodOptions;
67
85
  /** The gas settings to use for the transaction */
68
86
  gasSettings: GasSettings;
69
87
  };
70
88
 
89
+ /** Options for `simulateViaEntrypoint`. */
90
+ export type SimulateViaEntrypointOptions = Pick<
91
+ SimulateOptions,
92
+ 'from' | 'additionalScopes' | 'skipTxValidation' | 'skipFeeEnforcement'
93
+ > & {
94
+ /** Fee options for the entrypoint */
95
+ feeOptions: FeeOptions;
96
+ /** Scopes to use for the simulation */
97
+ scopes: AccessScopes;
98
+ };
71
99
  /**
72
100
  * A base class for Wallet implementations
73
101
  */
74
102
  export abstract class BaseWallet implements Wallet {
75
- protected log = createLogger('wallet-sdk:base_wallet');
76
-
77
103
  protected minFeePadding = 0.5;
78
104
  protected cancellableTransactions = false;
79
105
 
@@ -81,8 +107,15 @@ export abstract class BaseWallet implements Wallet {
81
107
  protected constructor(
82
108
  protected readonly pxe: PXE,
83
109
  protected readonly aztecNode: AztecNode,
110
+ protected log = createLogger('wallet-sdk:base_wallet'),
84
111
  ) {}
85
112
 
113
+ protected scopesFrom(from: AztecAddress | NoFrom, additionalScopes: AztecAddress[] = []): AztecAddress[] {
114
+ const allScopes = from === NO_FROM ? additionalScopes : [from, ...additionalScopes];
115
+ const scopeSet = new Set(allScopes.map(address => address.toString()));
116
+ return [...scopeSet].map(AztecAddress.fromString);
117
+ }
118
+
86
119
  protected abstract getAccountFromAddress(address: AztecAddress): Promise<Account>;
87
120
 
88
121
  abstract getAccounts(): Promise<Aliased<AztecAddress>[]>;
@@ -106,26 +139,33 @@ export abstract class BaseWallet implements Wallet {
106
139
 
107
140
  protected async createTxExecutionRequestFromPayloadAndFee(
108
141
  executionPayload: ExecutionPayload,
109
- from: AztecAddress,
142
+ from: AztecAddress | NoFrom,
110
143
  feeOptions: FeeOptions,
111
144
  ): Promise<TxExecutionRequest> {
112
145
  const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
113
- const executionOptions: DefaultAccountEntrypointOptions = {
114
- txNonce: Fr.random(),
115
- cancellable: this.cancellableTransactions,
116
- feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions,
117
- };
118
146
  const finalExecutionPayload = feeExecutionPayload
119
147
  ? mergeExecutionPayloads([feeExecutionPayload, executionPayload])
120
148
  : executionPayload;
121
- const fromAccount = await this.getAccountFromAddress(from);
122
149
  const chainInfo = await this.getChainInfo();
123
- return fromAccount.createTxExecutionRequest(
124
- finalExecutionPayload,
125
- feeOptions.gasSettings,
126
- chainInfo,
127
- executionOptions,
128
- );
150
+
151
+ if (from === NO_FROM) {
152
+ const entrypoint = new DefaultEntrypoint();
153
+ return entrypoint.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo);
154
+ } else {
155
+ const fromAccount = await this.getAccountFromAddress(from);
156
+ const executionOptions: DefaultAccountEntrypointOptions = {
157
+ txNonce: Fr.random(),
158
+ cancellable: this.cancellableTransactions,
159
+ // If from is an address, feeOptions include the way the account contract should handle the fee payment
160
+ feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions!,
161
+ };
162
+ return fromAccount.createTxExecutionRequest(
163
+ finalExecutionPayload,
164
+ feeOptions.gasSettings,
165
+ chainInfo,
166
+ executionOptions,
167
+ );
168
+ }
129
169
  }
130
170
 
131
171
  public async createAuthWit(
@@ -137,6 +177,23 @@ export abstract class BaseWallet implements Wallet {
137
177
  return account.createAuthWit(messageHashOrIntent, chainInfo);
138
178
  }
139
179
 
180
+ /**
181
+ * Request capabilities from the wallet.
182
+ *
183
+ * This method is wallet-implementation-dependent and must be provided by classes extending BaseWallet.
184
+ * Embedded wallets typically don't support capability-based authorization (no user authorization flow),
185
+ * while external wallets (browser extensions, hardware wallets) implement this to reduce authorization
186
+ * friction by allowing apps to request permissions upfront.
187
+ *
188
+ * TODO: Consider making it abstract so implementing it is a conscious decision. Leaving it as-is
189
+ * while the feature stabilizes.
190
+ *
191
+ * @param _manifest - Application capability manifest declaring what operations the app needs
192
+ */
193
+ public requestCapabilities(_manifest: AppCapabilities): Promise<WalletCapabilities> {
194
+ throw new Error('Not implemented');
195
+ }
196
+
140
197
  public async batch<const T extends readonly BatchedMethod[]>(methods: T): Promise<BatchResults<T>> {
141
198
  const results: any[] = [];
142
199
  for (const method of methods) {
@@ -163,23 +220,27 @@ export abstract class BaseWallet implements Wallet {
163
220
  * @returns - Complete fee options that can be used to create a transaction execution request
164
221
  */
165
222
  protected async completeFeeOptions(
166
- from: AztecAddress,
223
+ from: AztecAddress | NoFrom,
167
224
  feePayer?: AztecAddress,
168
225
  gasSettings?: Partial<FieldsOf<GasSettings>>,
169
226
  ): Promise<FeeOptions> {
170
227
  const maxFeesPerGas =
171
228
  gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentMinFees()).mul(1 + this.minFeePadding);
172
229
  let accountFeePaymentMethodOptions;
173
- // The transaction does not include a fee payment method, so we set the flag
174
- // for the account to use its fee juice balance
175
- if (!feePayer) {
176
- accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
177
- } else {
178
- // The transaction includes fee payment method, so we check if we are the fee payer for it
179
- // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
180
- accountFeePaymentMethodOptions = from.equals(feePayer)
181
- ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM
182
- : AccountFeePaymentMethodOptions.EXTERNAL;
230
+ // If from is an address, we need to determine the appropriate fee payment method options for the
231
+ // account contract entrypoint to use
232
+ if (from !== NO_FROM) {
233
+ if (!feePayer) {
234
+ // The transaction does not include a fee payment method, so we set the flag
235
+ // for the account to use its fee juice balance
236
+ accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
237
+ } else {
238
+ // The transaction includes fee payment method, so we check if we are the fee payer for it
239
+ // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
240
+ accountFeePaymentMethodOptions = from.equals(feePayer)
241
+ ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM
242
+ : AccountFeePaymentMethodOptions.EXTERNAL;
243
+ }
183
244
  }
184
245
  const fullGasSettings: GasSettings = GasSettings.default({ ...gasSettings, maxFeesPerGas });
185
246
  this.log.debug(`Using L2 gas settings`, fullGasSettings);
@@ -199,7 +260,7 @@ export abstract class BaseWallet implements Wallet {
199
260
  * @param gasSettings - User-provided partial gas settings
200
261
  */
201
262
  protected async completeFeeOptionsForEstimation(
202
- from: AztecAddress,
263
+ from: AztecAddress | NoFrom,
203
264
  feePayer?: AztecAddress,
204
265
  gasSettings?: Partial<FieldsOf<GasSettings>>,
205
266
  ) {
@@ -263,23 +324,86 @@ export abstract class BaseWallet implements Wallet {
263
324
  return instance;
264
325
  }
265
326
 
327
+ /**
328
+ * Simulates calls through the standard PXE path (account entrypoint).
329
+ * @param executionPayload - The execution payload to simulate.
330
+ * @param opts - Simulation options.
331
+ */
332
+ protected async simulateViaEntrypoint(executionPayload: ExecutionPayload, opts: SimulateViaEntrypointOptions) {
333
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(
334
+ executionPayload,
335
+ opts.from,
336
+ opts.feeOptions,
337
+ );
338
+ return this.pxe.simulateTx(txRequest, {
339
+ simulatePublic: true,
340
+ skipTxValidation: opts.skipTxValidation,
341
+ skipFeeEnforcement: opts.skipFeeEnforcement,
342
+ scopes: opts.scopes,
343
+ });
344
+ }
345
+
346
+ /**
347
+ * Simulates a transaction, optimizing leading public static calls by running them directly
348
+ * on the node while sending the remaining calls through the standard PXE path.
349
+ * Return values from both paths are merged back in original call order.
350
+ * @param executionPayload - The execution payload to simulate.
351
+ * @param opts - Simulation options (from address, fee settings, etc.).
352
+ * @returns The merged simulation result.
353
+ */
266
354
  async simulateTx(executionPayload: ExecutionPayload, opts: SimulateOptions): Promise<TxSimulationResult> {
267
355
  const feeOptions = opts.fee?.estimateGas
268
356
  ? await this.completeFeeOptionsForEstimation(opts.from, executionPayload.feePayer, opts.fee?.gasSettings)
269
357
  : await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
270
- const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
271
- return this.pxe.simulateTx(
272
- txRequest,
273
- true /* simulatePublic */,
274
- opts?.skipTxValidation,
275
- opts?.skipFeeEnforcement ?? true,
276
- );
358
+ const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
359
+ const remainingPayload = { ...executionPayload, calls: remainingCalls };
360
+
361
+ const chainInfo = await this.getChainInfo();
362
+ let blockHeader: BlockHeader;
363
+ // PXE might not be synced yet, so we pull the latest header from the node
364
+ // To keep things consistent, we'll always try with PXE first
365
+ try {
366
+ blockHeader = await this.pxe.getSyncedBlockHeader();
367
+ } catch {
368
+ blockHeader = (await this.aztecNode.getBlockHeader())!;
369
+ }
370
+
371
+ const simulationOrigin = opts.from === NO_FROM ? AztecAddress.ZERO : opts.from;
372
+ const [optimizedResults, normalResult] = await Promise.all([
373
+ optimizableCalls.length > 0
374
+ ? simulateViaNode(
375
+ this.aztecNode,
376
+ optimizableCalls,
377
+ simulationOrigin,
378
+ chainInfo,
379
+ feeOptions.gasSettings,
380
+ blockHeader,
381
+ opts.skipFeeEnforcement ?? true,
382
+ this.getContractName.bind(this),
383
+ )
384
+ : Promise.resolve([]),
385
+ remainingCalls.length > 0
386
+ ? this.simulateViaEntrypoint(remainingPayload, {
387
+ from: opts.from,
388
+ feeOptions,
389
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
390
+ skipTxValidation: opts.skipTxValidation,
391
+ skipFeeEnforcement: opts.skipFeeEnforcement ?? true,
392
+ })
393
+ : Promise.resolve(null),
394
+ ]);
395
+
396
+ return buildMergedSimulationResult(optimizedResults, normalResult);
277
397
  }
278
398
 
279
399
  async profileTx(executionPayload: ExecutionPayload, opts: ProfileOptions): Promise<TxProfileResult> {
280
400
  const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
281
401
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
282
- return this.pxe.profileTx(txRequest, opts.profileMode, opts.skipProofGeneration ?? true);
402
+ return this.pxe.profileTx(txRequest, {
403
+ profileMode: opts.profileMode,
404
+ skipProofGeneration: opts.skipProofGeneration ?? true,
405
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
406
+ });
283
407
  }
284
408
 
285
409
  public async sendTx<W extends InteractionWaitOptions = undefined>(
@@ -288,7 +412,11 @@ export abstract class BaseWallet implements Wallet {
288
412
  ): Promise<SendReturn<W>> {
289
413
  const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
290
414
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
291
- const provenTx = await this.pxe.proveTx(txRequest);
415
+ const provenTx = await this.pxe.proveTx(txRequest, this.scopesFrom(opts.from, opts.additionalScopes));
416
+ const offchainOutput = extractOffchainOutput(
417
+ provenTx.getOffchainEffects(),
418
+ provenTx.publicInputs.constants.anchorBlockHeader.globalVariables.timestamp,
419
+ );
292
420
  const tx = await provenTx.toTx();
293
421
  const txHash = tx.getTxHash();
294
422
  if (await this.aztecNode.getTxEffect(txHash)) {
@@ -302,12 +430,32 @@ export abstract class BaseWallet implements Wallet {
302
430
 
303
431
  // If wait is NO_WAIT, return txHash immediately
304
432
  if (opts.wait === NO_WAIT) {
305
- return txHash as SendReturn<W>;
433
+ return { txHash, ...offchainOutput } as SendReturn<W>;
306
434
  }
307
435
 
308
436
  // Otherwise, wait for the full receipt (default behavior on wait: undefined)
309
437
  const waitOpts = typeof opts.wait === 'object' ? opts.wait : undefined;
310
- return (await waitForTx(this.aztecNode, txHash, waitOpts)) as SendReturn<W>;
438
+ const receipt = await waitForTx(this.aztecNode, txHash, waitOpts);
439
+
440
+ // Display debug logs from public execution if present (served in test mode only)
441
+ if (receipt.debugLogs?.length) {
442
+ await displayDebugLogs(receipt.debugLogs, this.getContractName.bind(this));
443
+ }
444
+
445
+ return { receipt, ...offchainOutput } as SendReturn<W>;
446
+ }
447
+
448
+ /**
449
+ * Resolves a contract address to a human-readable name via PXE, if available.
450
+ * @param address - The contract address to resolve.
451
+ */
452
+ protected async getContractName(address: AztecAddress): Promise<string | undefined> {
453
+ const instance = await this.pxe.getContractInstance(address);
454
+ if (!instance) {
455
+ return undefined;
456
+ }
457
+ const artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
458
+ return artifact?.name;
311
459
  }
312
460
 
313
461
  protected contextualizeError(err: Error, ...context: string[]): Error {
@@ -324,8 +472,8 @@ export abstract class BaseWallet implements Wallet {
324
472
  return err;
325
473
  }
326
474
 
327
- simulateUtility(call: FunctionCall, authwits?: AuthWitness[]): Promise<UtilitySimulationResult> {
328
- return this.pxe.simulateUtility(call, authwits);
475
+ executeUtility(call: FunctionCall, opts: ExecuteUtilityOptions): Promise<UtilityExecutionResult> {
476
+ return this.pxe.executeUtility(call, { authwits: opts.authWitnesses, scopes: opts.scopes });
329
477
  }
330
478
 
331
479
  async getPrivateEvents<T>(
@@ -348,17 +496,39 @@ export abstract class BaseWallet implements Wallet {
348
496
  return decodedEvents;
349
497
  }
350
498
 
499
+ /**
500
+ * Returns metadata about a contract, including whether it has been initialized, published, and updated.
501
+ * @param address - The contract address to query.
502
+ */
351
503
  async getContractMetadata(address: AztecAddress) {
352
504
  const instance = await this.pxe.getContractInstance(address);
353
- const initNullifier = await siloNullifier(address, address.toField());
354
- const publiclyRegisteredContract = await this.aztecNode.getContract(address);
355
- const initNullifierMembershipWitness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
505
+ const publiclyRegisteredContractPromise = this.aztecNode.getContract(address);
506
+
507
+ let initializationStatus: ContractInitializationStatus;
508
+ if (instance) {
509
+ // We have the instance, so we can compute the private initialization nullifier (which includes init_hash and is
510
+ // emitted by both private and public initializers) and get a definitive INITIALIZED/UNINITIALIZED answer.
511
+ const initNullifier = await computeSiloedPrivateInitializationNullifier(address, instance.initializationHash);
512
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
513
+ initializationStatus = witness
514
+ ? ContractInitializationStatus.INITIALIZED
515
+ : ContractInitializationStatus.UNINITIALIZED;
516
+ } else {
517
+ // Without the instance we lack the init_hash needed for the private nullifier. We fall back to checking the
518
+ // public initialization nullifier (computed from address alone). Not all contracts emit it (only those with
519
+ // public functions that require initialization checks), so its absence doesn't mean the contract is
520
+ // uninitialized.
521
+ const publicNullifier = await computeSiloedPublicInitializationNullifier(address);
522
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', publicNullifier);
523
+ initializationStatus = witness ? ContractInitializationStatus.INITIALIZED : ContractInitializationStatus.UNKNOWN;
524
+ }
525
+ const publiclyRegisteredContract = await publiclyRegisteredContractPromise;
356
526
  const isContractUpdated =
357
527
  publiclyRegisteredContract &&
358
528
  !publiclyRegisteredContract.currentContractClassId.equals(publiclyRegisteredContract.originalContractClassId);
359
529
  return {
360
530
  instance: instance ?? undefined,
361
- isContractInitialized: !!initNullifierMembershipWitness,
531
+ initializationStatus,
362
532
  isContractPublished: !!publiclyRegisteredContract,
363
533
  isContractUpdated: !!isContractUpdated,
364
534
  updatedContractClassId: isContractUpdated ? publiclyRegisteredContract.currentContractClassId : undefined,
@@ -1 +1,2 @@
1
- export { BaseWallet, type FeeOptions } from './base_wallet.js';
1
+ export { BaseWallet, type FeeOptions, type SimulateViaEntrypointOptions } from './base_wallet.js';
2
+ export { simulateViaNode, buildMergedSimulationResult, extractOptimizablePublicStaticCalls } from './utils.js';