@aztec/wallet-sdk 0.0.1-commit.a89ec08 → 0.0.1-commit.aa0c64f

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 +44 -9
  3. package/dest/base-wallet/base_wallet.d.ts.map +1 -1
  4. package/dest/base-wallet/base_wallet.js +157 -60
  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 +2 -1
  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 +5 -3
  12. package/dest/base-wallet/utils.d.ts.map +1 -1
  13. package/dest/base-wallet/utils.js +8 -4
  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 +169 -64
  37. package/src/base-wallet/get_gas_limits.ts +88 -0
  38. package/src/base-wallet/index.ts +1 -0
  39. package/src/base-wallet/utils.ts +9 -1
  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
@@ -41,29 +41,27 @@ import {
41
41
  } from '@aztec/stdlib/abi';
42
42
  import type { AuthWitness } from '@aztec/stdlib/auth-witness';
43
43
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
44
- import {
45
- type ContractInstanceWithAddress,
46
- type NodeInfo,
47
- computePartialAddress,
48
- getContractClassFromArtifact,
49
- } from '@aztec/stdlib/contract';
44
+ import { type ContractInstancePreimage, type NodeInfo, computePartialAddress } from '@aztec/stdlib/contract';
50
45
  import { SimulationError } from '@aztec/stdlib/errors';
51
- import { Gas, GasFees, GasSettings } from '@aztec/stdlib/gas';
46
+ import { Gas, GasFees, GasSettings, ManaUsageEstimate } from '@aztec/stdlib/gas';
52
47
  import {
53
48
  computeSiloedPrivateInitializationNullifier,
54
49
  computeSiloedPublicInitializationNullifier,
55
50
  } from '@aztec/stdlib/hash';
56
51
  import type { AztecNode } from '@aztec/stdlib/interfaces/client';
52
+ import { type MasterSecretKeys, deriveKeys, deriveKeysFromMasterSecretKeys } from '@aztec/stdlib/keys';
57
53
  import {
58
54
  BlockHeader,
55
+ ExecutionPayload,
59
56
  type TxExecutionRequest,
60
57
  type TxProfileResult,
61
58
  type UtilityExecutionResult,
59
+ mergeExecutionPayloads,
62
60
  } from '@aztec/stdlib/tx';
63
- import { ExecutionPayload, mergeExecutionPayloads } from '@aztec/stdlib/tx';
64
61
 
65
62
  import { inspect } from 'util';
66
63
 
64
+ import { assertGasLimitsWithinNetworkLimits } from './get_gas_limits.js';
67
65
  import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simulateViaNode } from './utils.js';
68
66
 
69
67
  /**
@@ -84,7 +82,7 @@ export type FeeOptions = {
84
82
  /** Options for `simulateViaEntrypoint`. */
85
83
  export type SimulateViaEntrypointOptions = Pick<
86
84
  SimulateOptions,
