@aztec-labs/wallet-sdk 6.0.0-nightly.20260829

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 (94) hide show
  1. package/README.md +478 -0
  2. package/dest/base-wallet/base_wallet.d.ts +179 -0
  3. package/dest/base-wallet/base_wallet.d.ts.map +1 -0
  4. package/dest/base-wallet/base_wallet.js +503 -0
  5. package/dest/base-wallet/get_gas_limits.d.ts +36 -0
  6. package/dest/base-wallet/get_gas_limits.d.ts.map +1 -0
  7. package/dest/base-wallet/get_gas_limits.js +55 -0
  8. package/dest/base-wallet/index.d.ts +4 -0
  9. package/dest/base-wallet/index.d.ts.map +1 -0
  10. package/dest/base-wallet/index.js +3 -0
  11. package/dest/base-wallet/utils.d.ts +52 -0
  12. package/dest/base-wallet/utils.d.ts.map +1 -0
  13. package/dest/base-wallet/utils.js +137 -0
  14. package/dest/crypto.d.ts +230 -0
  15. package/dest/crypto.d.ts.map +1 -0
  16. package/dest/crypto.js +482 -0
  17. package/dest/emoji_alphabet.d.ts +35 -0
  18. package/dest/emoji_alphabet.d.ts.map +1 -0
  19. package/dest/emoji_alphabet.js +299 -0
  20. package/dest/extension/handlers/background_connection_handler.d.ts +168 -0
  21. package/dest/extension/handlers/background_connection_handler.d.ts.map +1 -0
  22. package/dest/extension/handlers/background_connection_handler.js +294 -0
  23. package/dest/extension/handlers/content_script_connection_handler.d.ts +57 -0
  24. package/dest/extension/handlers/content_script_connection_handler.d.ts.map +1 -0
  25. package/dest/extension/handlers/content_script_connection_handler.js +193 -0
  26. package/dest/extension/handlers/index.d.ts +12 -0
  27. package/dest/extension/handlers/index.d.ts.map +1 -0
  28. package/dest/extension/handlers/index.js +10 -0
  29. package/dest/extension/handlers/internal_message_types.d.ts +65 -0
  30. package/dest/extension/handlers/internal_message_types.d.ts.map +1 -0
  31. package/dest/extension/handlers/internal_message_types.js +24 -0
  32. package/dest/extension/provider/extension_provider.d.ts +107 -0
  33. package/dest/extension/provider/extension_provider.d.ts.map +1 -0
  34. package/dest/extension/provider/extension_provider.js +160 -0
  35. package/dest/extension/provider/extension_wallet.d.ts +152 -0
  36. package/dest/extension/provider/extension_wallet.d.ts.map +1 -0
  37. package/dest/extension/provider/extension_wallet.js +349 -0
  38. package/dest/extension/provider/index.d.ts +3 -0
  39. package/dest/extension/provider/index.d.ts.map +1 -0
  40. package/dest/extension/provider/index.js +2 -0
  41. package/dest/iframe/handlers/iframe_connection_handler.d.ts +122 -0
  42. package/dest/iframe/handlers/iframe_connection_handler.d.ts.map +1 -0
  43. package/dest/iframe/handlers/iframe_connection_handler.js +239 -0
  44. package/dest/iframe/handlers/index.d.ts +2 -0
  45. package/dest/iframe/handlers/index.d.ts.map +1 -0
  46. package/dest/iframe/handlers/index.js +1 -0
  47. package/dest/iframe/provider/iframe_discovery.d.ts +25 -0
  48. package/dest/iframe/provider/iframe_discovery.d.ts.map +1 -0
  49. package/dest/iframe/provider/iframe_discovery.js +167 -0
  50. package/dest/iframe/provider/iframe_provider.d.ts +65 -0
  51. package/dest/iframe/provider/iframe_provider.d.ts.map +1 -0
  52. package/dest/iframe/provider/iframe_provider.js +257 -0
  53. package/dest/iframe/provider/iframe_wallet.d.ts +85 -0
  54. package/dest/iframe/provider/iframe_wallet.d.ts.map +1 -0
  55. package/dest/iframe/provider/iframe_wallet.js +269 -0
  56. package/dest/iframe/provider/index.d.ts +4 -0
  57. package/dest/iframe/provider/index.d.ts.map +1 -0
  58. package/dest/iframe/provider/index.js +3 -0
  59. package/dest/manager/index.d.ts +3 -0
  60. package/dest/manager/index.d.ts.map +1 -0
  61. package/dest/manager/index.js +1 -0
  62. package/dest/manager/types.d.ts +168 -0
  63. package/dest/manager/types.d.ts.map +1 -0
  64. package/dest/manager/types.js +19 -0
  65. package/dest/manager/wallet_manager.d.ts +70 -0
  66. package/dest/manager/wallet_manager.d.ts.map +1 -0
  67. package/dest/manager/wallet_manager.js +256 -0
  68. package/dest/types.d.ts +185 -0
  69. package/dest/types.d.ts.map +1 -0
  70. package/dest/types.js +40 -0
  71. package/package.json +109 -0
  72. package/src/base-wallet/base_wallet.ts +665 -0
  73. package/src/base-wallet/get_gas_limits.ts +88 -0
  74. package/src/base-wallet/index.ts +8 -0
  75. package/src/base-wallet/utils.ts +248 -0
  76. package/src/crypto.ts +603 -0
  77. package/src/emoji_alphabet.ts +317 -0
  78. package/src/extension/handlers/background_connection_handler.ts +456 -0
  79. package/src/extension/handlers/content_script_connection_handler.ts +264 -0
  80. package/src/extension/handlers/index.ts +25 -0
  81. package/src/extension/handlers/internal_message_types.ts +71 -0
  82. package/src/extension/provider/extension_provider.ts +233 -0
  83. package/src/extension/provider/extension_wallet.ts +410 -0
  84. package/src/extension/provider/index.ts +7 -0
  85. package/src/iframe/handlers/iframe_connection_handler.ts +341 -0
  86. package/src/iframe/handlers/index.ts +7 -0
  87. package/src/iframe/provider/iframe_discovery.ts +185 -0
  88. package/src/iframe/provider/iframe_provider.ts +331 -0
  89. package/src/iframe/provider/iframe_wallet.ts +323 -0
  90. package/src/iframe/provider/index.ts +3 -0
  91. package/src/manager/index.ts +12 -0
  92. package/src/manager/types.ts +178 -0
  93. package/src/manager/wallet_manager.ts +291 -0
  94. package/src/types.ts +204 -0
