@aztec/wallet-sdk 0.0.1-commit.5476d83 → 0.0.1-commit.5914bae

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 (105) hide show
  1. package/README.md +228 -331
  2. package/dest/base-wallet/base_wallet.d.ts +92 -42
  3. package/dest/base-wallet/base_wallet.d.ts.map +1 -1
  4. package/dest/base-wallet/base_wallet.js +261 -80
  5. package/dest/base-wallet/index.d.ts +3 -2
  6. package/dest/base-wallet/index.d.ts.map +1 -1
  7. package/dest/base-wallet/index.js +1 -0
  8. package/dest/base-wallet/utils.d.ts +50 -0
  9. package/dest/base-wallet/utils.d.ts.map +1 -0
  10. package/dest/base-wallet/utils.js +133 -0
  11. package/dest/crypto.d.ts +230 -0
  12. package/dest/crypto.d.ts.map +1 -0
  13. package/dest/crypto.js +482 -0
  14. package/dest/emoji_alphabet.d.ts +35 -0
  15. package/dest/emoji_alphabet.d.ts.map +1 -0
  16. package/dest/emoji_alphabet.js +299 -0
  17. package/dest/extension/handlers/background_connection_handler.d.ts +158 -0
  18. package/dest/extension/handlers/background_connection_handler.d.ts.map +1 -0
  19. package/dest/extension/handlers/background_connection_handler.js +258 -0
  20. package/dest/extension/handlers/content_script_connection_handler.d.ts +56 -0
  21. package/dest/extension/handlers/content_script_connection_handler.d.ts.map +1 -0
  22. package/dest/extension/handlers/content_script_connection_handler.js +174 -0
  23. package/dest/extension/handlers/index.d.ts +12 -0
  24. package/dest/extension/handlers/index.d.ts.map +1 -0
  25. package/dest/extension/handlers/index.js +10 -0
  26. package/dest/extension/handlers/internal_message_types.d.ts +63 -0
  27. package/dest/extension/handlers/internal_message_types.d.ts.map +1 -0
  28. package/dest/extension/handlers/internal_message_types.js +22 -0
  29. package/dest/extension/provider/extension_provider.d.ts +107 -0
  30. package/dest/extension/provider/extension_provider.d.ts.map +1 -0
  31. package/dest/extension/provider/extension_provider.js +160 -0
  32. package/dest/extension/provider/extension_wallet.d.ts +129 -0
  33. package/dest/extension/provider/extension_wallet.d.ts.map +1 -0
  34. package/dest/extension/provider/extension_wallet.js +278 -0
  35. package/dest/extension/provider/index.d.ts +3 -0
  36. package/dest/extension/provider/index.d.ts.map +1 -0
  37. package/dest/iframe/handlers/iframe_connection_handler.d.ts +118 -0
  38. package/dest/iframe/handlers/iframe_connection_handler.d.ts.map +1 -0
  39. package/dest/iframe/handlers/iframe_connection_handler.js +228 -0
  40. package/dest/iframe/handlers/index.d.ts +2 -0
  41. package/dest/iframe/handlers/index.d.ts.map +1 -0
  42. package/dest/iframe/handlers/index.js +1 -0
  43. package/dest/iframe/provider/iframe_discovery.d.ts +25 -0
  44. package/dest/iframe/provider/iframe_discovery.d.ts.map +1 -0
  45. package/dest/iframe/provider/iframe_discovery.js +167 -0
  46. package/dest/iframe/provider/iframe_provider.d.ts +65 -0
  47. package/dest/iframe/provider/iframe_provider.d.ts.map +1 -0
  48. package/dest/iframe/provider/iframe_provider.js +257 -0
  49. package/dest/iframe/provider/iframe_wallet.d.ts +68 -0
  50. package/dest/iframe/provider/iframe_wallet.d.ts.map +1 -0
  51. package/dest/iframe/provider/iframe_wallet.js +200 -0
  52. package/dest/iframe/provider/index.d.ts +4 -0
  53. package/dest/iframe/provider/index.d.ts.map +1 -0
  54. package/dest/iframe/provider/index.js +3 -0
  55. package/dest/manager/index.d.ts +2 -7
  56. package/dest/manager/index.d.ts.map +1 -1
  57. package/dest/manager/index.js +0 -4
  58. package/dest/manager/types.d.ts +109 -5
  59. package/dest/manager/types.d.ts.map +1 -1
  60. package/dest/manager/types.js +17 -1
  61. package/dest/manager/wallet_manager.d.ts +50 -7
  62. package/dest/manager/wallet_manager.d.ts.map +1 -1
  63. package/dest/manager/wallet_manager.js +208 -29
  64. package/dest/types.d.ts +135 -0
  65. package/dest/types.d.ts.map +1 -0
  66. package/dest/types.js +15 -0
  67. package/package.json +26 -13
  68. package/src/base-wallet/base_wallet.ts +360 -142
  69. package/src/base-wallet/index.ts +7 -1
  70. package/src/base-wallet/utils.ts +240 -0
  71. package/src/crypto.ts +603 -0
  72. package/src/emoji_alphabet.ts +317 -0
  73. package/src/extension/handlers/background_connection_handler.ts +423 -0
  74. package/src/extension/handlers/content_script_connection_handler.ts +246 -0
  75. package/src/extension/handlers/index.ts +25 -0
  76. package/src/extension/handlers/internal_message_types.ts +69 -0
  77. package/src/extension/provider/extension_provider.ts +233 -0
  78. package/src/extension/provider/extension_wallet.ts +324 -0
  79. package/src/extension/provider/index.ts +7 -0
  80. package/src/iframe/handlers/iframe_connection_handler.ts +328 -0
  81. package/src/iframe/handlers/index.ts +7 -0
  82. package/src/iframe/provider/iframe_discovery.ts +185 -0
  83. package/src/iframe/provider/iframe_provider.ts +331 -0
  84. package/src/iframe/provider/iframe_wallet.ts +229 -0
  85. package/src/iframe/provider/index.ts +3 -0
  86. package/src/manager/index.ts +3 -15
  87. package/src/manager/types.ts +113 -4
  88. package/src/manager/wallet_manager.ts +235 -30
  89. package/src/types.ts +145 -0
  90. package/dest/providers/extension/extension_provider.d.ts +0 -17
  91. package/dest/providers/extension/extension_provider.d.ts.map +0 -1
  92. package/dest/providers/extension/extension_provider.js +0 -56
  93. package/dest/providers/extension/extension_wallet.d.ts +0 -23
  94. package/dest/providers/extension/extension_wallet.d.ts.map +0 -1
  95. package/dest/providers/extension/extension_wallet.js +0 -96
  96. package/dest/providers/extension/index.d.ts +0 -4
  97. package/dest/providers/extension/index.d.ts.map +0 -1
  98. package/dest/providers/types.d.ts +0 -67
  99. package/dest/providers/types.d.ts.map +0 -1
  100. package/dest/providers/types.js +0 -3
  101. package/src/providers/extension/extension_provider.ts +0 -72
  102. package/src/providers/extension/extension_wallet.ts +0 -124
  103. package/src/providers/extension/index.ts +0 -3
  104. package/src/providers/types.ts +0 -71
  105. /package/dest/{providers/extension → extension/provider}/index.js +0 -0
