@aztec/wallet-sdk 0.0.1-commit.c2eed6949 → 0.0.1-commit.c52d6e7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +125 -0
  2. package/dest/base-wallet/base_wallet.d.ts +66 -36
  3. package/dest/base-wallet/base_wallet.d.ts.map +1 -1
  4. package/dest/base-wallet/base_wallet.js +206 -92
  5. package/dest/base-wallet/get_gas_limits.d.ts +36 -0
  6. package/dest/base-wallet/get_gas_limits.d.ts.map +1 -0
  7. package/dest/base-wallet/get_gas_limits.js +55 -0
  8. package/dest/base-wallet/index.d.ts +3 -2
  9. package/dest/base-wallet/index.d.ts.map +1 -1
  10. package/dest/base-wallet/index.js +1 -0
  11. package/dest/base-wallet/utils.d.ts +7 -4
  12. package/dest/base-wallet/utils.d.ts.map +1 -1
  13. package/dest/base-wallet/utils.js +11 -5
  14. package/dest/crypto.d.ts +39 -1
  15. package/dest/crypto.d.ts.map +1 -1
  16. package/dest/crypto.js +88 -0
  17. package/dest/extension/handlers/background_connection_handler.d.ts +12 -2
  18. package/dest/extension/handlers/background_connection_handler.d.ts.map +1 -1
  19. package/dest/extension/handlers/background_connection_handler.js +44 -8
  20. package/dest/extension/handlers/content_script_connection_handler.d.ts +2 -1
  21. package/dest/extension/handlers/content_script_connection_handler.d.ts.map +1 -1
  22. package/dest/extension/handlers/content_script_connection_handler.js +19 -0
  23. package/dest/extension/handlers/internal_message_types.d.ts +3 -1
  24. package/dest/extension/handlers/internal_message_types.d.ts.map +1 -1
  25. package/dest/extension/handlers/internal_message_types.js +3 -1
  26. package/dest/extension/provider/extension_wallet.d.ts +26 -6
  27. package/dest/extension/provider/extension_wallet.d.ts.map +1 -1
  28. package/dest/extension/provider/extension_wallet.js +80 -9
  29. package/dest/extension/provider/index.d.ts +2 -2
  30. package/dest/extension/provider/index.d.ts.map +1 -1
  31. package/dest/iframe/handlers/iframe_connection_handler.d.ts +122 -0
  32. package/dest/iframe/handlers/iframe_connection_handler.d.ts.map +1 -0
  33. package/dest/iframe/handlers/iframe_connection_handler.js +239 -0
  34. package/dest/iframe/handlers/index.d.ts +2 -0
  35. package/dest/iframe/handlers/index.d.ts.map +1 -0
  36. package/dest/iframe/handlers/index.js +1 -0
  37. package/dest/iframe/provider/iframe_discovery.d.ts +25 -0
  38. package/dest/iframe/provider/iframe_discovery.d.ts.map +1 -0
  39. package/dest/iframe/provider/iframe_discovery.js +167 -0
  40. package/dest/iframe/provider/iframe_provider.d.ts +65 -0
  41. package/dest/iframe/provider/iframe_provider.d.ts.map +1 -0
  42. package/dest/iframe/provider/iframe_provider.js +257 -0
  43. package/dest/iframe/provider/iframe_wallet.d.ts +85 -0
  44. package/dest/iframe/provider/iframe_wallet.d.ts.map +1 -0
  45. package/dest/iframe/provider/iframe_wallet.js +269 -0
  46. package/dest/iframe/provider/index.d.ts +4 -0
  47. package/dest/iframe/provider/index.d.ts.map +1 -0
  48. package/dest/iframe/provider/index.js +3 -0
  49. package/dest/manager/types.d.ts +3 -2
  50. package/dest/manager/types.d.ts.map +1 -1
  51. package/dest/manager/wallet_manager.d.ts +1 -1
  52. package/dest/manager/wallet_manager.d.ts.map +1 -1
  53. package/dest/manager/wallet_manager.js +46 -16
  54. package/dest/types.d.ts +64 -2
  55. package/dest/types.d.ts.map +1 -1
  56. package/dest/types.js +29 -0
  57. package/package.json +12 -8
  58. package/src/base-wallet/base_wallet.ts +236 -115
  59. package/src/base-wallet/get_gas_limits.ts +88 -0
  60. package/src/base-wallet/index.ts +7 -1
  61. package/src/base-wallet/utils.ts +15 -5
  62. package/src/crypto.ts +104 -0
  63. package/src/extension/handlers/background_connection_handler.ts +42 -9
  64. package/src/extension/handlers/content_script_connection_handler.ts +18 -0
  65. package/src/extension/handlers/internal_message_types.ts +2 -0
  66. package/src/extension/provider/extension_wallet.ts +94 -13
  67. package/src/extension/provider/index.ts +1 -1
  68. package/src/iframe/handlers/iframe_connection_handler.ts +341 -0
  69. package/src/iframe/handlers/index.ts +7 -0
  70. package/src/iframe/provider/iframe_discovery.ts +185 -0
  71. package/src/iframe/provider/iframe_provider.ts +331 -0
  72. package/src/iframe/provider/iframe_wallet.ts +323 -0
  73. package/src/iframe/provider/index.ts +3 -0
  74. package/src/manager/types.ts +2 -1
  75. package/src/manager/wallet_manager.ts +48 -14
  76. package/src/types.ts +72 -0
