@aztec/wallet-sdk 0.0.1-commit.fffb133c → 0.0.6-commit.a2d1860fe9

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.
@@ -67,4 +67,4 @@ export declare class WalletManager {
67
67
  */
68
68
  private isExtensionAllowed;
69
69
  }
70
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoid2FsbGV0X21hbmFnZXIuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9tYW5hZ2VyL3dhbGxldF9tYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUtBLE9BQU8sS0FBSyxFQUNWLHNCQUFzQixFQUN0QixnQkFBZ0IsRUFJaEIsbUJBQW1CLEVBRXBCLE1BQU0sWUFBWSxDQUFDO0FBRXBCOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7R0E4Qkc7QUFDSCxxQkFBYSxhQUFhO0lBQ3hCLE9BQU8sQ0FBQyxNQUFNLENBR1o7SUFFRixPQUFPLGVBQWlCO0lBRXhCOzs7T0FHRztJQUNILE1BQU0sQ0FBQyxTQUFTLENBQUMsTUFBTSxFQUFFLG1CQUFtQixHQUFHLGFBQWEsQ0FPM0Q7SUFFRDs7Ozs7Ozs7Ozs7O09BWUc7SUFDSCxtQkFBbUIsQ0FBQyxPQUFPLEVBQUUsc0JBQXNCLEdBQUcsZ0JBQWdCLENBNkVyRTtJQUVEOzs7Ozs7T0FNRztJQUNILE9BQU8sQ0FBQyxrQ0FBa0M7SUE0RTFDOzs7O09BSUc7SUFDSCxPQUFPLENBQUMsa0JBQWtCO0NBVzNCIn0=
70
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoid2FsbGV0X21hbmFnZXIuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9tYW5hZ2VyL3dhbGxldF9tYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUtBLE9BQU8sS0FBSyxFQUNWLHNCQUFzQixFQUN0QixnQkFBZ0IsRUFJaEIsbUJBQW1CLEVBRXBCLE1BQU0sWUFBWSxDQUFDO0FBRXBCOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7R0E4Qkc7QUFDSCxxQkFBYSxhQUFhO0lBQ3hCLE9BQU8sQ0FBQyxNQUFNLENBR1o7SUFFRixPQUFPLGVBQWlCO0lBRXhCOzs7T0FHRztJQUNILE1BQU0sQ0FBQyxTQUFTLENBQUMsTUFBTSxFQUFFLG1CQUFtQixHQUFHLGFBQWEsQ0FPM0Q7SUFFRDs7Ozs7Ozs7Ozs7O09BWUc7SUFDSCxtQkFBbUIsQ0FBQyxPQUFPLEVBQUUsc0JBQXNCLEdBQUcsZ0JBQWdCLENBNkVyRTtJQUVEOzs7Ozs7T0FNRztJQUNILE9BQU8sQ0FBQyxrQ0FBa0M7SUEwRTFDOzs7O09BSUc7SUFDSCxPQUFPLENBQUMsa0JBQWtCO0NBVzNCIn0=
@@ -1 +1 @@
1
- {"version":3,"file":"wallet_manager.d.ts","sourceRoot":"","sources":["../../src/manager/wallet_manager.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EACV,sBAAsB,EACtB,gBAAgB,EAIhB,mBAAmB,EAEpB,MAAM,YAAY,CAAC;AAEpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,qBAAa,aAAa;IACxB,OAAO,CAAC,MAAM,CAGZ;IAEF,OAAO,eAAiB;IAExB;;;OAGG;IACH,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,mBAAmB,GAAG,aAAa,CAO3D;IAED;;;;;;;;;;;;OAYG;IACH,mBAAmB,CAAC,OAAO,EAAE,sBAAsB,GAAG,gBAAgB,CA6ErE;IAED;;;;;;OAMG;IACH,OAAO,CAAC,kCAAkC;IA4E1C;;;;OAIG;IACH,OAAO,CAAC,kBAAkB;CAW3B"}
1
+ {"version":3,"file":"wallet_manager.d.ts","sourceRoot":"","sources":["../../src/manager/wallet_manager.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EACV,sBAAsB,EACtB,gBAAgB,EAIhB,mBAAmB,EAEpB,MAAM,YAAY,CAAC;AAEpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,qBAAa,aAAa;IACxB,OAAO,CAAC,MAAM,CAGZ;IAEF,OAAO,eAAiB;IAExB;;;OAGG;IACH,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,mBAAmB,GAAG,aAAa,CAO3D;IAED;;;;;;;;;;;;OAYG;IACH,mBAAmB,CAAC,OAAO,EAAE,sBAAsB,GAAG,gBAAgB,CA6ErE;IAED;;;;;;OAMG;IACH,OAAO,CAAC,kCAAkC;IA0E1C;;;;OAIG;IACH,OAAO,CAAC,kBAAkB;CAW3B"}
@@ -176,7 +176,8 @@ import { WalletMessageType } from '../types.js';
176
176
  return {
177
177
  verificationHash: connection.info.verificationHash,
178
178
  confirm: ()=>{
179
- return Promise.resolve(ExtensionWallet.create(connection.info.id, connection.port, connection.sharedKey, chainInfo, connectAppId));
179
+ extensionWallet = ExtensionWallet.create(connection.info.id, connection.port, connection.sharedKey, chainInfo, connectAppId);
180
+ return Promise.resolve(extensionWallet.asWallet());
180
181
  },
181
182
  cancel: ()=>{
182
183
  // Send disconnect to terminate the session on the extension side
@@ -185,7 +186,6 @@ import { WalletMessageType } from '../types.js';
185
186
  type: WalletMessageType.DISCONNECT,
186
187
  requestId: discoveredWallet.requestId
187
188
  });
188
- // Don't close the port - allow retry with fresh key exchange
189
189
  }
190
190
  };
