@aztec/wallet-sdk 0.0.1-commit.f2ce05ee → 0.0.1-commit.f5a9928

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 +157 -0
  2. package/dest/base-wallet/base_wallet.d.ts +87 -42
  3. package/dest/base-wallet/base_wallet.d.ts.map +1 -1
  4. package/dest/base-wallet/base_wallet.js +315 -110
  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 +8 -4
  12. package/dest/base-wallet/utils.d.ts.map +1 -1
  13. package/dest/base-wallet/utils.js +15 -6
  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 +27 -6
  27. package/dest/extension/provider/extension_wallet.d.ts.map +1 -1
  28. package/dest/extension/provider/extension_wallet.js +89 -11
  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 +6 -5
  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 +48 -18
  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 +391 -171
  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 +24 -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 +106 -17
  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 +5 -4
  75. package/src/manager/wallet_manager.ts +55 -23
  76. package/src/types.ts +72 -0
@@ -1,16 +1,22 @@
1
- import { NO_WAIT } from '@aztec/aztec.js/contracts';
1
+ import { NO_FROM } from '@aztec/aztec.js/account';
2
+ import { DefaultWaitOpts, NO_WAIT, extractOffchainOutput } from '@aztec/aztec.js/contracts';
2
3
  import { waitForTx } from '@aztec/aztec.js/node';
3
- import { GAS_ESTIMATION_DA_GAS_LIMIT, GAS_ESTIMATION_L2_GAS_LIMIT, GAS_ESTIMATION_TEARDOWN_DA_GAS_LIMIT, GAS_ESTIMATION_TEARDOWN_L2_GAS_LIMIT } from '@aztec/constants';
4
+ import { ContractInitializationStatus, TxSimulationResultWithAppOffset } from '@aztec/aztec.js/wallet';
4
5
  import { AccountFeePaymentMethodOptions } from '@aztec/entrypoints/account';
6
+ import { DefaultEntrypoint } from '@aztec/entrypoints/default';
5
7
  import { Fr } from '@aztec/foundation/curves/bn254';
6
8
  import { createLogger } from '@aztec/foundation/log';
9
+ import { displayDebugLogs } from '@aztec/pxe/client/lazy';
7
10
  import { decodeFromAbi } from '@aztec/stdlib/abi';
8
- import { computePartialAddress, getContractClassFromArtifact } from '@aztec/stdlib/contract';
11
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
12
+ import { computePartialAddress } from '@aztec/stdlib/contract';
9
13
  import { SimulationError } from '@aztec/stdlib/errors';
10
- import { Gas, GasSettings } from '@aztec/stdlib/gas';
11
- import { siloNullifier } from '@aztec/stdlib/hash';
14
+ import { Gas, GasFees, GasSettings, ManaUsageEstimate } from '@aztec/stdlib/gas';
15
+ import { computeSiloedPrivateInitializationNullifier, computeSiloedPublicInitializationNullifier } from '@aztec/stdlib/hash';
16
+ import { deriveKeys, deriveKeysFromMasterSecretKeys } from '@aztec/stdlib/keys';
12
17
  import { mergeExecutionPayloads } from '@aztec/stdlib/tx';
13
18
  import { inspect } from 'util';
19
+ import { assertGasLimitsWithinNetworkLimits } from './get_gas_limits.js';
14
20
  import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simulateViaNode } from './utils.js';