@@ -2,9 +2,11 @@ import type { Account, NoFrom } from '@aztec/aztec.js/account';
2
2
  import { NO_FROM } from '@aztec/aztec.js/account';
3
3
  import type { CallIntent, IntentInnerHash } from '@aztec/aztec.js/authorization';
4
4
  import {
5
+ DefaultWaitOpts,
5
6
  type InteractionWaitOptions,
6
7
  NO_WAIT,
7
8
  type SendReturn,
9
+ type WaitOpts,
8
10
  extractOffchainOutput,
9
11
  } from '@aztec/aztec.js/contracts';
10
12
  import type { FeePaymentMethod } from '@aztec/aztec.js/fee';
@@ -21,22 +23,17 @@ import {
21
23
  type ProfileOptions,
22
24
  type SendOptions,
23
25
  type SimulateOptions,
26
+ TxSimulationResultWithAppOffset,
24
27
  type Wallet,
25
28
  type WalletCapabilities,
26
29
  } 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
30
  import { AccountFeePaymentMethodOptions, type DefaultAccountEntrypointOptions } from '@aztec/entrypoints/account';
34
31
  import { DefaultEntrypoint } from '@aztec/entrypoints/default';
35
32
  import type { ChainInfo } from '@aztec/entrypoints/interfaces';
36
33
  import { Fr } from '@aztec/foundation/curves/bn254';
37
34
  import { createLogger } from '@aztec/foundation/log';
38
35
  import type { FieldsOf } from '@aztec/foundation/types';
39
- import { type AccessScopes, displayDebugLogs } from '@aztec/pxe/client/lazy';
36
+ import { displayDebugLogs } from '@aztec/pxe/client/lazy';
40
37
  import type { PXE, PackedPrivateEvent } from '@aztec/pxe/server';
41
38
  import {
42
39
  type ContractArtifact,
@@ -46,29 +43,27 @@ import {
46
43
  } from '@aztec/stdlib/abi';
47
44
  import type { AuthWitness } from '@aztec/stdlib/auth-witness';
48
45
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
49
- import {
50
- type ContractInstanceWithAddress,
51
- computePartialAddress,
52
- getContractClassFromArtifact,
53
- } from '@aztec/stdlib/contract';
46
+ import { type ContractInstancePreimage, type NodeInfo, computePartialAddress } from '@aztec/stdlib/contract';
54
47
  import { SimulationError } from '@aztec/stdlib/errors';
55
- import { Gas, GasSettings } from '@aztec/stdlib/gas';
48
+ import { Gas, GasFees, GasSettings, ManaUsageEstimate } from '@aztec/stdlib/gas';
56
49
  import {
57
50
  computeSiloedPrivateInitializationNullifier,
58
51
  computeSiloedPublicInitializationNullifier,
59
52
  } from '@aztec/stdlib/hash';
60
53
  import type { AztecNode } from '@aztec/stdlib/interfaces/client';
54
+ import { type MasterSecretKeys, deriveKeys, deriveKeysFromMasterSecretKeys } from '@aztec/stdlib/keys';
61
55
  import {
62
56
  BlockHeader,
57
+ ExecutionPayload,
63
58
  type TxExecutionRequest,
64
59
  type TxProfileResult,
65
- TxSimulationResult,
66
60
  type UtilityExecutionResult,
61
+ mergeExecutionPayloads,
67
62
  } from '@aztec/stdlib/tx';
68
- import { ExecutionPayload, mergeExecutionPayloads } from '@aztec/stdlib/tx';
69
63
 
70
64
  import { inspect } from 'util';
71
65
 
66
+ import { assertGasLimitsWithinNetworkLimits } from './get_gas_limits.js';
72
67
  import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simulateViaNode } from './utils.js';
