@aztec-labs/wallet-sdk 6.0.0-nightly.20260829

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 (94) hide show
  1. package/README.md +478 -0
  2. package/dest/base-wallet/base_wallet.d.ts +179 -0
  3. package/dest/base-wallet/base_wallet.d.ts.map +1 -0
  4. package/dest/base-wallet/base_wallet.js +503 -0
  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 +4 -0
  9. package/dest/base-wallet/index.d.ts.map +1 -0
  10. package/dest/base-wallet/index.js +3 -0
  11. package/dest/base-wallet/utils.d.ts +52 -0
  12. package/dest/base-wallet/utils.d.ts.map +1 -0
  13. package/dest/base-wallet/utils.js +137 -0
  14. package/dest/crypto.d.ts +230 -0
  15. package/dest/crypto.d.ts.map +1 -0
  16. package/dest/crypto.js +482 -0
  17. package/dest/emoji_alphabet.d.ts +35 -0
  18. package/dest/emoji_alphabet.d.ts.map +1 -0
  19. package/dest/emoji_alphabet.js +299 -0
  20. package/dest/extension/handlers/background_connection_handler.d.ts +168 -0
  21. package/dest/extension/handlers/background_connection_handler.d.ts.map +1 -0
  22. package/dest/extension/handlers/background_connection_handler.js +294 -0
  23. package/dest/extension/handlers/content_script_connection_handler.d.ts +57 -0
  24. package/dest/extension/handlers/content_script_connection_handler.d.ts.map +1 -0
  25. package/dest/extension/handlers/content_script_connection_handler.js +193 -0
  26. package/dest/extension/handlers/index.d.ts +12 -0
  27. package/dest/extension/handlers/index.d.ts.map +1 -0
  28. package/dest/extension/handlers/index.js +10 -0
  29. package/dest/extension/handlers/internal_message_types.d.ts +65 -0
  30. package/dest/extension/handlers/internal_message_types.d.ts.map +1 -0
  31. package/dest/extension/handlers/internal_message_types.js +24 -0
  32. package/dest/extension/provider/extension_provider.d.ts +107 -0
  33. package/dest/extension/provider/extension_provider.d.ts.map +1 -0
  34. package/dest/extension/provider/extension_provider.js +160 -0
  35. package/dest/extension/provider/extension_wallet.d.ts +152 -0
  36. package/dest/extension/provider/extension_wallet.d.ts.map +1 -0
  37. package/dest/extension/provider/extension_wallet.js +349 -0
  38. package/dest/extension/provider/index.d.ts +3 -0
  39. package/dest/extension/provider/index.d.ts.map +1 -0
  40. package/dest/extension/provider/index.js +2 -0
  41. package/dest/iframe/handlers/iframe_connection_handler.d.ts +122 -0
  42. package/dest/iframe/handlers/iframe_connection_handler.d.ts.map +1 -0
  43. package/dest/iframe/handlers/iframe_connection_handler.js +239 -0
  44. package/dest/iframe/handlers/index.d.ts +2 -0
  45. package/dest/iframe/handlers/index.d.ts.map +1 -0
  46. package/dest/iframe/handlers/index.js +1 -0
  47. package/dest/iframe/provider/iframe_discovery.d.ts +25 -0
  48. package/dest/iframe/provider/iframe_discovery.d.ts.map +1 -0
  49. package/dest/iframe/provider/iframe_discovery.js +167 -0
  50. package/dest/iframe/provider/iframe_provider.d.ts +65 -0
  51. package/dest/iframe/provider/iframe_provider.d.ts.map +1 -0
  52. package/dest/iframe/provider/iframe_provider.js +257 -0
  53. package/dest/iframe/provider/iframe_wallet.d.ts +85 -0
  54. package/dest/iframe/provider/iframe_wallet.d.ts.map +1 -0
  55. package/dest/iframe/provider/iframe_wallet.js +269 -0
  56. package/dest/iframe/provider/index.d.ts +4 -0
  57. package/dest/iframe/provider/index.d.ts.map +1 -0
  58. package/dest/iframe/provider/index.js +3 -0
  59. package/dest/manager/index.d.ts +3 -0
  60. package/dest/manager/index.d.ts.map +1 -0
  61. package/dest/manager/index.js +1 -0
  62. package/dest/manager/types.d.ts +168 -0
  63. package/dest/manager/types.d.ts.map +1 -0
  64. package/dest/manager/types.js +19 -0
  65. package/dest/manager/wallet_manager.d.ts +70 -0
  66. package/dest/manager/wallet_manager.d.ts.map +1 -0
  67. package/dest/manager/wallet_manager.js +256 -0
  68. package/dest/types.d.ts +185 -0
  69. package/dest/types.d.ts.map +1 -0
  70. package/dest/types.js +40 -0
  71. package/package.json +109 -0
  72. package/src/base-wallet/base_wallet.ts +665 -0
  73. package/src/base-wallet/get_gas_limits.ts +88 -0
  74. package/src/base-wallet/index.ts +8 -0
  75. package/src/base-wallet/utils.ts +248 -0
  76. package/src/crypto.ts +603 -0
  77. package/src/emoji_alphabet.ts +317 -0
  78. package/src/extension/handlers/background_connection_handler.ts +456 -0
  79. package/src/extension/handlers/content_script_connection_handler.ts +264 -0
  80. package/src/extension/handlers/index.ts +25 -0
  81. package/src/extension/handlers/internal_message_types.ts +71 -0
  82. package/src/extension/provider/extension_provider.ts +233 -0
  83. package/src/extension/provider/extension_wallet.ts +410 -0
  84. package/src/extension/provider/index.ts +7 -0
  85. package/src/iframe/handlers/iframe_connection_handler.ts +341 -0
  86. package/src/iframe/handlers/index.ts +7 -0
  87. package/src/iframe/provider/iframe_discovery.ts +185 -0
  88. package/src/iframe/provider/iframe_provider.ts +331 -0
  89. package/src/iframe/provider/iframe_wallet.ts +323 -0
  90. package/src/iframe/provider/index.ts +3 -0
  91. package/src/manager/index.ts +12 -0
  92. package/src/manager/types.ts +178 -0
  93. package/src/manager/wallet_manager.ts +291 -0
  94. package/src/types.ts +204 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base_wallet.d.ts","sourceRoot":"","sources":["../../src/base-wallet/base_wallet.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,8BAA8B,CAAC;AAEpE,OAAO,KAAK,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AACtF,OAAO,EAEL,KAAK,sBAAsB,EAE3B,KAAK,UAAU,EAGhB,MAAM,gCAAgC,CAAC;AACxC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAEjE,OAAO,EACL,KAAK,OAAO,EACZ,KAAK,eAAe,EACpB,KAAK,YAAY,EACjB,KAAK,aAAa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AI,EAAE,qBAAqB,GAAG,OAAO,CAAC,sBAAsB,CAAC,CAE/F;IAEK,gBAAgB,CAAC,CAAC,EACtB,QAAQ,EAAE,uBAAuB,EACjC,WAAW,EAAE,kBAAkB,GAC9B,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,CAAC,CAe5B;IAED;;;OAGG;IACG,mBAAmB,CAAC,OAAO,EAAE,YAAY;;;;;;OAiC9C;IAEK,wBAAwB,CAAC,EAAE,EAAE,EAAE;;;OAMpC;CACF"}