15
21
  /**
16
22
  * A base class for Wallet implementations
@@ -20,14 +26,47 @@ import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simul
20
26
  log;
21
27
  minFeePadding;
22
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;
23
35
  // Protected because we want to force wallets to instantiate their own PXE.
24
- constructor(pxe, aztecNode){
36
+ constructor(pxe, aztecNode, log = createLogger('wallet-sdk:base_wallet')){
25
37
  this.pxe = pxe;
26
38
  this.aztecNode = aztecNode;
27
- this.log = createLogger('wallet-sdk:base_wallet');
39
+ this.log = log;
28
40
  this.minFeePadding = 0.5;
29
41
  this.cancellableTransactions = false;
30
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
+ }
31
70
  /**
32
71
  * Returns the list of aliased contacts associated with the wallet.
33
72
  * This base implementation directly returns PXE's senders, but note that in general contacts are a superset of senders.
@@ -35,33 +74,64 @@ import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simul
35
74
  * - Contacts: more general concept akin to a phone's contact list.
36
75
  * @returns The aliased collection of AztecAddresses that form this wallet's address book
37
76
  */ async getAddressBook() {
38
- const senders = await this.pxe.getSenders();
39
- return senders.map((sender)=>({
40
- item: sender,
77
+ const sources = await this.pxe.getTaggingSecretSources({
78
+ kind: 'address-derived'
79
+ });
80
+ return sources.map((source)=>({
81
+ item: source.sender,
41
82
  alias: ''
42
83
  }));
43
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
+ }
44
99
  async getChainInfo() {
45
- const { l1ChainId, rollupVersion } = await this.aztecNode.getNodeInfo();
100
+ const { l1ChainId, rollupVersion } = await this.getNodeInfo();
46
101
  return {
47
102
  chainId: new Fr(l1ChainId),
48
103
  version: new Fr(rollupVersion)
49
104
  };
50
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
+ }
51
115
  async createTxExecutionRequestFromPayloadAndFee(executionPayload, from, feeOptions) {
52
116
  const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
53
- const executionOptions = {
54
- txNonce: Fr.random(),
55
- cancellable: this.cancellableTransactions,
56
- feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions
57
- };
58
117
  const finalExecutionPayload = feeExecutionPayload ? mergeExecutionPayloads([
59
118
  feeExecutionPayload,
60
119
  executionPayload
61
120
  ]) : executionPayload;
62
- const fromAccount = await this.getAccountFromAddress(from);
63
121
  const chainInfo = await this.getChainInfo();
64
- return fromAccount.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo, executionOptions);
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
+ }
65
135
  }
66
136
  async createAuthWit(from, messageHashOrIntent) {
67
137
  const account = await this.getAccountFromAddress(from);
@@ -104,26 +174,50 @@ import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simul
104
174
  }
105
175
  /**
106
176
  * Completes partial user-provided fee options with wallet defaults.
107
- * @param from - The address where the transaction is being sent from
108
- * @param feePayer - The address paying for fees (if any fee payment method is embedded in the execution payload)
109
- * @param gasSettings - User-provided partial gas settings
110
- * @returns - Complete fee options that can be used to create a transaction execution request
111
- */ async completeFeeOptions(from, feePayer, gasSettings) {
112
- const maxFeesPerGas = gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentMinFees()).mul(1 + this.minFeePadding);
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);
113
181
  let accountFeePaymentMethodOptions;
114
- // The transaction does not include a fee payment method, so we set the flag
115
- // for the account to use its fee juice balance
116
- if (!feePayer) {
117
- accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
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 and skips tx validation, so we do not
207
+ // validate against the network admission limit here.
208
+ fullGasSettings = GasSettings.forEstimation(gasSettingsOverrides);
118
209
  } else {
119
- // The transaction includes fee payment method, so we check if we are the fee payer for it
120
- // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
121
- accountFeePaymentMethodOptions = from.equals(feePayer) ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM : AccountFeePaymentMethodOptions.EXTERNAL;
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 GasLimitsValidator). 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
+ });
122
220
  }
123
- const fullGasSettings = GasSettings.default({
124
- ...gasSettings,
125
- maxFeesPerGas
126
- });
127
221
  this.log.debug(`Using L2 gas settings`, fullGasSettings);
128
222
  return {
129
223
  gasSettings: fullGasSettings,
@@ -132,68 +226,85 @@ import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simul
132
226
  };
133
227
  }
134
228
  /**
135
- * Completes partial user-provided fee options with unreasonably high gas limits
136
- * for gas estimation. Uses the same logic as completeFeeOptions but sets high limits
137
- * to avoid running out of gas during estimation.
138
- * @param from - The address where the transaction is being sent from
139
- * @param feePayer - The address paying for fees (if any fee payment method is embedded in the execution payload)
140
- * @param gasSettings - User-provided partial gas settings
141
- */ async completeFeeOptionsForEstimation(from, feePayer, gasSettings) {
142
- const defaultFeeOptions = await this.completeFeeOptions(from, feePayer, gasSettings);
143
- const { gasSettings: { maxFeesPerGas, maxPriorityFeesPerGas } } = defaultFeeOptions;
144
- // Use unrealistically high gas limits for estimation to avoid running out of gas.
145
- // They will be tuned down after the simulation.
146
- const gasSettingsForEstimation = new GasSettings(new Gas(GAS_ESTIMATION_DA_GAS_LIMIT, GAS_ESTIMATION_L2_GAS_LIMIT), new Gas(GAS_ESTIMATION_TEARDOWN_DA_GAS_LIMIT, GAS_ESTIMATION_TEARDOWN_L2_GAS_LIMIT), maxFeesPerGas, maxPriorityFeesPerGas);
147
- return {
148
- ...defaultFeeOptions,
149
- gasSettings: gasSettingsForEstimation
150
- };
151
- }
152
- registerSender(address, _alias = '') {
153
- return this.pxe.registerSender(address);
154
- }
155
- async registerContract(instance, artifact, secretKey) {
156
- const existingInstance = await this.pxe.getContractInstance(instance.address);
157
- if (existingInstance) {
158
- // Instance already registered in the wallet
159
- if (artifact) {
160
- const thisContractClass = await getContractClassFromArtifact(artifact);
161
- if (!thisContractClass.id.equals(existingInstance.currentContractClassId)) {
162
- // wallet holds an outdated version of this contract
163
- await this.pxe.updateContract(instance.address, artifact);
164
- instance.currentContractClassId = thisContractClass.id;
165
- }
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();
166
237
  }
167
- // If no artifact provided, we just use the existing registration
168
- } else {
169
- // Instance not registered yet
170
- if (!artifact) {
171
- // Try to get the artifact from the wallet's contract class storage
172
- artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
173
- if (!artifact) {
174
- throw new Error(`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()}`);
175
- }
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();
176
244
  }
177
- await this.pxe.registerContract({
178
- artifact,
179
- instance
180
- });
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);
181
261
  }
