@aztec/wallet-sdk 0.0.1-commit.4d3c002 → 0.0.1-commit.4d9804df

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 (46) hide show
  1. package/README.md +125 -0
  2. package/dest/base-wallet/base_wallet.d.ts +66 -35
  3. package/dest/base-wallet/base_wallet.d.ts.map +1 -1
  4. package/dest/base-wallet/base_wallet.js +199 -85
  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/extension/handlers/background_connection_handler.d.ts +12 -2
  15. package/dest/extension/handlers/background_connection_handler.d.ts.map +1 -1
  16. package/dest/extension/handlers/background_connection_handler.js +44 -8
  17. package/dest/extension/handlers/content_script_connection_handler.d.ts +2 -1
  18. package/dest/extension/handlers/content_script_connection_handler.d.ts.map +1 -1
  19. package/dest/extension/handlers/content_script_connection_handler.js +19 -0
  20. package/dest/extension/handlers/internal_message_types.d.ts +3 -1
  21. package/dest/extension/handlers/internal_message_types.d.ts.map +1 -1
  22. package/dest/extension/handlers/internal_message_types.js +3 -1
  23. package/dest/extension/provider/extension_wallet.d.ts +26 -3
  24. package/dest/extension/provider/extension_wallet.d.ts.map +1 -1
  25. package/dest/extension/provider/extension_wallet.js +80 -9
  26. package/dest/iframe/handlers/iframe_connection_handler.d.ts +6 -2
  27. package/dest/iframe/handlers/iframe_connection_handler.d.ts.map +1 -1
  28. package/dest/iframe/handlers/iframe_connection_handler.js +18 -7
  29. package/dest/iframe/provider/iframe_wallet.d.ts +20 -3
  30. package/dest/iframe/provider/iframe_wallet.d.ts.map +1 -1
  31. package/dest/iframe/provider/iframe_wallet.js +79 -10
  32. package/dest/types.d.ts +52 -2
  33. package/dest/types.d.ts.map +1 -1
  34. package/dest/types.js +25 -0
  35. package/package.json +8 -8
  36. package/src/base-wallet/base_wallet.ts +230 -110
  37. package/src/base-wallet/get_gas_limits.ts +88 -0
  38. package/src/base-wallet/index.ts +7 -1
  39. package/src/base-wallet/utils.ts +15 -5
  40. package/src/extension/handlers/background_connection_handler.ts +42 -9
  41. package/src/extension/handlers/content_script_connection_handler.ts +18 -0
  42. package/src/extension/handlers/internal_message_types.ts +2 -0
  43. package/src/extension/provider/extension_wallet.ts +94 -8
  44. package/src/iframe/handlers/iframe_connection_handler.ts +21 -8
  45. package/src/iframe/provider/iframe_wallet.ts +103 -9
  46. package/src/types.ts +59 -0
@@ -21,15 +21,10 @@ import {
21
21
  type ProfileOptions,
22
22
  type SendOptions,
23
23
  type SimulateOptions,
24
+ TxSimulationResultWithAppOffset,
24
25
  type Wallet,
25
26
  type WalletCapabilities,
26
27
  } from '@aztec/aztec.js/wallet';
27
- import {
28
- GAS_ESTIMATION_DA_GAS_LIMIT,
29
- GAS_ESTIMATION_L2_GAS_LIMIT,
30
- GAS_ESTIMATION_TEARDOWN_DA_GAS_LIMIT,
31
- GAS_ESTIMATION_TEARDOWN_L2_GAS_LIMIT,
32
- } from '@aztec/constants';
33
28
  import { AccountFeePaymentMethodOptions, type DefaultAccountEntrypointOptions } from '@aztec/entrypoints/account';
34
29
  import { DefaultEntrypoint } from '@aztec/entrypoints/default';
35
30
  import type { ChainInfo } from '@aztec/entrypoints/interfaces';
@@ -46,29 +41,27 @@ import {
46
41
  } from '@aztec/stdlib/abi';
47
42
  import type { AuthWitness } from '@aztec/stdlib/auth-witness';
48
43
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
49
- import {
50
- type ContractInstanceWithAddress,
51
- computePartialAddress,
52
- getContractClassFromArtifact,
53
- } from '@aztec/stdlib/contract';
44
+ import { type ContractInstancePreimage, type NodeInfo, computePartialAddress } from '@aztec/stdlib/contract';
54
45
  import { SimulationError } from '@aztec/stdlib/errors';