@@ -0,0 +1,665 @@
1
+ import type { Account, NoFrom } from '@aztec-labs/aztec.js/account';
2
+ import { NO_FROM } from '@aztec-labs/aztec.js/account';
3
+ import type { CallIntent, IntentInnerHash } from '@aztec-labs/aztec.js/authorization';
4
+ import {
5
+ DefaultWaitOpts,
6
+ type InteractionWaitOptions,
7
+ NO_WAIT,
8
+ type SendReturn,
9
+ type WaitOpts,
10
+ extractOffchainOutput,
11
+ } from '@aztec-labs/aztec.js/contracts';
12
+ import type { FeePaymentMethod } from '@aztec-labs/aztec.js/fee';
13
+ import { waitForTx } from '@aztec-labs/aztec.js/node';
14
+ import {
15
+ type Aliased,
16
+ type AppCapabilities,
17
+ type BatchResults,
18
+ type BatchedMethod,
19
+ ContractInitializationStatus,
20
+ type ExecuteUtilityOptions,
21
+ type PrivateEvent,
22
+ type PrivateEventFilter,
23
+ type ProfileOptions,
24
+ type SendOptions,
25
+ type SimulateOptions,
26
+ TxSimulationResultWithAppOffset,
27
+ type Wallet,
28
+ type WalletCapabilities,
29
+ } from '@aztec-labs/aztec.js/wallet';
30
+ import { AccountFeePaymentMethodOptions, type DefaultAccountEntrypointOptions } from '@aztec-labs/entrypoints/account';
31
+ import { DefaultEntrypoint } from '@aztec-labs/entrypoints/default';
32
+ import type { ChainInfo } from '@aztec-labs/entrypoints/interfaces';
33
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
34
+ import { createLogger } from '@aztec-labs/foundation/log';
35
+ import type { FieldsOf } from '@aztec-labs/foundation/types';
36
+ import { displayDebugLogs } from '@aztec-labs/pxe/client/lazy';
37
+ import type { PXE, PackedPrivateEvent } from '@aztec-labs/pxe/server';
38
+ import {
39
+ type ContractArtifact,
40
+ type EventMetadataDefinition,
41
+ type FunctionCall,
42
+ decodeFromAbi,
43
+ } from '@aztec-labs/stdlib/abi';
44
+ import type { AuthWitness } from '@aztec-labs/stdlib/auth-witness';
45
+ import { AztecAddress } from '@aztec-labs/stdlib/aztec-address';
46
+ import { type ContractInstancePreimage, type NodeInfo, computePartialAddress } from '@aztec-labs/stdlib/contract';
47
+ import { SimulationError } from '@aztec-labs/stdlib/errors';
48
+ import { Gas, GasFees, GasSettings, ManaUsageEstimate } from '@aztec-labs/stdlib/gas';
49
+ import {
50
+ computeSiloedPrivateInitializationNullifier,
51
+ computeSiloedPublicInitializationNullifier,
52
+ } from '@aztec-labs/stdlib/hash';
53
+ import type { AztecNode } from '@aztec-labs/stdlib/interfaces/client';
54
+ import { type MasterSecretKeys, deriveKeys, deriveKeysFromMasterSecretKeys } from '@aztec-labs/stdlib/keys';
55
+ import {
56
+ BlockHeader,
57
+ ExecutionPayload,
58
+ type TxExecutionRequest,
59
+ type TxProfileResult,
60
+ type UtilityExecutionResult,
61
+ mergeExecutionPayloads,
62
+ } from '@aztec-labs/stdlib/tx';
63
+ import { inspect } from 'util';
64
+
65
+ import { assertGasLimitsWithinNetworkLimits } from './get_gas_limits.js';
66
+ import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simulateViaNode } from './utils.js';
67
+
68
+ /**
69
+ * Options to configure fee payment for a transaction
70
+ */
71
+ export type FeeOptions = {
72
+ /**
73
+ * A wallet-provided fallback fee payment method that is used only if the transaction that is being constructed
74
+ * doesn't already include one
75
+ */
76
+ walletFeePaymentMethod?: FeePaymentMethod;
77
+ /** Configuration options for the account to properly handle the selected fee payment method */
78
+ accountFeePaymentMethodOptions?: AccountFeePaymentMethodOptions;
79
+ /** The gas settings to use for the transaction */
80
+ gasSettings: GasSettings;
81
+ };
82
+
83
+ /** Options for `simulateViaEntrypoint`. */
84
+ export type SimulateViaEntrypointOptions = Pick<
85
+ SimulateOptions,
86
+ 'from' | 'additionalScopes' | 'skipTxValidation' | 'skipFeeEnforcement' | 'sendMessagesAs' | 'overrides'
87
+ > & {
88
+ /** Fee options for the entrypoint */
89
+ feeOptions: FeeOptions;
90
+ };
91
+
92
+ /** Options for `completeFeeOptions`. */
93
+ export type CompleteFeeOptionsConfig = {
94
+ /** The address where the transaction is being sent from. */
95
+ from: AztecAddress | NoFrom;
96
+ /** The address paying for fees (if any fee payment method is embedded in the execution payload). */
97
+ feePayer?: AztecAddress;
98
+ /** User-provided partial gas settings. */
99
+ gasSettings?: Partial<FieldsOf<GasSettings>>;
100
+ /** If true, returns gas settings with high gas limits for estimation. If false, uses fallback limits. */
101
+ forEstimation?: boolean;
102
+ /**
103
+ * Assumed network congestion level for fee prediction. Controls how aggressively the wallet
104
+ * estimates future fees. Defaults to Limit (worst case) when not specified.
105
+ */
106
+ congestionEstimate?: ManaUsageEstimate;
107
+ };
108
+
109
+ /**
110
+ * A base class for Wallet implementations
111
+ */
112
+ export abstract class BaseWallet implements Wallet {
113
+ protected minFeePadding = 0.5;
114
+ protected cancellableTransactions = false;
115
+ // Poll interval (in seconds) injected into sendTx waits when the caller does not specify one. Left undefined on
116
+ // production wallets so the DefaultWaitOpts 1s cadence stands; test wallets talking to in-process nodes lower it.
117
+ protected defaultWaitInterval?: number;
118
+ // A wallet is instantiated for a particular chain, so chain info never changes during its lifetime.
119
+ // We cache it here because getChainInfo is called frequently (every tx simulation, send, auth wit, etc.).
120
+ private nodeInfoPromise: Promise<NodeInfo> | undefined;
121
+
122
+ // Protected because we want to force wallets to instantiate their own PXE.
123
+ protected constructor(
124
+ protected readonly pxe: PXE,
125
+ protected readonly aztecNode: AztecNode,
126
+ protected log = createLogger('wallet-sdk:base_wallet'),
127
+ ) {}
128
+
129
+ protected scopesFrom(
130
+ from: AztecAddress | NoFrom,
131
+ additionalScopes: AztecAddress[],
132
+ sendMessagesAs: AztecAddress | undefined,
133
+ ): AztecAddress[] {
134
+ // The sendMessagesAs account must be in scope so that its tagging secrets can be accessed.
135
+ const tagSenderScopes = sendMessagesAs ? [sendMessagesAs] : [];
136
+ const baseScopes = from === NO_FROM ? [] : [from];
137
+ const allScopes = [...baseScopes, ...additionalScopes, ...tagSenderScopes];
138
+ const scopeSet = new Set(allScopes.map(address => address.toString()));
139
+ return [...scopeSet].map(AztecAddress.fromStringUnsafe);
140
+ }
141
+
142
+ /**
143
+ * Picks the sender address PXE should tag private messages with. Returns `undefined` when there is no signing
144
+ * account (`from === NO_FROM`) and no explicit override; in that case any private log emitted by the tx using
145
+ * the wallet-supplied default sender will fail the "Sender for tags is not set" assertion.
146
+ * @param from - Tx sender, or `NO_FROM`.
147
+ * @param sendMessagesAs - Explicit override.
148
+ */
149
+ protected senderForTagsFrom(from: AztecAddress | NoFrom, sendMessagesAs?: AztecAddress): AztecAddress | undefined {
150
+ return sendMessagesAs ?? (from === NO_FROM ? undefined : from);
151
+ }
152
+
153
+ protected abstract getAccountFromAddress(address: AztecAddress): Promise<Account>;
154
+
155
+ abstract getAccounts(): Promise<Aliased<AztecAddress>[]>;
156
+
157
+ /**
158
+ * Returns the list of aliased contacts associated with the wallet.
159
+ * This base implementation directly returns PXE's senders, but note that in general contacts are a superset of senders.
160
+ * - Senders: Addresses we check during synching in case they sent us notes,
161
+ * - Contacts: more general concept akin to a phone's contact list.
162
+ * @returns The aliased collection of AztecAddresses that form this wallet's address book
163
+ */
164
+ async getAddressBook(): Promise<Aliased<AztecAddress>[]> {
165
+ const sources = await this.pxe.getTaggingSecretSources({ kind: 'address-derived' });
166
+ return sources.map(source => ({ item: source.sender, alias: '' }));
167
+ }
168
+
169
+ /**
170
+ * Fetches and caches the node info for the wallet's lifetime, since a wallet talks to a single network and
171
+ * node info never changes. A rejected fetch clears the cache so the next call retries instead of replaying
172
+ * the cached rejection forever — important because the gas-limit fill-in and validation (run on every send)
173
+ * depend on it.
174
+ */
175
+ private getNodeInfo(): Promise<NodeInfo> {
176
+ if (!this.nodeInfoPromise) {
177
+ this.nodeInfoPromise = this.aztecNode.getNodeInfo().catch(err => {
178
+ this.nodeInfoPromise = undefined;
179
+ throw err;
180
+ });
181
+ }
182
+ return this.nodeInfoPromise;
183
+ }
184
+
185
+ async getChainInfo(): Promise<ChainInfo> {
186
+ const { l1ChainId, rollupVersion } = await this.getNodeInfo();
187
+ return { chainId: new Fr(l1ChainId), version: new Fr(rollupVersion) };
188
+ }
189
+
190
+ /**
191
+ * Returns the maximum gas limits a single transaction may declare on this wallet's network (the
192
+ * node-advertised `txsLimits.gas`). Internal helper used to fill in default gas limits when sending a
193
+ * transaction without explicit limits, and to validate caller-provided limits before sending. Backed by
194
+ * the cached node info, since a wallet talks to a single network.
195
+ */
196
+ protected async getMaxTxGasLimits(): Promise<Gas> {
197
+ const { txsLimits } = await this.getNodeInfo();
198
+ return new Gas(txsLimits.gas.daGas, txsLimits.gas.l2Gas);
199
+ }
200
+
201
+ protected async createTxExecutionRequestFromPayloadAndFee(
202
+ executionPayload: ExecutionPayload,
203
+ from: AztecAddress | NoFrom,
204
+ feeOptions: FeeOptions,
205
+ ): Promise<TxExecutionRequest> {
206
+ const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
207
+ const finalExecutionPayload = feeExecutionPayload
208
+ ? mergeExecutionPayloads([feeExecutionPayload, executionPayload])
209
+ : executionPayload;
210
+ const chainInfo = await this.getChainInfo();
211
+
212
+ if (from === NO_FROM) {
213
+ const entrypoint = new DefaultEntrypoint();
214
+ return entrypoint.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo);
215
+ } else {
216
+ const fromAccount = await this.getAccountFromAddress(from);
217
+ const executionOptions: DefaultAccountEntrypointOptions = {
218
+ txNonce: Fr.random(),
219
+ cancellable: this.cancellableTransactions,
220
+ // If from is an address, feeOptions include the way the account contract should handle the fee payment
221
+ feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions!,
222
+ };
223
+ return fromAccount.createTxExecutionRequest(
224
+ finalExecutionPayload,
225
+ feeOptions.gasSettings,
226
+ chainInfo,
227
+ executionOptions,
228
+ );
229
+ }
230
+ }
231
+
232
+ public async createAuthWit(
233
+ from: AztecAddress,
234
+ messageHashOrIntent: IntentInnerHash | CallIntent,
235
+ ): Promise<AuthWitness> {
236
+ const account = await this.getAccountFromAddress(from);
237
+ const chainInfo = await this.getChainInfo();
238
+ return account.createAuthWit(messageHashOrIntent, chainInfo);
239
+ }
240
+
241
+ /**
242
+ * Request capabilities from the wallet.
243
+ *
244
+ * This method is wallet-implementation-dependent and must be provided by classes extending BaseWallet.
245
+ * Embedded wallets typically don't support capability-based authorization (no user authorization flow),
246
+ * while external wallets (browser extensions, hardware wallets) implement this to reduce authorization
247
+ * friction by allowing apps to request permissions upfront.
248
+ *
249
+ * TODO: Consider making it abstract so implementing it is a conscious decision. Leaving it as-is
250
+ * while the feature stabilizes.
251
+ *
252
+ * @param _manifest - Application capability manifest declaring what operations the app needs
253
+ */
254
+ public requestCapabilities(_manifest: AppCapabilities): Promise<WalletCapabilities> {
255
+ throw new Error('Not implemented');
256
+ }
257
+
258
+ public async batch<const T extends readonly BatchedMethod[]>(methods: T): Promise<BatchResults<T>> {
259
+ const results: any[] = [];
260
+ for (const method of methods) {
261
+ const { name, args } = method;
262
+ // Type safety is guaranteed by the BatchedMethod type, which ensures that:
263
+ // 1. `name` is a valid batchable method name
264
+ // 2. `args` matches the parameter types of that specific method
265
+ // 3. The return type is correctly mapped in BatchResults<T>
266
+ // We use dynamic dispatch here for simplicity, but the types are enforced at the call site.
267
+
268
+ const fn = this[name] as (...args: any[]) => Promise<any>;
269
+ const result = await fn.apply(this, args);
270
+ // Wrap result with method name for discriminated union deserialization
271
+ results.push({ name, result });
272
+ }
273
+ return results as BatchResults<T>;
274
+ }
275
+
276
+ /**
277
+ * Completes partial user-provided fee options with wallet defaults.
278
+ * @param config - Fee completion config.
279
+ */
280
+ protected async completeFeeOptions(config: CompleteFeeOptionsConfig): Promise<FeeOptions> {
281
+ const { from, feePayer, gasSettings, forEstimation, congestionEstimate } = config;
282
+ const maxFeesPerGas =
283
+ gasSettings?.maxFeesPerGas ?? (await this.getMinFees(congestionEstimate)).mul(1 + this.minFeePadding);
284
+ let accountFeePaymentMethodOptions;
285
+ // If from is an address, we need to determine the appropriate fee payment method options for the
286
+ // account contract entrypoint to use
287
+ if (from !== NO_FROM) {
288
+ if (!feePayer) {
289
+ // The transaction does not include a fee payment method, so we set the flag
290
+ // for the account to use its fee juice balance
291
+ accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
292
+ } else {
293
+ // The transaction includes fee payment method, so we check if we are the fee payer for it
294
+ // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
295
+ accountFeePaymentMethodOptions = from.equals(feePayer)
296
+ ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM
297
+ : AccountFeePaymentMethodOptions.EXTERNAL;
298
+ }
299
+ }
300
+ const gasSettingsOverrides = {
301
+ gasLimits: gasSettings?.gasLimits ? Gas.from(gasSettings.gasLimits) : undefined,
302
+ teardownGasLimits: gasSettings?.teardownGasLimits ? Gas.from(gasSettings.teardownGasLimits) : undefined,
303
+ maxFeesPerGas,
304
+ maxPriorityFeesPerGas: gasSettings?.maxPriorityFeesPerGas ?? GasFees.empty(),
305
+ };
306
+ // When estimating gas (simulation), use high limits so the simulation doesn't run out of gas.
307
+ // When sending for real without explicit limits, declare the most a single tx may use on this network
308
+ // (the node's per-tx admission limit), so the proposer does not skip the tx for over-declaring gas.
309
+ let fullGasSettings;
310
+ if (forEstimation) {
311
+ // Estimation deliberately uses very high internal limits, which the node exempts from gas-limit
312
+ // admission during simulation, so we do not validate against the network admission limit here.
313
+ fullGasSettings = GasSettings.forEstimation(gasSettingsOverrides);
314
+ } else {
315
+ const maxTxGasLimits = await this.getMaxTxGasLimits();
316
+ // If the caller declared explicit gas limits, reject them up front when they exceed the network's
317
+ // per-tx admission limit (mirroring the node's MaxGasLimitsValidator). Otherwise fill in the limit.
318
+ if (gasSettingsOverrides.gasLimits) {
319
+ assertGasLimitsWithinNetworkLimits(gasSettingsOverrides.gasLimits, maxTxGasLimits);
320
+ }
321
+ fullGasSettings = GasSettings.fallback({
322
+ ...gasSettingsOverrides,
323
+ gasLimits: gasSettingsOverrides.gasLimits ?? maxTxGasLimits,
324
+ });
325
+ }
326
+ this.log.debug(`Using L2 gas settings`, fullGasSettings);
327
+ return {
328
+ gasSettings: fullGasSettings,
329
+ walletFeePaymentMethod: undefined,
330
+ accountFeePaymentMethodOptions,
331
+ };
332
+ }
333
+
334
+ /**
335
+ * Returns the worst-case min fee across predicted future slots.
336
+ * Falls back to getCurrentMinFees if the node doesn't support getPredictedMinFees.
337
+ * @param estimate - The mana usage estimate to use for fee prediction. Defaults to Limit for conservative estimation.
338
+ */
339
+ protected async getMinFees(estimate: ManaUsageEstimate = ManaUsageEstimate.Limit): Promise<GasFees> {
340
+ try {
341
+ const predicted = await this.aztecNode.getPredictedMinFees(estimate);
342
+ if (predicted.length === 0) {
343
+ return this.aztecNode.getCurrentMinFees();
344
+ }
345
+ return predicted.reduce((worst, fees) => (fees.feePerL2Gas > worst.feePerL2Gas ? fees : worst));
346
+ } catch (err: any) {
347
+ // Fallback for old nodes that don't support getPredictedMinFees.
348
+ // Only fall back on method-not-found errors (JSON-RPC code -32601); rethrow others.
349
+ if (err?.cause?.code === -32601 || err?.message?.includes('Method not found')) {
350
+ return this.aztecNode.getCurrentMinFees();
351
+ }
352
+ throw err;
353
+ }
354
+ }
355
+
356
+ async registerSender(address: AztecAddress, _alias: string = ''): Promise<AztecAddress> {
357
+ await this.pxe.registerTaggingSecretSource({ kind: 'address-derived', sender: address });
358
+ return address;
359
+ }
360
+
361
+ async registerContract(
362
+ instance: ContractInstancePreimage,
363
+ artifact?: ContractArtifact,
364
+ secretKeyOrKeys?: Fr | MasterSecretKeys,
365
+ ): Promise<void> {
366
+ // Classes and instances are registered independently: register the artifact (if provided) then the instance.
367
+ // Neither call validates that the artifact matches the class the instance runs, a missing artifact only surfaces
368
+ // when the contract is later simulated.
369
+ if (artifact) {
370
+ await this.pxe.registerContractClass(artifact);
371
+ }
372
+ const contractAddress = await this.pxe.registerContract(instance);
373
+
374
+ if (secretKeyOrKeys) {
375
+ // PXE never receives the account seed (from which the message-signing/fallback secret keys could be re-derived):
376
+ // the wallet derives the keys here. Of these, PXE only reads and stores the four privacy secret keys and the
377
+ // message-signing and fallback *public* keys — it never touches the message-signing or fallback secret keys.
378
+ //
379
+ // Since PXE recomputes the address from those keys, we assert it matches the instance's address: a mismatch means
380
+ // the provided keys don't correspond to this account.
381
+ const derivedKeys =
382
+ secretKeyOrKeys instanceof Fr
383
+ ? await deriveKeys(secretKeyOrKeys)
384
+ : await deriveKeysFromMasterSecretKeys(secretKeyOrKeys);
385
+ const { address } = await this.pxe.registerAccount(derivedKeys, await computePartialAddress(instance));
386
+ if (!address.equals(contractAddress)) {
387
+ throw new Error(
388
+ `Registered account address ${address.toString()} does not match contract instance address ${contractAddress.toString()}: the provided keys do not correspond to this account.`,
389
+ );
390
+ }
391
+ }
392
+ }
393
+
394
+ registerContractClass(artifact: ContractArtifact): Promise<void> {
395
+ return this.pxe.registerContractClass(artifact);
396
+ }
397
+
398
+ /**
399
+ * Simulates calls through the standard PXE path (account entrypoint).
400
+ * @param executionPayload - The execution payload to simulate.
401
+ * @param opts - Simulation options.
402
+ */
403
+ protected async simulateViaEntrypoint(executionPayload: ExecutionPayload, opts: SimulateViaEntrypointOptions) {
404
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(
405
+ executionPayload,
406
+ opts.from,
407
+ opts.feeOptions,
408
+ );
409
+ const result = await this.pxe.simulateTx(txRequest, {
410
+ simulatePublic: true,
411
+ skipTxValidation: opts.skipTxValidation,
412
+ skipFeeEnforcement: opts.skipFeeEnforcement,
413
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes ?? [], opts.sendMessagesAs),
414
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
415
+ overrides: opts.overrides,
416
+ });
417
+ const appCallOffset = await this.computeAppCallOffset(opts.from, opts.feeOptions);
418
+ return TxSimulationResultWithAppOffset.fromResultAndOffset(result, appCallOffset);
419
+ }
420
+
421
+ /**
422
+ * Computes the index where the app's calls begin in the flattened array of calls (0 = entrypoint/root, 1..N = fee
423
+ * calls, N+1 = app).
424
+ * @param from - The sender address, or NO_FROM for the default entrypoint.
425
+ * @param feeOptions - Fee options containing the wallet fee payment method.
426
+ */
427
+ protected async computeAppCallOffset(from: AztecAddress | NoFrom, feeOptions: FeeOptions): Promise<number> {
428
+ if (from === NO_FROM) {
429
+ return 0;
430
+ }
431
+ const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
432
+ return (feeExecutionPayload?.calls.length ?? 0) + 1; // +1 for entrypoint
433
+ }
434
+
435
+ /**
436
+ * Simulates a transaction, optimizing leading public static calls by running them directly
437
+ * on the node while sending the remaining calls through the standard PXE path.
438
+ * Return values from both paths are merged back in original call order.
439
+ * @param executionPayload - The execution payload to simulate.
440
+ * @param opts - Simulation options (from address, fee settings, etc.).
441
+ * @returns The merged simulation result.
442
+ */
443
+ async simulateTx(
444
+ executionPayload: ExecutionPayload,
445
+ opts: SimulateOptions,
446
+ ): Promise<TxSimulationResultWithAppOffset> {
447
+ const feeOptions = await this.completeFeeOptions({
448
+ from: opts.from,
449
+ feePayer: executionPayload.feePayer,
450
+ gasSettings: opts.fee?.gasSettings,
451
+ forEstimation: true,
452
+ congestionEstimate: opts.fee?.congestionEstimate,
453
+ });
454
+ const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
455
+ const remainingPayload = { ...executionPayload, calls: remainingCalls };
456
+
457
+ const chainInfo = await this.getChainInfo();
458
+ let blockHeader: BlockHeader;
459
+ // PXE might not be synced yet, so we pull the latest header from the node
460
+ // To keep things consistent, we'll always try with PXE first
461
+ try {
462
+ blockHeader = await this.pxe.getSyncedBlockHeader();
463
+ } catch {
464
+ blockHeader = (await this.aztecNode.getBlockData('latest'))!.header;
465
+ }
466
+
467
+ const simulationOrigin = opts.from === NO_FROM ? AztecAddress.ZERO : opts.from;
468
+ const [optimizedResults, normalResult] = await Promise.all([
469
+ optimizableCalls.length > 0
470
+ ? simulateViaNode(
471
+ this.aztecNode,
472
+ optimizableCalls,
473
+ simulationOrigin,
474
+ chainInfo,
475
+ feeOptions.gasSettings,
476
+ blockHeader,
477
+ opts.skipFeeEnforcement ?? true,
478
+ this.getContractName.bind(this),
479
+ opts.overrides,
480
+ )
481
+ : Promise.resolve([]),
482
+ remainingCalls.length > 0
483
+ ? this.simulateViaEntrypoint(remainingPayload, {
484
+ from: opts.from,
485
+ feeOptions,
486
+ additionalScopes: opts.additionalScopes,
487
+ skipTxValidation: opts.skipTxValidation,
488
+ skipFeeEnforcement: opts.skipFeeEnforcement ?? true,
489
+ sendMessagesAs: opts.sendMessagesAs,
490
+ overrides: opts.overrides,
491
+ })
492
+ : Promise.resolve(null),
493
+ ]);
494
+
495
+ return buildMergedSimulationResult(optimizedResults, normalResult);
496
+ }
497
+
498
+ async profileTx(executionPayload: ExecutionPayload, opts: ProfileOptions): Promise<TxProfileResult> {
499
+ const feeOptions = await this.completeFeeOptions({
500
+ from: opts.from,
501
+ feePayer: executionPayload.feePayer,
502
+ gasSettings: opts.fee?.gasSettings,
503
+ congestionEstimate: opts.fee?.congestionEstimate,
504
+ });
505
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
506
+ return this.pxe.profileTx(txRequest, {
507
+ profileMode: opts.profileMode,
508
+ skipProofGeneration: opts.skipProofGeneration ?? true,
509
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes ?? [], opts.sendMessagesAs),
510
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
511
+ });
512
+ }
513
+
514
+ public async sendTx<W extends InteractionWaitOptions = undefined>(
515
+ executionPayload: ExecutionPayload,
516
+ opts: SendOptions<W>,
517
+ ): Promise<SendReturn<W>> {
518
+ const feeOptions = await this.completeFeeOptions({
519
+ from: opts.from,
520
+ feePayer: executionPayload.feePayer,
521
+ gasSettings: opts.fee?.gasSettings,
522
+ congestionEstimate: opts.fee?.congestionEstimate,
523
+ });
524
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
525
+ const provenTx = await this.pxe.proveTx(txRequest, {
526
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes ?? [], opts.sendMessagesAs),
527
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
528
+ });
529
+ const offchainOutput = extractOffchainOutput(
530
+ provenTx.getOffchainEffects(),
531
+ provenTx.publicInputs.constants.anchorBlockHeader.globalVariables.timestamp,
532
+ );
533
+ const tx = await provenTx.toTx();
534
+ const txHash = tx.getTxHash();
535
+ this.log.debug(`Sending transaction ${txHash}`);
536
+ await this.aztecNode.sendTx(tx).catch(err => {
537
+ throw this.contextualizeError(err, inspect(tx));
538
+ });
539
+ this.log.info(`Sent transaction ${txHash}`);
540
+
541
+ // If wait is NO_WAIT, return txHash immediately
542
+ if (opts.wait === NO_WAIT) {
543
+ return { txHash, ...offchainOutput } as SendReturn<W>;
544
+ }
545
+
546
+ // Otherwise, wait for the full receipt (default behavior on wait: undefined)
547
+ const callerWaitOpts = typeof opts.wait === 'object' ? opts.wait : undefined;
548
+ const waitOpts: WaitOpts | undefined =
549
+ this.defaultWaitInterval !== undefined && callerWaitOpts?.interval === undefined
550
+ ? { ...callerWaitOpts, interval: this.defaultWaitInterval }
551
+ : callerWaitOpts;
552
+ // The tx was just sent, so an immediate first poll cannot find it mined; skip one poll interval up front.
553
+ const initialDelay = waitOpts?.initialDelay ?? waitOpts?.interval ?? DefaultWaitOpts.interval;
554
+ const receipt = await waitForTx(this.aztecNode, txHash, { ...waitOpts, initialDelay });
555
+
556
+ // Display debug logs from public execution if present (served in test mode only)
557
+ if (receipt.isMined() && receipt.debugLogs?.length) {
558
+ await displayDebugLogs(receipt.debugLogs, this.getContractName.bind(this));
559
+ }
560
+
561
+ return { receipt, ...offchainOutput } as SendReturn<W>;
562
+ }
563
+
564
+ /**
565
+ * Resolves a contract address to a human-readable name via PXE, if available.
566
+ * @param address - The contract address to resolve.
567
+ */
568
+ protected async getContractName(address: AztecAddress): Promise<string | undefined> {
569
+ const instance = await this.pxe.getContractInstance(address);
570
+ if (!instance) {
571
+ return undefined;
572
+ }
573
+ // Contract names are class-stable (an upgrade preserves the contract name), so the original class artifact is a
574
+ // sufficient source for the display name without resolving the current class against the node.
575
+ // TODO: if a contract were to be upgraded and its original artifact never registered, then this would fail and we'd
576
+ // want to fallback to the current class.
577
+ const artifact = await this.pxe.getContractArtifact(instance.originalContractClassId);
578
+ return artifact?.name;
579
+ }
580
+
581
+ protected contextualizeError(err: Error, ...context: string[]): Error {
582
+ let contextStr = '';
583
+ if (context.length > 0) {
584
+ contextStr = `\nContext:\n${context.join('\n')}`;
585
+ }
586
+ if (err instanceof SimulationError) {
587
+ err.setAztecContext(contextStr);
588
+ } else {
589
+ this.log.error(err.name, err);
590
+ this.log.debug(contextStr);
591
+ }
592
+ return err;
593
+ }
594
+
595
+ executeUtility(call: FunctionCall, opts: ExecuteUtilityOptions): Promise<UtilityExecutionResult> {
596
+ return this.pxe.executeUtility(call, { authwits: opts.authWitnesses, scopes: opts.scopes });
597
+ }
598
+
599
+ async getPrivateEvents<T>(
600
+ eventDef: EventMetadataDefinition,
601
+ eventFilter: PrivateEventFilter,
602
+ ): Promise<PrivateEvent<T>[]> {
603
+ const pxeEvents = await this.pxe.getPrivateEvents(eventDef.eventSelector, eventFilter);
604
+
605
+ const decodedEvents = pxeEvents.map((pxeEvent: PackedPrivateEvent): PrivateEvent<T> => {
606
+ return {
607
+ event: decodeFromAbi(eventDef.abiType, pxeEvent.packedEvent) as T,
608
+ metadata: {
609
+ l2BlockNumber: pxeEvent.l2BlockNumber,
610
+ l2BlockHash: pxeEvent.l2BlockHash,
611
+ txHash: pxeEvent.txHash,
612
+ },
613
+ };
614
+ });
615
+
616
+ return decodedEvents;
617
+ }
618
+
619
+ /**
620
+ * Returns metadata about a contract, including whether it has been initialized, published, and updated.
621
+ * @param address - The contract address to query.
622
+ */
623
+ async getContractMetadata(address: AztecAddress) {
624
+ const instance = await this.pxe.getContractInstance(address);
625
+ const publiclyRegisteredContractPromise = this.aztecNode.getContract(address);
626
+
627
+ let initializationStatus: ContractInitializationStatus;
628
+ if (instance) {
629
+ // We have the instance, so we can compute the private initialization nullifier (which includes init_hash and is
630
+ // emitted by both private and public initializers) and get a definitive INITIALIZED/UNINITIALIZED answer.
631
+ const initNullifier = await computeSiloedPrivateInitializationNullifier(address, instance.initializationHash);
632
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
633
+ initializationStatus = witness
634
+ ? ContractInitializationStatus.INITIALIZED
635
+ : ContractInitializationStatus.UNINITIALIZED;
636
+ } else {
637
+ // Without the instance we lack the init_hash needed for the private nullifier. We fall back to checking the
638
+ // public initialization nullifier (computed from address alone). Not all contracts emit it (only those with
639
+ // public functions that require initialization checks), so its absence doesn't mean the contract is
640
+ // uninitialized.
641
+ const publicNullifier = await computeSiloedPublicInitializationNullifier(address);
642
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', publicNullifier);
643
+ initializationStatus = witness ? ContractInitializationStatus.INITIALIZED : ContractInitializationStatus.UNKNOWN;
644
+ }
645
+ const publiclyRegisteredContract = await publiclyRegisteredContractPromise;
646
+ const isContractUpdated =
647
+ publiclyRegisteredContract &&
648
+ !publiclyRegisteredContract.currentContractClassId.equals(publiclyRegisteredContract.originalContractClassId);
649
+ return {
650
+ instance: instance ?? undefined,
651
+ initializationStatus,
652
+ isContractPublished: !!publiclyRegisteredContract,
653
+ isContractUpdated: !!isContractUpdated,
654
+ updatedContractClassId: isContractUpdated ? publiclyRegisteredContract.currentContractClassId : undefined,
655
+ };
656
+ }
657
+
658
+ async getContractClassMetadata(id: Fr) {
659
+ const publiclyRegisteredContractClass = await this.aztecNode.getContractClass(id);
660
+ return {
661
+ isArtifactRegistered: !!(await this.pxe.getContractArtifact(id)),
662
+ isContractClassPubliclyRegistered: !!publiclyRegisteredContractClass,
663
+ };
664
+ }
665
+ }