182
- if (secretKey) {
183
- await this.pxe.registerAccount(secretKey, await computePartialAddress(instance));
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
+ }
184
275
  }
185
- return instance;
276
+ }
277
+ registerContractClass(artifact) {
278
+ return this.pxe.registerContractClass(artifact);
186
279
  }
187
280
  /**
188
281
  * Simulates calls through the standard PXE path (account entrypoint).
189
282
  * @param executionPayload - The execution payload to simulate.
190
- * @param from - The sender address.
191
- * @param feeOptions - Fee options for the transaction.
192
- * @param skipTxValidation - Whether to skip tx validation.
193
- * @param skipFeeEnforcement - Whether to skip fee enforcement.
194
- */ async simulateViaEntrypoint(executionPayload, from, feeOptions, skipTxValidation, skipFeeEnforcement) {
195
- const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, from, feeOptions);
196
- return this.pxe.simulateTx(txRequest, true, skipTxValidation, skipFeeEnforcement);
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
197
308
  }
198
309
  /**
199
310
  * Simulates a transaction, optimizing leading public static calls by running them directly
@@ -203,34 +314,72 @@ import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simul
203
314
  * @param opts - Simulation options (from address, fee settings, etc.).
204
315
  * @returns The merged simulation result.
205
316
  */ async simulateTx(executionPayload, opts) {
206
- const feeOptions = opts.fee?.estimateGas ? await this.completeFeeOptionsForEstimation(opts.from, executionPayload.feePayer, opts.fee?.gasSettings) : await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
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
+ });
207
324
  const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
208
325
  const remainingPayload = {
209
326
  ...executionPayload,
210
327
  calls: remainingCalls
211
328
  };
212
329
  const chainInfo = await this.getChainInfo();
213
- const blockHeader = await this.pxe.getSyncedBlockHeader();
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;
214
339
  const [optimizedResults, normalResult] = await Promise.all([
215
- optimizableCalls.length > 0 ? simulateViaNode(this.aztecNode, optimizableCalls, opts.from, chainInfo, feeOptions.gasSettings, blockHeader, opts.skipFeeEnforcement ?? true) : Promise.resolve([]),
216
- remainingCalls.length > 0 ? this.simulateViaEntrypoint(remainingPayload, opts.from, feeOptions, opts.skipTxValidation, opts.skipFeeEnforcement ?? true) : Promise.resolve(null)
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)
217
350
  ]);
218
351
  return buildMergedSimulationResult(optimizedResults, normalResult);
219
352
  }
220
353
  async profileTx(executionPayload, opts) {
221
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
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
+ });
222
360
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
223
- return this.pxe.profileTx(txRequest, opts.profileMode, opts.skipProofGeneration ?? true);
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
+ });
224
367
  }
225
368
  async sendTx(executionPayload, opts) {
226
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
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
+ });
227
375
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
228
- const provenTx = await this.pxe.proveTx(txRequest);
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);
229
381
  const tx = await provenTx.toTx();
230
382
  const txHash = tx.getTxHash();
231
- if (await this.aztecNode.getTxEffect(txHash)) {
232
- throw new Error(`A settled tx with equal hash ${txHash.toString()} exists.`);
233
- }
234
383
  this.log.debug(`Sending transaction ${txHash}`);
235
384
  await this.aztecNode.sendTx(tx).catch((err)=>{
236
385
  throw this.contextualizeError(err, inspect(tx));
@@ -238,11 +387,46 @@ import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simul
238
387
  this.log.info(`Sent transaction ${txHash}`);
239
388
  // If wait is NO_WAIT, return txHash immediately
240
389
  if (opts.wait === NO_WAIT) {
241
- return txHash;
390
+ return {
391
+ txHash,
392
+ ...offchainOutput
393
+ };
242
394
  }
243
395
  // Otherwise, wait for the full receipt (default behavior on wait: undefined)
244
- const waitOpts = typeof opts.wait === 'object' ? opts.wait : undefined;
245
- return await waitForTx(this.aztecNode, txHash, waitOpts);
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;
246
430
  }
247
431
  contextualizeError(err, ...context) {
248
432
  let contextStr = '';
@@ -257,8 +441,11 @@ import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simul
257
441
  }
258
442
  return err;
259
443
  }