73
68
 
74
69
  /**
@@ -89,19 +84,41 @@ export type FeeOptions = {
89
84
  /** Options for `simulateViaEntrypoint`. */
90
85
  export type SimulateViaEntrypointOptions = Pick<
91
86
  SimulateOptions,
92
- 'from' | 'additionalScopes' | 'skipTxValidation' | 'skipFeeEnforcement'
87
+ 'from' | 'additionalScopes' | 'skipTxValidation' | 'skipFeeEnforcement' | 'sendMessagesAs' | 'overrides'
93
88
  > & {
94
89
  /** Fee options for the entrypoint */
95
90
  feeOptions: FeeOptions;
96
- /** Scopes to use for the simulation */
97
- scopes: AccessScopes;
98
91
  };
92
+
93
+ /** Options for `completeFeeOptions`. */
94
+ export type CompleteFeeOptionsConfig = {
95
+ /** The address where the transaction is being sent from. */
96
+ from: AztecAddress | NoFrom;
97
+ /** The address paying for fees (if any fee payment method is embedded in the execution payload). */
98
+ feePayer?: AztecAddress;
99
+ /** User-provided partial gas settings. */
100
+ gasSettings?: Partial<FieldsOf<GasSettings>>;
101
+ /** If true, returns gas settings with high gas limits for estimation. If false, uses fallback limits. */
102
+ forEstimation?: boolean;
103
+ /**
104
+ * Assumed network congestion level for fee prediction. Controls how aggressively the wallet
105
+ * estimates future fees. Defaults to Limit (worst case) when not specified.
106
+ */
107
+ congestionEstimate?: ManaUsageEstimate;
108
+ };
109
+
99
110
  /**
100
111
  * A base class for Wallet implementations
101
112
  */