55
- import { Gas, GasSettings } from '@aztec/stdlib/gas';
46
+ import { Gas, GasFees, GasSettings, ManaUsageEstimate } from '@aztec/stdlib/gas';
56
47
  import {
57
48
  computeSiloedPrivateInitializationNullifier,
58
49
  computeSiloedPublicInitializationNullifier,
59
50
  } from '@aztec/stdlib/hash';
60
51
  import type { AztecNode } from '@aztec/stdlib/interfaces/client';
52
+ import { type MasterSecretKeys, deriveKeys, deriveKeysFromMasterSecretKeys } from '@aztec/stdlib/keys';
61
53
  import {
62
54
  BlockHeader,
55
+ ExecutionPayload,
63
56
  type TxExecutionRequest,
64
57
  type TxProfileResult,
65
- TxSimulationResult,
66
58
  type UtilityExecutionResult,
59
+ mergeExecutionPayloads,
67
60
  } from '@aztec/stdlib/tx';
68
- import { ExecutionPayload, mergeExecutionPayloads } from '@aztec/stdlib/tx';
69
61
 
70
62
  import { inspect } from 'util';
71
63
 
64
+ import { assertGasLimitsWithinNetworkLimits } from './get_gas_limits.js';
72
65
  import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simulateViaNode } from './utils.js';
73
66
 
74
67
  /**
@@ -89,19 +82,41 @@ export type FeeOptions = {
89
82
  /** Options for `simulateViaEntrypoint`. */
90
83
  export type SimulateViaEntrypointOptions = Pick<
91
84
  SimulateOptions,
