@aztec/wallet-sdk 0.0.1-commit.96bb3f7 → 0.0.1-commit.993d240

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 (101) hide show
  1. package/README.md +218 -355
  2. package/dest/base-wallet/base_wallet.d.ts +109 -40
  3. package/dest/base-wallet/base_wallet.d.ts.map +1 -1
  4. package/dest/base-wallet/base_wallet.js +286 -71
  5. package/dest/base-wallet/index.d.ts +3 -2
  6. package/dest/base-wallet/index.d.ts.map +1 -1
  7. package/dest/base-wallet/index.js +1 -0
  8. package/dest/base-wallet/utils.d.ts +52 -0
  9. package/dest/base-wallet/utils.d.ts.map +1 -0
  10. package/dest/base-wallet/utils.js +137 -0
  11. package/dest/crypto.d.ts +111 -27
  12. package/dest/crypto.d.ts.map +1 -1
  13. package/dest/crypto.js +307 -41
  14. package/dest/emoji_alphabet.d.ts +35 -0
  15. package/dest/emoji_alphabet.d.ts.map +1 -0
  16. package/dest/emoji_alphabet.js +299 -0
  17. package/dest/extension/handlers/background_connection_handler.d.ts +168 -0
  18. package/dest/extension/handlers/background_connection_handler.d.ts.map +1 -0
  19. package/dest/extension/handlers/background_connection_handler.js +294 -0
  20. package/dest/extension/handlers/content_script_connection_handler.d.ts +57 -0
  21. package/dest/extension/handlers/content_script_connection_handler.d.ts.map +1 -0
  22. package/dest/extension/handlers/content_script_connection_handler.js +193 -0
  23. package/dest/extension/handlers/index.d.ts +12 -0
  24. package/dest/extension/handlers/index.d.ts.map +1 -0
  25. package/dest/extension/handlers/index.js +10 -0
  26. package/dest/extension/handlers/internal_message_types.d.ts +65 -0
  27. package/dest/extension/handlers/internal_message_types.d.ts.map +1 -0
  28. package/dest/extension/handlers/internal_message_types.js +24 -0
  29. package/dest/extension/provider/extension_provider.d.ts +107 -0
  30. package/dest/extension/provider/extension_provider.d.ts.map +1 -0
  31. package/dest/extension/provider/extension_provider.js +160 -0
  32. package/dest/extension/provider/extension_wallet.d.ts +152 -0
  33. package/dest/extension/provider/extension_wallet.d.ts.map +1 -0
  34. package/dest/extension/provider/extension_wallet.js +349 -0
  35. package/dest/extension/provider/index.d.ts +3 -0
  36. package/dest/extension/provider/index.d.ts.map +1 -0
  37. package/dest/{providers/extension → extension/provider}/index.js +0 -1
  38. package/dest/iframe/handlers/iframe_connection_handler.d.ts +122 -0
  39. package/dest/iframe/handlers/iframe_connection_handler.d.ts.map +1 -0
  40. package/dest/iframe/handlers/iframe_connection_handler.js +239 -0
  41. package/dest/iframe/handlers/index.d.ts +2 -0
  42. package/dest/iframe/handlers/index.d.ts.map +1 -0
  43. package/dest/iframe/handlers/index.js +1 -0
  44. package/dest/iframe/provider/iframe_discovery.d.ts +25 -0
  45. package/dest/iframe/provider/iframe_discovery.d.ts.map +1 -0
  46. package/dest/iframe/provider/iframe_discovery.js +167 -0
  47. package/dest/iframe/provider/iframe_provider.d.ts +65 -0
  48. package/dest/iframe/provider/iframe_provider.d.ts.map +1 -0
  49. package/dest/iframe/provider/iframe_provider.js +257 -0
  50. package/dest/iframe/provider/iframe_wallet.d.ts +85 -0
  51. package/dest/iframe/provider/iframe_wallet.d.ts.map +1 -0
  52. package/dest/iframe/provider/iframe_wallet.js +269 -0
  53. package/dest/iframe/provider/index.d.ts +4 -0
  54. package/dest/iframe/provider/index.d.ts.map +1 -0
  55. package/dest/iframe/provider/index.js +3 -0
  56. package/dest/manager/index.d.ts +2 -7
  57. package/dest/manager/index.d.ts.map +1 -1
  58. package/dest/manager/index.js +0 -4
  59. package/dest/manager/types.d.ts +109 -5
  60. package/dest/manager/types.d.ts.map +1 -1
  61. package/dest/manager/types.js +17 -1
  62. package/dest/manager/wallet_manager.d.ts +50 -7
  63. package/dest/manager/wallet_manager.d.ts.map +1 -1
  64. package/dest/manager/wallet_manager.js +208 -29
  65. package/dest/types.d.ts +117 -15
  66. package/dest/types.d.ts.map +1 -1
  67. package/dest/types.js +39 -2
  68. package/package.json +22 -11
  69. package/src/base-wallet/base_wallet.ts +395 -128
  70. package/src/base-wallet/index.ts +7 -1
  71. package/src/base-wallet/utils.ts +248 -0
  72. package/src/crypto.ts +367 -47
  73. package/src/emoji_alphabet.ts +317 -0
  74. package/src/extension/handlers/background_connection_handler.ts +456 -0
  75. package/src/extension/handlers/content_script_connection_handler.ts +264 -0
  76. package/src/extension/handlers/index.ts +25 -0
  77. package/src/extension/handlers/internal_message_types.ts +71 -0
  78. package/src/extension/provider/extension_provider.ts +233 -0
  79. package/src/extension/provider/extension_wallet.ts +410 -0
  80. package/src/extension/provider/index.ts +7 -0
  81. package/src/iframe/handlers/iframe_connection_handler.ts +341 -0
  82. package/src/iframe/handlers/index.ts +7 -0
  83. package/src/iframe/provider/iframe_discovery.ts +185 -0
  84. package/src/iframe/provider/iframe_provider.ts +331 -0
  85. package/src/iframe/provider/iframe_wallet.ts +323 -0
  86. package/src/iframe/provider/index.ts +3 -0
  87. package/src/manager/index.ts +3 -9
  88. package/src/manager/types.ts +113 -4
  89. package/src/manager/wallet_manager.ts +235 -30
  90. package/src/types.ts +129 -14
  91. package/dest/providers/extension/extension_provider.d.ts +0 -17
  92. package/dest/providers/extension/extension_provider.d.ts.map +0 -1
  93. package/dest/providers/extension/extension_provider.js +0 -56
  94. package/dest/providers/extension/extension_wallet.d.ts +0 -95
  95. package/dest/providers/extension/extension_wallet.d.ts.map +0 -1
  96. package/dest/providers/extension/extension_wallet.js +0 -225
  97. package/dest/providers/extension/index.d.ts +0 -5
  98. package/dest/providers/extension/index.d.ts.map +0 -1
  99. package/src/providers/extension/extension_provider.ts +0 -72
  100. package/src/providers/extension/extension_wallet.ts +0 -275
  101. package/src/providers/extension/index.ts +0 -11