102
113
  export abstract class BaseWallet implements Wallet {
103
114
  protected minFeePadding = 0.5;
104
115
  protected cancellableTransactions = false;
116
+ // Poll interval (in seconds) injected into sendTx waits when the caller does not specify one. Left undefined on
117
+ // production wallets so the DefaultWaitOpts 1s cadence stands; test wallets talking to in-process nodes lower it.
118
+ protected defaultWaitInterval?: number;
119
+ // A wallet is instantiated for a particular chain, so chain info never changes during its lifetime.
120
+ // We cache it here because getChainInfo is called frequently (every tx simulation, send, auth wit, etc.).
121
+ private nodeInfoPromise: Promise<NodeInfo> | undefined;
105
122
 
106
123
  // Protected because we want to force wallets to instantiate their own PXE.
107
124
  protected constructor(
@@ -110,10 +127,28 @@ export abstract class BaseWallet implements Wallet {
110
127
  protected log = createLogger('wallet-sdk:base_wallet'),
111
128
  ) {}
112
129
 
113
- protected scopesFrom(from: AztecAddress | NoFrom, additionalScopes: AztecAddress[] = []): AztecAddress[] {
114
- const allScopes = from === NO_FROM ? additionalScopes : [from, ...additionalScopes];
130
+ protected scopesFrom(
131
+ from: AztecAddress | NoFrom,
132
+ additionalScopes: AztecAddress[],
133
+ sendMessagesAs: AztecAddress | undefined,
134
+ ): AztecAddress[] {
135
+ // The sendMessagesAs account must be in scope so that its tagging secrets can be accessed.
136
+ const tagSenderScopes = sendMessagesAs ? [sendMessagesAs] : [];
137
+ const baseScopes = from === NO_FROM ? [] : [from];
138
+ const allScopes = [...baseScopes, ...additionalScopes, ...tagSenderScopes];
115
139
  const scopeSet = new Set(allScopes.map(address => address.toString()));
116
- return [...scopeSet].map(AztecAddress.fromString);
140
+ return [...scopeSet].map(AztecAddress.fromStringUnsafe);
141
+ }
142
+
143
+ /**
144
+ * Picks the sender address PXE should tag private messages with. Returns `undefined` when there is no signing
145
+ * account (`from === NO_FROM`) and no explicit override; in that case any private log emitted by the tx using
146
+ * the wallet-supplied default sender will fail the "Sender for tags is not set" assertion.
147
+ * @param from - Tx sender, or `NO_FROM`.
148
+ * @param sendMessagesAs - Explicit override.
149
+ */
150
+ protected senderForTagsFrom(from: AztecAddress | NoFrom, sendMessagesAs?: AztecAddress): AztecAddress | undefined {
151
+ return sendMessagesAs ?? (from === NO_FROM ? undefined : from);
117
152
  }
118
153
 
119
154
  protected abstract getAccountFromAddress(address: AztecAddress): Promise<Account>;
@@ -128,15 +163,42 @@ export abstract class BaseWallet implements Wallet {
128
163
  * @returns The aliased collection of AztecAddresses that form this wallet's address book
129
164
  */
130
165
  async getAddressBook(): Promise<Aliased<AztecAddress>[]> {
131
- const senders: AztecAddress[] = await this.pxe.getSenders();
132
- return senders.map(sender => ({ item: sender, alias: '' }));
166
+ const sources = await this.pxe.getTaggingSecretSources({ kind: 'address-derived' });
167
+ return sources.map(source => ({ item: source.sender, alias: '' }));
168
+ }
169
+
170
+ /**
171
+ * Fetches and caches the node info for the wallet's lifetime, since a wallet talks to a single network and
172
+ * node info never changes. A rejected fetch clears the cache so the next call retries instead of replaying
173
+ * the cached rejection forever — important because the gas-limit fill-in and validation (run on every send)
174
+ * depend on it.
175
+ */
176
+ private getNodeInfo(): Promise<NodeInfo> {
177
+ if (!this.nodeInfoPromise) {
178
+ this.nodeInfoPromise = this.aztecNode.getNodeInfo().catch(err => {
179
+ this.nodeInfoPromise = undefined;
180
+ throw err;
181
+ });
182
+ }
183
+ return this.nodeInfoPromise;
133
184
  }
134
185
 
135
186
  async getChainInfo(): Promise<ChainInfo> {
136
- const { l1ChainId, rollupVersion } = await this.aztecNode.getNodeInfo();
187
+ const { l1ChainId, rollupVersion } = await this.getNodeInfo();
137
188
  return { chainId: new Fr(l1ChainId), version: new Fr(rollupVersion) };
138
189
  }
139
190
 
191
+ /**
192
+ * Returns the maximum gas limits a single transaction may declare on this wallet's network (the
193
+ * node-advertised `txsLimits.gas`). Internal helper used to fill in default gas limits when sending a
194
+ * transaction without explicit limits, and to validate caller-provided limits before sending. Backed by
195
+ * the cached node info, since a wallet talks to a single network.
196
+ */
197
+ protected async getMaxTxGasLimits(): Promise<Gas> {
198
+ const { txsLimits } = await this.getNodeInfo();
199
+ return new Gas(txsLimits.gas.daGas, txsLimits.gas.l2Gas);
200
+ }
201
+
140
202
  protected async createTxExecutionRequestFromPayloadAndFee(
141
203
  executionPayload: ExecutionPayload,
142
204
  from: AztecAddress | NoFrom,
@@ -214,18 +276,12 @@ export abstract class BaseWallet implements Wallet {
214
276
 
215
277
  /**
216
278
  * 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
279
+ * @param config - Fee completion config.
221
280
  */
222
- protected async completeFeeOptions(
223
- from: AztecAddress | NoFrom,
224
- feePayer?: AztecAddress,
225
- gasSettings?: Partial<FieldsOf<GasSettings>>,
226
- ): Promise<FeeOptions> {
281
+ protected async completeFeeOptions(config: CompleteFeeOptionsConfig): Promise<FeeOptions> {
282
+ const { from, feePayer, gasSettings, forEstimation, congestionEstimate } = config;
227
283
  const maxFeesPerGas =
228
- gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentMinFees()).mul(1 + this.minFeePadding);
284
+ gasSettings?.maxFeesPerGas ?? (await this.getMinFees(congestionEstimate)).mul(1 + this.minFeePadding);
229
285
  let accountFeePaymentMethodOptions;
230
286
  // If from is an address, we need to determine the appropriate fee payment method options for the
231
287
  // account contract entrypoint to use
@@ -242,7 +298,32 @@ export abstract class BaseWallet implements Wallet {
242
298
  : AccountFeePaymentMethodOptions.EXTERNAL;
243
299
  }
244
300
  }
245
- const fullGasSettings: GasSettings = GasSettings.default({ ...gasSettings, maxFeesPerGas });
301
+ const gasSettingsOverrides = {
302
+ gasLimits: gasSettings?.gasLimits ? Gas.from(gasSettings.gasLimits) : undefined,
303
+ teardownGasLimits: gasSettings?.teardownGasLimits ? Gas.from(gasSettings.teardownGasLimits) : undefined,
304
+ maxFeesPerGas,
305
+ maxPriorityFeesPerGas: gasSettings?.maxPriorityFeesPerGas ?? GasFees.empty(),
306
+ };
307
+ // When estimating gas (simulation), use high limits so the simulation doesn't run out of gas.
308
+ // When sending for real without explicit limits, declare the most a single tx may use on this network
309
+ // (the node's per-tx admission limit), so the proposer does not skip the tx for over-declaring gas.
310
+ let fullGasSettings;
311
+ if (forEstimation) {
312
+ // Estimation deliberately uses very high internal limits and skips tx validation, so we do not
313
+ // validate against the network admission limit here.
314
+ fullGasSettings = GasSettings.forEstimation(gasSettingsOverrides);
315
+ } else {
316
+ const maxTxGasLimits = await this.getMaxTxGasLimits();
317
+ // If the caller declared explicit gas limits, reject them up front when they exceed the network's
318
+ // per-tx admission limit (mirroring the node's GasLimitsValidator). Otherwise fill in the limit.
319
+ if (gasSettingsOverrides.gasLimits) {
320
+ assertGasLimitsWithinNetworkLimits(gasSettingsOverrides.gasLimits, maxTxGasLimits);
321
+ }
322
+ fullGasSettings = GasSettings.fallback({
323
+ ...gasSettingsOverrides,
324
+ gasLimits: gasSettingsOverrides.gasLimits ?? maxTxGasLimits,
325
+ });
326
+ }
246
327
  this.log.debug(`Using L2 gas settings`, fullGasSettings);
247
328
  return {
248
329
  gasSettings: fullGasSettings,
@@ -252,76 +333,67 @@ export abstract class BaseWallet implements Wallet {
252
333
  }
253
334
 
254
335
  /**
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
336
+ * Returns the worst-case min fee across predicted future slots.
337
+ * Falls back to getCurrentMinFees if the node doesn't support getPredictedMinFees.
338
+ * @param estimate - The mana usage estimate to use for fee prediction. Defaults to Limit for conservative estimation.
261
339
  */
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
- };
340
+ protected async getMinFees(estimate: ManaUsageEstimate = ManaUsageEstimate.Limit): Promise<GasFees> {
341
+ try {
342
+ const predicted = await this.aztecNode.getPredictedMinFees(estimate);
343
+ if (predicted.length === 0) {
344
+ return this.aztecNode.getCurrentMinFees();
345
+ }
346
+ return predicted.reduce((worst, fees) => (fees.feePerL2Gas > worst.feePerL2Gas ? fees : worst));
347
+ } catch (err: any) {
348
+ // Fallback for old nodes that don't support getPredictedMinFees.
349
+ // Only fall back on method-not-found errors (JSON-RPC code -32601); rethrow others.
350
+ if (err?.cause?.code === -32601 || err?.message?.includes('Method not found')) {
351
+ return this.aztecNode.getCurrentMinFees();
352
+ }
353
+ throw err;
354
+ }
283
355
  }
284
356
 
285
- registerSender(address: AztecAddress, _alias: string = ''): Promise<AztecAddress> {
286
- return this.pxe.registerSender(address);
357
+ async registerSender(address: AztecAddress, _alias: string = ''): Promise<AztecAddress> {
358
+ await this.pxe.registerTaggingSecretSource({ kind: 'address-derived', sender: address });
359
+ return address;
287
360
  }
288
361
 
289
362
  async registerContract(
290
- instance: ContractInstanceWithAddress,
363
+ instance: ContractInstancePreimage,
291
364
  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
- }
365
+ secretKeyOrKeys?: Fr | MasterSecretKeys,
366
+ ): Promise<void> {
367
+ // Classes and instances are registered independently: register the artifact (if provided) then the instance.
368
+ // Neither call validates that the artifact matches the class the instance runs, a missing artifact only surfaces
369
+ // when the contract is later simulated.
370
+ if (artifact) {
371
+ await this.pxe.registerContractClass(artifact);
372
+ }
373
+ const contractAddress = await this.pxe.registerContract(instance);
374
+
375
+ if (secretKeyOrKeys) {
376
+ // PXE never receives the account seed (from which the message-signing/fallback secret keys could be re-derived):
377
+ // the wallet derives the keys here. Of these, PXE only reads and stores the four privacy secret keys and the
378
+ // message-signing and fallback *public* keys — it never touches the message-signing or fallback secret keys.
379
+ //
380
+ // Since PXE recomputes the address from those keys, we assert it matches the instance's address: a mismatch means
381
+ // the provided keys don't correspond to this account.
382
+ const derivedKeys =
383
+ secretKeyOrKeys instanceof Fr
384
+ ? await deriveKeys(secretKeyOrKeys)
385
+ : await deriveKeysFromMasterSecretKeys(secretKeyOrKeys);
386
+ const { address } = await this.pxe.registerAccount(derivedKeys, await computePartialAddress(instance));
387
+ if (!address.equals(contractAddress)) {
388
+ throw new Error(
389
+ `Registered account address ${address.toString()} does not match contract instance address ${contractAddress.toString()}: the provided keys do not correspond to this account.`,
390
+ );
317
391
  }
318
- await this.pxe.registerContract({ artifact, instance });
319
392
  }
393
+ }
320
394
 
321
- if (secretKey) {
322
- await this.pxe.registerAccount(secretKey, await computePartialAddress(instance));
323
- }
324
- return instance;
395
+ registerContractClass(artifact: ContractArtifact): Promise<void> {
396
+ return this.pxe.registerContractClass(artifact);
325
397
  }
326
398
 
327
399
  /**
@@ -335,12 +407,30 @@ export abstract class BaseWallet implements Wallet {
335
407
  opts.from,
336
408
  opts.feeOptions,
337
409
  );
338
- return this.pxe.simulateTx(txRequest, {
410
+ const result = await this.pxe.simulateTx(txRequest, {
339
411
  simulatePublic: true,
340
412
  skipTxValidation: opts.skipTxValidation,
341
413
  skipFeeEnforcement: opts.skipFeeEnforcement,
342
- scopes: opts.scopes,
414
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes ?? [], opts.sendMessagesAs),
415
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
416
+ overrides: opts.overrides,
343
417
  });
418
+ const appCallOffset = await this.computeAppCallOffset(opts.from, opts.feeOptions);
419
+ return TxSimulationResultWithAppOffset.fromResultAndOffset(result, appCallOffset);
420
+ }
421
+
422
+ /**
423
+ * Computes the index where the app's calls begin in the flattened array of calls (0 = entrypoint/root, 1..N = fee
424
+ * calls, N+1 = app).
425
+ * @param from - The sender address, or NO_FROM for the default entrypoint.
426
+ * @param feeOptions - Fee options containing the wallet fee payment method.
427
+ */
428
+ protected async computeAppCallOffset(from: AztecAddress | NoFrom, feeOptions: FeeOptions): Promise<number> {
429
+ if (from === NO_FROM) {
430
+ return 0;
431
+ }
432
+ const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
433
+ return (feeExecutionPayload?.calls.length ?? 0) + 1; // +1 for entrypoint
344
434
  }
345
435
 
346
436
  /**
@@ -351,10 +441,17 @@ export abstract class BaseWallet implements Wallet {
351
441
  * @param opts - Simulation options (from address, fee settings, etc.).
352
442
  * @returns The merged simulation result.
353
443
  */
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);
444
+ async simulateTx(
445
+ executionPayload: ExecutionPayload,
446
+ opts: SimulateOptions,
447
+ ): Promise<TxSimulationResultWithAppOffset> {
448
+ const feeOptions = await this.completeFeeOptions({
449
+ from: opts.from,
450
+ feePayer: executionPayload.feePayer,
451
+ gasSettings: opts.fee?.gasSettings,
452
+ forEstimation: true,
453
+ congestionEstimate: opts.fee?.congestionEstimate,
454
+ });
358
455
  const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
359
456
  const remainingPayload = { ...executionPayload, calls: remainingCalls };
360
457
 
@@ -365,7 +462,7 @@ export abstract class BaseWallet implements Wallet {
365
462
  try {
366
463
  blockHeader = await this.pxe.getSyncedBlockHeader();
367
464
  } catch {
368
- blockHeader = (await this.aztecNode.getBlockHeader())!;
465
+ blockHeader = (await this.aztecNode.getBlockData('latest'))!.header;
369
466
  }
370
467
 
371
468
  const simulationOrigin = opts.from === NO_FROM ? AztecAddress.ZERO : opts.from;
@@ -380,15 +477,18 @@ export abstract class BaseWallet implements Wallet {
380
477
  blockHeader,
381
478
  opts.skipFeeEnforcement ?? true,
382
479
  this.getContractName.bind(this),
480
+ opts.overrides,
383
481
  )
384
482
  : Promise.resolve([]),
385
483
  remainingCalls.length > 0
386
484
  ? this.simulateViaEntrypoint(remainingPayload, {
387
485
  from: opts.from,
388
486
  feeOptions,
389
- scopes: this.scopesFrom(opts.from, opts.additionalScopes),
487
+ additionalScopes: opts.additionalScopes,
390
488
  skipTxValidation: opts.skipTxValidation,
391
489
  skipFeeEnforcement: opts.skipFeeEnforcement ?? true,
490
+ sendMessagesAs: opts.sendMessagesAs,
491
+ overrides: opts.overrides,
392
492
  })
393
493
  : Promise.resolve(null),
394
494
  ]);
@@ -397,12 +497,18 @@ export abstract class BaseWallet implements Wallet {
397
497
  }
398
498
 
399
499
  async profileTx(executionPayload: ExecutionPayload, opts: ProfileOptions): Promise<TxProfileResult> {
400
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
500
+ const feeOptions = await this.completeFeeOptions({
501
+ from: opts.from,
502
+ feePayer: executionPayload.feePayer,
503
+ gasSettings: opts.fee?.gasSettings,
504
+ congestionEstimate: opts.fee?.congestionEstimate,
505
+ });
401
506
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
402
507
  return this.pxe.profileTx(txRequest, {
403
508
  profileMode: opts.profileMode,
404
509
  skipProofGeneration: opts.skipProofGeneration ?? true,
405
- scopes: this.scopesFrom(opts.from, opts.additionalScopes),
510
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes ?? [], opts.sendMessagesAs),
511
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
406
512
  });
407
513
  }
408
514
 
@@ -410,18 +516,23 @@ export abstract class BaseWallet implements Wallet {
410
516
  executionPayload: ExecutionPayload,
411
517
  opts: SendOptions<W>,
412
518
  ): Promise<SendReturn<W>> {
413
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
519
+ const feeOptions = await this.completeFeeOptions({
520
+ from: opts.from,
521
+ feePayer: executionPayload.feePayer,
522
+ gasSettings: opts.fee?.gasSettings,
523
+ congestionEstimate: opts.fee?.congestionEstimate,
524
+ });
414
525
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
415
- const provenTx = await this.pxe.proveTx(txRequest, this.scopesFrom(opts.from, opts.additionalScopes));
526
+ const provenTx = await this.pxe.proveTx(txRequest, {
527
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes ?? [], opts.sendMessagesAs),
528
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
529
+ });
416
530
  const offchainOutput = extractOffchainOutput(
417
531
  provenTx.getOffchainEffects(),
418
532
  provenTx.publicInputs.constants.anchorBlockHeader.globalVariables.timestamp,
419
533
  );
420
534
  const tx = await provenTx.toTx();
421
535
  const txHash = tx.getTxHash();
422
- if (await this.aztecNode.getTxEffect(txHash)) {
423
- throw new Error(`A settled tx with equal hash ${txHash.toString()} exists.`);
424
- }
425
536
  this.log.debug(`Sending transaction ${txHash}`);
426
537
  await this.aztecNode.sendTx(tx).catch(err => {
427
538
  throw this.contextualizeError(err, inspect(tx));
@@ -434,11 +545,17 @@ export abstract class BaseWallet implements Wallet {
434
545
  }
435
546
 
436
547
  // Otherwise, wait for the full receipt (default behavior on wait: undefined)
437
- const waitOpts = typeof opts.wait === 'object' ? opts.wait : undefined;
438
- const receipt = await waitForTx(this.aztecNode, txHash, waitOpts);
548
+ const callerWaitOpts = typeof opts.wait === 'object' ? opts.wait : undefined;
549
+ const waitOpts: WaitOpts | undefined =
550
+ this.defaultWaitInterval !== undefined && callerWaitOpts?.interval === undefined
551
+ ? { ...callerWaitOpts, interval: this.defaultWaitInterval }
552
+ : callerWaitOpts;
553
+ // The tx was just sent, so an immediate first poll cannot find it mined; skip one poll interval up front.
554
+ const initialDelay = waitOpts?.initialDelay ?? waitOpts?.interval ?? DefaultWaitOpts.interval;
555
+ const receipt = await waitForTx(this.aztecNode, txHash, { ...waitOpts, initialDelay });
439
556
 
440
557
  // Display debug logs from public execution if present (served in test mode only)
441
- if (receipt.debugLogs?.length) {
558
+ if (receipt.isMined() && receipt.debugLogs?.length) {
442
559
  await displayDebugLogs(receipt.debugLogs, this.getContractName.bind(this));
443
560
  }
444
561
 
@@ -454,7 +571,11 @@ export abstract class BaseWallet implements Wallet {
454
571
  if (!instance) {
455
572
  return undefined;
456
573
  }
457
- const artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
574
+ // Contract names are class-stable (an upgrade preserves the contract name), so the original class artifact is a
575
+ // sufficient source for the display name without resolving the current class against the node.
576
+ // TODO: if a contract were to be upgraded and its original artifact never registered, then this would fail and we'd
577
+ // want to fallback to the current class.
578
+ const artifact = await this.pxe.getContractArtifact(instance.originalContractClassId);
458
579
  return artifact?.name;
459
580
  }
460
581
 
@@ -484,7 +605,7 @@ export abstract class BaseWallet implements Wallet {
484
605
 
485
606
  const decodedEvents = pxeEvents.map((pxeEvent: PackedPrivateEvent): PrivateEvent<T> => {
486
607
  return {
487
- event: decodeFromAbi([eventDef.abiType], pxeEvent.packedEvent) as T,
608
+ event: decodeFromAbi(eventDef.abiType, pxeEvent.packedEvent) as T,
488
609
  metadata: {
489
610
  l2BlockNumber: pxeEvent.l2BlockNumber,
490
611
  l2BlockHash: pxeEvent.l2BlockHash,
@@ -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';