260
- simulateUtility(call, authwits) {
261
- return this.pxe.simulateUtility(call, authwits);
444
+ executeUtility(call, opts) {
445
+ return this.pxe.executeUtility(call, {
446
+ authwits: opts.authWitnesses,
447
+ scopes: opts.scopes
448
+ });
262
449
  }
263
450
  async getPrivateEvents(eventDef, eventFilter) {
264
451
  const pxeEvents = await this.pxe.getPrivateEvents(eventDef.eventSelector, eventFilter);
@@ -276,15 +463,33 @@ import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simul
276
463
  });
277
464
  return decodedEvents;
278
465
  }
279
- async getContractMetadata(address) {
466
+ /**
467
+ * Returns metadata about a contract, including whether it has been initialized, published, and updated.
468
+ * @param address - The contract address to query.
469
+ */ async getContractMetadata(address) {
280
470
  const instance = await this.pxe.getContractInstance(address);
281
- const initNullifier = await siloNullifier(address, address.toField());
282
- const publiclyRegisteredContract = await this.aztecNode.getContract(address);
283
- const initNullifierMembershipWitness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
471
+ const publiclyRegisteredContractPromise = this.aztecNode.getContract(address);
472
+ let initializationStatus;
473
+ if (instance) {
474
+ // We have the instance, so we can compute the private initialization nullifier (which includes init_hash and is
475
+ // emitted by both private and public initializers) and get a definitive INITIALIZED/UNINITIALIZED answer.
476
+ const initNullifier = await computeSiloedPrivateInitializationNullifier(address, instance.initializationHash);
477
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
478
+ initializationStatus = witness ? ContractInitializationStatus.INITIALIZED : ContractInitializationStatus.UNINITIALIZED;
479
+ } else {
480
+ // Without the instance we lack the init_hash needed for the private nullifier. We fall back to checking the
481
+ // public initialization nullifier (computed from address alone). Not all contracts emit it (only those with
482
+ // public functions that require initialization checks), so its absence doesn't mean the contract is
483
+ // uninitialized.
484
+ const publicNullifier = await computeSiloedPublicInitializationNullifier(address);
485
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', publicNullifier);
486
+ initializationStatus = witness ? ContractInitializationStatus.INITIALIZED : ContractInitializationStatus.UNKNOWN;
487
+ }
488
+ const publiclyRegisteredContract = await publiclyRegisteredContractPromise;
284
489
  const isContractUpdated = publiclyRegisteredContract && !publiclyRegisteredContract.currentContractClassId.equals(publiclyRegisteredContract.originalContractClassId);
285
490
  return {
286
491
  instance: instance ?? undefined,
287
- isContractInitialized: !!initNullifierMembershipWitness,
492
+ initializationStatus,
288
493
  isContractPublished: !!publiclyRegisteredContract,
289
494
  isContractUpdated: !!isContractUpdated,
290
495
  updatedContractClassId: isContractUpdated ? publiclyRegisteredContract.currentContractClassId : undefined
@@ -0,0 +1,36 @@
1
+ import { Gas, type GasUsed } from '@aztec/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
+ * Gas limit for the tx, excluding teardown gas
21
+ */
22
+ gasLimits: Gas;
23
+ /**
24
+ * Gas limit 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,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2V0X2dhc19saW1pdHMuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9iYXNlLXdhbGxldC9nZXRfZ2FzX2xpbWl0cy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFDQSxPQUFPLEVBQUUsR0FBRyxFQUFFLEtBQUssT0FBTyxFQUFFLE1BQU0sbUJBQW1CLENBQUM7QUFFdEQ7Ozs7Ozs7Ozs7Ozs7OztHQWVHO0FBQ0gsd0JBQWdCLFlBQVksQ0FDMUIsT0FBTyxFQUFFLE9BQU8sRUFDaEIsY0FBYyxFQUFFLEdBQUcsRUFDbkIsR0FBRyxTQUFNLEdBQ1I7SUFDRDs7T0FFRztJQUNILFNBQVMsRUFBRSxHQUFHLENBQUM7SUFDZjs7T0FFRztJQUNILGlCQUFpQixFQUFFLEdBQUcsQ0FBQztDQUN4QixDQTZCQTtBQVFEOzs7Ozs7R0FNRztBQUNILHdCQUFnQixrQ0FBa0MsQ0FBQyxTQUFTLEVBQUUsR0FBRyxFQUFFLGNBQWMsRUFBRSxHQUFHLEdBQUcsSUFBSSxDQVc1RiJ9
@@ -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,mBAAmB,CAAC;AAEtD;;;;;;;;;;;;;;;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"}