87
- 'from' | 'additionalScopes' | 'skipTxValidation' | 'skipFeeEnforcement'
85
+ 'from' | 'additionalScopes' | 'skipTxValidation' | 'skipFeeEnforcement' | 'sendMessagesAs' | 'overrides'
88
86
  > & {
89
87
  /** Fee options for the entrypoint */
90
88
  feeOptions: FeeOptions;
@@ -100,6 +98,11 @@ export type CompleteFeeOptionsConfig = {
100
98
  gasSettings?: Partial<FieldsOf<GasSettings>>;
101
99
  /** If true, returns gas settings with high gas limits for estimation. If false, uses fallback limits. */
102
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;
103
106
  };
104
107
 
105
108
  /**
@@ -108,6 +111,9 @@ export type CompleteFeeOptionsConfig = {
108
111
  export abstract class BaseWallet implements Wallet {
109
112
  protected minFeePadding = 0.5;
110
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;
111
117
  // A wallet is instantiated for a particular chain, so chain info never changes during its lifetime.
112
118
  // We cache it here because getChainInfo is called frequently (every tx simulation, send, auth wit, etc.).
113
119
  private nodeInfoPromise: Promise<NodeInfo> | undefined;
@@ -119,10 +125,28 @@ export abstract class BaseWallet implements Wallet {
119
125
  protected log = createLogger('wallet-sdk:base_wallet'),
120
126
  ) {}
121
127
 
122
- protected scopesFrom(from: AztecAddress | NoFrom, additionalScopes: AztecAddress[] = []): AztecAddress[] {
123
- 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];
124
137
  const scopeSet = new Set(allScopes.map(address => address.toString()));
125
- 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);
126
150
  }
127
151
 
128
152
  protected abstract getAccountFromAddress(address: AztecAddress): Promise<Account>;
@@ -137,18 +161,42 @@ export abstract class BaseWallet implements Wallet {
137
161
  * @returns The aliased collection of AztecAddresses that form this wallet's address book
138
162
  */
139
163
  async getAddressBook(): Promise<Aliased<AztecAddress>[]> {
140
- const senders: AztecAddress[] = await this.pxe.getSenders();
141
- 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: '' }));
142
166
  }
143
167
 
144
- async getChainInfo(): Promise<ChainInfo> {
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> {
145
175
  if (!this.nodeInfoPromise) {
146
- this.nodeInfoPromise = this.aztecNode.getNodeInfo();
176
+ this.nodeInfoPromise = this.aztecNode.getNodeInfo().catch(err => {
177
+ this.nodeInfoPromise = undefined;
178
+ throw err;
179
+ });
147
180
  }
148
- const { l1ChainId, rollupVersion } = await this.nodeInfoPromise;
181
+ return this.nodeInfoPromise;
182
+ }
183
+
184
+ async getChainInfo(): Promise<ChainInfo> {
185
+ const { l1ChainId, rollupVersion } = await this.getNodeInfo();
149
186
  return { chainId: new Fr(l1ChainId), version: new Fr(rollupVersion) };
150
187
  }
151
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
+
152
200
  protected async createTxExecutionRequestFromPayloadAndFee(
153
201
  executionPayload: ExecutionPayload,
154
202
  from: AztecAddress | NoFrom,
@@ -229,9 +277,9 @@ export abstract class BaseWallet implements Wallet {
229
277
  * @param config - Fee completion config.
230
278
  */
231
279
  protected async completeFeeOptions(config: CompleteFeeOptionsConfig): Promise<FeeOptions> {
232
- const { from, feePayer, gasSettings, forEstimation } = config;
280
+ const { from, feePayer, gasSettings, forEstimation, congestionEstimate } = config;
233
281
  const maxFeesPerGas =
234
- gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentMinFees()).mul(1 + this.minFeePadding);
282
+ gasSettings?.maxFeesPerGas ?? (await this.getMinFees(congestionEstimate)).mul(1 + this.minFeePadding);
235
283
  let accountFeePaymentMethodOptions;
236
284
  // If from is an address, we need to determine the appropriate fee payment method options for the
237
285
  // account contract entrypoint to use
@@ -255,10 +303,25 @@ export abstract class BaseWallet implements Wallet {
255
303
  maxPriorityFeesPerGas: gasSettings?.maxPriorityFeesPerGas ?? GasFees.empty(),
256
304
  };
257
305
  // When estimating gas (simulation), use high limits so the simulation doesn't run out of gas.
258
- // When sending for real, use protocol max limits that the network will actually accept.
259
- const fullGasSettings = forEstimation
260
- ? GasSettings.forEstimation(gasSettingsOverrides)
261
- : GasSettings.fallback(gasSettingsOverrides);
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
+ }
262
325
  this.log.debug(`Using L2 gas settings`, fullGasSettings);
263
326
  return {
264
327
  gasSettings: fullGasSettings,
@@ -267,46 +330,68 @@ export abstract class BaseWallet implements Wallet {
267
330
  };
268
331
  }
269
332
 
270
- registerSender(address: AztecAddress, _alias: string = ''): Promise<AztecAddress> {
271
- return this.pxe.registerSender(address);
333
+ /**
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.
337
+ */
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
+ }
353
+ }
354
+
355
+ async registerSender(address: AztecAddress, _alias: string = ''): Promise<AztecAddress> {
356
+ await this.pxe.registerTaggingSecretSource({ kind: 'address-derived', sender: address });
357
+ return address;
272
358
  }
273
359
 
274
360
  async registerContract(
275
- instance: ContractInstanceWithAddress,
361
+ instance: ContractInstancePreimage,
276
362
  artifact?: ContractArtifact,
277
- secretKey?: Fr,
278
- ): Promise<ContractInstanceWithAddress> {
279
- const existingInstance = await this.pxe.getContractInstance(instance.address);
280
-
281
- if (existingInstance) {
282
- // Instance already registered in the wallet
283
- if (artifact) {
284
- const thisContractClass = await getContractClassFromArtifact(artifact);
285
- if (!thisContractClass.id.equals(existingInstance.currentContractClassId)) {
286
- // wallet holds an outdated version of this contract
287
- await this.pxe.updateContract(instance.address, artifact);
288
- instance.currentContractClassId = thisContractClass.id;
289
- }
290
- }
291
- // If no artifact provided, we just use the existing registration
292
- } else {
293
- // Instance not registered yet
294
- if (!artifact) {
295
- // Try to get the artifact from the wallet's contract class storage
296
- artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
297
- if (!artifact) {
298
- throw new Error(
299
- `Cannot register contract at ${instance.address.toString()}: artifact is required but not provided, and wallet does not have the artifact for contract class ${instance.currentContractClassId.toString()}`,
300
- );
301
- }
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
+ );
302
389
  }
303
- await this.pxe.registerContract({ artifact, instance });
304
390
  }
391
+ }
305
392
 
