@aztec/wallet-sdk 0.0.1-commit.b6e433891 → 0.0.1-commit.b8a057fa

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