@@ -1,29 +1,37 @@
1
- import type { Account } from '@aztec/aztec.js/account';
1
+ import type { Account, NoFrom } from '@aztec/aztec.js/account';
2
+ import { NO_FROM } from '@aztec/aztec.js/account';
2
3
  import type { CallIntent, IntentInnerHash } from '@aztec/aztec.js/authorization';
4
+ import {
5
+ type InteractionWaitOptions,
6
+ NO_WAIT,
7
+ type SendReturn,
8
+ extractOffchainOutput,
9
+ } from '@aztec/aztec.js/contracts';
3
10
  import type { FeePaymentMethod } from '@aztec/aztec.js/fee';
4
- import type {
5
- Aliased,
6
- BatchResults,
7
- BatchableMethods,
8
- BatchedMethod,
9
- PrivateEvent,
10
- PrivateEventFilter,
11
- ProfileOptions,
12
- SendOptions,
13
- SimulateOptions,
14
- Wallet,
15
- } from '@aztec/aztec.js/wallet';
11
+ import { waitForTx } from '@aztec/aztec.js/node';
16
12
  import {
17
- GAS_ESTIMATION_DA_GAS_LIMIT,
18
- GAS_ESTIMATION_L2_GAS_LIMIT,
19
- GAS_ESTIMATION_TEARDOWN_DA_GAS_LIMIT,
20
- GAS_ESTIMATION_TEARDOWN_L2_GAS_LIMIT,
21
- } from '@aztec/constants';
13
+ type Aliased,
14
+ type AppCapabilities,
15
+ type BatchResults,
16
+ type BatchedMethod,
17
+ ContractInitializationStatus,
18
+ type ExecuteUtilityOptions,
19
+ type PrivateEvent,
20
+ type PrivateEventFilter,
21
+ type ProfileOptions,
22
+ type SendOptions,
23
+ type SimulateOptions,
24
+ TxSimulationResultWithAppOffset,
25
+ type Wallet,
26
+ type WalletCapabilities,
27
+ } from '@aztec/aztec.js/wallet';
22
28
  import { AccountFeePaymentMethodOptions, type DefaultAccountEntrypointOptions } from '@aztec/entrypoints/account';
29
+ import { DefaultEntrypoint } from '@aztec/entrypoints/default';
23
30
  import type { ChainInfo } from '@aztec/entrypoints/interfaces';
24
31
  import { Fr } from '@aztec/foundation/curves/bn254';
25
32
  import { createLogger } from '@aztec/foundation/log';
26
33
  import type { FieldsOf } from '@aztec/foundation/types';
34
+ import { displayDebugLogs } from '@aztec/pxe/client/lazy';
27
35
  import type { PXE, PackedPrivateEvent } from '@aztec/pxe/server';