306
- if (secretKey) {
307
- await this.pxe.registerAccount(secretKey, await computePartialAddress(instance));
308
- }
309
- return instance;
393
+ registerContractClass(artifact: ContractArtifact): Promise<void> {
394
+ return this.pxe.registerContractClass(artifact);
310
395
  }
311
396
 
312
397
  /**
@@ -324,7 +409,9 @@ export abstract class BaseWallet implements Wallet {
324
409
  simulatePublic: true,
325
410
  skipTxValidation: opts.skipTxValidation,
326
411
  skipFeeEnforcement: opts.skipFeeEnforcement,
327
- scopes: this.scopesFrom(opts.from, opts.additionalScopes),
412
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes ?? [], opts.sendMessagesAs),
413
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
414
+ overrides: opts.overrides,
328
415
  });
329
416
  const appCallOffset = await this.computeAppCallOffset(opts.from, opts.feeOptions);
330
417
  return TxSimulationResultWithAppOffset.fromResultAndOffset(result, appCallOffset);
@@ -361,6 +448,7 @@ export abstract class BaseWallet implements Wallet {
361
448
  feePayer: executionPayload.feePayer,
362
449
  gasSettings: opts.fee?.gasSettings,
363
450
  forEstimation: true,
451
+ congestionEstimate: opts.fee?.congestionEstimate,
364
452
  });
365
453
  const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
366
454
  const remainingPayload = { ...executionPayload, calls: remainingCalls };
@@ -372,7 +460,7 @@ export abstract class BaseWallet implements Wallet {
372
460
  try {
373
461
  blockHeader = await this.pxe.getSyncedBlockHeader();
374
462
  } catch {
375
- blockHeader = (await this.aztecNode.getBlockHeader())!;
463
+ blockHeader = (await this.aztecNode.getBlockData('latest'))!.header;
376
464
  }
377
465
 
378
466
  const simulationOrigin = opts.from === NO_FROM ? AztecAddress.ZERO : opts.from;
@@ -387,6 +475,7 @@ export abstract class BaseWallet implements Wallet {
387
475
  blockHeader,
388
476
  opts.skipFeeEnforcement ?? true,
389
477
  this.getContractName.bind(this),
478
+ opts.overrides,
390
479
  )
391
480
  : Promise.resolve([]),
392
481
  remainingCalls.length > 0
@@ -396,6 +485,8 @@ export abstract class BaseWallet implements Wallet {
396
485
  additionalScopes: opts.additionalScopes,
397
486
  skipTxValidation: opts.skipTxValidation,
398
487
  skipFeeEnforcement: opts.skipFeeEnforcement ?? true,
488
+ sendMessagesAs: opts.sendMessagesAs,
489
+ overrides: opts.overrides,
399
490
  })
400
491
  : Promise.resolve(null),
401
492
  ]);
@@ -408,12 +499,14 @@ export abstract class BaseWallet implements Wallet {
408
499
  from: opts.from,
409
500
  feePayer: executionPayload.feePayer,
410
501
  gasSettings: opts.fee?.gasSettings,
502
+ congestionEstimate: opts.fee?.congestionEstimate,
411
503
  });
412
504
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
413
505
  return this.pxe.profileTx(txRequest, {
414
506
  profileMode: opts.profileMode,
415
507
  skipProofGeneration: opts.skipProofGeneration ?? true,
416
- 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),
417
510
  });
418
511
  }
419
512
 
@@ -425,16 +518,20 @@ export abstract class BaseWallet implements Wallet {
425
518
  from: opts.from,
426
519
  feePayer: executionPayload.feePayer,
427
520
  gasSettings: opts.fee?.gasSettings,
521
+ congestionEstimate: opts.fee?.congestionEstimate,
428
522
  });
429
523
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
430
- 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
+ });
431
528
  const offchainOutput = extractOffchainOutput(
432
529
  provenTx.getOffchainEffects(),
433
530
  provenTx.publicInputs.constants.anchorBlockHeader.globalVariables.timestamp,
434
531
  );
435
532
  const tx = await provenTx.toTx();
436
533
  const txHash = tx.getTxHash();
437
- if (await this.aztecNode.getTxEffect(txHash)) {
534
+ if ((await this.aztecNode.getTxReceipt(txHash)).isMined()) {
438
535
  throw new Error(`A settled tx with equal hash ${txHash.toString()} exists.`);
439
536
  }
440
537
  this.log.debug(`Sending transaction ${txHash}`);
@@ -449,11 +546,15 @@ export abstract class BaseWallet implements Wallet {
449
546
  }
450
547
 
451
548
  // Otherwise, wait for the full receipt (default behavior on wait: undefined)
452
- 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;
453
554
  const receipt = await waitForTx(this.aztecNode, txHash, waitOpts);
454
555
 
455
556
  // Display debug logs from public execution if present (served in test mode only)
456
- if (receipt.debugLogs?.length) {
557
+ if (receipt.isMined() && receipt.debugLogs?.length) {
457
558
  await displayDebugLogs(receipt.debugLogs, this.getContractName.bind(this));
458
559
  }
459
560
 
@@ -469,7 +570,11 @@ export abstract class BaseWallet implements Wallet {
469
570
  if (!instance) {
470
571
  return undefined;
471
572
  }
472
- 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);
473
578
  return artifact?.name;
474
579
  }
475
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
+ }
@@ -5,3 +5,4 @@ export {
5
5
  type SimulateViaEntrypointOptions,
6
6
  } from './base_wallet.js';
7
7
  export { simulateViaNode, buildMergedSimulationResult, extractOptimizablePublicStaticCalls } from './utils.js';
8
+ export { getGasLimits, assertGasLimitsWithinNetworkLimits } from './get_gas_limits.js';
@@ -25,6 +25,7 @@ import {
25
25
  PrivateCallExecutionResult,
26
26
  PrivateExecutionResult,
27
27
  PublicSimulationOutput,
28
+ type SimulationOverrides,
28
29
  Tx,
29
30
  TxContext,
30
31
  TxSimulationResult,
@@ -65,6 +66,8 @@ export function extractOptimizablePublicStaticCalls(payload: ExecutionPayload):
65
66
  * @param gasSettings - Gas settings for the transaction.
66
67
  * @param blockHeader - Block header to use as anchor.
67
68
  * @param skipFeeEnforcement - Whether to skip fee enforcement during simulation.
69
+ * @param getContractName - Resolver for contract names (used for debug log display).
70
+ * @param overrides - Optional pre-simulation overrides applied to the ephemeral fork and contract DB.
68
71
  * @returns TxSimulationResult with public return values.
69
72
  */
