@aztec/wallet-sdk 0.0.1-commit.9ef841308 → 0.0.1-commit.a4600f49

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 +65 -35
  3. package/dest/base-wallet/base_wallet.d.ts.map +1 -1
  4. package/dest/base-wallet/base_wallet.js +187 -81
  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 +221 -108
  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,22 +21,17 @@ 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';
36
31
  import { Fr } from '@aztec/foundation/curves/bn254';
37
32
  import { createLogger } from '@aztec/foundation/log';
38
33
  import type { FieldsOf } from '@aztec/foundation/types';
39
- import { type AccessScopes, displayDebugLogs } from '@aztec/pxe/client/lazy';
34
+ import { displayDebugLogs } from '@aztec/pxe/client/lazy';
40
35
  import type { PXE, PackedPrivateEvent } from '@aztec/pxe/server';
41
36
  import {
42
37
  type ContractArtifact,
@@ -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: AccessScopes;
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(
@@ -113,7 +128,18 @@ export abstract class BaseWallet implements Wallet {
113
128
  protected scopesFrom(from: AztecAddress | NoFrom, additionalScopes: AztecAddress[] = []): AztecAddress[] {
114
129
  const allScopes = from === NO_FROM ? additionalScopes : [from, ...additionalScopes];
115
130
  const scopeSet = new Set(allScopes.map(address => address.toString()));
116
- 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);
117
143
  }
118
144
 
119
145
  protected abstract getAccountFromAddress(address: AztecAddress): Promise<Account>;
@@ -128,15 +154,42 @@ export abstract class BaseWallet implements Wallet {
128
154
  * @returns The aliased collection of AztecAddresses that form this wallet's address book
129
155
  */
130
156
  async getAddressBook(): Promise<Aliased<AztecAddress>[]> {
131
- const senders: AztecAddress[] = await this.pxe.getSenders();
132
- 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;
133
175
  }
134
176
 
135
177
  async getChainInfo(): Promise<ChainInfo> {
136
- const { l1ChainId, rollupVersion } = await this.aztecNode.getNodeInfo();
178
+ const { l1ChainId, rollupVersion } = await this.getNodeInfo();
137
179
  return { chainId: new Fr(l1ChainId), version: new Fr(rollupVersion) };
138
180
  }
139
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
+
140
193
  protected async createTxExecutionRequestFromPayloadAndFee(
141
194
  executionPayload: ExecutionPayload,
142
195
  from: AztecAddress | NoFrom,
@@ -214,18 +267,12 @@ export abstract class BaseWallet implements Wallet {
214
267
 
215
268
  /**
216
269
  * 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
270
+ * @param config - Fee completion config.
221
271
  */
222
- protected async completeFeeOptions(
223
- from: AztecAddress | NoFrom,
224
- feePayer?: AztecAddress,
225
- gasSettings?: Partial<FieldsOf<GasSettings>>,
226
- ): Promise<FeeOptions> {
272
+ protected async completeFeeOptions(config: CompleteFeeOptionsConfig): Promise<FeeOptions> {
273
+ const { from, feePayer, gasSettings, forEstimation, congestionEstimate } = config;
227
274
  const maxFeesPerGas =
228
- gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentMinFees()).mul(1 + this.minFeePadding);
275
+ gasSettings?.maxFeesPerGas ?? (await this.getMinFees(congestionEstimate)).mul(1 + this.minFeePadding);
229
276
  let accountFeePaymentMethodOptions;
230
277
  // If from is an address, we need to determine the appropriate fee payment method options for the
231
278
  // account contract entrypoint to use
@@ -242,7 +289,32 @@ export abstract class BaseWallet implements Wallet {
242
289
  : AccountFeePaymentMethodOptions.EXTERNAL;
243
290
  }
244
291
  }
245
- const fullGasSettings: GasSettings = GasSettings.default({ ...gasSettings, maxFeesPerGas });
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);
306
+ } else {
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
+ });
317
+ }
246
318
  this.log.debug(`Using L2 gas settings`, fullGasSettings);
247
319
  return {
248
320
  gasSettings: fullGasSettings,
@@ -252,76 +324,67 @@ export abstract class BaseWallet implements Wallet {
252
324
  }
253
325
 
254
326
  /**
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
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.
261
330
  */
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
- };
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
+ }
283
346
  }
284
347
 
285
- registerSender(address: AztecAddress, _alias: string = ''): Promise<AztecAddress> {
286
- 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;
287
351
  }
288
352
 
289
353
  async registerContract(
290
- instance: ContractInstanceWithAddress,
354
+ instance: ContractInstancePreimage,
291
355
  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
- }
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
+ );
317
382
  }
318
- await this.pxe.registerContract({ artifact, instance });
319
383
  }
384
+ }
320
385
 
321
- if (secretKey) {
322
- await this.pxe.registerAccount(secretKey, await computePartialAddress(instance));
323
- }
324
- return instance;
386
+ registerContractClass(artifact: ContractArtifact): Promise<void> {
387
+ return this.pxe.registerContractClass(artifact);
325
388
  }