28
36
  import {
29
37
  type ContractArtifact,
@@ -32,29 +40,33 @@ import {
32
40
  decodeFromAbi,
33
41
  } from '@aztec/stdlib/abi';
34
42
  import type { AuthWitness } from '@aztec/stdlib/auth-witness';
35
- import type { AztecAddress } from '@aztec/stdlib/aztec-address';
43
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
36
44
  import {
37
- type ContractClassMetadata,
38
45
  type ContractInstanceWithAddress,
39
- type ContractMetadata,
46
+ type NodeInfo,
40
47
  computePartialAddress,
41
48
  getContractClassFromArtifact,
42
49
  } from '@aztec/stdlib/contract';
43
50
  import { SimulationError } from '@aztec/stdlib/errors';
44
- import { Gas, GasSettings } from '@aztec/stdlib/gas';
51
+ import { Gas, GasFees, GasSettings, ManaUsageEstimate } from '@aztec/stdlib/gas';
52
+ import {
53
+ computeSiloedPrivateInitializationNullifier,
54
+ computeSiloedPublicInitializationNullifier,
55
+ } from '@aztec/stdlib/hash';
45
56
  import type { AztecNode } from '@aztec/stdlib/interfaces/client';
46
- import type {
47
- TxExecutionRequest,
48
- TxHash,
49
- TxProfileResult,
50
- TxReceipt,
51
- TxSimulationResult,
52
- UtilitySimulationResult,
57
+ import {
58
+ BlockHeader,
59
+ ExecutionPayload,
60
+ type TxExecutionRequest,
61
+ type TxProfileResult,
62
+ type UtilityExecutionResult,
63
+ mergeExecutionPayloads,
53
64
  } from '@aztec/stdlib/tx';
54
- import { ExecutionPayload, mergeExecutionPayloads } from '@aztec/stdlib/tx';
55
65
 
56
66
  import { inspect } from 'util';
57
67
 
68
+ import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simulateViaNode } from './utils.js';
69
+
58
70
  /**
59
71
  * Options to configure fee payment for a transaction
60
72
  */
@@ -65,26 +77,71 @@ export type FeeOptions = {
65
77
  */
66
78
  walletFeePaymentMethod?: FeePaymentMethod;
67
79
  /** Configuration options for the account to properly handle the selected fee payment method */
68
- accountFeePaymentMethodOptions: AccountFeePaymentMethodOptions;
80
+ accountFeePaymentMethodOptions?: AccountFeePaymentMethodOptions;
69
81
  /** The gas settings to use for the transaction */
70
82
  gasSettings: GasSettings;
71
83
  };
72
84
 
85
+ /** Options for `simulateViaEntrypoint`. */
86
+ export type SimulateViaEntrypointOptions = Pick<
87
+ SimulateOptions,
88
+ 'from' | 'additionalScopes' | 'skipTxValidation' | 'skipFeeEnforcement' | 'sendMessagesAs' | 'overrides'
89
+ > & {
90
+ /** Fee options for the entrypoint */
91
+ feeOptions: FeeOptions;
92
+ };
93
+
94
+ /** Options for `completeFeeOptions`. */
95
+ export type CompleteFeeOptionsConfig = {
96
+ /** The address where the transaction is being sent from. */
97
+ from: AztecAddress | NoFrom;
98
+ /** The address paying for fees (if any fee payment method is embedded in the execution payload). */
99
+ feePayer?: AztecAddress;
100
+ /** User-provided partial gas settings. */
101
+ gasSettings?: Partial<FieldsOf<GasSettings>>;
102
+ /** If true, returns gas settings with high gas limits for estimation. If false, uses fallback limits. */
103
+ forEstimation?: boolean;
104
+ /**
105
+ * Assumed network congestion level for fee prediction. Controls how aggressively the wallet
106
+ * estimates future fees. Defaults to Limit (worst case) when not specified.
107
+ */
108
+ congestionEstimate?: ManaUsageEstimate;
109
+ };
110
+
73
111
  /**
74
112
  * A base class for Wallet implementations
75
113
  */
76
114
  export abstract class BaseWallet implements Wallet {
77
- protected log = createLogger('wallet-sdk:base_wallet');
78
-
79
115
  protected minFeePadding = 0.5;
80
116
  protected cancellableTransactions = false;
117
+ // A wallet is instantiated for a particular chain, so chain info never changes during its lifetime.
118
+ // We cache it here because getChainInfo is called frequently (every tx simulation, send, auth wit, etc.).
119
+ private nodeInfoPromise: Promise<NodeInfo> | undefined;
81
120
 
82
121
  // Protected because we want to force wallets to instantiate their own PXE.
83
122
  protected constructor(
84
123
  protected readonly pxe: PXE,
85
124
  protected readonly aztecNode: AztecNode,
125
+ protected log = createLogger('wallet-sdk:base_wallet'),
86
126
  ) {}
87
127
 
128
+ protected scopesFrom(from: AztecAddress | NoFrom, additionalScopes: AztecAddress[] = []): AztecAddress[] {
129
+ const allScopes = from === NO_FROM ? additionalScopes : [from, ...additionalScopes];
130
+ const scopeSet = new Set(allScopes.map(address => address.toString()));
131
+ return [...scopeSet].map(AztecAddress.fromString);
132
+ }
133
+
134
+ /**
135
+ * Picks the sender address PXE should tag private messages with. Returns `undefined` when there is no signing
136
+ * account (`from === NO_FROM`) and no explicit override; in that case any private log emitted by the tx using
137
+ * the wallet-supplied default sender will fail the "Sender for tags is not set" assertion.
138
+ * @param from - Tx sender, or `NO_FROM`.
139
+ * @param sendMessagesAs - Explicit override.
140
+ */
141
+ protected senderForTagsFrom(from: AztecAddress | NoFrom, sendMessagesAs?: AztecAddress): AztecAddress | undefined {
142
+ return sendMessagesAs ?? (from === NO_FROM ? undefined : from);
143
+ }
144
+
88
145
  protected abstract getAccountFromAddress(address: AztecAddress): Promise<Account>;
89
146
 
90
147
  abstract getAccounts(): Promise<Aliased<AztecAddress>[]>;
@@ -102,39 +159,71 @@ export abstract class BaseWallet implements Wallet {
102
159
  }
103
160
 
104
161
  async getChainInfo(): Promise<ChainInfo> {
105
- const { l1ChainId, rollupVersion } = await this.aztecNode.getNodeInfo();
162
+ if (!this.nodeInfoPromise) {
163
+ this.nodeInfoPromise = this.aztecNode.getNodeInfo();
164
+ }
165
+ const { l1ChainId, rollupVersion } = await this.nodeInfoPromise;
106
166
  return { chainId: new Fr(l1ChainId), version: new Fr(rollupVersion) };
107
167
  }
108
168
 
109
169
  protected async createTxExecutionRequestFromPayloadAndFee(
110
170
  executionPayload: ExecutionPayload,
111
- from: AztecAddress,
171
+ from: AztecAddress | NoFrom,
112
172
  feeOptions: FeeOptions,
113
173
  ): Promise<TxExecutionRequest> {
114
174
  const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
115
- const executionOptions: DefaultAccountEntrypointOptions = {
116
- txNonce: Fr.random(),
117
- cancellable: this.cancellableTransactions,
118
- feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions,
119
- };
120
175
  const finalExecutionPayload = feeExecutionPayload
121
176
  ? mergeExecutionPayloads([feeExecutionPayload, executionPayload])
122
177
  : executionPayload;
123
- const fromAccount = await this.getAccountFromAddress(from);
124
- return fromAccount.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, executionOptions);
178
+ const chainInfo = await this.getChainInfo();
179
+
180
+ if (from === NO_FROM) {
181
+ const entrypoint = new DefaultEntrypoint();
182
+ return entrypoint.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo);
183
+ } else {
184
+ const fromAccount = await this.getAccountFromAddress(from);
185
+ const executionOptions: DefaultAccountEntrypointOptions = {
186
+ txNonce: Fr.random(),
187
+ cancellable: this.cancellableTransactions,
188
+ // If from is an address, feeOptions include the way the account contract should handle the fee payment
189
+ feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions!,
190
+ };
191
+ return fromAccount.createTxExecutionRequest(
192
+ finalExecutionPayload,
193
+ feeOptions.gasSettings,
194
+ chainInfo,
195
+ executionOptions,
196
+ );
197
+ }
125
198
  }