@@ -0,0 +1,503 @@
1
+ import { NO_FROM } from '@aztec-labs/aztec.js/account';
2
+ import { DefaultWaitOpts, NO_WAIT, extractOffchainOutput } from '@aztec-labs/aztec.js/contracts';
3
+ import { waitForTx } from '@aztec-labs/aztec.js/node';
4
+ import { ContractInitializationStatus, TxSimulationResultWithAppOffset } from '@aztec-labs/aztec.js/wallet';
5
+ import { AccountFeePaymentMethodOptions } from '@aztec-labs/entrypoints/account';
6
+ import { DefaultEntrypoint } from '@aztec-labs/entrypoints/default';
7
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
8
+ import { createLogger } from '@aztec-labs/foundation/log';
9
+ import { displayDebugLogs } from '@aztec-labs/pxe/client/lazy';
10
+ import { decodeFromAbi } from '@aztec-labs/stdlib/abi';
11
+ import { AztecAddress } from '@aztec-labs/stdlib/aztec-address';
12
+ import { computePartialAddress } from '@aztec-labs/stdlib/contract';
13
+ import { SimulationError } from '@aztec-labs/stdlib/errors';
14
+ import { Gas, GasFees, GasSettings, ManaUsageEstimate } from '@aztec-labs/stdlib/gas';
15
+ import { computeSiloedPrivateInitializationNullifier, computeSiloedPublicInitializationNullifier } from '@aztec-labs/stdlib/hash';
16
+ import { deriveKeys, deriveKeysFromMasterSecretKeys } from '@aztec-labs/stdlib/keys';
17
+ import { mergeExecutionPayloads } from '@aztec-labs/stdlib/tx';
18
+ import { inspect } from 'util';
19
+ import { assertGasLimitsWithinNetworkLimits } from './get_gas_limits.js';
20
+ import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simulateViaNode } from './utils.js';
21
+ /**
22
+ * A base class for Wallet implementations
23
+ */ export class BaseWallet {
24
+ pxe;
25
+ aztecNode;
26
+ log;
27
+ minFeePadding;
28
+ cancellableTransactions;
29
+ // Poll interval (in seconds) injected into sendTx waits when the caller does not specify one. Left undefined on
30
+ // production wallets so the DefaultWaitOpts 1s cadence stands; test wallets talking to in-process nodes lower it.
31
+ defaultWaitInterval;
32
+ // A wallet is instantiated for a particular chain, so chain info never changes during its lifetime.
33
+ // We cache it here because getChainInfo is called frequently (every tx simulation, send, auth wit, etc.).
34
+ nodeInfoPromise;
35
+ // Protected because we want to force wallets to instantiate their own PXE.
36
+ constructor(pxe, aztecNode, log = createLogger('wallet-sdk:base_wallet')){
37
+ this.pxe = pxe;
38
+ this.aztecNode = aztecNode;
39
+ this.log = log;
40
+ this.minFeePadding = 0.5;
41
+ this.cancellableTransactions = false;
42
+ }
43
+ scopesFrom(from, additionalScopes, sendMessagesAs) {
44
+ // The sendMessagesAs account must be in scope so that its tagging secrets can be accessed.
45
+ const tagSenderScopes = sendMessagesAs ? [
46
+ sendMessagesAs
47
+ ] : [];
48
+ const baseScopes = from === NO_FROM ? [] : [
49
+ from
50
+ ];
51
+ const allScopes = [
52
+ ...baseScopes,
53
+ ...additionalScopes,
54
+ ...tagSenderScopes
55
+ ];
56
+ const scopeSet = new Set(allScopes.map((address)=>address.toString()));
57
+ return [
58
+ ...scopeSet
59
+ ].map(AztecAddress.fromStringUnsafe);
60
+ }
61
+ /**
62
+ * Picks the sender address PXE should tag private messages with. Returns `undefined` when there is no signing
63
+ * account (`from === NO_FROM`) and no explicit override; in that case any private log emitted by the tx using
64
+ * the wallet-supplied default sender will fail the "Sender for tags is not set" assertion.
65
+ * @param from - Tx sender, or `NO_FROM`.
66
+ * @param sendMessagesAs - Explicit override.
67
+ */ senderForTagsFrom(from, sendMessagesAs) {
68
+ return sendMessagesAs ?? (from === NO_FROM ? undefined : from);
69
+ }
70
+ /**
71
+ * Returns the list of aliased contacts associated with the wallet.
72
+ * This base implementation directly returns PXE's senders, but note that in general contacts are a superset of senders.
73
+ * - Senders: Addresses we check during synching in case they sent us notes,
74
+ * - Contacts: more general concept akin to a phone's contact list.
75
+ * @returns The aliased collection of AztecAddresses that form this wallet's address book
76
+ */ async getAddressBook() {
77
+ const sources = await this.pxe.getTaggingSecretSources({
78
+ kind: 'address-derived'
79
+ });
80
+ return sources.map((source)=>({
81
+ item: source.sender,
82
+ alias: ''
83
+ }));
84
+ }
85
+ /**
86
+ * Fetches and caches the node info for the wallet's lifetime, since a wallet talks to a single network and
87
+ * node info never changes. A rejected fetch clears the cache so the next call retries instead of replaying
88
+ * the cached rejection forever — important because the gas-limit fill-in and validation (run on every send)
89
+ * depend on it.
90
+ */ getNodeInfo() {
91
+ if (!this.nodeInfoPromise) {
92
+ this.nodeInfoPromise = this.aztecNode.getNodeInfo().catch((err)=>{
93
+ this.nodeInfoPromise = undefined;
94
+ throw err;
95
+ });
96
+ }
97
+ return this.nodeInfoPromise;
98
+ }
99
+ async getChainInfo() {
100
+ const { l1ChainId, rollupVersion } = await this.getNodeInfo();
101
+ return {
102
+ chainId: new Fr(l1ChainId),
103
+ version: new Fr(rollupVersion)
104
+ };
105
+ }
106
+ /**
107
+ * Returns the maximum gas limits a single transaction may declare on this wallet's network (the
108
+ * node-advertised `txsLimits.gas`). Internal helper used to fill in default gas limits when sending a
109
+ * transaction without explicit limits, and to validate caller-provided limits before sending. Backed by
110
+ * the cached node info, since a wallet talks to a single network.
111
+ */ async getMaxTxGasLimits() {
112
+ const { txsLimits } = await this.getNodeInfo();
113
+ return new Gas(txsLimits.gas.daGas, txsLimits.gas.l2Gas);
114
+ }
115
+ async createTxExecutionRequestFromPayloadAndFee(executionPayload, from, feeOptions) {
116
+ const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
117
+ const finalExecutionPayload = feeExecutionPayload ? mergeExecutionPayloads([
118
+ feeExecutionPayload,
119
+ executionPayload
120
+ ]) : executionPayload;
121
+ const chainInfo = await this.getChainInfo();
122
+ if (from === NO_FROM) {
123
+ const entrypoint = new DefaultEntrypoint();
124
+ return entrypoint.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo);
125
+ } else {
126
+ const fromAccount = await this.getAccountFromAddress(from);
127
+ const executionOptions = {
128
+ txNonce: Fr.random(),
129
+ cancellable: this.cancellableTransactions,
130
+ // If from is an address, feeOptions include the way the account contract should handle the fee payment
131
+ feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions
132
+ };
133
+ return fromAccount.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo, executionOptions);
134
+ }
135
+ }
136
+ async createAuthWit(from, messageHashOrIntent) {
137
+ const account = await this.getAccountFromAddress(from);
138
+ const chainInfo = await this.getChainInfo();
139
+ return account.createAuthWit(messageHashOrIntent, chainInfo);
140
+ }
141
+ /**
142
+ * Request capabilities from the wallet.
143
+ *
144
+ * This method is wallet-implementation-dependent and must be provided by classes extending BaseWallet.
145
+ * Embedded wallets typically don't support capability-based authorization (no user authorization flow),
146
+ * while external wallets (browser extensions, hardware wallets) implement this to reduce authorization
147
+ * friction by allowing apps to request permissions upfront.
148
+ *
149
+ * TODO: Consider making it abstract so implementing it is a conscious decision. Leaving it as-is
150
+ * while the feature stabilizes.
151
+ *
152
+ * @param _manifest - Application capability manifest declaring what operations the app needs
153
+ */ requestCapabilities(_manifest) {
154
+ throw new Error('Not implemented');
155
+ }
156
+ async batch(methods) {
157
+ const results = [];
158
+ for (const method of methods){
159
+ const { name, args } = method;
160
+ // Type safety is guaranteed by the BatchedMethod type, which ensures that:
161
+ // 1. `name` is a valid batchable method name
162
+ // 2. `args` matches the parameter types of that specific method
163
+ // 3. The return type is correctly mapped in BatchResults<T>
164
+ // We use dynamic dispatch here for simplicity, but the types are enforced at the call site.
165
+ const fn = this[name];
166
+ const result = await fn.apply(this, args);
167
+ // Wrap result with method name for discriminated union deserialization
168
+ results.push({
169
+ name,
170
+ result
171
+ });
172
+ }
173
+ return results;
174
+ }
175
+ /**
176
+ * Completes partial user-provided fee options with wallet defaults.
177
+ * @param config - Fee completion config.
178
+ */ async completeFeeOptions(config) {
179
+ const { from, feePayer, gasSettings, forEstimation, congestionEstimate } = config;
180
+ const maxFeesPerGas = gasSettings?.maxFeesPerGas ?? (await this.getMinFees(congestionEstimate)).mul(1 + this.minFeePadding);
181
+ let accountFeePaymentMethodOptions;
182
+ // If from is an address, we need to determine the appropriate fee payment method options for the
183
+ // account contract entrypoint to use
184
+ if (from !== NO_FROM) {
185
+ if (!feePayer) {
186
+ // The transaction does not include a fee payment method, so we set the flag
187
+ // for the account to use its fee juice balance
188
+ accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
189
+ } else {
190
+ // The transaction includes fee payment method, so we check if we are the fee payer for it
191
+ // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
192
+ accountFeePaymentMethodOptions = from.equals(feePayer) ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM : AccountFeePaymentMethodOptions.EXTERNAL;
193
+ }
194
+ }
195
+ const gasSettingsOverrides = {
196
+ gasLimits: gasSettings?.gasLimits ? Gas.from(gasSettings.gasLimits) : undefined,
197
+ teardownGasLimits: gasSettings?.teardownGasLimits ? Gas.from(gasSettings.teardownGasLimits) : undefined,
198
+ maxFeesPerGas,
199
+ maxPriorityFeesPerGas: gasSettings?.maxPriorityFeesPerGas ?? GasFees.empty()
200
+ };
201
+ // When estimating gas (simulation), use high limits so the simulation doesn't run out of gas.
202
+ // When sending for real without explicit limits, declare the most a single tx may use on this network
203
+ // (the node's per-tx admission limit), so the proposer does not skip the tx for over-declaring gas.
204
+ let fullGasSettings;
205
+ if (forEstimation) {
206
+ // Estimation deliberately uses very high internal limits, which the node exempts from gas-limit
207
+ // admission during simulation, so we do not validate against the network admission limit here.
208
+ fullGasSettings = GasSettings.forEstimation(gasSettingsOverrides);
209
+ } else {
210
+ const maxTxGasLimits = await this.getMaxTxGasLimits();
211
+ // If the caller declared explicit gas limits, reject them up front when they exceed the network's
212
+ // per-tx admission limit (mirroring the node's MaxGasLimitsValidator). Otherwise fill in the limit.
213
+ if (gasSettingsOverrides.gasLimits) {
214
+ assertGasLimitsWithinNetworkLimits(gasSettingsOverrides.gasLimits, maxTxGasLimits);
215
+ }
216
+ fullGasSettings = GasSettings.fallback({
217
+ ...gasSettingsOverrides,
218
+ gasLimits: gasSettingsOverrides.gasLimits ?? maxTxGasLimits
219
+ });
220
+ }
221
+ this.log.debug(`Using L2 gas settings`, fullGasSettings);
222
+ return {
223
+ gasSettings: fullGasSettings,
224
+ walletFeePaymentMethod: undefined,
225
+ accountFeePaymentMethodOptions
226
+ };
227
+ }
228
+ /**
229
+ * Returns the worst-case min fee across predicted future slots.
230
+ * Falls back to getCurrentMinFees if the node doesn't support getPredictedMinFees.
231
+ * @param estimate - The mana usage estimate to use for fee prediction. Defaults to Limit for conservative estimation.
232
+ */ async getMinFees(estimate = ManaUsageEstimate.Limit) {
233
+ try {
234
+ const predicted = await this.aztecNode.getPredictedMinFees(estimate);
235
+ if (predicted.length === 0) {
236
+ return this.aztecNode.getCurrentMinFees();
237
+ }
238
+ return predicted.reduce((worst, fees)=>fees.feePerL2Gas > worst.feePerL2Gas ? fees : worst);
239
+ } catch (err) {
240
+ // Fallback for old nodes that don't support getPredictedMinFees.
241
+ // Only fall back on method-not-found errors (JSON-RPC code -32601); rethrow others.
242
+ if (err?.cause?.code === -32601 || err?.message?.includes('Method not found')) {
243
+ return this.aztecNode.getCurrentMinFees();
244
+ }
245
+ throw err;
246
+ }
247
+ }
248
+ async registerSender(address, _alias = '') {
249
+ await this.pxe.registerTaggingSecretSource({
250
+ kind: 'address-derived',
251
+ sender: address
252
+ });
253
+ return address;
254
+ }
255
+ async registerContract(instance, artifact, secretKeyOrKeys) {
256
+ // Classes and instances are registered independently: register the artifact (if provided) then the instance.
257
+ // Neither call validates that the artifact matches the class the instance runs, a missing artifact only surfaces
258
+ // when the contract is later simulated.
259
+ if (artifact) {
260
+ await this.pxe.registerContractClass(artifact);
261
+ }
262
+ const contractAddress = await this.pxe.registerContract(instance);
263
+ if (secretKeyOrKeys) {
264
+ // PXE never receives the account seed (from which the message-signing/fallback secret keys could be re-derived):
265
+ // the wallet derives the keys here. Of these, PXE only reads and stores the four privacy secret keys and the
266
+ // message-signing and fallback *public* keys — it never touches the message-signing or fallback secret keys.
267
+ //
268
+ // Since PXE recomputes the address from those keys, we assert it matches the instance's address: a mismatch means
269
+ // the provided keys don't correspond to this account.
270
+ const derivedKeys = secretKeyOrKeys instanceof Fr ? await deriveKeys(secretKeyOrKeys) : await deriveKeysFromMasterSecretKeys(secretKeyOrKeys);
271
+ const { address } = await this.pxe.registerAccount(derivedKeys, await computePartialAddress(instance));
272
+ if (!address.equals(contractAddress)) {
273
+ throw new Error(`Registered account address ${address.toString()} does not match contract instance address ${contractAddress.toString()}: the provided keys do not correspond to this account.`);
274
+ }
275
+ }
276
+ }
277
+ registerContractClass(artifact) {
278
+ return this.pxe.registerContractClass(artifact);
279
+ }
280
+ /**
281
+ * Simulates calls through the standard PXE path (account entrypoint).
282
+ * @param executionPayload - The execution payload to simulate.
283
+ * @param opts - Simulation options.
284
+ */ async simulateViaEntrypoint(executionPayload, opts) {
285
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, opts.feeOptions);
286
+ const result = await this.pxe.simulateTx(txRequest, {
287
+ simulatePublic: true,
288
+ skipTxValidation: opts.skipTxValidation,
289
+ skipFeeEnforcement: opts.skipFeeEnforcement,
290
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes ?? [], opts.sendMessagesAs),
291
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
292
+ overrides: opts.overrides
293
+ });
294
+ const appCallOffset = await this.computeAppCallOffset(opts.from, opts.feeOptions);
295
+ return TxSimulationResultWithAppOffset.fromResultAndOffset(result, appCallOffset);
296
+ }
297
+ /**
298
+ * Computes the index where the app's calls begin in the flattened array of calls (0 = entrypoint/root, 1..N = fee
299
+ * calls, N+1 = app).
300
+ * @param from - The sender address, or NO_FROM for the default entrypoint.
301
+ * @param feeOptions - Fee options containing the wallet fee payment method.
302
+ */ async computeAppCallOffset(from, feeOptions) {
303
+ if (from === NO_FROM) {
304
+ return 0;
305
+ }
306
+ const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
307
+ return (feeExecutionPayload?.calls.length ?? 0) + 1; // +1 for entrypoint
308
+ }
309
+ /**
310
+ * Simulates a transaction, optimizing leading public static calls by running them directly
311
+ * on the node while sending the remaining calls through the standard PXE path.
312
+ * Return values from both paths are merged back in original call order.
313
+ * @param executionPayload - The execution payload to simulate.
314
+ * @param opts - Simulation options (from address, fee settings, etc.).
315
+ * @returns The merged simulation result.
316
+ */ async simulateTx(executionPayload, opts) {
317
+ const feeOptions = await this.completeFeeOptions({
318
+ from: opts.from,
319
+ feePayer: executionPayload.feePayer,
320
+ gasSettings: opts.fee?.gasSettings,
321
+ forEstimation: true,
322
+ congestionEstimate: opts.fee?.congestionEstimate
323
+ });
324
+ const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
325
+ const remainingPayload = {
326
+ ...executionPayload,
327
+ calls: remainingCalls
328
+ };
329
+ const chainInfo = await this.getChainInfo();
330
+ let blockHeader;
331
+ // PXE might not be synced yet, so we pull the latest header from the node
332
+ // To keep things consistent, we'll always try with PXE first
333
+ try {
334
+ blockHeader = await this.pxe.getSyncedBlockHeader();
335
+ } catch {
336
+ blockHeader = (await this.aztecNode.getBlockData('latest')).header;
337
+ }
338
+ const simulationOrigin = opts.from === NO_FROM ? AztecAddress.ZERO : opts.from;
339
+ const [optimizedResults, normalResult] = await Promise.all([
340
+ optimizableCalls.length > 0 ? simulateViaNode(this.aztecNode, optimizableCalls, simulationOrigin, chainInfo, feeOptions.gasSettings, blockHeader, opts.skipFeeEnforcement ?? true, this.getContractName.bind(this), opts.overrides) : Promise.resolve([]),
341
+ remainingCalls.length > 0 ? this.simulateViaEntrypoint(remainingPayload, {
342
+ from: opts.from,
343
+ feeOptions,
344
+ additionalScopes: opts.additionalScopes,
345
+ skipTxValidation: opts.skipTxValidation,
346
+ skipFeeEnforcement: opts.skipFeeEnforcement ?? true,
347
+ sendMessagesAs: opts.sendMessagesAs,
348
+ overrides: opts.overrides
349
+ }) : Promise.resolve(null)
350
+ ]);
351
+ return buildMergedSimulationResult(optimizedResults, normalResult);
352
+ }
353
+ async profileTx(executionPayload, opts) {
354
+ const feeOptions = await this.completeFeeOptions({
355
+ from: opts.from,
356
+ feePayer: executionPayload.feePayer,
357
+ gasSettings: opts.fee?.gasSettings,
358
+ congestionEstimate: opts.fee?.congestionEstimate
359
+ });
360
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
361
+ return this.pxe.profileTx(txRequest, {
362
+ profileMode: opts.profileMode,
363
+ skipProofGeneration: opts.skipProofGeneration ?? true,
364
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes ?? [], opts.sendMessagesAs),
365
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs)
366
+ });
367
+ }
368
+ async sendTx(executionPayload, opts) {
369
+ const feeOptions = await this.completeFeeOptions({
370
+ from: opts.from,
371
+ feePayer: executionPayload.feePayer,
372
+ gasSettings: opts.fee?.gasSettings,
373
+ congestionEstimate: opts.fee?.congestionEstimate
374
+ });
375
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
376
+ const provenTx = await this.pxe.proveTx(txRequest, {
377
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes ?? [], opts.sendMessagesAs),
378
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs)
379
+ });
380
+ const offchainOutput = extractOffchainOutput(provenTx.getOffchainEffects(), provenTx.publicInputs.constants.anchorBlockHeader.globalVariables.timestamp);
381
+ const tx = await provenTx.toTx();
382
+ const txHash = tx.getTxHash();
383
+ this.log.debug(`Sending transaction ${txHash}`);
384
+ await this.aztecNode.sendTx(tx).catch((err)=>{
385
+ throw this.contextualizeError(err, inspect(tx));
386
+ });
387
+ this.log.info(`Sent transaction ${txHash}`);
388
+ // If wait is NO_WAIT, return txHash immediately
389
+ if (opts.wait === NO_WAIT) {
390
+ return {
391
+ txHash,
392
+ ...offchainOutput
393
+ };
394
+ }
395
+ // Otherwise, wait for the full receipt (default behavior on wait: undefined)
396
+ const callerWaitOpts = typeof opts.wait === 'object' ? opts.wait : undefined;
397
+ const waitOpts = this.defaultWaitInterval !== undefined && callerWaitOpts?.interval === undefined ? {
398
+ ...callerWaitOpts,
399
+ interval: this.defaultWaitInterval
400
+ } : callerWaitOpts;
401
+ // The tx was just sent, so an immediate first poll cannot find it mined; skip one poll interval up front.
402
+ const initialDelay = waitOpts?.initialDelay ?? waitOpts?.interval ?? DefaultWaitOpts.interval;
403
+ const receipt = await waitForTx(this.aztecNode, txHash, {
404
+ ...waitOpts,
405
+ initialDelay
406
+ });
407
+ // Display debug logs from public execution if present (served in test mode only)
408
+ if (receipt.isMined() && receipt.debugLogs?.length) {
409
+ await displayDebugLogs(receipt.debugLogs, this.getContractName.bind(this));
410
+ }
411
+ return {
412
+ receipt,
413
+ ...offchainOutput
414
+ };
415
+ }
416
+ /**
417
+ * Resolves a contract address to a human-readable name via PXE, if available.
418
+ * @param address - The contract address to resolve.
419
+ */ async getContractName(address) {
420
+ const instance = await this.pxe.getContractInstance(address);
421
+ if (!instance) {
422
+ return undefined;
423
+ }
424
+ // Contract names are class-stable (an upgrade preserves the contract name), so the original class artifact is a
425
+ // sufficient source for the display name without resolving the current class against the node.
426
+ // TODO: if a contract were to be upgraded and its original artifact never registered, then this would fail and we'd
427
+ // want to fallback to the current class.
428
+ const artifact = await this.pxe.getContractArtifact(instance.originalContractClassId);
429
+ return artifact?.name;
430
+ }
431
+ contextualizeError(err, ...context) {
432
+ let contextStr = '';
433
+ if (context.length > 0) {
434
+ contextStr = `\nContext:\n${context.join('\n')}`;
435
+ }
436
+ if (err instanceof SimulationError) {
437
+ err.setAztecContext(contextStr);
438
+ } else {
439
+ this.log.error(err.name, err);
440
+ this.log.debug(contextStr);
441
+ }
442
+ return err;
443
+ }
444
+ executeUtility(call, opts) {
445
+ return this.pxe.executeUtility(call, {
446
+ authwits: opts.authWitnesses,
447
+ scopes: opts.scopes
448
+ });
449
+ }
450
+ async getPrivateEvents(eventDef, eventFilter) {
451
+ const pxeEvents = await this.pxe.getPrivateEvents(eventDef.eventSelector, eventFilter);
452
+ const decodedEvents = pxeEvents.map((pxeEvent)=>{
453
+ return {
454
+ event: decodeFromAbi(eventDef.abiType, pxeEvent.packedEvent),
455
+ metadata: {
456
+ l2BlockNumber: pxeEvent.l2BlockNumber,
457
+ l2BlockHash: pxeEvent.l2BlockHash,
458
+ txHash: pxeEvent.txHash
459
+ }
460
+ };
461
+ });
462
+ return decodedEvents;
463
+ }
464
+ /**
465
+ * Returns metadata about a contract, including whether it has been initialized, published, and updated.
466
+ * @param address - The contract address to query.
467
+ */ async getContractMetadata(address) {
468
+ const instance = await this.pxe.getContractInstance(address);
469
+ const publiclyRegisteredContractPromise = this.aztecNode.getContract(address);
470
+ let initializationStatus;
471
+ if (instance) {
472
+ // We have the instance, so we can compute the private initialization nullifier (which includes init_hash and is
473
+ // emitted by both private and public initializers) and get a definitive INITIALIZED/UNINITIALIZED answer.
474
+ const initNullifier = await computeSiloedPrivateInitializationNullifier(address, instance.initializationHash);
475
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
476
+ initializationStatus = witness ? ContractInitializationStatus.INITIALIZED : ContractInitializationStatus.UNINITIALIZED;
477
+ } else {
478
+ // Without the instance we lack the init_hash needed for the private nullifier. We fall back to checking the
479
+ // public initialization nullifier (computed from address alone). Not all contracts emit it (only those with
480
+ // public functions that require initialization checks), so its absence doesn't mean the contract is
481
+ // uninitialized.
482
+ const publicNullifier = await computeSiloedPublicInitializationNullifier(address);
483
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', publicNullifier);
484
+ initializationStatus = witness ? ContractInitializationStatus.INITIALIZED : ContractInitializationStatus.UNKNOWN;
485
+ }
486
+ const publiclyRegisteredContract = await publiclyRegisteredContractPromise;
487
+ const isContractUpdated = publiclyRegisteredContract && !publiclyRegisteredContract.currentContractClassId.equals(publiclyRegisteredContract.originalContractClassId);
488
+ return {
489
+ instance: instance ?? undefined,
490
+ initializationStatus,
491
+ isContractPublished: !!publiclyRegisteredContract,
492
+ isContractUpdated: !!isContractUpdated,
493
+ updatedContractClassId: isContractUpdated ? publiclyRegisteredContract.currentContractClassId : undefined
494
+ };
495
+ }
496
+ async getContractClassMetadata(id) {
497
+ const publiclyRegisteredContractClass = await this.aztecNode.getContractClass(id);
498
+ return {
499
+ isArtifactRegistered: !!await this.pxe.getContractArtifact(id),
500
+ isContractClassPubliclyRegistered: !!publiclyRegisteredContractClass
501
+ };
502
+ }
503
+ }
@@ -0,0 +1,36 @@
1
+ import { Gas, type GasUsed } from '@aztec-labs/stdlib/gas';
2
+ /**
3
+ * Returns suggested total and teardown gas limits for a simulated tx, clamped to the network's per-tx
4
+ * admission limits.
5
+ *
6
+ * The network only admits transactions that declare up to `maxTxGasLimits` per dimension (the
7
+ * node-advertised `txsLimits.gas`). Wallets pass the value read from their own node info, but since node info
8
+ * is remote input it is defensively clamped here to the per-tx protocol maxima so a value above them is never
9
+ * honored. If the simulated usage already exceeds the resulting admission limits the tx can never be included,
10
+ * so this throws a descriptive error instead of returning a limit the node would reject. Otherwise it pads the
11
+ * usage and clamps each dimension to the admission limit.
12
+ * @param gasUsed - The gas actually consumed during simulation.
13
+ * @param maxTxGasLimits - The maximum gas a single tx may declare on this network (the node-advertised `txsLimits.gas`).
14
+ * @param pad - Fraction to pad the suggested gas limits by (as a decimal, e.g. 0.1 for 10%). The effective
15
+ * padding shrinks to zero as usage approaches the network limit, since the network will not admit a higher
16
+ * declared limit regardless of the buffer.
17
+ */
18
+ export declare function getGasLimits(gasUsed: GasUsed, maxTxGasLimits: Gas, pad?: number): {
19
+ /**
20
+ * Total gas limit for the tx, including teardown gas
21
+ */
22
+ gasLimits: Gas;
23
+ /**
24
+ * Portion of the total gas limit reserved for the teardown phase
25
+ */
26
+ teardownGasLimits: Gas;
27
+ };
28
+ /**
29
+ * Validates that caller-declared gas limits do not exceed the network's per-tx admission limits, throwing a
30
+ * descriptive error per dimension when they do. The node's inbound validation checks declared
31
+ * `gasSettings.gasLimits`, so we mirror that here to surface the rejection locally before the tx is sent.
32
+ * @param gasLimits - The gas limits the transaction will declare.
33
+ * @param maxTxGasLimits - The maximum gas a single tx may declare on this network (the node-advertised `txsLimits.gas`).
34
+ */
35
+ export declare function assertGasLimitsWithinNetworkLimits(gasLimits: Gas, maxTxGasLimits: Gas): void;
36
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2V0X2dhc19saW1pdHMuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9iYXNlLXdhbGxldC9nZXRfZ2FzX2xpbWl0cy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFDQSxPQUFPLEVBQUUsR0FBRyxFQUFFLEtBQUssT0FBTyxFQUFFLE1BQU0sd0JBQXdCLENBQUM7QUFFM0Q7Ozs7Ozs7Ozs7Ozs7OztHQWVHO0FBQ0gsd0JBQWdCLFlBQVksQ0FDMUIsT0FBTyxFQUFFLE9BQU8sRUFDaEIsY0FBYyxFQUFFLEdBQUcsRUFDbkIsR0FBRyxTQUFNLEdBQ1I7SUFDRDs7T0FFRztJQUNILFNBQVMsRUFBRSxHQUFHLENBQUM7SUFDZjs7T0FFRztJQUNILGlCQUFpQixFQUFFLEdBQUcsQ0FBQztDQUN4QixDQTZCQTtBQVFEOzs7Ozs7R0FNRztBQUNILHdCQUFnQixrQ0FBa0MsQ0FBQyxTQUFTLEVBQUUsR0FBRyxFQUFFLGNBQWMsRUFBRSxHQUFHLEdBQUcsSUFBSSxDQVc1RiJ9
@@ -0,0 +1 @@
1
+ {"version":3,"file":"get_gas_limits.d.ts","sourceRoot":"","sources":["../../src/base-wallet/get_gas_limits.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,KAAK,OAAO,EAAE,MAAM,wBAAwB,CAAC;AAE3D;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,YAAY,CAC1B,OAAO,EAAE,OAAO,EAChB,cAAc,EAAE,GAAG,EACnB,GAAG,SAAM,GACR;IACD;;OAEG;IACH,SAAS,EAAE,GAAG,CAAC;IACf;;OAEG;IACH,iBAAiB,EAAE,GAAG,CAAC;CACxB,CA6BA;AAQD;;;;;;GAMG;AACH,wBAAgB,kCAAkC,CAAC,SAAS,EAAE,GAAG,EAAE,cAAc,EAAE,GAAG,GAAG,IAAI,CAW5F"}
@@ -0,0 +1,55 @@
1
+ import { MAX_PROCESSABLE_L2_GAS, MAX_TX_DA_GAS } from '@aztec-labs/constants';
2
+ import { Gas } from '@aztec-labs/stdlib/gas';
3
+ /**
4
+ * Returns suggested total and teardown gas limits for a simulated tx, clamped to the network's per-tx
5
+ * admission limits.
6
+ *
7
+ * The network only admits transactions that declare up to `maxTxGasLimits` per dimension (the
8
+ * node-advertised `txsLimits.gas`). Wallets pass the value read from their own node info, but since node info
9
+ * is remote input it is defensively clamped here to the per-tx protocol maxima so a value above them is never
10
+ * honored. If the simulated usage already exceeds the resulting admission limits the tx can never be included,
11
+ * so this throws a descriptive error instead of returning a limit the node would reject. Otherwise it pads the
12
+ * usage and clamps each dimension to the admission limit.
13
+ * @param gasUsed - The gas actually consumed during simulation.
14
+ * @param maxTxGasLimits - The maximum gas a single tx may declare on this network (the node-advertised `txsLimits.gas`).
15
+ * @param pad - Fraction to pad the suggested gas limits by (as a decimal, e.g. 0.1 for 10%). The effective
16
+ * padding shrinks to zero as usage approaches the network limit, since the network will not admit a higher
17
+ * declared limit regardless of the buffer.
18
+ */ export function getGasLimits(gasUsed, maxTxGasLimits, pad = 0.1) {
19
+ const { totalGas, teardownGas } = gasUsed;
20
+ // `maxTxGasLimits` is the node-advertised admission limit. Node info is remote input, so we defensively
21
+ // clamp to the per-tx protocol maxima so a value above them can never be honored.
22
+ const maxLimits = new Gas(Math.min(maxTxGasLimits.daGas, MAX_TX_DA_GAS), Math.min(maxTxGasLimits.l2Gas, MAX_PROCESSABLE_L2_GAS));
23
+ // The simulated usage must fit within the admission limits, otherwise the tx can never be included.
24
+ if (totalGas.daGas > maxLimits.daGas) {
25
+ throw new Error(`Transaction consumes ${totalGas.daGas} DA gas but the network only admits transactions declaring up to ${maxLimits.daGas} DA gas`);
26
+ }
27
+ if (totalGas.l2Gas > maxLimits.l2Gas) {
28
+ throw new Error(`Transaction consumes ${totalGas.l2Gas} L2 gas but the network only admits transactions declaring up to ${maxLimits.l2Gas} L2 gas`);
29
+ }
30
+ // Pad the limits by the buffer, then cap each dimension at the admission limit so the buffer cannot push a
31
+ // declared limit past what inbound validation accepts. Teardown is part of the total, so clamping it to the
32
+ // admission limit is safe.
33
+ return {
34
+ gasLimits: padGas(totalGas, pad, maxLimits),
35
+ teardownGasLimits: padGas(teardownGas, pad, maxLimits)
36
+ };
37
+ }
38
+ /** Pads each gas dimension, capping it at the network admission limit. */ function padGas(gas, pad, cap) {
39
+ const padded = gas.mul(1 + pad);
40
+ return new Gas(Math.min(padded.daGas, cap.daGas), Math.min(padded.l2Gas, cap.l2Gas));
41
+ }
42
+ /**
43
+ * Validates that caller-declared gas limits do not exceed the network's per-tx admission limits, throwing a
44
+ * descriptive error per dimension when they do. The node's inbound validation checks declared
45
+ * `gasSettings.gasLimits`, so we mirror that here to surface the rejection locally before the tx is sent.
46
+ * @param gasLimits - The gas limits the transaction will declare.
47
+ * @param maxTxGasLimits - The maximum gas a single tx may declare on this network (the node-advertised `txsLimits.gas`).
48
+ */ export function assertGasLimitsWithinNetworkLimits(gasLimits, maxTxGasLimits) {
49
+ if (gasLimits.daGas > maxTxGasLimits.daGas) {
50
+ throw new Error(`Declared DA gas limit (${gasLimits.daGas}) exceeds the maximum this network allows per tx (${maxTxGasLimits.daGas})`);
51
+ }
52
+ if (gasLimits.l2Gas > maxTxGasLimits.l2Gas) {
53
+ throw new Error(`Declared L2 gas limit (${gasLimits.l2Gas}) exceeds the maximum this network allows per tx (${maxTxGasLimits.l2Gas})`);
54
+ }
55
+ }
@@ -0,0 +1,4 @@
1
+ export { BaseWallet, type CompleteFeeOptionsConfig, type FeeOptions, type SimulateViaEntrypointOptions, } from './base_wallet.js';
2
+ export { simulateViaNode, buildMergedSimulationResult, extractOptimizablePublicStaticCalls } from './utils.js';
3
+ export { getGasLimits, assertGasLimitsWithinNetworkLimits } from './get_gas_limits.js';
4
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9iYXNlLXdhbGxldC9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEVBQ0wsVUFBVSxFQUNWLEtBQUssd0JBQXdCLEVBQzdCLEtBQUssVUFBVSxFQUNmLEtBQUssNEJBQTRCLEdBQ2xDLE1BQU0sa0JBQWtCLENBQUM7QUFDMUIsT0FBTyxFQUFFLGVBQWUsRUFBRSwyQkFBMkIsRUFBRSxtQ0FBbUMsRUFBRSxNQUFNLFlBQVksQ0FBQztBQUMvRyxPQUFPLEVBQUUsWUFBWSxFQUFFLGtDQUFrQyxFQUFFLE1BQU0scUJBQXFCLENBQUMifQ==
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/base-wallet/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,KAAK,wBAAwB,EAC7B,KAAK,UAAU,EACf,KAAK,4BAA4B,GAClC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,eAAe,EAAE,2BAA2B,EAAE,mCAAmC,EAAE,MAAM,YAAY,CAAC;AAC/G,OAAO,EAAE,YAAY,EAAE,kCAAkC,EAAE,MAAM,qBAAqB,CAAC"}
@@ -0,0 +1,3 @@
1
+ export { BaseWallet } from './base_wallet.js';
2
+ export { simulateViaNode, buildMergedSimulationResult, extractOptimizablePublicStaticCalls } from './utils.js';
3
+ export { getGasLimits, assertGasLimitsWithinNetworkLimits } from './get_gas_limits.js';