92
- 'from' | 'additionalScopes' | 'skipTxValidation' | 'skipFeeEnforcement'
85
+ 'from' | 'additionalScopes' | 'skipTxValidation' | 'skipFeeEnforcement' | 'sendMessagesAs' | 'overrides'
93
86
  > & {
94
87
  /** Fee options for the entrypoint */
95
88
  feeOptions: FeeOptions;
96
- /** Scopes to use for the simulation */
97
- scopes: AztecAddress[];
98
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
+
99
108
  /**
100
109
  * A base class for Wallet implementations
101
110
  */
102
111
  export abstract class BaseWallet implements Wallet {
103
112
  protected minFeePadding = 0.5;
104
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;
105
120
 
106
121
  // Protected because we want to force wallets to instantiate their own PXE.
107
122
  protected constructor(
@@ -110,10 +125,28 @@ export abstract class BaseWallet implements Wallet {
110
125
  protected log = createLogger('wallet-sdk:base_wallet'),
111
126
  ) {}
112
127
 
113
- protected scopesFrom(from: AztecAddress | NoFrom, additionalScopes: AztecAddress[] = []): AztecAddress[] {
114
- const allScopes = from === NO_FROM ? additionalScopes : [from, ...additionalScopes];
128
+ protected scopesFrom(
129
+ from: AztecAddress | NoFrom,
130
+ additionalScopes: AztecAddress[],
131
+ sendMessagesAs: AztecAddress | undefined,
132
+ ): AztecAddress[] {
133
+ // The sendMessagesAs account must be in scope so that its tagging secrets can be accessed.
134
+ const tagSenderScopes = sendMessagesAs ? [sendMessagesAs] : [];
135
+ const baseScopes = from === NO_FROM ? [] : [from];
136
+ const allScopes = [...baseScopes, ...additionalScopes, ...tagSenderScopes];
115
137
  const scopeSet = new Set(allScopes.map(address => address.toString()));
116
- return [...scopeSet].map(AztecAddress.fromString);
138
+ return [...scopeSet].map(AztecAddress.fromStringUnsafe);
139
+ }
140
+
141
+ /**
142
+ * Picks the sender address PXE should tag private messages with. Returns `undefined` when there is no signing
143
+ * account (`from === NO_FROM`) and no explicit override; in that case any private log emitted by the tx using
144
+ * the wallet-supplied default sender will fail the "Sender for tags is not set" assertion.
145
+ * @param from - Tx sender, or `NO_FROM`.
146
+ * @param sendMessagesAs - Explicit override.
147
+ */
148
+ protected senderForTagsFrom(from: AztecAddress | NoFrom, sendMessagesAs?: AztecAddress): AztecAddress | undefined {
149
+ return sendMessagesAs ?? (from === NO_FROM ? undefined : from);
117
150
  }
118
151
 
119
152
  protected abstract getAccountFromAddress(address: AztecAddress): Promise<Account>;
@@ -128,15 +161,42 @@ export abstract class BaseWallet implements Wallet {
128
161
  * @returns The aliased collection of AztecAddresses that form this wallet's address book
129
162
  */
130
163
  async getAddressBook(): Promise<Aliased<AztecAddress>[]> {
131
- const senders: AztecAddress[] = await this.pxe.getSenders();
132
- return senders.map(sender => ({ item: sender, alias: '' }));
164
+ const sources = await this.pxe.getTaggingSecretSources({ kind: 'address-derived' });
165
+ return sources.map(source => ({ item: source.sender, alias: '' }));
166
+ }
167
+
168
+ /**
169
+ * Fetches and caches the node info for the wallet's lifetime, since a wallet talks to a single network and
170
+ * node info never changes. A rejected fetch clears the cache so the next call retries instead of replaying
171
+ * the cached rejection forever — important because the gas-limit fill-in and validation (run on every send)
172
+ * depend on it.
173
+ */
174
+ private getNodeInfo(): Promise<NodeInfo> {
175
+ if (!this.nodeInfoPromise) {
176
+ this.nodeInfoPromise = this.aztecNode.getNodeInfo().catch(err => {
177
+ this.nodeInfoPromise = undefined;
178
+ throw err;
179
+ });
180
+ }
181
+ return this.nodeInfoPromise;
133
182
  }
134
183
 
135
184
  async getChainInfo(): Promise<ChainInfo> {
136
- const { l1ChainId, rollupVersion } = await this.aztecNode.getNodeInfo();
185
+ const { l1ChainId, rollupVersion } = await this.getNodeInfo();
137
186
  return { chainId: new Fr(l1ChainId), version: new Fr(rollupVersion) };
138
187
  }
139
188
 
189
+ /**
190
+ * Returns the maximum gas limits a single transaction may declare on this wallet's network (the
191
+ * node-advertised `txsLimits.gas`). Internal helper used to fill in default gas limits when sending a
192
+ * transaction without explicit limits, and to validate caller-provided limits before sending. Backed by
193
+ * the cached node info, since a wallet talks to a single network.
194
+ */
195
+ protected async getMaxTxGasLimits(): Promise<Gas> {
196
+ const { txsLimits } = await this.getNodeInfo();
197
+ return new Gas(txsLimits.gas.daGas, txsLimits.gas.l2Gas);
198
+ }
199
+
140
200
  protected async createTxExecutionRequestFromPayloadAndFee(
141
201
  executionPayload: ExecutionPayload,
142
202
  from: AztecAddress | NoFrom,
@@ -214,18 +274,12 @@ export abstract class BaseWallet implements Wallet {
214
274
 
215
275
  /**
216
276
  * Completes partial user-provided fee options with wallet defaults.
217
- * @param from - The address where the transaction is being sent from
218
- * @param feePayer - The address paying for fees (if any fee payment method is embedded in the execution payload)
219
- * @param gasSettings - User-provided partial gas settings
220
- * @returns - Complete fee options that can be used to create a transaction execution request
277
+ * @param config - Fee completion config.
221
278
  */
222
- protected async completeFeeOptions(
223
- from: AztecAddress | NoFrom,
224
- feePayer?: AztecAddress,
225
- gasSettings?: Partial<FieldsOf<GasSettings>>,
226
- ): Promise<FeeOptions> {
279
+ protected async completeFeeOptions(config: CompleteFeeOptionsConfig): Promise<FeeOptions> {
280
+ const { from, feePayer, gasSettings, forEstimation, congestionEstimate } = config;
227
281
  const maxFeesPerGas =
228
- gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentMinFees()).mul(1 + this.minFeePadding);
282
+ gasSettings?.maxFeesPerGas ?? (await this.getMinFees(congestionEstimate)).mul(1 + this.minFeePadding);
229
283
  let accountFeePaymentMethodOptions;
230
284
  // If from is an address, we need to determine the appropriate fee payment method options for the
231
285
  // account contract entrypoint to use
@@ -242,7 +296,32 @@ export abstract class BaseWallet implements Wallet {
242
296
  : AccountFeePaymentMethodOptions.EXTERNAL;
243
297
  }
244
298
  }
245
- const fullGasSettings: GasSettings = GasSettings.default({ ...gasSettings, maxFeesPerGas });
299
+ const gasSettingsOverrides = {
300
+ gasLimits: gasSettings?.gasLimits ? Gas.from(gasSettings.gasLimits) : undefined,
301
+ teardownGasLimits: gasSettings?.teardownGasLimits ? Gas.from(gasSettings.teardownGasLimits) : undefined,
302
+ maxFeesPerGas,
303
+ maxPriorityFeesPerGas: gasSettings?.maxPriorityFeesPerGas ?? GasFees.empty(),
304
+ };
305
+ // When estimating gas (simulation), use high limits so the simulation doesn't run out of gas.
306
+ // When sending for real without explicit limits, declare the most a single tx may use on this network
307
+ // (the node's per-tx admission limit), so the proposer does not skip the tx for over-declaring gas.
308
+ let fullGasSettings;
309
+ if (forEstimation) {
310
+ // Estimation deliberately uses very high internal limits and skips tx validation, so we do not
311
+ // validate against the network admission limit here.
312
+ fullGasSettings = GasSettings.forEstimation(gasSettingsOverrides);
313
+ } else {
314
+ const maxTxGasLimits = await this.getMaxTxGasLimits();
315
+ // If the caller declared explicit gas limits, reject them up front when they exceed the network's
316
+ // per-tx admission limit (mirroring the node's GasLimitsValidator). Otherwise fill in the limit.
317
+ if (gasSettingsOverrides.gasLimits) {
318
+ assertGasLimitsWithinNetworkLimits(gasSettingsOverrides.gasLimits, maxTxGasLimits);
319
+ }
320
+ fullGasSettings = GasSettings.fallback({
321
+ ...gasSettingsOverrides,
322
+ gasLimits: gasSettingsOverrides.gasLimits ?? maxTxGasLimits,
323
+ });
324
+ }
246
325
  this.log.debug(`Using L2 gas settings`, fullGasSettings);
247
326
  return {
248
327
  gasSettings: fullGasSettings,
@@ -252,76 +331,67 @@ export abstract class BaseWallet implements Wallet {
252
331
  }
253
332
 
254
333
  /**
255
- * Completes partial user-provided fee options with unreasonably high gas limits
256
- * for gas estimation. Uses the same logic as completeFeeOptions but sets high limits
257
- * to avoid running out of gas during estimation.
258
- * @param from - The address where the transaction is being sent from
259
- * @param feePayer - The address paying for fees (if any fee payment method is embedded in the execution payload)
260
- * @param gasSettings - User-provided partial gas settings
334
+ * Returns the worst-case min fee across predicted future slots.
335
+ * Falls back to getCurrentMinFees if the node doesn't support getPredictedMinFees.
336
+ * @param estimate - The mana usage estimate to use for fee prediction. Defaults to Limit for conservative estimation.
261
337
  */
262
- protected async completeFeeOptionsForEstimation(
263
- from: AztecAddress | NoFrom,
264
- feePayer?: AztecAddress,
265
- gasSettings?: Partial<FieldsOf<GasSettings>>,
266
- ) {
267
- const defaultFeeOptions = await this.completeFeeOptions(from, feePayer, gasSettings);
268
- const {
269
- gasSettings: { maxFeesPerGas, maxPriorityFeesPerGas },
270
- } = defaultFeeOptions;
271
- // Use unrealistically high gas limits for estimation to avoid running out of gas.
272
- // They will be tuned down after the simulation.
273
- const gasSettingsForEstimation = new GasSettings(
274
- new Gas(GAS_ESTIMATION_DA_GAS_LIMIT, GAS_ESTIMATION_L2_GAS_LIMIT),
275
- new Gas(GAS_ESTIMATION_TEARDOWN_DA_GAS_LIMIT, GAS_ESTIMATION_TEARDOWN_L2_GAS_LIMIT),
276
- maxFeesPerGas,
277
- maxPriorityFeesPerGas,
278
- );
279
- return {
280
- ...defaultFeeOptions,
281
- gasSettings: gasSettingsForEstimation,
282
- };
338
+ protected async getMinFees(estimate: ManaUsageEstimate = ManaUsageEstimate.Limit): Promise<GasFees> {
339
+ try {
340
+ const predicted = await this.aztecNode.getPredictedMinFees(estimate);
341
+ if (predicted.length === 0) {
342
+ return this.aztecNode.getCurrentMinFees();
343
+ }
344
+ return predicted.reduce((worst, fees) => (fees.feePerL2Gas > worst.feePerL2Gas ? fees : worst));
345
+ } catch (err: any) {
346
+ // Fallback for old nodes that don't support getPredictedMinFees.
347
+ // Only fall back on method-not-found errors (JSON-RPC code -32601); rethrow others.
348
+ if (err?.cause?.code === -32601 || err?.message?.includes('Method not found')) {
349
+ return this.aztecNode.getCurrentMinFees();
350
+ }
351
+ throw err;
352
+ }
283
353
  }
284
354
 
285
- registerSender(address: AztecAddress, _alias: string = ''): Promise<AztecAddress> {
286
- return this.pxe.registerSender(address);
355
+ async registerSender(address: AztecAddress, _alias: string = ''): Promise<AztecAddress> {
356
+ await this.pxe.registerTaggingSecretSource({ kind: 'address-derived', sender: address });
357
+ return address;
287
358
  }
288
359
 
289
360
  async registerContract(
290
- instance: ContractInstanceWithAddress,
361
+ instance: ContractInstancePreimage,
291
362
  artifact?: ContractArtifact,
292
- secretKey?: Fr,
293
- ): Promise<ContractInstanceWithAddress> {
294
- const existingInstance = await this.pxe.getContractInstance(instance.address);
295
-
296
- if (existingInstance) {
297
- // Instance already registered in the wallet
298
- if (artifact) {
299
- const thisContractClass = await getContractClassFromArtifact(artifact);
300
- if (!thisContractClass.id.equals(existingInstance.currentContractClassId)) {
301
- // wallet holds an outdated version of this contract
302
- await this.pxe.updateContract(instance.address, artifact);
303
- instance.currentContractClassId = thisContractClass.id;
304
- }
305
- }
306
- // If no artifact provided, we just use the existing registration
307
- } else {
308
- // Instance not registered yet
309
- if (!artifact) {
310
- // Try to get the artifact from the wallet's contract class storage
311
- artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
312
- if (!artifact) {
313
- throw new Error(
314
- `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()}`,
315
- );
316
- }
363
+ secretKeyOrKeys?: Fr | MasterSecretKeys,
364
+ ): Promise<void> {
365
+ // Classes and instances are registered independently: register the artifact (if provided) then the instance.
366
+ // Neither call validates that the artifact matches the class the instance runs, a missing artifact only surfaces
367
+ // when the contract is later simulated.
368
+ if (artifact) {
369
+ await this.pxe.registerContractClass(artifact);
370
+ }
371
+ const contractAddress = await this.pxe.registerContract(instance);
372
+
373
+ if (secretKeyOrKeys) {
374
+ // PXE never receives the account seed (from which the message-signing/fallback secret keys could be re-derived):
375
+ // the wallet derives the keys here. Of these, PXE only reads and stores the four privacy secret keys and the
376
+ // message-signing and fallback *public* keys — it never touches the message-signing or fallback secret keys.
377
+ //
378
+ // Since PXE recomputes the address from those keys, we assert it matches the instance's address: a mismatch means
379
+ // the provided keys don't correspond to this account.
380
+ const derivedKeys =
381
+ secretKeyOrKeys instanceof Fr
382
+ ? await deriveKeys(secretKeyOrKeys)
383
+ : await deriveKeysFromMasterSecretKeys(secretKeyOrKeys);
384
+ const { address } = await this.pxe.registerAccount(derivedKeys, await computePartialAddress(instance));
385
+ if (!address.equals(contractAddress)) {
386
+ throw new Error(
387
+ `Registered account address ${address.toString()} does not match contract instance address ${contractAddress.toString()}: the provided keys do not correspond to this account.`,
388
+ );
317
389
  }
318
- await this.pxe.registerContract({ artifact, instance });
319
390
  }
391
+ }
320
392
 
321
- if (secretKey) {
322
- await this.pxe.registerAccount(secretKey, await computePartialAddress(instance));
323
- }
324
- return instance;
393
+ registerContractClass(artifact: ContractArtifact): Promise<void> {
394
+ return this.pxe.registerContractClass(artifact);
325
395
  }
326
396
 
327
397
  /**
@@ -335,12 +405,30 @@ export abstract class BaseWallet implements Wallet {
335
405
  opts.from,
336
406
  opts.feeOptions,
337
407
  );
338
- return this.pxe.simulateTx(txRequest, {
408
+ const result = await this.pxe.simulateTx(txRequest, {
339
409
  simulatePublic: true,
340
410
  skipTxValidation: opts.skipTxValidation,
341
411
  skipFeeEnforcement: opts.skipFeeEnforcement,
342
- scopes: opts.scopes,
412
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes ?? [], opts.sendMessagesAs),
413
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
414
+ overrides: opts.overrides,
343
415
  });
416
+ const appCallOffset = await this.computeAppCallOffset(opts.from, opts.feeOptions);
417
+ return TxSimulationResultWithAppOffset.fromResultAndOffset(result, appCallOffset);
418
+ }
419
+
420
+ /**
421
+ * Computes the index where the app's calls begin in the flattened array of calls (0 = entrypoint/root, 1..N = fee
422
+ * calls, N+1 = app).
423
+ * @param from - The sender address, or NO_FROM for the default entrypoint.
424
+ * @param feeOptions - Fee options containing the wallet fee payment method.
425
+ */
426
+ protected async computeAppCallOffset(from: AztecAddress | NoFrom, feeOptions: FeeOptions): Promise<number> {
427
+ if (from === NO_FROM) {
428
+ return 0;
429
+ }
430
+ const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
431
+ return (feeExecutionPayload?.calls.length ?? 0) + 1; // +1 for entrypoint
344
432
  }
345
433
 
346
434
  /**
@@ -351,10 +439,17 @@ export abstract class BaseWallet implements Wallet {
351
439
  * @param opts - Simulation options (from address, fee settings, etc.).
352
440
  * @returns The merged simulation result.
353
441
  */
354
- async simulateTx(executionPayload: ExecutionPayload, opts: SimulateOptions): Promise<TxSimulationResult> {
355
- const feeOptions = opts.fee?.estimateGas
356
- ? await this.completeFeeOptionsForEstimation(opts.from, executionPayload.feePayer, opts.fee?.gasSettings)
357
- : await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
442
+ async simulateTx(
443
+ executionPayload: ExecutionPayload,
444
+ opts: SimulateOptions,
445
+ ): Promise<TxSimulationResultWithAppOffset> {
446
+ const feeOptions = await this.completeFeeOptions({
447
+ from: opts.from,
448
+ feePayer: executionPayload.feePayer,
449
+ gasSettings: opts.fee?.gasSettings,
450
+ forEstimation: true,
451
+ congestionEstimate: opts.fee?.congestionEstimate,
452
+ });
358
453
  const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
359
454
  const remainingPayload = { ...executionPayload, calls: remainingCalls };
360
455
 
@@ -365,7 +460,7 @@ export abstract class BaseWallet implements Wallet {
365
460
  try {
366
461
  blockHeader = await this.pxe.getSyncedBlockHeader();
367
462
  } catch {
368
- blockHeader = (await this.aztecNode.getBlockHeader())!;
463
+ blockHeader = (await this.aztecNode.getBlockData('latest'))!.header;
369
464
  }
370
465
 
371
466
  const simulationOrigin = opts.from === NO_FROM ? AztecAddress.ZERO : opts.from;
@@ -380,15 +475,18 @@ export abstract class BaseWallet implements Wallet {
380
475
  blockHeader,
381
476
  opts.skipFeeEnforcement ?? true,
382
477
  this.getContractName.bind(this),
478
+ opts.overrides,
383
479
  )
384
480
  : Promise.resolve([]),
385
481
  remainingCalls.length > 0
386
482
  ? this.simulateViaEntrypoint(remainingPayload, {
387
483
  from: opts.from,
388
484
  feeOptions,
389
- scopes: this.scopesFrom(opts.from, opts.additionalScopes),
485
+ additionalScopes: opts.additionalScopes,
390
486
  skipTxValidation: opts.skipTxValidation,
391
487
  skipFeeEnforcement: opts.skipFeeEnforcement ?? true,
488
+ sendMessagesAs: opts.sendMessagesAs,
489
+ overrides: opts.overrides,
392
490
  })
393
491
  : Promise.resolve(null),
394
492
  ]);
@@ -397,12 +495,18 @@ export abstract class BaseWallet implements Wallet {
397
495
  }
398
496
 
399
497
  async profileTx(executionPayload: ExecutionPayload, opts: ProfileOptions): Promise<TxProfileResult> {
400
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
498
+ const feeOptions = await this.completeFeeOptions({
499
+ from: opts.from,
500
+ feePayer: executionPayload.feePayer,
501
+ gasSettings: opts.fee?.gasSettings,
502
+ congestionEstimate: opts.fee?.congestionEstimate,
503
+ });
401
504
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
402
505
  return this.pxe.profileTx(txRequest, {
403
506
  profileMode: opts.profileMode,
404
507
  skipProofGeneration: opts.skipProofGeneration ?? true,
405
- scopes: this.scopesFrom(opts.from, opts.additionalScopes),
508
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes ?? [], opts.sendMessagesAs),
509
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
406
510
  });
407
511
  }
408
512
 
@@ -410,16 +514,24 @@ export abstract class BaseWallet implements Wallet {
410
514
  executionPayload: ExecutionPayload,
411
515
  opts: SendOptions<W>,
412
516
  ): Promise<SendReturn<W>> {
413
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
517
+ const feeOptions = await this.completeFeeOptions({
518
+ from: opts.from,
519
+ feePayer: executionPayload.feePayer,
520
+ gasSettings: opts.fee?.gasSettings,
521
+ congestionEstimate: opts.fee?.congestionEstimate,
522
+ });
414
523
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
415
- const provenTx = await this.pxe.proveTx(txRequest, this.scopesFrom(opts.from, opts.additionalScopes));
524
+ const provenTx = await this.pxe.proveTx(txRequest, {
525
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes ?? [], opts.sendMessagesAs),
526
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
527
+ });
416
528
  const offchainOutput = extractOffchainOutput(
417
529
  provenTx.getOffchainEffects(),
418
530
  provenTx.publicInputs.constants.anchorBlockHeader.globalVariables.timestamp,
419
531
  );
420
532
  const tx = await provenTx.toTx();
421
533
  const txHash = tx.getTxHash();
422
- if (await this.aztecNode.getTxEffect(txHash)) {
534
+ if ((await this.aztecNode.getTxReceipt(txHash)).isMined()) {
423
535
  throw new Error(`A settled tx with equal hash ${txHash.toString()} exists.`);
424
536
  }
425
537
  this.log.debug(`Sending transaction ${txHash}`);
@@ -434,11 +546,15 @@ export abstract class BaseWallet implements Wallet {
434
546
  }
435
547
 
436
548
  // Otherwise, wait for the full receipt (default behavior on wait: undefined)
437
- const waitOpts = typeof opts.wait === 'object' ? opts.wait : undefined;
549
+ const callerWaitOpts = typeof opts.wait === 'object' ? opts.wait : undefined;
550
+ const waitOpts =
551
+ this.defaultWaitInterval !== undefined && callerWaitOpts?.interval === undefined
552
+ ? { ...callerWaitOpts, interval: this.defaultWaitInterval }
553
+ : callerWaitOpts;
438
554
  const receipt = await waitForTx(this.aztecNode, txHash, waitOpts);
439
555
 
440
556
  // Display debug logs from public execution if present (served in test mode only)
441
- if (receipt.debugLogs?.length) {
557
+ if (receipt.isMined() && receipt.debugLogs?.length) {
442
558
  await displayDebugLogs(receipt.debugLogs, this.getContractName.bind(this));
443
559
  }
444
560
 
@@ -454,7 +570,11 @@ export abstract class BaseWallet implements Wallet {
454
570
  if (!instance) {
455
571
  return undefined;
456
572
  }
457
- const artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
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);
458
578
  return artifact?.name;
459
579
  }
460
580
 
@@ -0,0 +1,88 @@
1
+ import { MAX_PROCESSABLE_L2_GAS, MAX_TX_DA_GAS } from '@aztec/constants';
2
+ import { Gas, type GasUsed } from '@aztec/stdlib/gas';
3
+
4
+ /**
5
+ * Returns suggested total and teardown gas limits for a simulated tx, clamped to the network's per-tx
6
+ * admission limits.
7
+ *
8
+ * The network only admits transactions that declare up to `maxTxGasLimits` per dimension (the
9
+ * node-advertised `txsLimits.gas`). Wallets pass the value read from their own node info, but since node info
10
+ * is remote input it is defensively clamped here to the per-tx protocol maxima so a value above them is never
11
+ * honored. If the simulated usage already exceeds the resulting admission limits the tx can never be included,
12
+ * so this throws a descriptive error instead of returning a limit the node would reject. Otherwise it pads the
13
+ * usage and clamps each dimension to the admission limit.
14
+ * @param gasUsed - The gas actually consumed during simulation.
15
+ * @param maxTxGasLimits - The maximum gas a single tx may declare on this network (the node-advertised `txsLimits.gas`).
16
+ * @param pad - Fraction to pad the suggested gas limits by (as a decimal, e.g. 0.1 for 10%). The effective
17
+ * padding shrinks to zero as usage approaches the network limit, since the network will not admit a higher
18
+ * declared limit regardless of the buffer.
19
+ */
20
+ export function getGasLimits(
21
+ gasUsed: GasUsed,
22
+ maxTxGasLimits: Gas,
23
+ pad = 0.1,
24
+ ): {
25
+ /**
26
+ * Gas limit for the tx, excluding teardown gas
27
+ */
28
+ gasLimits: Gas;
29
+ /**
30
+ * Gas limit for the teardown phase
31
+ */
32
+ teardownGasLimits: Gas;
33
+ } {
34
+ const { totalGas, teardownGas } = gasUsed;
35
+
36
+ // `maxTxGasLimits` is the node-advertised admission limit. Node info is remote input, so we defensively
37
+ // clamp to the per-tx protocol maxima so a value above them can never be honored.
38
+ const maxLimits = new Gas(
39
+ Math.min(maxTxGasLimits.daGas, MAX_TX_DA_GAS),
40
+ Math.min(maxTxGasLimits.l2Gas, MAX_PROCESSABLE_L2_GAS),
41
+ );
42
+
43
+ // The simulated usage must fit within the admission limits, otherwise the tx can never be included.
44
+ if (totalGas.daGas > maxLimits.daGas) {
45
+ throw new Error(
46
+ `Transaction consumes ${totalGas.daGas} DA gas but the network only admits transactions declaring up to ${maxLimits.daGas} DA gas`,
47
+ );
48
+ }
49
+ if (totalGas.l2Gas > maxLimits.l2Gas) {
50
+ throw new Error(
51
+ `Transaction consumes ${totalGas.l2Gas} L2 gas but the network only admits transactions declaring up to ${maxLimits.l2Gas} L2 gas`,
52
+ );
53
+ }
54
+
55
+ // Pad the limits by the buffer, then cap each dimension at the admission limit so the buffer cannot push a
56
+ // declared limit past what inbound validation accepts. Teardown is part of the total, so clamping it to the
57
+ // admission limit is safe.
58
+ return {
59
+ gasLimits: padGas(totalGas, pad, maxLimits),
60
+ teardownGasLimits: padGas(teardownGas, pad, maxLimits),
61
+ };
62
+ }
63
+
64
+ /** Pads each gas dimension, capping it at the network admission limit. */
65
+ function padGas(gas: Gas, pad: number, cap: Gas): Gas {
66
+ const padded = gas.mul(1 + pad);
67
+ return new Gas(Math.min(padded.daGas, cap.daGas), Math.min(padded.l2Gas, cap.l2Gas));
68
+ }
69
+
70
+ /**
71
+ * Validates that caller-declared gas limits do not exceed the network's per-tx admission limits, throwing a
72
+ * descriptive error per dimension when they do. The node's inbound validation checks declared
73
+ * `gasSettings.gasLimits`, so we mirror that here to surface the rejection locally before the tx is sent.
74
+ * @param gasLimits - The gas limits the transaction will declare.
75
+ * @param maxTxGasLimits - The maximum gas a single tx may declare on this network (the node-advertised `txsLimits.gas`).
76
+ */
77
+ export function assertGasLimitsWithinNetworkLimits(gasLimits: Gas, maxTxGasLimits: Gas): void {
78
+ if (gasLimits.daGas > maxTxGasLimits.daGas) {
79
+ throw new Error(
80
+ `Declared DA gas limit (${gasLimits.daGas}) exceeds the maximum this network allows per tx (${maxTxGasLimits.daGas})`,
81
+ );
82
+ }
83
+ if (gasLimits.l2Gas > maxTxGasLimits.l2Gas) {
84
+ throw new Error(
85
+ `Declared L2 gas limit (${gasLimits.l2Gas}) exceeds the maximum this network allows per tx (${maxTxGasLimits.l2Gas})`,
86
+ );
87
+ }
88
+ }
@@ -1,2 +1,8 @@
1
- export { BaseWallet, type FeeOptions, type SimulateViaEntrypointOptions } from './base_wallet.js';
1
+ export {
2
+ BaseWallet,
3
+ type CompleteFeeOptionsConfig,
4
+ type FeeOptions,
5
+ type SimulateViaEntrypointOptions,
6
+ } from './base_wallet.js';
2
7
  export { simulateViaNode, buildMergedSimulationResult, extractOptimizablePublicStaticCalls } from './utils.js';
8
+ export { getGasLimits, assertGasLimitsWithinNetworkLimits } from './get_gas_limits.js';