326
389
 
327
390
  /**
@@ -335,12 +398,30 @@ export abstract class BaseWallet implements Wallet {
335
398
  opts.from,
336
399
  opts.feeOptions,
337
400
  );
338
- return this.pxe.simulateTx(txRequest, {
401
+ const result = await this.pxe.simulateTx(txRequest, {
339
402
  simulatePublic: true,
340
403
  skipTxValidation: opts.skipTxValidation,
341
404
  skipFeeEnforcement: opts.skipFeeEnforcement,
342
- scopes: opts.scopes,
405
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
406
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
407
+ overrides: opts.overrides,
343
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
344
425
  }
345
426
 
346
427
  /**
@@ -351,10 +432,17 @@ export abstract class BaseWallet implements Wallet {
351
432
  * @param opts - Simulation options (from address, fee settings, etc.).
352
433
  * @returns The merged simulation result.
353
434
  */
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);
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
+ });
358
446
  const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
359
447
  const remainingPayload = { ...executionPayload, calls: remainingCalls };
360
448
 
@@ -365,7 +453,7 @@ export abstract class BaseWallet implements Wallet {
365
453
  try {
366
454
  blockHeader = await this.pxe.getSyncedBlockHeader();
367
455
  } catch {
368
- blockHeader = (await this.aztecNode.getBlockHeader())!;
456
+ blockHeader = (await this.aztecNode.getBlockData('latest'))!.header;
369
457
  }
370
458
 
371
459
  const simulationOrigin = opts.from === NO_FROM ? AztecAddress.ZERO : opts.from;
@@ -380,15 +468,18 @@ export abstract class BaseWallet implements Wallet {
380
468
  blockHeader,
381
469
  opts.skipFeeEnforcement ?? true,
382
470
  this.getContractName.bind(this),
471
+ opts.overrides,
383
472
  )
384
473
  : Promise.resolve([]),
385
474
  remainingCalls.length > 0
386
475
  ? this.simulateViaEntrypoint(remainingPayload, {
387
476
  from: opts.from,
388
477
  feeOptions,
389
- scopes: this.scopesFrom(opts.from, opts.additionalScopes),
478
+ additionalScopes: opts.additionalScopes,
390
479
  skipTxValidation: opts.skipTxValidation,
391
480
  skipFeeEnforcement: opts.skipFeeEnforcement ?? true,
481
+ sendMessagesAs: opts.sendMessagesAs,
482
+ overrides: opts.overrides,
392
483
  })
393
484
  : Promise.resolve(null),
394
485
  ]);
@@ -397,12 +488,18 @@ export abstract class BaseWallet implements Wallet {
397
488
  }
398
489
 
399
490
  async profileTx(executionPayload: ExecutionPayload, opts: ProfileOptions): Promise<TxProfileResult> {
400
- 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
+ });
401
497
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
402
498
  return this.pxe.profileTx(txRequest, {
403
499
  profileMode: opts.profileMode,
404
500
  skipProofGeneration: opts.skipProofGeneration ?? true,
405
501
  scopes: this.scopesFrom(opts.from, opts.additionalScopes),
502
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
406
503
  });
407
504
  }
408
505
 
@@ -410,16 +507,24 @@ export abstract class BaseWallet implements Wallet {
410
507
  executionPayload: ExecutionPayload,
411
508
  opts: SendOptions<W>,
412
509
  ): Promise<SendReturn<W>> {
413
- 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
+ });
414
516
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
415
- 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
+ });
416
521
  const offchainOutput = extractOffchainOutput(
417
522
  provenTx.getOffchainEffects(),
418
523
  provenTx.publicInputs.constants.anchorBlockHeader.globalVariables.timestamp,
419
524
  );
420
525
  const tx = await provenTx.toTx();
421
526
  const txHash = tx.getTxHash();
422
- if (await this.aztecNode.getTxEffect(txHash)) {
527
+ if ((await this.aztecNode.getTxReceipt(txHash)).isMined()) {
423
528
  throw new Error(`A settled tx with equal hash ${txHash.toString()} exists.`);
424
529
  }
425
530
  this.log.debug(`Sending transaction ${txHash}`);
@@ -434,11 +539,15 @@ export abstract class BaseWallet implements Wallet {
434
539
  }
435
540
 
436
541
  // Otherwise, wait for the full receipt (default behavior on wait: undefined)
437
- 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;
438
547
  const receipt = await waitForTx(this.aztecNode, txHash, waitOpts);
439
548
 
440
549
  // Display debug logs from public execution if present (served in test mode only)
441
- if (receipt.debugLogs?.length) {
550
+ if (receipt.isMined() && receipt.debugLogs?.length) {
442
551
  await displayDebugLogs(receipt.debugLogs, this.getContractName.bind(this));
443
552
  }
444
553
 
@@ -454,7 +563,11 @@ export abstract class BaseWallet implements Wallet {
454
563
  if (!instance) {
455
564
  return undefined;
456
565
  }
457
- 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);
458
571
  return artifact?.name;
459
572
  }
460
573
 
@@ -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';