@@ -1,28 +1,38 @@
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';
4
+ import {
5
+ type InteractionWaitOptions,
6
+ NO_WAIT,
7
+ type SendReturn,
8
+ extractOffchainOutput,
9
+ } from '@aztec/aztec.js/contracts';
3
10
  import type { FeePaymentMethod } from '@aztec/aztec.js/fee';
4
- import type {
5
- Aliased,
6
- BatchResults,
7
- BatchableMethods,
8
- BatchedMethod,
9
- ProfileOptions,
10
- SendOptions,
11
- SimulateOptions,
12
- Wallet,
13
- } from '@aztec/aztec.js/wallet';
11
+ import { waitForTx } from '@aztec/aztec.js/node';
14
12
  import {
15
- GAS_ESTIMATION_DA_GAS_LIMIT,
16
- GAS_ESTIMATION_L2_GAS_LIMIT,
17
- GAS_ESTIMATION_TEARDOWN_DA_GAS_LIMIT,
18
- GAS_ESTIMATION_TEARDOWN_L2_GAS_LIMIT,
19
- } from '@aztec/constants';
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
+ TxSimulationResultWithAppOffset,
25
+ type Wallet,
26
+ type WalletCapabilities,
27
+ } from '@aztec/aztec.js/wallet';
20
28
  import { AccountFeePaymentMethodOptions, type DefaultAccountEntrypointOptions } from '@aztec/entrypoints/account';
29
+ import { DefaultEntrypoint } from '@aztec/entrypoints/default';
21
30
  import type { ChainInfo } from '@aztec/entrypoints/interfaces';
22
- import { Fr } from '@aztec/foundation/fields';
31
+ import { Fr } from '@aztec/foundation/curves/bn254';
23
32
  import { createLogger } from '@aztec/foundation/log';
24
33
  import type { FieldsOf } from '@aztec/foundation/types';