191
191
  },
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@aztec/wallet-sdk",
3
3
  "homepage": "https://github.com/AztecProtocol/aztec-packages/tree/master/yarn-project/wallet-sdk",
4
- "version": "0.0.1-commit.fffb133c",
4
+ "version": "0.0.6-commit.a2d1860fe9",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  "./base-wallet": "./dest/base-wallet/index.js",
@@ -13,8 +13,14 @@
13
13
  },
14
14
  "typedocOptions": {
15
15
  "entryPoints": [
16
- "./src/index.ts"
16
+ "./src/base-wallet/index.ts",
17
+ "./src/extension/handlers/index.ts",
18
+ "./src/extension/provider/index.ts",
19
+ "./src/crypto.ts",
20
+ "./src/types.ts",
21
+ "./src/manager/index.ts"
17
22
  ],
23
+ "name": "Wallet SDK",
18
24
  "tsconfig": "./tsconfig.json"
19
25
  },
20
26
  "scripts": {
@@ -65,15 +71,15 @@
65
71
  ]
66
72
  },
67
73
  "dependencies": {
68
- "@aztec/aztec.js": "0.0.1-commit.fffb133c",
69
- "@aztec/constants": "0.0.1-commit.fffb133c",
70
- "@aztec/entrypoints": "0.0.1-commit.fffb133c",
71
- "@aztec/foundation": "0.0.1-commit.fffb133c",
72
- "@aztec/pxe": "0.0.1-commit.fffb133c",
73
- "@aztec/stdlib": "0.0.1-commit.fffb133c"
74
+ "@aztec/aztec.js": "0.0.6-commit.a2d1860fe9",
75
+ "@aztec/constants": "0.0.6-commit.a2d1860fe9",
76
+ "@aztec/entrypoints": "0.0.6-commit.a2d1860fe9",
77
+ "@aztec/foundation": "0.0.6-commit.a2d1860fe9",
78
+ "@aztec/pxe": "0.0.6-commit.a2d1860fe9",
79
+ "@aztec/stdlib": "0.0.6-commit.a2d1860fe9"
74
80
  },