70
73
  async function simulateBatchViaNode(
@@ -76,6 +79,7 @@ async function simulateBatchViaNode(
76
79
  blockHeader: BlockHeader,
77
80
  skipFeeEnforcement: boolean,
78
81
  getContractName: ContractNameResolver,
82
+ overrides?: SimulationOverrides,
79
83
  ): Promise<TxSimulationResult> {
80
84
  const txContext = new TxContext(chainInfo.chainId, chainInfo.version, gasSettings);
81
85
 
@@ -143,7 +147,7 @@ async function simulateBatchViaNode(
143
147
  publicFunctionCalldata: publicFunctionCalldata,
144
148
  });
145
149
 
146
- const publicOutput = await node.simulatePublicCalls(tx, skipFeeEnforcement);
150
+ const publicOutput = await node.simulatePublicCalls(tx, skipFeeEnforcement, overrides);
147
151
 
148
152
  if (publicOutput.revertReason) {
149
153
  throw publicOutput.revertReason;
@@ -166,6 +170,8 @@ async function simulateBatchViaNode(
166
170
  * @param gasSettings - Gas settings for the transaction.
167
171
  * @param blockHeader - Block header to use as anchor.
168
172
  * @param skipFeeEnforcement - Whether to skip fee enforcement during simulation.
173
+ * @param getContractName - Resolver for contract names (used for debug log display).
174
+ * @param overrides - Optional pre-simulation overrides applied to the ephemeral fork and contract DB.
169
175
  * @returns Array of TxSimulationResult, one per batch.
170
176
  */
171
177
  export async function simulateViaNode(
@@ -177,6 +183,7 @@ export async function simulateViaNode(
177
183
  blockHeader: BlockHeader,
178
184
  skipFeeEnforcement: boolean = true,
179
185
  getContractName: ContractNameResolver,
186
+ overrides?: SimulationOverrides,
180
187
  ): Promise<TxSimulationResult[]> {
181
188
  const batches: FunctionCall[][] = [];
182
189
 
@@ -196,6 +203,7 @@ export async function simulateViaNode(
196
203
  blockHeader,
197
204
  skipFeeEnforcement,
198
205
  getContractName,
206
+ overrides,
199
207
  );
200
208
  results.push(result);
201
209
  }
@@ -17,6 +17,7 @@ import {
17
17
  type WalletMessage,
18
18
  WalletMessageType,
19
19
  type WalletResponse,
20
+ type WalletSdkLogger,
20
21
  } from '../../types.js';
21
22
  import {
22
23
  type BackgroundMessage,
@@ -131,6 +132,8 @@ export interface BackgroundConnectionConfig {
131
132
  walletVersion: string;
132
133
  /** Optional wallet icon URL. */
133
134
  walletIcon?: string;
135
+ /** Logger used for diagnostics. */
136
+ logger: WalletSdkLogger;
134
137
  }
135
138
 
136
139
  /**
@@ -149,6 +152,7 @@ export interface BackgroundConnectionConfig {
149
152
  * walletId: 'my-wallet',
150
153
  * walletName: 'My Wallet',
151
154
  * walletVersion: '1.0.0',
155
+ * logger: console,
152
156
  * },
153
157
  * {
154
158
  * sendToTab: (tabId, message) => browser.tabs.sendMessage(tabId, message),
@@ -167,12 +171,15 @@ export interface BackgroundConnectionConfig {
167
171
  export class BackgroundConnectionHandler {
168
172
  private pendingDiscoveries = new Map<string, PendingDiscovery>();
169
173
  private activeSessions = new Map<string, ActiveSession>();
174
+ private log: WalletSdkLogger;
170
175
 
171
176
  constructor(
172
177
  private config: BackgroundConnectionConfig,
173
178
  private transport: BackgroundTransport,
174
179
  private callbacks: BackgroundConnectionCallbacks = {},
175
- ) {}
180
+ ) {
181
+ this.log = config.logger;
182
+ }
176
183
 
177
184
  initialize(): void {
178
185
  this.transport.addContentListener(this.handleMessage);
@@ -198,8 +205,8 @@ export class BackgroundConnectionHandler {
198
205
  break;
199
206
  case InternalMessageType.KEY_EXCHANGE_REQUEST:
200
207
  if (sessionId) {
201
- this.handleKeyExchangeRequest(sessionId, content as KeyExchangeRequest).catch(() => {
202
- // Key exchange failed - session won't be established
208
+ this.handleKeyExchangeRequest(sessionId, content as KeyExchangeRequest).catch(err => {
209
+ this.log.warn('Key exchange failed session will not be established', { sessionId, err });
203
210
  });
204
211
  }
205
212
  break;
@@ -213,9 +220,31 @@ export class BackgroundConnectionHandler {
213
220
  void this.handleEncryptedMessage(sessionId, content as EncryptedPayload);
214
221
  }
215
222
  break;
223
+ case InternalMessageType.PING:
224
+ if (sessionId) {
225
+ this.handlePing(sessionId);
226
+ }
227
+ break;
216
228
  }
217
229
  };
218
230
 
231
+ /**
232
+ * Reply to a dApp PING with a PONG. Used as a liveness probe so the dApp can
233
+ * tell the difference between a slow request and a dead extension.
234
+ * @param sessionId - The session that sent the PING.
235
+ */
236
+ private handlePing(sessionId: string): void {
237
+ const session = this.activeSessions.get(sessionId);
238
+ if (!session) {
239
+ return;
240
+ }
241
+ this.transport.sendToTab(session.tabId, {
242
+ origin: MessageOrigin.BACKGROUND,
243
+ type: InternalMessageType.PONG,
244
+ sessionId,
245
+ });
246
+ }
247
+
219
248
  getWalletInfo(): WalletInfo {
220
249
  return {
221
250
  id: this.config.walletId,
@@ -315,8 +344,8 @@ export class BackgroundConnectionHandler {
315
344
  });
316
345
 
317
346
  this.callbacks.onSessionEstablished?.(session);
318
- } catch {
319
- // Key exchange failed silently - session won't be established
347
+ } catch (err) {
348
+ this.log.warn('Key exchange failed session will not be established', { sessionId, err });
320
349
  }
321
350
  }
322
351
 
@@ -329,8 +358,8 @@ export class BackgroundConnectionHandler {
329
358
  try {
330
359
  const message = await decrypt<WalletMessage>(session.sharedKey, encrypted);
331
360
  this.callbacks.onWalletMessage?.(session, message);
332
- } catch {
333
- // Decryption failed - ignore malformed message
361
+ } catch (err) {
362
+ this.log.warn('Failed to decrypt incoming wallet message', { sessionId, err });
334
363
  }
335
364
  }
336
365
 
@@ -348,8 +377,12 @@ export class BackgroundConnectionHandler {
348
377
  sessionId,
349
378
  content: encrypted,
350
379
  });
351
- } catch {
352
- // Encryption failed - response won't be sent
380
+ } catch (err) {
381
+ this.log.error('Failed to encrypt wallet response response will not be sent', {
382
+ sessionId,
383
+ messageId: response.messageId,
384
+ err,
385
+ });
353
386
  }
354
387
  }
355
388