25
- import type { PXE } from '@aztec/pxe/server';
34
+ import { displayDebugLogs } from '@aztec/pxe/client/lazy';
35
+ import type { PXE, PackedPrivateEvent } from '@aztec/pxe/server';
26
36
  import {
27
37
  type ContractArtifact,
28
38
  type EventMetadataDefinition,
@@ -30,29 +40,32 @@ import {
30
40
  decodeFromAbi,
31
41
  } from '@aztec/stdlib/abi';
32
42
  import type { AuthWitness } from '@aztec/stdlib/auth-witness';
33
- import type { AztecAddress } from '@aztec/stdlib/aztec-address';
43
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
34
44
  import {
35
- type ContractClassMetadata,
36
45
  type ContractInstanceWithAddress,
37
- type ContractMetadata,
46
+ type NodeInfo,
38
47
  computePartialAddress,
39
48
  getContractClassFromArtifact,
40
49
  } from '@aztec/stdlib/contract';
41
50
  import { SimulationError } from '@aztec/stdlib/errors';
42
- import { Gas, GasSettings } from '@aztec/stdlib/gas';
51
+ import { Gas, GasFees, GasSettings } from '@aztec/stdlib/gas';
52
+ import {
53
+ computeSiloedPrivateInitializationNullifier,
54
+ computeSiloedPublicInitializationNullifier,
55
+ } from '@aztec/stdlib/hash';
43
56
  import type { AztecNode } from '@aztec/stdlib/interfaces/client';
44
- import type {
45
- TxExecutionRequest,
46
- TxHash,
47
- TxProfileResult,
48
- TxReceipt,
49
- TxSimulationResult,
50
- UtilitySimulationResult,
57
+ import {
58
+ BlockHeader,
59
+ type TxExecutionRequest,
60
+ type TxProfileResult,
61
+ type UtilityExecutionResult,
51
62
  } from '@aztec/stdlib/tx';
52
63
  import { ExecutionPayload, mergeExecutionPayloads } from '@aztec/stdlib/tx';
53
64
 
54
65
  import { inspect } from 'util';
55
66
 
67
+ import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simulateViaNode } from './utils.js';
68
+
56
69
  /**
57
70
  * Options to configure fee payment for a transaction
58
71
  */
@@ -63,26 +76,55 @@ export type FeeOptions = {
63
76
  */
64
77
  walletFeePaymentMethod?: FeePaymentMethod;
65
78
  /** Configuration options for the account to properly handle the selected fee payment method */
66
- accountFeePaymentMethodOptions: AccountFeePaymentMethodOptions;
79
+ accountFeePaymentMethodOptions?: AccountFeePaymentMethodOptions;
67
80
  /** The gas settings to use for the transaction */
68
81
  gasSettings: GasSettings;
69
82
  };
70
83
 
84
+ /** Options for `simulateViaEntrypoint`. */
85
+ export type SimulateViaEntrypointOptions = Pick<
86
+ SimulateOptions,
87
+ 'from' | 'additionalScopes' | 'skipTxValidation' | 'skipFeeEnforcement'
88
+ > & {
89
+ /** Fee options for the entrypoint */
90
+ feeOptions: FeeOptions;
91
+ };
92
+
93
+ /** Options for `completeFeeOptions`. */
94
+ export type CompleteFeeOptionsConfig = {
95
+ /** The address where the transaction is being sent from. */
96
+ from: AztecAddress | NoFrom;
97
+ /** The address paying for fees (if any fee payment method is embedded in the execution payload). */
98
+ feePayer?: AztecAddress;
99
+ /** User-provided partial gas settings. */
100
+ gasSettings?: Partial<FieldsOf<GasSettings>>;
101
+ /** If true, returns gas settings with high gas limits for estimation. If false, uses fallback limits. */
102
+ forEstimation?: boolean;
103
+ };
104
+
71
105
  /**
72
106
  * A base class for Wallet implementations
73
107
  */
74
108
  export abstract class BaseWallet implements Wallet {
75
- protected log = createLogger('wallet-sdk:base_wallet');
76
-
77
- protected baseFeePadding = 0.5;
109
+ protected minFeePadding = 0.5;
78
110
  protected cancellableTransactions = false;
111
+ // A wallet is instantiated for a particular chain, so chain info never changes during its lifetime.
112
+ // We cache it here because getChainInfo is called frequently (every tx simulation, send, auth wit, etc.).
113
+ private nodeInfoPromise: Promise<NodeInfo> | undefined;
79
114
 
80
115
  // Protected because we want to force wallets to instantiate their own PXE.
81
116
  protected constructor(
82
117
  protected readonly pxe: PXE,
83
118
  protected readonly aztecNode: AztecNode,
119
+ protected log = createLogger('wallet-sdk:base_wallet'),
84
120
  ) {}
85
121
 
122
+ protected scopesFrom(from: AztecAddress | NoFrom, additionalScopes: AztecAddress[] = []): AztecAddress[] {
123
+ const allScopes = from === NO_FROM ? additionalScopes : [from, ...additionalScopes];
124
+ const scopeSet = new Set(allScopes.map(address => address.toString()));
125
+ return [...scopeSet].map(AztecAddress.fromString);
126
+ }
127
+
86
128
  protected abstract getAccountFromAddress(address: AztecAddress): Promise<Account>;
87
129
 
88
130
  abstract getAccounts(): Promise<Aliased<AztecAddress>[]>;
@@ -100,39 +142,71 @@ export abstract class BaseWallet implements Wallet {
100
142
  }
101
143
 
102
144
  async getChainInfo(): Promise<ChainInfo> {
103
- const { l1ChainId, rollupVersion } = await this.aztecNode.getNodeInfo();
145
+ if (!this.nodeInfoPromise) {
146
+ this.nodeInfoPromise = this.aztecNode.getNodeInfo();
147
+ }
148
+ const { l1ChainId, rollupVersion } = await this.nodeInfoPromise;
104
149
  return { chainId: new Fr(l1ChainId), version: new Fr(rollupVersion) };
105
150
  }
106
151
 
107
152
  protected async createTxExecutionRequestFromPayloadAndFee(
108
153
  executionPayload: ExecutionPayload,
109
- from: AztecAddress,
154
+ from: AztecAddress | NoFrom,
110
155
  feeOptions: FeeOptions,
111
156
  ): Promise<TxExecutionRequest> {
112
157
  const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
113
- const executionOptions: DefaultAccountEntrypointOptions = {
114
- txNonce: Fr.random(),
115
- cancellable: this.cancellableTransactions,
116
- feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions,
117
- };
118
158
  const finalExecutionPayload = feeExecutionPayload
119
159
  ? mergeExecutionPayloads([feeExecutionPayload, executionPayload])
120
160
  : executionPayload;
121
- const fromAccount = await this.getAccountFromAddress(from);
122
- return fromAccount.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, executionOptions);
161
+ const chainInfo = await this.getChainInfo();
162
+
163
+ if (from === NO_FROM) {
164
+ const entrypoint = new DefaultEntrypoint();
165
+ return entrypoint.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo);
166
+ } else {
167
+ const fromAccount = await this.getAccountFromAddress(from);
168
+ const executionOptions: DefaultAccountEntrypointOptions = {
169
+ txNonce: Fr.random(),
170
+ cancellable: this.cancellableTransactions,
171
+ // If from is an address, feeOptions include the way the account contract should handle the fee payment
172
+ feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions!,
173
+ };
174
+ return fromAccount.createTxExecutionRequest(
175
+ finalExecutionPayload,
176
+ feeOptions.gasSettings,
177
+ chainInfo,
178
+ executionOptions,
179
+ );
180
+ }
123
181
  }