75
81
  "devDependencies": {
76
- "@aztec/noir-contracts.js": "0.0.1-commit.fffb133c",
82
+ "@aztec/noir-contracts.js": "0.0.6-commit.a2d1860fe9",
77
83
  "@jest/globals": "^30.0.0",
78
84
  "@types/jest": "^30.0.0",
79
85
  "@types/node": "^22.15.17",
@@ -5,14 +5,17 @@ import type { FeePaymentMethod } from '@aztec/aztec.js/fee';
5
5
  import { waitForTx } from '@aztec/aztec.js/node';
6
6
  import type {
7
7
  Aliased,
8
+ AppCapabilities,
8
9
  BatchResults,
9
10
  BatchedMethod,
11
+ ExecuteUtilityOptions,
10
12
  PrivateEvent,
11
13
  PrivateEventFilter,
12
14
  ProfileOptions,
13
15
  SendOptions,
14
16
  SimulateOptions,
15
17
  Wallet,
18
+ WalletCapabilities,
16
19
  } from '@aztec/aztec.js/wallet';
17
20
  import {
18
21
  GAS_ESTIMATION_DA_GAS_LIMIT,
@@ -25,6 +28,7 @@ import type { ChainInfo } from '@aztec/entrypoints/interfaces';
25
28
  import { Fr } from '@aztec/foundation/curves/bn254';
26
29
  import { createLogger } from '@aztec/foundation/log';
27
30
  import type { FieldsOf } from '@aztec/foundation/types';
31
+ import type { AccessScopes, ContractNameResolver } from '@aztec/pxe/client/lazy';
28
32
  import type { PXE, PackedPrivateEvent } from '@aztec/pxe/server';
29
33
  import {
30
34
  type ContractArtifact,
@@ -33,7 +37,7 @@ import {
33
37
  decodeFromAbi,
34
38
  } from '@aztec/stdlib/abi';
35
39
  import type { AuthWitness } from '@aztec/stdlib/auth-witness';
36
- import type { AztecAddress } from '@aztec/stdlib/aztec-address';
40
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
37
41
  import {
38
42
  type ContractInstanceWithAddress,
39
43
  computePartialAddress,
@@ -43,16 +47,19 @@ import { SimulationError } from '@aztec/stdlib/errors';
43
47
  import { Gas, GasSettings } from '@aztec/stdlib/gas';
44
48
  import { siloNullifier } from '@aztec/stdlib/hash';
45
49
  import type { AztecNode } from '@aztec/stdlib/interfaces/client';
46
- import type {
47
- TxExecutionRequest,
48
- TxProfileResult,
50
+ import {
51
+ BlockHeader,
52
+ type TxExecutionRequest,
53
+ type TxProfileResult,
49
54
  TxSimulationResult,
50
- UtilitySimulationResult,
55
+ type UtilityExecutionResult,
51
56
  } from '@aztec/stdlib/tx';
52
57
  import { ExecutionPayload, mergeExecutionPayloads } from '@aztec/stdlib/tx';
53
58
 
54
59
  import { inspect } from 'util';
55
60
 
61
+ import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simulateViaNode } from './utils.js';
62
+
56
63
  /**
57
64
  * Options to configure fee payment for a transaction
58
65
  */
@@ -72,8 +79,6 @@ export type FeeOptions = {
72
79
  * A base class for Wallet implementations
73
80
  */
74
81
  export abstract class BaseWallet implements Wallet {
75
- protected log = createLogger('wallet-sdk:base_wallet');
76
-
77
82
  protected minFeePadding = 0.5;
78
83
  protected cancellableTransactions = false;
79
84
 
@@ -81,8 +86,15 @@ export abstract class BaseWallet implements Wallet {
81
86
  protected constructor(
82
87
  protected readonly pxe: PXE,
83
88
  protected readonly aztecNode: AztecNode,
89
+ protected log = createLogger('wallet-sdk:base_wallet'),
84
90
  ) {}
85
91
 
92
+ protected scopesFrom(from: AztecAddress, additionalScopes: AztecAddress[] = []): AztecAddress[] {
93
+ const allScopes = from.isZero() ? additionalScopes : [from, ...additionalScopes];
94
+ const scopeSet = new Set(allScopes.map(address => address.toString()));
95
+ return [...scopeSet].map(AztecAddress.fromString);
96
+ }
97
+
86
98
  protected abstract getAccountFromAddress(address: AztecAddress): Promise<Account>;
87
99
 
88
100
  abstract getAccounts(): Promise<Aliased<AztecAddress>[]>;
@@ -137,6 +149,23 @@ export abstract class BaseWallet implements Wallet {
137
149
  return account.createAuthWit(messageHashOrIntent, chainInfo);
138
150
  }
139
151
 
152
+ /**
153
+ * Request capabilities from the wallet.
154
+ *
155
+ * This method is wallet-implementation-dependent and must be provided by classes extending BaseWallet.
156
+ * Embedded wallets typically don't support capability-based authorization (no user authorization flow),
157
+ * while external wallets (browser extensions, hardware wallets) implement this to reduce authorization
158
+ * friction by allowing apps to request permissions upfront.
159
+ *
160
+ * TODO: Consider making it abstract so implementing it is a conscious decision. Leaving it as-is
161
+ * while the feature stabilizes.
162
+ *
163
+ * @param _manifest - Application capability manifest declaring what operations the app needs
164
+ */
165
+ public requestCapabilities(_manifest: AppCapabilities): Promise<WalletCapabilities> {
166
+ throw new Error('Not implemented');
167
+ }
168
+
140
169
  public async batch<const T extends readonly BatchedMethod[]>(methods: T): Promise<BatchResults<T>> {
141
170
  const results: any[] = [];
142
171
  for (const method of methods) {
@@ -263,23 +292,97 @@ export abstract class BaseWallet implements Wallet {
263
292
  return instance;
264
293
  }
265
294
 
295
+ /**
296
+ * Simulates calls through the standard PXE path (account entrypoint).
297
+ * @param executionPayload - The execution payload to simulate.
298
+ * @param from - The sender address.
299
+ * @param feeOptions - Fee options for the transaction.
300
+ * @param skipTxValidation - Whether to skip tx validation.
301
+ * @param skipFeeEnforcement - Whether to skip fee enforcement.
302
+ * @param scopes - The scopes to use for the simulation.
303
+ */
304
+ protected async simulateViaEntrypoint(
305
+ executionPayload: ExecutionPayload,
306
+ from: AztecAddress,
307
+ feeOptions: FeeOptions,
308
+ scopes: AccessScopes,
309
+ skipTxValidation?: boolean,
310
+ skipFeeEnforcement?: boolean,
311
+ ) {
312
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, from, feeOptions);
313
+ return this.pxe.simulateTx(txRequest, { simulatePublic: true, skipTxValidation, skipFeeEnforcement, scopes });
314
+ }
315
+
316
+ /**
317
+ * Simulates a transaction, optimizing leading public static calls by running them directly
318
+ * on the node while sending the remaining calls through the standard PXE path.
319
+ * Return values from both paths are merged back in original call order.
320
+ * @param executionPayload - The execution payload to simulate.
321
+ * @param opts - Simulation options (from address, fee settings, etc.).
322
+ * @returns The merged simulation result.
323
+ */
266
324
  async simulateTx(executionPayload: ExecutionPayload, opts: SimulateOptions): Promise<TxSimulationResult> {
267
325
  const feeOptions = opts.fee?.estimateGas
268
326
  ? await this.completeFeeOptionsForEstimation(opts.from, executionPayload.feePayer, opts.fee?.gasSettings)
269
327
  : 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
- );
328
+ const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
329
+ const remainingPayload = { ...executionPayload, calls: remainingCalls };
330
+
331
+ const chainInfo = await this.getChainInfo();
332
+ let blockHeader: BlockHeader;
333
+ // PXE might not be synced yet, so we pull the latest header from the node
334
+ // To keep things consistent, we'll always try with PXE first
335
+ try {
336
+ blockHeader = await this.pxe.getSyncedBlockHeader();
337
+ } catch {
338
+ blockHeader = (await this.aztecNode.getBlockHeader())!;
339
+ }
340
+
341
+ const getContractName: ContractNameResolver = async address => {
342
+ const instance = await this.pxe.getContractInstance(address);
343
+ if (!instance) {
344
+ return undefined;
345
+ }
346
+ const artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
347
+ return artifact?.name;
348
+ };
349
+
350
+ const [optimizedResults, normalResult] = await Promise.all([
351
+ optimizableCalls.length > 0
352
+ ? simulateViaNode(
353
+ this.aztecNode,
354
+ optimizableCalls,
355
+ opts.from,
356
+ chainInfo,
357
+ feeOptions.gasSettings,
358
+ blockHeader,
359
+ opts.skipFeeEnforcement ?? true,
360
+ getContractName,
361
+ )
362
+ : Promise.resolve([]),
363
+ remainingCalls.length > 0
364
+ ? this.simulateViaEntrypoint(
365
+ remainingPayload,
366
+ opts.from,
367
+ feeOptions,
368
+ this.scopesFrom(opts.from, opts.additionalScopes),
369
+ opts.skipTxValidation,
370
+ opts.skipFeeEnforcement ?? true,
371
+ )
372
+ : Promise.resolve(null),
373
+ ]);
374
+
375
+ return buildMergedSimulationResult(optimizedResults, normalResult);
277
376
  }
278
377
 
279
378
  async profileTx(executionPayload: ExecutionPayload, opts: ProfileOptions): Promise<TxProfileResult> {
280
379
  const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
281
380
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
282
- return this.pxe.profileTx(txRequest, opts.profileMode, opts.skipProofGeneration ?? true);
381
+ return this.pxe.profileTx(txRequest, {
382
+ profileMode: opts.profileMode,
383
+ skipProofGeneration: opts.skipProofGeneration ?? true,
384
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
385
+ });
283
386
  }
284
387
 
285
388
  public async sendTx<W extends InteractionWaitOptions = undefined>(
@@ -288,7 +391,7 @@ export abstract class BaseWallet implements Wallet {
288
391
  ): Promise<SendReturn<W>> {
289
392
  const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
290
393
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
291
- const provenTx = await this.pxe.proveTx(txRequest);
394
+ const provenTx = await this.pxe.proveTx(txRequest, this.scopesFrom(opts.from, opts.additionalScopes));
292
395
  const tx = await provenTx.toTx();
293
396
  const txHash = tx.getTxHash();
294
397
  if (await this.aztecNode.getTxEffect(txHash)) {
@@ -324,8 +427,8 @@ export abstract class BaseWallet implements Wallet {
324
427
  return err;
325
428
  }
326
429
 
327
- simulateUtility(call: FunctionCall, authwits?: AuthWitness[]): Promise<UtilitySimulationResult> {
328
- return this.pxe.simulateUtility(call, authwits);
430
+ executeUtility(call: FunctionCall, opts: ExecuteUtilityOptions): Promise<UtilityExecutionResult> {
431
+ return this.pxe.executeUtility(call, { authwits: opts.authWitnesses, scopes: [opts.scope] });
329
432
  }
330
433
 
331
434
  async getPrivateEvents<T>(
@@ -352,14 +455,7 @@ export abstract class BaseWallet implements Wallet {
352
455
  const instance = await this.pxe.getContractInstance(address);
353
456
  const initNullifier = await siloNullifier(address, address.toField());
354
457
  const publiclyRegisteredContract = await this.aztecNode.getContract(address);
355
- const [initNullifierMembershipWitness, publiclyRegisteredContractClass] = await Promise.all([
356
- this.aztecNode.getNullifierMembershipWitness('latest', initNullifier),
357
- publiclyRegisteredContract
358
- ? this.aztecNode.getContractClass(
359
- publiclyRegisteredContract.currentContractClassId || instance?.currentContractClassId,
360
- )
361
- : undefined,
362
- ]);
458
+ const initNullifierMembershipWitness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
363
459
  const isContractUpdated =
364
460
  publiclyRegisteredContract &&
365
461
  !publiclyRegisteredContract.currentContractClassId.equals(publiclyRegisteredContract.originalContractClassId);
@@ -367,7 +463,6 @@ export abstract class BaseWallet implements Wallet {
367
463
  instance: instance ?? undefined,
368
464
  isContractInitialized: !!initNullifierMembershipWitness,
369
465
  isContractPublished: !!publiclyRegisteredContract,
370
- isContractClassPubliclyRegistered: !!publiclyRegisteredContractClass,
371
466
  isContractUpdated: !!isContractUpdated,
372
467
  updatedContractClassId: isContractUpdated ? publiclyRegisteredContract.currentContractClassId : undefined,
373
468
  };
@@ -1 +1,2 @@
1
1
  export { BaseWallet, type FeeOptions } from './base_wallet.js';
2
+ export { simulateViaNode, buildMergedSimulationResult, extractOptimizablePublicStaticCalls } from './utils.js';
@@ -0,0 +1,238 @@
1
+ import type { AztecNode } from '@aztec/aztec.js/node';
2
+ import { MAX_ENQUEUED_CALLS_PER_CALL } from '@aztec/constants';
3
+ import type { ChainInfo } from '@aztec/entrypoints/interfaces';
4
+ import { makeTuple } from '@aztec/foundation/array';
5
+ import { Fr } from '@aztec/foundation/curves/bn254';
6
+ import type { Tuple } from '@aztec/foundation/serialize';
7
+ import type { ContractNameResolver } from '@aztec/pxe/client/lazy';
8
+ import { displayDebugLogs } from '@aztec/pxe/client/lazy';
9
+ import { generateSimulatedProvingResult } from '@aztec/pxe/simulator';
10
+ import { type FunctionCall, FunctionSelector } from '@aztec/stdlib/abi';
11
+ import type { AztecAddress } from '@aztec/stdlib/aztec-address';
12
+ import type { GasSettings } from '@aztec/stdlib/gas';
13
+ import {
14
+ ClaimedLengthArray,
15
+ CountedPublicCallRequest,
16
+ PrivateCircuitPublicInputs,
17
+ PublicCallRequest,
18
+ } from '@aztec/stdlib/kernel';
19
+ import { ChonkProof } from '@aztec/stdlib/proofs';
20
+ import {
21
+ type BlockHeader,
22
+ type ExecutionPayload,
23
+ HashedValues,
24
+ PrivateCallExecutionResult,
25
+ PrivateExecutionResult,
26
+ PublicSimulationOutput,
27
+ Tx,
28
+ TxContext,
29
+ TxSimulationResult,
30
+ } from '@aztec/stdlib/tx';
31
+
32
+ /**
33
+ * Splits an execution payload into a leading prefix of public static calls
34
+ * (eligible for direct node simulation) and the remaining calls.
35
+ *
36
+ * Only a leading run of public static calls is eligible for optimization.
37
+ * Any non-public-static call may enqueue public state mutations
38
+ * (e.g. private calls can enqueue public calls), so all calls that follow
39
+ * must go through the normal simulation path to see the correct state.
40
+ *
41
+ */
42
+ export function extractOptimizablePublicStaticCalls(payload: ExecutionPayload): {
43
+ /** Leading public static calls eligible for direct node simulation. */
44
+ optimizableCalls: FunctionCall[];
45
+ /** All remaining calls. */
46
+ remainingCalls: FunctionCall[];
47
+ } {
48
+ const splitIndex = payload.calls.findIndex(call => !call.isPublicStatic());
49
+ const boundary = splitIndex === -1 ? payload.calls.length : splitIndex;
50
+ return {
51
+ optimizableCalls: payload.calls.slice(0, boundary),
52
+ remainingCalls: payload.calls.slice(boundary),
53
+ };
54
+ }
55
+
56
+ /**
57
+ * Simulates a batch of public static calls by bypassing account entrypoint and private execution,
58
+ * directly constructing a minimal Tx and calling node.simulatePublicCalls.
59
+ *
60
+ * @param node - The Aztec node to simulate on.
61
+ * @param publicStaticCalls - Array of public static function calls (max MAX_ENQUEUED_CALLS_PER_CALL).
62
+ * @param from - The account address making the calls.
63
+ * @param chainInfo - Chain information (chainId and version).
64
+ * @param gasSettings - Gas settings for the transaction.
65
+ * @param blockHeader - Block header to use as anchor.
66
+ * @param skipFeeEnforcement - Whether to skip fee enforcement during simulation.
67
+ * @returns TxSimulationResult with public return values.
68
+ */
69
+ async function simulateBatchViaNode(
70
+ node: AztecNode,
71
+ publicStaticCalls: FunctionCall[],
72
+ from: AztecAddress,
73
+ chainInfo: ChainInfo,
74
+ gasSettings: GasSettings,
75
+ blockHeader: BlockHeader,
76
+ skipFeeEnforcement: boolean,
77
+ getContractName: ContractNameResolver,
78
+ ): Promise<TxSimulationResult> {
79
+ const txContext = new TxContext(chainInfo.chainId, chainInfo.version, gasSettings);
80
+
81
+ const publicFunctionCalldata: HashedValues[] = [];
82
+ for (const call of publicStaticCalls) {
83
+ const calldata = await HashedValues.fromCalldata([call.selector.toField(), ...call.args]);
84
+ publicFunctionCalldata.push(calldata);
85
+ }
86
+
87
+ const publicCallRequests = makeTuple(MAX_ENQUEUED_CALLS_PER_CALL, i => {
88
+ const call = publicStaticCalls[i];
89
+ if (!call) {
90
+ return CountedPublicCallRequest.empty();
91
+ }
92
+ const publicCallRequest = new PublicCallRequest(from, call.to, call.isStatic, publicFunctionCalldata[i]!.hash);
93
+ // Counter starts at 1 (minRevertibleSideEffectCounter) so all calls are revertible
94
+ return new CountedPublicCallRequest(publicCallRequest, i + 1);
95
+ });
96
+
97
+ const publicCallRequestsArray: ClaimedLengthArray<CountedPublicCallRequest, typeof MAX_ENQUEUED_CALLS_PER_CALL> =
98
+ new ClaimedLengthArray(
99
+ publicCallRequests as Tuple<CountedPublicCallRequest, typeof MAX_ENQUEUED_CALLS_PER_CALL>,
100
+ publicStaticCalls.length,
101
+ );
102
+
103
+ const publicInputs = PrivateCircuitPublicInputs.from({
104
+ ...PrivateCircuitPublicInputs.empty(),
105
+ anchorBlockHeader: blockHeader,
106
+ txContext: txContext,
107
+ publicCallRequests: publicCallRequestsArray,
108
+ startSideEffectCounter: new Fr(0),
109
+ endSideEffectCounter: new Fr(publicStaticCalls.length + 1),
110
+ });
111
+
112
+ // Minimal entrypoint structure — no real private execution, just public call requests
113
+ const emptyEntrypoint = new PrivateCallExecutionResult(
114
+ Buffer.alloc(0),
115
+ Buffer.alloc(0),
116
+ new Map(),
117
+ publicInputs,
118
+ [],
119
+ new Map(),
120
+ [],
121
+ [],
122
+ [],
123
+ [],
124
+ [],
125
+ );
126
+
127
+ const privateResult = new PrivateExecutionResult(emptyEntrypoint, Fr.random(), publicFunctionCalldata);
128
+
129
+ const provingResult = await generateSimulatedProvingResult(
130
+ privateResult,
131
+ (_contractAddress: AztecAddress, _functionSelector: FunctionSelector) => Promise.resolve(''),
132
+ node,
133
+ 1, // minRevertibleSideEffectCounter
134
+ );
135
+
136
+ provingResult.publicInputs.feePayer = from;
137
+
138
+ const tx = await Tx.create({
139
+ data: provingResult.publicInputs,
140
+ chonkProof: ChonkProof.empty(),
141
+ contractClassLogFields: [],
142
+ publicFunctionCalldata: publicFunctionCalldata,
143
+ });
144
+
145
+ const publicOutput = await node.simulatePublicCalls(tx, skipFeeEnforcement);
146
+
147
+ if (publicOutput.revertReason) {
148
+ throw publicOutput.revertReason;
149
+ }
150
+
151
+ // Display debug logs from the public simulation.
152
+ await displayDebugLogs(publicOutput.debugLogs, getContractName);
153
+
154
+ return new TxSimulationResult(privateResult, provingResult.publicInputs, publicOutput, undefined);
155
+ }
156
+
157
+ /**
158
+ * Simulates public static calls by splitting them into batches of MAX_ENQUEUED_CALLS_PER_CALL
159
+ * and sending each batch directly to the node.
160
+ *
161
+ * @param node - The Aztec node to simulate on.
162
+ * @param publicStaticCalls - Array of public static function calls to optimize.
163
+ * @param from - The account address making the calls.
164
+ * @param chainInfo - Chain information (chainId and version).
165
+ * @param gasSettings - Gas settings for the transaction.
166
+ * @param blockHeader - Block header to use as anchor.
167
+ * @param skipFeeEnforcement - Whether to skip fee enforcement during simulation.
168
+ * @returns Array of TxSimulationResult, one per batch.
169
+ */
170
+ export async function simulateViaNode(
171
+ node: AztecNode,
172
+ publicStaticCalls: FunctionCall[],
173
+ from: AztecAddress,
174
+ chainInfo: ChainInfo,
175
+ gasSettings: GasSettings,
176
+ blockHeader: BlockHeader,
177
+ skipFeeEnforcement: boolean = true,
178
+ getContractName: ContractNameResolver,
179
+ ): Promise<TxSimulationResult[]> {
180
+ const batches: FunctionCall[][] = [];
181
+
182
+ for (let i = 0; i < publicStaticCalls.length; i += MAX_ENQUEUED_CALLS_PER_CALL) {
183
+ batches.push(publicStaticCalls.slice(i, i + MAX_ENQUEUED_CALLS_PER_CALL));
184
+ }
185
+
186
+ const results: TxSimulationResult[] = [];
187
+
188
+ for (const batch of batches) {
189
+ const result = await simulateBatchViaNode(
190
+ node,
191
+ batch,
192
+ from,
193
+ chainInfo,
194
+ gasSettings,
195
+ blockHeader,
196
+ skipFeeEnforcement,
197
+ getContractName,
198
+ );
199
+ results.push(result);
200
+ }
201
+
202
+ return results;
203
+ }
204
+
205
+ /**
206
+ * Merges simulation results from the optimized (public static) and normal paths.
207
+ * Since optimized calls are always a leading prefix, return values are simply
208
+ * concatenated: optimized first, then normal.
209
+ * Stats are taken from the normal result only (the optimized path doesn't produce them).
210
+ *
211
+ * @param optimizedResults - Results from optimized public static call batches.
212
+ * @param normalResult - Result from normal simulation (null if all calls were optimized).
213
+ * @returns A single TxSimulationResult with return values in original call order.
214
+ */
215
+ export function buildMergedSimulationResult(
216
+ optimizedResults: TxSimulationResult[],
217
+ normalResult: TxSimulationResult | null,
218
+ ): TxSimulationResult {
219
+ const optimizedReturnValues = optimizedResults.flatMap(r => r.publicOutput?.publicReturnValues ?? []);
220
+ const normalReturnValues = normalResult?.publicOutput?.publicReturnValues ?? [];
221
+ const allReturnValues = [...optimizedReturnValues, ...normalReturnValues];
222
+
223
+ const baseResult = normalResult ?? optimizedResults[0];
224
+
225
+ const mergedPublicOutput: PublicSimulationOutput | undefined = baseResult.publicOutput
226
+ ? {
227
+ ...baseResult.publicOutput,
228
+ publicReturnValues: allReturnValues,
229
+ }
230
+ : undefined;
231
+
232
+ return new TxSimulationResult(
233
+ baseResult.privateExecutionResult,
234
+ baseResult.publicInputs,
235
+ mergedPublicOutput,
236
+ normalResult?.stats,
237
+ );
238
+ }
@@ -109,7 +109,7 @@ export class ExtensionWallet {
109
109
  sharedKey: CryptoKey,
110
110
  chainInfo: ChainInfo,
111
111
  appId: string,
112
- ): Wallet {
112
+ ): ExtensionWallet {
113
113
  const wallet = new ExtensionWallet(chainInfo, appId, extensionId, port, sharedKey);
114
114
 
115
115
  // Set up message handler for encrypted responses and unencrypted control messages
@@ -127,8 +127,10 @@ export class ExtensionWallet {
127
127
  wallet.port.start();
128
128
 
129
129
  return new Proxy(wallet, {
130
- get: (target, prop) => {
131
- if (schemaHasMethod(WalletSchema, prop.toString())) {
130
+ get: (target, prop, receiver) => {
131
+ if (prop === 'asWallet') {
132
+ return () => receiver as unknown as Wallet;
133
+ } else if (schemaHasMethod(WalletSchema, prop.toString())) {
132
134
  return async (...args: unknown[]) => {
133
135
  const result = await target.postMessage({
134
136
  type: prop.toString() as keyof FunctionsOf<Wallet>,
@@ -140,7 +142,13 @@ export class ExtensionWallet {
140
142
  return target[prop as keyof ExtensionWallet];
141
143
  }
142
144
  },
143
- }) as unknown as Wallet;
145
+ });
146
+ }
147
+
148
+ asWallet(): Wallet {
149
+ // Overridden by the proxy in create() to return the proxy itself.
150
+ // This body is never reached when accessed through create().
151
+ return this as unknown as Wallet;
144
152
  }
145
153
 
146
154
  /**
@@ -116,18 +116,18 @@ export interface WalletProvider {
116
116
  * After calling this, the wallet returned from confirm() should no longer be used.
117
117
  * @returns A promise that resolves when disconnection is complete
118
118
  */
119
- disconnect?(): Promise<void>;
119
+ disconnect(): Promise<void>;
120
120
  /**
121
121
  * Registers a callback to be invoked when the wallet disconnects unexpectedly.
122
122
  * @param callback - Function to call when wallet disconnects
123
123
  * @returns A function to unregister the callback
124
124
  */
125
- onDisconnect?(callback: ProviderDisconnectionCallback): () => void;
125
+ onDisconnect(callback: ProviderDisconnectionCallback): () => void;
126
126
  /**
127
127
  * Returns whether the provider's wallet connection has been disconnected.
128
128
  * @returns true if the wallet is no longer connected
129
129
  */
130
- isDisconnected?(): boolean;
130
+ isDisconnected(): boolean;
131
131
  }
132
132
 
133
133
  /**
@@ -196,15 +196,14 @@ export class WalletManager {
196
196
  return {
197
197
  verificationHash: connection.info.verificationHash!,
198
198
  confirm: () => {
199
- return Promise.resolve(
200
- ExtensionWallet.create(
201
- connection.info.id,
202
- connection.port,
203
- connection.sharedKey,
204
- chainInfo,
205
- connectAppId,
206
- ),
199
+ extensionWallet = ExtensionWallet.create(
200
+ connection.info.id,
201
+ connection.port,
202
+ connection.sharedKey,
203
+ chainInfo,
204
+ connectAppId,
207
205
  );
206
+ return Promise.resolve(extensionWallet.asWallet());
208
207
  },
209
208
  cancel: () => {
210
209
  // Send disconnect to terminate the session on the extension side
@@ -213,7 +212,6 @@ export class WalletManager {
213
212
  type: WalletMessageType.DISCONNECT,
214
213
  requestId: discoveredWallet.requestId,
215
214
  });
216
- // Don't close the port - allow retry with fresh key exchange
217
215
  },
218
216
  };
219
217
  },