126
199
 
127
200
  public async createAuthWit(
128
201
  from: AztecAddress,
129
- messageHashOrIntent: Fr | IntentInnerHash | CallIntent,
202
+ messageHashOrIntent: IntentInnerHash | CallIntent,
130
203
  ): Promise<AuthWitness> {
131
204
  const account = await this.getAccountFromAddress(from);
132
- return account.createAuthWit(messageHashOrIntent);
205
+ const chainInfo = await this.getChainInfo();
206
+ return account.createAuthWit(messageHashOrIntent, chainInfo);
133
207
  }
134
208
 
135
- public async batch<const T extends readonly BatchedMethod<keyof BatchableMethods>[]>(
136
- methods: T,
137
- ): Promise<BatchResults<T>> {
209
+ /**
210
+ * Request capabilities from the wallet.
211
+ *
212
+ * This method is wallet-implementation-dependent and must be provided by classes extending BaseWallet.
213
+ * Embedded wallets typically don't support capability-based authorization (no user authorization flow),
214
+ * while external wallets (browser extensions, hardware wallets) implement this to reduce authorization
215
+ * friction by allowing apps to request permissions upfront.
216
+ *
217
+ * TODO: Consider making it abstract so implementing it is a conscious decision. Leaving it as-is
218
+ * while the feature stabilizes.
219
+ *
220
+ * @param _manifest - Application capability manifest declaring what operations the app needs
221
+ */
222
+ public requestCapabilities(_manifest: AppCapabilities): Promise<WalletCapabilities> {
223
+ throw new Error('Not implemented');
224
+ }
225
+
226
+ public async batch<const T extends readonly BatchedMethod[]>(methods: T): Promise<BatchResults<T>> {
138
227
  const results: any[] = [];
139
228
  for (const method of methods) {
140
229
  const { name, args } = method;
@@ -154,31 +243,39 @@ export abstract class BaseWallet implements Wallet {
154
243
 
155
244
  /**
156
245
  * Completes partial user-provided fee options with wallet defaults.
157
- * @param from - The address where the transaction is being sent from
158
- * @param feePayer - The address paying for fees (if any fee payment method is embedded in the execution payload)
159
- * @param gasSettings - User-provided partial gas settings
160
- * @returns - Complete fee options that can be used to create a transaction execution request
246
+ * @param config - Fee completion config.
161
247
  */
162
- protected async completeFeeOptions(
163
- from: AztecAddress,
164
- feePayer?: AztecAddress,
165
- gasSettings?: Partial<FieldsOf<GasSettings>>,
166
- ): Promise<FeeOptions> {
248
+ protected async completeFeeOptions(config: CompleteFeeOptionsConfig): Promise<FeeOptions> {
249
+ const { from, feePayer, gasSettings, forEstimation, congestionEstimate } = config;
167
250
  const maxFeesPerGas =
168
- gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentMinFees()).mul(1 + this.minFeePadding);
251
+ gasSettings?.maxFeesPerGas ?? (await this.getMinFees(congestionEstimate)).mul(1 + this.minFeePadding);
169
252
  let accountFeePaymentMethodOptions;
170
- // The transaction does not include a fee payment method, so we set the flag
171
- // for the account to use its fee juice balance
172
- if (!feePayer) {
173
- accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
174
- } else {
175
- // The transaction includes fee payment method, so we check if we are the fee payer for it
176
- // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
177
- accountFeePaymentMethodOptions = from.equals(feePayer)
178
- ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM
179
- : AccountFeePaymentMethodOptions.EXTERNAL;
253
+ // If from is an address, we need to determine the appropriate fee payment method options for the
254
+ // account contract entrypoint to use
255
+ if (from !== NO_FROM) {
256
+ if (!feePayer) {
257
+ // The transaction does not include a fee payment method, so we set the flag
258
+ // for the account to use its fee juice balance
259
+ accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
260
+ } else {
261
+ // The transaction includes fee payment method, so we check if we are the fee payer for it
262
+ // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
263
+ accountFeePaymentMethodOptions = from.equals(feePayer)
264
+ ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM
265
+ : AccountFeePaymentMethodOptions.EXTERNAL;
266
+ }
180
267
  }
181
- const fullGasSettings: GasSettings = GasSettings.default({ ...gasSettings, maxFeesPerGas });
268
+ const gasSettingsOverrides = {
269
+ gasLimits: gasSettings?.gasLimits ? Gas.from(gasSettings.gasLimits) : undefined,
270
+ teardownGasLimits: gasSettings?.teardownGasLimits ? Gas.from(gasSettings.teardownGasLimits) : undefined,
271
+ maxFeesPerGas,
272
+ maxPriorityFeesPerGas: gasSettings?.maxPriorityFeesPerGas ?? GasFees.empty(),
273
+ };
274
+ // When estimating gas (simulation), use high limits so the simulation doesn't run out of gas.
275
+ // When sending for real, use protocol max limits that the network will actually accept.
276
+ const fullGasSettings = forEstimation
277
+ ? GasSettings.forEstimation(gasSettingsOverrides)
278
+ : GasSettings.fallback(gasSettingsOverrides);
182
279
  this.log.debug(`Using L2 gas settings`, fullGasSettings);
183
280
  return {
184
281
  gasSettings: fullGasSettings,
@@ -188,34 +285,25 @@ export abstract class BaseWallet implements Wallet {
188
285
  }
189
286
 
190
287
  /**
191
- * Completes partial user-provided fee options with unreasonably high gas limits
192
- * for gas estimation. Uses the same logic as completeFeeOptions but sets high limits
193
- * to avoid running out of gas during estimation.
194
- * @param from - The address where the transaction is being sent from
195
- * @param feePayer - The address paying for fees (if any fee payment method is embedded in the execution payload)
196
- * @param gasSettings - User-provided partial gas settings
288
+ * Returns the worst-case min fee across predicted future slots.
289
+ * Falls back to getCurrentMinFees if the node doesn't support getPredictedMinFees.
290
+ * @param estimate - The mana usage estimate to use for fee prediction. Defaults to Limit for conservative estimation.
197
291
  */
198
- protected async completeFeeOptionsForEstimation(
199
- from: AztecAddress,
200
- feePayer?: AztecAddress,
201
- gasSettings?: Partial<FieldsOf<GasSettings>>,
202
- ) {
203
- const defaultFeeOptions = await this.completeFeeOptions(from, feePayer, gasSettings);
204
- const {
205
- gasSettings: { maxFeesPerGas, maxPriorityFeesPerGas },
206
- } = defaultFeeOptions;
207
- // Use unrealistically high gas limits for estimation to avoid running out of gas.
208
- // They will be tuned down after the simulation.
209
- const gasSettingsForEstimation = new GasSettings(
210
- new Gas(GAS_ESTIMATION_DA_GAS_LIMIT, GAS_ESTIMATION_L2_GAS_LIMIT),
211
- new Gas(GAS_ESTIMATION_TEARDOWN_DA_GAS_LIMIT, GAS_ESTIMATION_TEARDOWN_L2_GAS_LIMIT),
212
- maxFeesPerGas,
213
- maxPriorityFeesPerGas,
214
- );
215
- return {
216
- ...defaultFeeOptions,
217
- gasSettings: gasSettingsForEstimation,
218
- };
292
+ protected async getMinFees(estimate: ManaUsageEstimate = ManaUsageEstimate.Limit): Promise<GasFees> {
293
+ try {
294
+ const predicted = await this.aztecNode.getPredictedMinFees(estimate);
295
+ if (predicted.length === 0) {
296
+ return this.aztecNode.getCurrentMinFees();
297
+ }
298
+ return predicted.reduce((worst, fees) => (fees.feePerL2Gas > worst.feePerL2Gas ? fees : worst));
299
+ } catch (err: any) {
300
+ // Fallback for old nodes that don't support getPredictedMinFees.
301
+ // Only fall back on method-not-found errors (JSON-RPC code -32601); rethrow others.
302
+ if (err?.cause?.code === -32601 || err?.message?.includes('Method not found')) {
303
+ return this.aztecNode.getCurrentMinFees();
304
+ }
305
+ throw err;
306
+ }
219
307
  }
220
308
 
221
309
  registerSender(address: AztecAddress, _alias: string = ''): Promise<AztecAddress> {
@@ -227,7 +315,7 @@ export abstract class BaseWallet implements Wallet {
227
315
  artifact?: ContractArtifact,
228
316
  secretKey?: Fr,
229
317
  ): Promise<ContractInstanceWithAddress> {
230
- const { contractInstance: existingInstance } = await this.pxe.getContractMetadata(instance.address);
318
+ const existingInstance = await this.pxe.getContractInstance(instance.address);
231
319
 
232
320
  if (existingInstance) {
233
321
  // Instance already registered in the wallet
@@ -244,13 +332,12 @@ export abstract class BaseWallet implements Wallet {
244
332
  // Instance not registered yet
245
333
  if (!artifact) {
246
334
  // Try to get the artifact from the wallet's contract class storage
247
- const classMetadata = await this.pxe.getContractClassMetadata(instance.currentContractClassId, true);
248
- if (!classMetadata.artifact) {
335
+ artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
336
+ if (!artifact) {
249
337
  throw new Error(
250
338
  `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()}`,
251
339
  );
252
340
  }
253
- artifact = classMetadata.artifact;
254
341
  }
255
342
  await this.pxe.registerContract({ artifact, instance });
256
343
  }
@@ -261,29 +348,145 @@ export abstract class BaseWallet implements Wallet {
261
348
  return instance;
262
349
  }
263
350
 
264
- async simulateTx(executionPayload: ExecutionPayload, opts: SimulateOptions): Promise<TxSimulationResult> {
265
- const feeOptions = opts.fee?.estimateGas
266
- ? await this.completeFeeOptionsForEstimation(opts.from, executionPayload.feePayer, opts.fee?.gasSettings)
267
- : await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
268
- const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
269
- return this.pxe.simulateTx(
270
- txRequest,
271
- true /* simulatePublic */,
272
- opts?.skipTxValidation,
273
- opts?.skipFeeEnforcement ?? true,
351
+ registerContractClass(artifact: ContractArtifact): Promise<void> {
352
+ return this.pxe.registerContractClass(artifact);
353
+ }
354
+
355
+ /**
356
+ * Simulates calls through the standard PXE path (account entrypoint).
357
+ * @param executionPayload - The execution payload to simulate.
358
+ * @param opts - Simulation options.
359
+ */
360
+ protected async simulateViaEntrypoint(executionPayload: ExecutionPayload, opts: SimulateViaEntrypointOptions) {
361
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(
362
+ executionPayload,
363
+ opts.from,
364
+ opts.feeOptions,
274
365
  );
366
+ const result = await this.pxe.simulateTx(txRequest, {
367
+ simulatePublic: true,
368
+ skipTxValidation: opts.skipTxValidation,
369
+ skipFeeEnforcement: opts.skipFeeEnforcement,
370
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
371
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
372
+ overrides: opts.overrides,
373
+ });
374
+ const appCallOffset = await this.computeAppCallOffset(opts.from, opts.feeOptions);
375
+ return TxSimulationResultWithAppOffset.fromResultAndOffset(result, appCallOffset);
376
+ }
377
+
378
+ /**
379
+ * Computes the index where the app's calls begin in the flattened array of calls (0 = entrypoint/root, 1..N = fee
380
+ * calls, N+1 = app).
381
+ * @param from - The sender address, or NO_FROM for the default entrypoint.
382
+ * @param feeOptions - Fee options containing the wallet fee payment method.
383
+ */
384
+ protected async computeAppCallOffset(from: AztecAddress | NoFrom, feeOptions: FeeOptions): Promise<number> {
385
+ if (from === NO_FROM) {
386
+ return 0;
387
+ }
388
+ const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
389
+ return (feeExecutionPayload?.calls.length ?? 0) + 1; // +1 for entrypoint
390
+ }
391
+
392
+ /**
393
+ * Simulates a transaction, optimizing leading public static calls by running them directly
394
+ * on the node while sending the remaining calls through the standard PXE path.
395
+ * Return values from both paths are merged back in original call order.
396
+ * @param executionPayload - The execution payload to simulate.
397
+ * @param opts - Simulation options (from address, fee settings, etc.).
398
+ * @returns The merged simulation result.
399
+ */
400
+ async simulateTx(
401
+ executionPayload: ExecutionPayload,
402
+ opts: SimulateOptions,
403
+ ): Promise<TxSimulationResultWithAppOffset> {
404
+ const feeOptions = await this.completeFeeOptions({
405
+ from: opts.from,
406
+ feePayer: executionPayload.feePayer,
407
+ gasSettings: opts.fee?.gasSettings,
408
+ forEstimation: true,
409
+ congestionEstimate: opts.fee?.congestionEstimate,
410
+ });
411
+ const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
412
+ const remainingPayload = { ...executionPayload, calls: remainingCalls };
413
+
414
+ const chainInfo = await this.getChainInfo();
415
+ let blockHeader: BlockHeader;
416
+ // PXE might not be synced yet, so we pull the latest header from the node
417
+ // To keep things consistent, we'll always try with PXE first
418
+ try {
419
+ blockHeader = await this.pxe.getSyncedBlockHeader();
420
+ } catch {
421
+ blockHeader = (await this.aztecNode.getBlockData('latest'))!.header;
422
+ }
423
+
424
+ const simulationOrigin = opts.from === NO_FROM ? AztecAddress.ZERO : opts.from;
425
+ const [optimizedResults, normalResult] = await Promise.all([
426
+ optimizableCalls.length > 0
427
+ ? simulateViaNode(
428
+ this.aztecNode,
429
+ optimizableCalls,
430
+ simulationOrigin,
431
+ chainInfo,
432
+ feeOptions.gasSettings,
433
+ blockHeader,
434
+ opts.skipFeeEnforcement ?? true,
435
+ this.getContractName.bind(this),
436
+ opts.overrides,
437
+ )
438
+ : Promise.resolve([]),
439
+ remainingCalls.length > 0
440
+ ? this.simulateViaEntrypoint(remainingPayload, {
441
+ from: opts.from,
442
+ feeOptions,
443
+ additionalScopes: opts.additionalScopes,
444
+ skipTxValidation: opts.skipTxValidation,
445
+ skipFeeEnforcement: opts.skipFeeEnforcement ?? true,
446
+ sendMessagesAs: opts.sendMessagesAs,
447
+ overrides: opts.overrides,
448
+ })
449
+ : Promise.resolve(null),
450
+ ]);
451
+
452
+ return buildMergedSimulationResult(optimizedResults, normalResult);
275
453
  }
276
454
 
277
455
  async profileTx(executionPayload: ExecutionPayload, opts: ProfileOptions): Promise<TxProfileResult> {
278
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
456
+ const feeOptions = await this.completeFeeOptions({
457
+ from: opts.from,
458
+ feePayer: executionPayload.feePayer,
459
+ gasSettings: opts.fee?.gasSettings,
460
+ congestionEstimate: opts.fee?.congestionEstimate,
461
+ });
279
462
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
280
- return this.pxe.profileTx(txRequest, opts.profileMode, opts.skipProofGeneration ?? true);
463
+ return this.pxe.profileTx(txRequest, {
464
+ profileMode: opts.profileMode,
465
+ skipProofGeneration: opts.skipProofGeneration ?? true,
466
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
467
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
468
+ });
281
469
  }
282
470
 
283
- async sendTx(executionPayload: ExecutionPayload, opts: SendOptions): Promise<TxHash> {
284
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
471
+ public async sendTx<W extends InteractionWaitOptions = undefined>(
472
+ executionPayload: ExecutionPayload,
473
+ opts: SendOptions<W>,
474
+ ): Promise<SendReturn<W>> {
475
+ const feeOptions = await this.completeFeeOptions({
476
+ from: opts.from,
477
+ feePayer: executionPayload.feePayer,
478
+ gasSettings: opts.fee?.gasSettings,
479
+ congestionEstimate: opts.fee?.congestionEstimate,
480
+ });
285
481
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
286
- const provenTx = await this.pxe.proveTx(txRequest);
482
+ const provenTx = await this.pxe.proveTx(txRequest, {
483
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
484
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
485
+ });
486
+ const offchainOutput = extractOffchainOutput(
487
+ provenTx.getOffchainEffects(),
488
+ provenTx.publicInputs.constants.anchorBlockHeader.globalVariables.timestamp,
489
+ );
287
490
  const tx = await provenTx.toTx();
288
491
  const txHash = tx.getTxHash();
289
492
  if (await this.aztecNode.getTxEffect(txHash)) {
@@ -294,7 +497,35 @@ export abstract class BaseWallet implements Wallet {
294
497
  throw this.contextualizeError(err, inspect(tx));
295
498
  });
296
499
  this.log.info(`Sent transaction ${txHash}`);
297
- return txHash;
500
+
501
+ // If wait is NO_WAIT, return txHash immediately
502
+ if (opts.wait === NO_WAIT) {
503
+ return { txHash, ...offchainOutput } as SendReturn<W>;
504
+ }
505
+
506
+ // Otherwise, wait for the full receipt (default behavior on wait: undefined)
507
+ const waitOpts = typeof opts.wait === 'object' ? opts.wait : undefined;
508
+ const receipt = await waitForTx(this.aztecNode, txHash, waitOpts);
509
+
510
+ // Display debug logs from public execution if present (served in test mode only)
511
+ if (receipt.debugLogs?.length) {
512
+ await displayDebugLogs(receipt.debugLogs, this.getContractName.bind(this));
513
+ }
514
+
515
+ return { receipt, ...offchainOutput } as SendReturn<W>;
516
+ }
517
+
518
+ /**
519
+ * Resolves a contract address to a human-readable name via PXE, if available.
520
+ * @param address - The contract address to resolve.
521
+ */
522
+ protected async getContractName(address: AztecAddress): Promise<string | undefined> {
523
+ const instance = await this.pxe.getContractInstance(address);
524
+ if (!instance) {
525
+ return undefined;
526
+ }
527
+ const artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
528
+ return artifact?.name;
298
529
  }
299
530
 
300
531
  protected contextualizeError(err: Error, ...context: string[]): Error {
@@ -311,19 +542,8 @@ export abstract class BaseWallet implements Wallet {
311
542
  return err;
312
543
  }
313
544
 
314
- simulateUtility(call: FunctionCall, authwits?: AuthWitness[]): Promise<UtilitySimulationResult> {
315
- return this.pxe.simulateUtility(call, authwits);
316
- }
317
-
318
- getContractClassMetadata(id: Fr, includeArtifact: boolean = false): Promise<ContractClassMetadata> {
319
- return this.pxe.getContractClassMetadata(id, includeArtifact);
320
- }
321
- getContractMetadata(address: AztecAddress): Promise<ContractMetadata> {
322
- return this.pxe.getContractMetadata(address);
323
- }
324
-
325
- getTxReceipt(txHash: TxHash): Promise<TxReceipt> {
326
- return this.aztecNode.getTxReceipt(txHash);
545
+ executeUtility(call: FunctionCall, opts: ExecuteUtilityOptions): Promise<UtilityExecutionResult> {
546
+ return this.pxe.executeUtility(call, { authwits: opts.authWitnesses, scopes: opts.scopes });
327
547
  }
328
548
 
329
549
  async getPrivateEvents<T>(
@@ -345,4 +565,51 @@ export abstract class BaseWallet implements Wallet {
345
565
 
346
566
  return decodedEvents;
347
567
  }
568
+
569
+ /**
570
+ * Returns metadata about a contract, including whether it has been initialized, published, and updated.
571
+ * @param address - The contract address to query.
572
+ */
573
+ async getContractMetadata(address: AztecAddress) {
574
+ const instance = await this.pxe.getContractInstance(address);
575
+ const publiclyRegisteredContractPromise = this.aztecNode.getContract(address);
576
+
577
+ let initializationStatus: ContractInitializationStatus;
578
+ if (instance) {
579
+ // We have the instance, so we can compute the private initialization nullifier (which includes init_hash and is
580
+ // emitted by both private and public initializers) and get a definitive INITIALIZED/UNINITIALIZED answer.
581
+ const initNullifier = await computeSiloedPrivateInitializationNullifier(address, instance.initializationHash);
582
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
583
+ initializationStatus = witness
584
+ ? ContractInitializationStatus.INITIALIZED
585
+ : ContractInitializationStatus.UNINITIALIZED;
586
+ } else {
587
+ // Without the instance we lack the init_hash needed for the private nullifier. We fall back to checking the
588
+ // public initialization nullifier (computed from address alone). Not all contracts emit it (only those with
589
+ // public functions that require initialization checks), so its absence doesn't mean the contract is
590
+ // uninitialized.
591
+ const publicNullifier = await computeSiloedPublicInitializationNullifier(address);
592
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', publicNullifier);
593
+ initializationStatus = witness ? ContractInitializationStatus.INITIALIZED : ContractInitializationStatus.UNKNOWN;
594
+ }
595
+ const publiclyRegisteredContract = await publiclyRegisteredContractPromise;
596
+ const isContractUpdated =
597
+ publiclyRegisteredContract &&
598
+ !publiclyRegisteredContract.currentContractClassId.equals(publiclyRegisteredContract.originalContractClassId);
599
+ return {
600
+ instance: instance ?? undefined,
601
+ initializationStatus,
602
+ isContractPublished: !!publiclyRegisteredContract,
603
+ isContractUpdated: !!isContractUpdated,
604
+ updatedContractClassId: isContractUpdated ? publiclyRegisteredContract.currentContractClassId : undefined,
605
+ };
606
+ }
607
+
608
+ async getContractClassMetadata(id: Fr) {
609
+ const publiclyRegisteredContractClass = await this.aztecNode.getContractClass(id);
610
+ return {
611
+ isArtifactRegistered: !!(await this.pxe.getContractArtifact(id)),
612
+ isContractClassPubliclyRegistered: !!publiclyRegisteredContractClass,
613
+ };
614
+ }
348
615
  }