124
182
 
125
183
  public async createAuthWit(
126
184
  from: AztecAddress,
127
- messageHashOrIntent: Fr | IntentInnerHash | CallIntent,
185
+ messageHashOrIntent: IntentInnerHash | CallIntent,
128
186
  ): Promise<AuthWitness> {
129
187
  const account = await this.getAccountFromAddress(from);
130
- return account.createAuthWit(messageHashOrIntent);
188
+ const chainInfo = await this.getChainInfo();
189
+ return account.createAuthWit(messageHashOrIntent, chainInfo);
190
+ }
191
+
192
+ /**
193
+ * Request capabilities from the wallet.
194
+ *
195
+ * This method is wallet-implementation-dependent and must be provided by classes extending BaseWallet.
196
+ * Embedded wallets typically don't support capability-based authorization (no user authorization flow),
197
+ * while external wallets (browser extensions, hardware wallets) implement this to reduce authorization
198
+ * friction by allowing apps to request permissions upfront.
199
+ *
200
+ * TODO: Consider making it abstract so implementing it is a conscious decision. Leaving it as-is
201
+ * while the feature stabilizes.
202
+ *
203
+ * @param _manifest - Application capability manifest declaring what operations the app needs
204
+ */
205
+ public requestCapabilities(_manifest: AppCapabilities): Promise<WalletCapabilities> {
206
+ throw new Error('Not implemented');
131
207
  }
132
208
 
133
- public async batch<const T extends readonly BatchedMethod<keyof BatchableMethods>[]>(
134
- methods: T,
135
- ): Promise<BatchResults<T>> {
209
+ public async batch<const T extends readonly BatchedMethod[]>(methods: T): Promise<BatchResults<T>> {
136
210
  const results: any[] = [];
137
211
  for (const method of methods) {
138
212
  const { name, args } = method;
@@ -152,31 +226,39 @@ export abstract class BaseWallet implements Wallet {
152
226
 
153
227
  /**
154
228
  * Completes partial user-provided fee options with wallet defaults.
155
- * @param from - The address where the transaction is being sent from
156
- * @param feePayer - The address paying for fees (if any fee payment method is embedded in the execution payload)
157
- * @param gasSettings - User-provided partial gas settings
158
- * @returns - Complete fee options that can be used to create a transaction execution request
229
+ * @param config - Fee completion config.
159
230
  */
160
- protected async completeFeeOptions(
161
- from: AztecAddress,
162
- feePayer?: AztecAddress,
163
- gasSettings?: Partial<FieldsOf<GasSettings>>,
164
- ): Promise<FeeOptions> {
231
+ protected async completeFeeOptions(config: CompleteFeeOptionsConfig): Promise<FeeOptions> {
232
+ const { from, feePayer, gasSettings, forEstimation } = config;
165
233
  const maxFeesPerGas =
166
- gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentBaseFees()).mul(1 + this.baseFeePadding);
234
+ gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentMinFees()).mul(1 + this.minFeePadding);
167
235
  let accountFeePaymentMethodOptions;
168
- // The transaction does not include a fee payment method, so we set the flag
169
- // for the account to use its fee juice balance
170
- if (!feePayer) {
171
- accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
172
- } else {
173
- // The transaction includes fee payment method, so we check if we are the fee payer for it
174
- // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
175
- accountFeePaymentMethodOptions = from.equals(feePayer)
176
- ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM
177
- : AccountFeePaymentMethodOptions.EXTERNAL;
236
+ // If from is an address, we need to determine the appropriate fee payment method options for the
237
+ // account contract entrypoint to use
238
+ if (from !== NO_FROM) {
239
+ if (!feePayer) {
240
+ // The transaction does not include a fee payment method, so we set the flag
241
+ // for the account to use its fee juice balance
242
+ accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
243
+ } else {
244
+ // The transaction includes fee payment method, so we check if we are the fee payer for it
245
+ // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
246
+ accountFeePaymentMethodOptions = from.equals(feePayer)
247
+ ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM
248
+ : AccountFeePaymentMethodOptions.EXTERNAL;
249
+ }
178
250
  }
179
- const fullGasSettings: GasSettings = GasSettings.default({ ...gasSettings, maxFeesPerGas });
251
+ const gasSettingsOverrides = {
252
+ gasLimits: gasSettings?.gasLimits ? Gas.from(gasSettings.gasLimits) : undefined,
253
+ teardownGasLimits: gasSettings?.teardownGasLimits ? Gas.from(gasSettings.teardownGasLimits) : undefined,
254
+ maxFeesPerGas,
255
+ maxPriorityFeesPerGas: gasSettings?.maxPriorityFeesPerGas ?? GasFees.empty(),
256
+ };
257
+ // When estimating gas (simulation), use high limits so the simulation doesn't run out of gas.
258
+ // When sending for real, use protocol max limits that the network will actually accept.
259
+ const fullGasSettings = forEstimation
260
+ ? GasSettings.forEstimation(gasSettingsOverrides)
261
+ : GasSettings.fallback(gasSettingsOverrides);
180
262
  this.log.debug(`Using L2 gas settings`, fullGasSettings);
181
263
  return {
182
264
  gasSettings: fullGasSettings,
@@ -185,37 +267,6 @@ export abstract class BaseWallet implements Wallet {
185
267
  };
186
268
  }
187
269
 
188
- /**
189
- * Completes partial user-provided fee options with unreasonably high gas limits
190
- * for gas estimation. Uses the same logic as completeFeeOptions but sets high limits
191
- * to avoid running out of gas during estimation.
192
- * @param from - The address where the transaction is being sent from
193
- * @param feePayer - The address paying for fees (if any fee payment method is embedded in the execution payload)
194
- * @param gasSettings - User-provided partial gas settings
195
- */
196
- protected async completeFeeOptionsForEstimation(
197
- from: AztecAddress,
198
- feePayer?: AztecAddress,
199
- gasSettings?: Partial<FieldsOf<GasSettings>>,
200
- ) {
201
- const defaultFeeOptions = await this.completeFeeOptions(from, feePayer, gasSettings);
202
- const {
203
- gasSettings: { maxFeesPerGas, maxPriorityFeesPerGas },
204
- } = defaultFeeOptions;
205
- // Use unrealistically high gas limits for estimation to avoid running out of gas.
206
- // They will be tuned down after the simulation.
207
- const gasSettingsForEstimation = new GasSettings(
208
- new Gas(GAS_ESTIMATION_DA_GAS_LIMIT, GAS_ESTIMATION_L2_GAS_LIMIT),
209
- new Gas(GAS_ESTIMATION_TEARDOWN_DA_GAS_LIMIT, GAS_ESTIMATION_TEARDOWN_L2_GAS_LIMIT),
210
- maxFeesPerGas,
211
- maxPriorityFeesPerGas,
212
- );
213
- return {
214
- ...defaultFeeOptions,
215
- gasSettings: gasSettingsForEstimation,
216
- };
217
- }
218
-
219
270
  registerSender(address: AztecAddress, _alias: string = ''): Promise<AztecAddress> {
220
271
  return this.pxe.registerSender(address);
221
272
  }
@@ -225,7 +276,7 @@ export abstract class BaseWallet implements Wallet {
225
276
  artifact?: ContractArtifact,
226
277
  secretKey?: Fr,
227
278
  ): Promise<ContractInstanceWithAddress> {
228
- const { contractInstance: existingInstance } = await this.pxe.getContractMetadata(instance.address);
279
+ const existingInstance = await this.pxe.getContractInstance(instance.address);
229
280
 
230
281
  if (existingInstance) {
231
282
  // Instance already registered in the wallet
@@ -242,13 +293,12 @@ export abstract class BaseWallet implements Wallet {
242
293
  // Instance not registered yet
243
294
  if (!artifact) {
244
295
  // Try to get the artifact from the wallet's contract class storage
245
- const classMetadata = await this.pxe.getContractClassMetadata(instance.currentContractClassId, true);
246
- if (!classMetadata.artifact) {
296
+ artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
297
+ if (!artifact) {
247
298
  throw new Error(
248
299
  `Cannot register contract at ${instance.address.toString()}: artifact is required but not provided, and wallet does not have the artifact for contract class ${instance.currentContractClassId.toString()}`,
249
300
  );
250
301
  }
251
- artifact = classMetadata.artifact;
252
302
  }
253
303
  await this.pxe.registerContract({ artifact, instance });
254
304
  }
@@ -259,29 +309,129 @@ export abstract class BaseWallet implements Wallet {
259
309
  return instance;
260
310
  }
261
311
 
262
- async simulateTx(executionPayload: ExecutionPayload, opts: SimulateOptions): Promise<TxSimulationResult> {
263
- const feeOptions = opts.fee?.estimateGas
264
- ? await this.completeFeeOptionsForEstimation(opts.from, executionPayload.feePayer, opts.fee?.gasSettings)
265
- : await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
266
- const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
267
- return this.pxe.simulateTx(
268
- txRequest,
269
- true /* simulatePublic */,
270
- opts?.skipTxValidation,
271
- opts?.skipFeeEnforcement ?? true,
312
+ /**
313
+ * Simulates calls through the standard PXE path (account entrypoint).
314
+ * @param executionPayload - The execution payload to simulate.
315
+ * @param opts - Simulation options.
316
+ */
317
+ protected async simulateViaEntrypoint(executionPayload: ExecutionPayload, opts: SimulateViaEntrypointOptions) {
318
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(
319
+ executionPayload,
320
+ opts.from,
321
+ opts.feeOptions,
272
322
  );
323
+ const result = await this.pxe.simulateTx(txRequest, {
324
+ simulatePublic: true,
325
+ skipTxValidation: opts.skipTxValidation,
326
+ skipFeeEnforcement: opts.skipFeeEnforcement,
327
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
328
+ });
329
+ const appCallOffset = await this.computeAppCallOffset(opts.from, opts.feeOptions);
330
+ return TxSimulationResultWithAppOffset.fromResultAndOffset(result, appCallOffset);
331
+ }
332
+
333
+ /**
334
+ * Computes the index where the app's calls begin in the flattened array of calls (0 = entrypoint/root, 1..N = fee
335
+ * calls, N+1 = app).
336
+ * @param from - The sender address, or NO_FROM for the default entrypoint.
337
+ * @param feeOptions - Fee options containing the wallet fee payment method.
338
+ */
339
+ protected async computeAppCallOffset(from: AztecAddress | NoFrom, feeOptions: FeeOptions): Promise<number> {
340
+ if (from === NO_FROM) {
341
+ return 0;
342
+ }
343
+ const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
344
+ return (feeExecutionPayload?.calls.length ?? 0) + 1; // +1 for entrypoint
345
+ }
346
+
347
+ /**
348
+ * Simulates a transaction, optimizing leading public static calls by running them directly
349
+ * on the node while sending the remaining calls through the standard PXE path.
350
+ * Return values from both paths are merged back in original call order.
351
+ * @param executionPayload - The execution payload to simulate.
352
+ * @param opts - Simulation options (from address, fee settings, etc.).
353
+ * @returns The merged simulation result.
354
+ */
355
+ async simulateTx(
356
+ executionPayload: ExecutionPayload,
357
+ opts: SimulateOptions,
358
+ ): Promise<TxSimulationResultWithAppOffset> {
359
+ const feeOptions = await this.completeFeeOptions({
360
+ from: opts.from,
361
+ feePayer: executionPayload.feePayer,
362
+ gasSettings: opts.fee?.gasSettings,
363
+ forEstimation: true,
364
+ });
365
+ const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
366
+ const remainingPayload = { ...executionPayload, calls: remainingCalls };
367
+
368
+ const chainInfo = await this.getChainInfo();
369
+ let blockHeader: BlockHeader;
370
+ // PXE might not be synced yet, so we pull the latest header from the node
371
+ // To keep things consistent, we'll always try with PXE first
372
+ try {
373
+ blockHeader = await this.pxe.getSyncedBlockHeader();
374
+ } catch {
375
+ blockHeader = (await this.aztecNode.getBlockHeader())!;
376
+ }
377
+
378
+ const simulationOrigin = opts.from === NO_FROM ? AztecAddress.ZERO : opts.from;
379
+ const [optimizedResults, normalResult] = await Promise.all([
380
+ optimizableCalls.length > 0
381
+ ? simulateViaNode(
382
+ this.aztecNode,
383
+ optimizableCalls,
384
+ simulationOrigin,
385
+ chainInfo,
386
+ feeOptions.gasSettings,
387
+ blockHeader,
388
+ opts.skipFeeEnforcement ?? true,
389
+ this.getContractName.bind(this),
390
+ )
391
+ : Promise.resolve([]),
392
+ remainingCalls.length > 0
393
+ ? this.simulateViaEntrypoint(remainingPayload, {
394
+ from: opts.from,
395
+ feeOptions,
396
+ additionalScopes: opts.additionalScopes,
397
+ skipTxValidation: opts.skipTxValidation,
398
+ skipFeeEnforcement: opts.skipFeeEnforcement ?? true,
399
+ })
400
+ : Promise.resolve(null),
401
+ ]);
402
+
403
+ return buildMergedSimulationResult(optimizedResults, normalResult);
273
404
  }
274
405
 
275
406
  async profileTx(executionPayload: ExecutionPayload, opts: ProfileOptions): Promise<TxProfileResult> {
276
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
407
+ const feeOptions = await this.completeFeeOptions({
408
+ from: opts.from,
409
+ feePayer: executionPayload.feePayer,
410
+ gasSettings: opts.fee?.gasSettings,
411
+ });
277
412
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
278
- return this.pxe.profileTx(txRequest, opts.profileMode, opts.skipProofGeneration ?? true);
413
+ return this.pxe.profileTx(txRequest, {
414
+ profileMode: opts.profileMode,
415
+ skipProofGeneration: opts.skipProofGeneration ?? true,
416
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
417
+ });
279
418
  }
280
419
 
281
- async sendTx(executionPayload: ExecutionPayload, opts: SendOptions): Promise<TxHash> {
282
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
420
+ public async sendTx<W extends InteractionWaitOptions = undefined>(
421
+ executionPayload: ExecutionPayload,
422
+ opts: SendOptions<W>,
423
+ ): Promise<SendReturn<W>> {
424
+ const feeOptions = await this.completeFeeOptions({
425
+ from: opts.from,
426
+ feePayer: executionPayload.feePayer,
427
+ gasSettings: opts.fee?.gasSettings,
428
+ });
283
429
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
284
- const provenTx = await this.pxe.proveTx(txRequest);
430
+ const provenTx = await this.pxe.proveTx(txRequest, this.scopesFrom(opts.from, opts.additionalScopes));
431
+ const offchainOutput = extractOffchainOutput(
432
+ provenTx.getOffchainEffects(),
433
+ provenTx.publicInputs.constants.anchorBlockHeader.globalVariables.timestamp,
434
+ );
285
435
  const tx = await provenTx.toTx();
286
436
  const txHash = tx.getTxHash();
287
437
  if (await this.aztecNode.getTxEffect(txHash)) {
@@ -292,7 +442,35 @@ export abstract class BaseWallet implements Wallet {
292
442
  throw this.contextualizeError(err, inspect(tx));
293
443
  });
294
444
  this.log.info(`Sent transaction ${txHash}`);
295
- return txHash;
445
+
446
+ // If wait is NO_WAIT, return txHash immediately
447
+ if (opts.wait === NO_WAIT) {
448
+ return { txHash, ...offchainOutput } as SendReturn<W>;
449
+ }
450
+
451
+ // Otherwise, wait for the full receipt (default behavior on wait: undefined)
452
+ const waitOpts = typeof opts.wait === 'object' ? opts.wait : undefined;
453
+ const receipt = await waitForTx(this.aztecNode, txHash, waitOpts);
454
+
455
+ // Display debug logs from public execution if present (served in test mode only)
456
+ if (receipt.debugLogs?.length) {
457
+ await displayDebugLogs(receipt.debugLogs, this.getContractName.bind(this));
458
+ }
459
+
460
+ return { receipt, ...offchainOutput } as SendReturn<W>;
461
+ }
462
+
463
+ /**
464
+ * Resolves a contract address to a human-readable name via PXE, if available.
465
+ * @param address - The contract address to resolve.
466
+ */
467
+ protected async getContractName(address: AztecAddress): Promise<string | undefined> {
468
+ const instance = await this.pxe.getContractInstance(address);
469
+ if (!instance) {
470
+ return undefined;
471
+ }
472
+ const artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
473
+ return artifact?.name;
296
474
  }
297
475
 
298
476
  protected contextualizeError(err: Error, ...context: string[]): Error {
@@ -309,34 +487,74 @@ export abstract class BaseWallet implements Wallet {
309
487
  return err;
310
488
  }
311
489
 
312
- simulateUtility(call: FunctionCall, authwits?: AuthWitness[]): Promise<UtilitySimulationResult> {
313
- return this.pxe.simulateUtility(call, authwits);
314
- }
315
-
316
- getContractClassMetadata(id: Fr, includeArtifact: boolean = false): Promise<ContractClassMetadata> {
317
- return this.pxe.getContractClassMetadata(id, includeArtifact);
318
- }
319
- getContractMetadata(address: AztecAddress): Promise<ContractMetadata> {
320
- return this.pxe.getContractMetadata(address);
321
- }
322
-
323
- getTxReceipt(txHash: TxHash): Promise<TxReceipt> {
324
- return this.aztecNode.getTxReceipt(txHash);
490
+ executeUtility(call: FunctionCall, opts: ExecuteUtilityOptions): Promise<UtilityExecutionResult> {
491
+ return this.pxe.executeUtility(call, { authwits: opts.authWitnesses, scopes: opts.scopes });
325
492
  }
326
493
 
327
494
  async getPrivateEvents<T>(
328
- contractAddress: AztecAddress,
329
495
  eventDef: EventMetadataDefinition,
330
- from: number,
331
- limit: number,
332
- recipients: AztecAddress[] = [],
333
- ): Promise<T[]> {
334
- const events = await this.pxe.getPrivateEvents(contractAddress, eventDef.eventSelector, from, limit, recipients);
335
-
336
- const decodedEvents = events.map(
337
- (event: any /** PrivateEvent */): T => decodeFromAbi([eventDef.abiType], event.packedEvent) as T,
338
- );
496
+ eventFilter: PrivateEventFilter,
497
+ ): Promise<PrivateEvent<T>[]> {
498
+ const pxeEvents = await this.pxe.getPrivateEvents(eventDef.eventSelector, eventFilter);
499
+
500
+ const decodedEvents = pxeEvents.map((pxeEvent: PackedPrivateEvent): PrivateEvent<T> => {
501
+ return {
502
+ event: decodeFromAbi([eventDef.abiType], pxeEvent.packedEvent) as T,
503
+ metadata: {
504
+ l2BlockNumber: pxeEvent.l2BlockNumber,
505
+ l2BlockHash: pxeEvent.l2BlockHash,
506
+ txHash: pxeEvent.txHash,
507
+ },
508
+ };
509
+ });
339
510
 
340
511
  return decodedEvents;
341
512
  }
513
+
514
+ /**
515
+ * Returns metadata about a contract, including whether it has been initialized, published, and updated.
516
+ * @param address - The contract address to query.
517
+ */
518
+ async getContractMetadata(address: AztecAddress) {
519
+ const instance = await this.pxe.getContractInstance(address);
520
+ const publiclyRegisteredContractPromise = this.aztecNode.getContract(address);
521
+
522
+ let initializationStatus: ContractInitializationStatus;
523
+ if (instance) {
524
+ // We have the instance, so we can compute the private initialization nullifier (which includes init_hash and is
525
+ // emitted by both private and public initializers) and get a definitive INITIALIZED/UNINITIALIZED answer.
526
+ const initNullifier = await computeSiloedPrivateInitializationNullifier(address, instance.initializationHash);
527
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
528
+ initializationStatus = witness
529
+ ? ContractInitializationStatus.INITIALIZED
530
+ : ContractInitializationStatus.UNINITIALIZED;
531
+ } else {
532
+ // Without the instance we lack the init_hash needed for the private nullifier. We fall back to checking the
533
+ // public initialization nullifier (computed from address alone). Not all contracts emit it (only those with
534
+ // public functions that require initialization checks), so its absence doesn't mean the contract is
535
+ // uninitialized.
536
+ const publicNullifier = await computeSiloedPublicInitializationNullifier(address);
537
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', publicNullifier);
538
+ initializationStatus = witness ? ContractInitializationStatus.INITIALIZED : ContractInitializationStatus.UNKNOWN;
539
+ }
540
+ const publiclyRegisteredContract = await publiclyRegisteredContractPromise;
541
+ const isContractUpdated =
542
+ publiclyRegisteredContract &&
543
+ !publiclyRegisteredContract.currentContractClassId.equals(publiclyRegisteredContract.originalContractClassId);
544
+ return {
545
+ instance: instance ?? undefined,
546
+ initializationStatus,
547
+ isContractPublished: !!publiclyRegisteredContract,
548
+ isContractUpdated: !!isContractUpdated,
549
+ updatedContractClassId: isContractUpdated ? publiclyRegisteredContract.currentContractClassId : undefined,
550
+ };
551
+ }
552
+
553
+ async getContractClassMetadata(id: Fr) {
554
+ const publiclyRegisteredContractClass = await this.aztecNode.getContractClass(id);
555
+ return {
556
+ isArtifactRegistered: !!(await this.pxe.getContractArtifact(id)),
557
+ isContractClassPubliclyRegistered: !!publiclyRegisteredContractClass,
558
+ };
559
+ }
342
560
  }
@@ -1 +1,7 @@
1
- export { BaseWallet, type FeeOptions } from './base_wallet.js';
1
+ export {
2
+ BaseWallet,
3
+ type CompleteFeeOptionsConfig,
4
+ type FeeOptions,
5
+ type SimulateViaEntrypointOptions,
6
+ } from './base_wallet.js';
7
+ export { simulateViaNode, buildMergedSimulationResult, extractOptimizablePublicStaticCalls } from './utils.js';