@aztec/wallet-sdk 0.0.1-commit.001888fc

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 (66) hide show
  1. package/README.md +321 -0
  2. package/dest/base-wallet/base_wallet.d.ts +142 -0
  3. package/dest/base-wallet/base_wallet.d.ts.map +1 -0
  4. package/dest/base-wallet/base_wallet.js +357 -0
  5. package/dest/base-wallet/index.d.ts +3 -0
  6. package/dest/base-wallet/index.d.ts.map +1 -0
  7. package/dest/base-wallet/index.js +2 -0
  8. package/dest/base-wallet/utils.d.ts +49 -0
  9. package/dest/base-wallet/utils.d.ts.map +1 -0
  10. package/dest/base-wallet/utils.js +131 -0
  11. package/dest/crypto.d.ts +192 -0
  12. package/dest/crypto.d.ts.map +1 -0
  13. package/dest/crypto.js +394 -0
  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 +158 -0
  18. package/dest/extension/handlers/background_connection_handler.d.ts.map +1 -0
  19. package/dest/extension/handlers/background_connection_handler.js +258 -0
  20. package/dest/extension/handlers/content_script_connection_handler.d.ts +56 -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 +174 -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 +63 -0
  27. package/dest/extension/handlers/internal_message_types.d.ts.map +1 -0
  28. package/dest/extension/handlers/internal_message_types.js +22 -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 +132 -0
  33. package/dest/extension/provider/extension_wallet.d.ts.map +1 -0
  34. package/dest/extension/provider/extension_wallet.js +278 -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/extension/provider/index.js +2 -0
  38. package/dest/manager/index.d.ts +3 -0
  39. package/dest/manager/index.d.ts.map +1 -0
  40. package/dest/manager/index.js +1 -0
  41. package/dest/manager/types.d.ts +167 -0
  42. package/dest/manager/types.d.ts.map +1 -0
  43. package/dest/manager/types.js +19 -0
  44. package/dest/manager/wallet_manager.d.ts +70 -0
  45. package/dest/manager/wallet_manager.d.ts.map +1 -0
  46. package/dest/manager/wallet_manager.js +226 -0
  47. package/dest/types.d.ts +123 -0
  48. package/dest/types.d.ts.map +1 -0
  49. package/dest/types.js +11 -0
  50. package/package.json +105 -0
  51. package/src/base-wallet/base_wallet.ts +498 -0
  52. package/src/base-wallet/index.ts +2 -0
  53. package/src/base-wallet/utils.ts +238 -0
  54. package/src/crypto.ts +499 -0
  55. package/src/emoji_alphabet.ts +317 -0
  56. package/src/extension/handlers/background_connection_handler.ts +423 -0
  57. package/src/extension/handlers/content_script_connection_handler.ts +246 -0
  58. package/src/extension/handlers/index.ts +25 -0
  59. package/src/extension/handlers/internal_message_types.ts +69 -0
  60. package/src/extension/provider/extension_provider.ts +233 -0
  61. package/src/extension/provider/extension_wallet.ts +329 -0
  62. package/src/extension/provider/index.ts +7 -0
  63. package/src/manager/index.ts +12 -0
  64. package/src/manager/types.ts +177 -0
  65. package/src/manager/wallet_manager.ts +257 -0
  66. package/src/types.ts +132 -0
@@ -0,0 +1,357 @@
1
+ import { NO_WAIT, extractOffchainOutput } from '@aztec/aztec.js/contracts';
2
+ 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 { AccountFeePaymentMethodOptions } from '@aztec/entrypoints/account';
5
+ import { Fr } from '@aztec/foundation/curves/bn254';
6
+ import { createLogger } from '@aztec/foundation/log';
7
+ import { displayDebugLogs } from '@aztec/pxe/client/lazy';
8
+ import { decodeFromAbi } from '@aztec/stdlib/abi';
9
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
10
+ import { computePartialAddress, getContractClassFromArtifact } from '@aztec/stdlib/contract';
11
+ import { SimulationError } from '@aztec/stdlib/errors';
12
+ import { Gas, GasSettings } from '@aztec/stdlib/gas';
13
+ import { siloNullifier } from '@aztec/stdlib/hash';
14
+ import { mergeExecutionPayloads } from '@aztec/stdlib/tx';
15
+ import { inspect } from 'util';
16
+ import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simulateViaNode } from './utils.js';
17
+ /**
18
+ * A base class for Wallet implementations
19
+ */ export class BaseWallet {
20
+ pxe;
21
+ aztecNode;
22
+ log;
23
+ minFeePadding;
24
+ cancellableTransactions;
25
+ // Protected because we want to force wallets to instantiate their own PXE.
26
+ constructor(pxe, aztecNode, log = createLogger('wallet-sdk:base_wallet')){
27
+ this.pxe = pxe;
28
+ this.aztecNode = aztecNode;
29
+ this.log = log;
30
+ this.minFeePadding = 0.5;
31
+ this.cancellableTransactions = false;
32
+ }
33
+ scopesFrom(from, additionalScopes = []) {
34
+ const allScopes = from.isZero() ? additionalScopes : [
35
+ from,
36
+ ...additionalScopes
37
+ ];
38
+ const scopeSet = new Set(allScopes.map((address)=>address.toString()));
39
+ return [
40
+ ...scopeSet
41
+ ].map(AztecAddress.fromString);
42
+ }
43
+ /**
44
+ * Returns the list of aliased contacts associated with the wallet.
45
+ * This base implementation directly returns PXE's senders, but note that in general contacts are a superset of senders.
46
+ * - Senders: Addresses we check during synching in case they sent us notes,
47
+ * - Contacts: more general concept akin to a phone's contact list.
48
+ * @returns The aliased collection of AztecAddresses that form this wallet's address book
49
+ */ async getAddressBook() {
50
+ const senders = await this.pxe.getSenders();
51
+ return senders.map((sender)=>({
52
+ item: sender,
53
+ alias: ''
54
+ }));
55
+ }
56
+ async getChainInfo() {
57
+ const { l1ChainId, rollupVersion } = await this.aztecNode.getNodeInfo();
58
+ return {
59
+ chainId: new Fr(l1ChainId),
60
+ version: new Fr(rollupVersion)
61
+ };
62
+ }
63
+ async createTxExecutionRequestFromPayloadAndFee(executionPayload, from, feeOptions) {
64
+ const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
65
+ const executionOptions = {
66
+ txNonce: Fr.random(),
67
+ cancellable: this.cancellableTransactions,
68
+ feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions
69
+ };
70
+ const finalExecutionPayload = feeExecutionPayload ? mergeExecutionPayloads([
71
+ feeExecutionPayload,
72
+ executionPayload
73
+ ]) : executionPayload;
74
+ const fromAccount = await this.getAccountFromAddress(from);
75
+ const chainInfo = await this.getChainInfo();
76
+ return fromAccount.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo, executionOptions);
77
+ }
78
+ async createAuthWit(from, messageHashOrIntent) {
79
+ const account = await this.getAccountFromAddress(from);
80
+ const chainInfo = await this.getChainInfo();
81
+ return account.createAuthWit(messageHashOrIntent, chainInfo);
82
+ }
83
+ /**
84
+ * Request capabilities from the wallet.
85
+ *
86
+ * This method is wallet-implementation-dependent and must be provided by classes extending BaseWallet.
87
+ * Embedded wallets typically don't support capability-based authorization (no user authorization flow),
88
+ * while external wallets (browser extensions, hardware wallets) implement this to reduce authorization
89
+ * friction by allowing apps to request permissions upfront.
90
+ *
91
+ * TODO: Consider making it abstract so implementing it is a conscious decision. Leaving it as-is
92
+ * while the feature stabilizes.
93
+ *
94
+ * @param _manifest - Application capability manifest declaring what operations the app needs
95
+ */ requestCapabilities(_manifest) {
96
+ throw new Error('Not implemented');
97
+ }
98
+ async batch(methods) {
99
+ const results = [];
100
+ for (const method of methods){
101
+ const { name, args } = method;
102
+ // Type safety is guaranteed by the BatchedMethod type, which ensures that:
103
+ // 1. `name` is a valid batchable method name
104
+ // 2. `args` matches the parameter types of that specific method
105
+ // 3. The return type is correctly mapped in BatchResults<T>
106
+ // We use dynamic dispatch here for simplicity, but the types are enforced at the call site.
107
+ const fn = this[name];
108
+ const result = await fn.apply(this, args);
109
+ // Wrap result with method name for discriminated union deserialization
110
+ results.push({
111
+ name,
112
+ result
113
+ });
114
+ }
115
+ return results;
116
+ }
117
+ /**
118
+ * Completes partial user-provided fee options with wallet defaults.
119
+ * @param from - The address where the transaction is being sent from
120
+ * @param feePayer - The address paying for fees (if any fee payment method is embedded in the execution payload)
121
+ * @param gasSettings - User-provided partial gas settings
122
+ * @returns - Complete fee options that can be used to create a transaction execution request
123
+ */ async completeFeeOptions(from, feePayer, gasSettings) {
124
+ const maxFeesPerGas = gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentMinFees()).mul(1 + this.minFeePadding);
125
+ let accountFeePaymentMethodOptions;
126
+ // The transaction does not include a fee payment method, so we set the flag
127
+ // for the account to use its fee juice balance
128
+ if (!feePayer) {
129
+ accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
130
+ } else {
131
+ // The transaction includes fee payment method, so we check if we are the fee payer for it
132
+ // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
133
+ accountFeePaymentMethodOptions = from.equals(feePayer) ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM : AccountFeePaymentMethodOptions.EXTERNAL;
134
+ }
135
+ const fullGasSettings = GasSettings.default({
136
+ ...gasSettings,
137
+ maxFeesPerGas
138
+ });
139
+ this.log.debug(`Using L2 gas settings`, fullGasSettings);
140
+ return {
141
+ gasSettings: fullGasSettings,
142
+ walletFeePaymentMethod: undefined,
143
+ accountFeePaymentMethodOptions
144
+ };
145
+ }
146
+ /**
147
+ * Completes partial user-provided fee options with unreasonably high gas limits
148
+ * for gas estimation. Uses the same logic as completeFeeOptions but sets high limits
149
+ * to avoid running out of gas during estimation.
150
+ * @param from - The address where the transaction is being sent from
151
+ * @param feePayer - The address paying for fees (if any fee payment method is embedded in the execution payload)
152
+ * @param gasSettings - User-provided partial gas settings
153
+ */ async completeFeeOptionsForEstimation(from, feePayer, gasSettings) {
154
+ const defaultFeeOptions = await this.completeFeeOptions(from, feePayer, gasSettings);
155
+ const { gasSettings: { maxFeesPerGas, maxPriorityFeesPerGas } } = defaultFeeOptions;
156
+ // Use unrealistically high gas limits for estimation to avoid running out of gas.
157
+ // They will be tuned down after the simulation.
158
+ 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);
159
+ return {
160
+ ...defaultFeeOptions,
161
+ gasSettings: gasSettingsForEstimation
162
+ };
163
+ }
164
+ registerSender(address, _alias = '') {
165
+ return this.pxe.registerSender(address);
166
+ }
167
+ async registerContract(instance, artifact, secretKey) {
168
+ const existingInstance = await this.pxe.getContractInstance(instance.address);
169
+ if (existingInstance) {
170
+ // Instance already registered in the wallet
171
+ if (artifact) {
172
+ const thisContractClass = await getContractClassFromArtifact(artifact);
173
+ if (!thisContractClass.id.equals(existingInstance.currentContractClassId)) {
174
+ // wallet holds an outdated version of this contract
175
+ await this.pxe.updateContract(instance.address, artifact);
176
+ instance.currentContractClassId = thisContractClass.id;
177
+ }
178
+ }
179
+ // If no artifact provided, we just use the existing registration
180
+ } else {
181
+ // Instance not registered yet
182
+ if (!artifact) {
183
+ // Try to get the artifact from the wallet's contract class storage
184
+ artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
185
+ if (!artifact) {
186
+ 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()}`);
187
+ }
188
+ }
189
+ await this.pxe.registerContract({
190
+ artifact,
191
+ instance
192
+ });
193
+ }
194
+ if (secretKey) {
195
+ await this.pxe.registerAccount(secretKey, await computePartialAddress(instance));
196
+ }
197
+ return instance;
198
+ }
199
+ /**
200
+ * Simulates calls through the standard PXE path (account entrypoint).
201
+ * @param executionPayload - The execution payload to simulate.
202
+ * @param from - The sender address.
203
+ * @param feeOptions - Fee options for the transaction.
204
+ * @param skipTxValidation - Whether to skip tx validation.
205
+ * @param skipFeeEnforcement - Whether to skip fee enforcement.
206
+ * @param scopes - The scopes to use for the simulation.
207
+ */ async simulateViaEntrypoint(executionPayload, from, feeOptions, scopes, skipTxValidation, skipFeeEnforcement) {
208
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, from, feeOptions);
209
+ return this.pxe.simulateTx(txRequest, {
210
+ simulatePublic: true,
211
+ skipTxValidation,
212
+ skipFeeEnforcement,
213
+ scopes
214
+ });
215
+ }
216
+ /**
217
+ * Simulates a transaction, optimizing leading public static calls by running them directly
218
+ * on the node while sending the remaining calls through the standard PXE path.
219
+ * Return values from both paths are merged back in original call order.
220
+ * @param executionPayload - The execution payload to simulate.
221
+ * @param opts - Simulation options (from address, fee settings, etc.).
222
+ * @returns The merged simulation result.
223
+ */ async simulateTx(executionPayload, opts) {
224
+ 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);
225
+ const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
226
+ const remainingPayload = {
227
+ ...executionPayload,
228
+ calls: remainingCalls
229
+ };
230
+ const chainInfo = await this.getChainInfo();
231
+ let blockHeader;
232
+ // PXE might not be synced yet, so we pull the latest header from the node
233
+ // To keep things consistent, we'll always try with PXE first
234
+ try {
235
+ blockHeader = await this.pxe.getSyncedBlockHeader();
236
+ } catch {
237
+ blockHeader = await this.aztecNode.getBlockHeader();
238
+ }
239
+ const [optimizedResults, normalResult] = await Promise.all([
240
+ optimizableCalls.length > 0 ? simulateViaNode(this.aztecNode, optimizableCalls, opts.from, chainInfo, feeOptions.gasSettings, blockHeader, opts.skipFeeEnforcement ?? true, this.getContractName.bind(this)) : Promise.resolve([]),
241
+ remainingCalls.length > 0 ? this.simulateViaEntrypoint(remainingPayload, opts.from, feeOptions, this.scopesFrom(opts.from, opts.additionalScopes), opts.skipTxValidation, opts.skipFeeEnforcement ?? true) : Promise.resolve(null)
242
+ ]);
243
+ return buildMergedSimulationResult(optimizedResults, normalResult);
244
+ }
245
+ async profileTx(executionPayload, opts) {
246
+ const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
247
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
248
+ return this.pxe.profileTx(txRequest, {
249
+ profileMode: opts.profileMode,
250
+ skipProofGeneration: opts.skipProofGeneration ?? true,
251
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes)
252
+ });
253
+ }
254
+ async sendTx(executionPayload, opts) {
255
+ const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
256
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
257
+ const provenTx = await this.pxe.proveTx(txRequest, this.scopesFrom(opts.from, opts.additionalScopes));
258
+ const offchainOutput = extractOffchainOutput(provenTx.getOffchainEffects(), provenTx.publicInputs.constants.anchorBlockHeader.globalVariables.timestamp);
259
+ const tx = await provenTx.toTx();
260
+ const txHash = tx.getTxHash();
261
+ if (await this.aztecNode.getTxEffect(txHash)) {
262
+ throw new Error(`A settled tx with equal hash ${txHash.toString()} exists.`);
263
+ }
264
+ this.log.debug(`Sending transaction ${txHash}`);
265
+ await this.aztecNode.sendTx(tx).catch((err)=>{
266
+ throw this.contextualizeError(err, inspect(tx));
267
+ });
268
+ this.log.info(`Sent transaction ${txHash}`);
269
+ // If wait is NO_WAIT, return txHash immediately
270
+ if (opts.wait === NO_WAIT) {
271
+ return {
272
+ txHash,
273
+ ...offchainOutput
274
+ };
275
+ }
276
+ // Otherwise, wait for the full receipt (default behavior on wait: undefined)
277
+ const waitOpts = typeof opts.wait === 'object' ? opts.wait : undefined;
278
+ const receipt = await waitForTx(this.aztecNode, txHash, waitOpts);
279
+ // Display debug logs from public execution if present (served in test mode only)
280
+ if (receipt.debugLogs?.length) {
281
+ await displayDebugLogs(receipt.debugLogs, this.getContractName.bind(this));
282
+ }
283
+ return {
284
+ receipt,
285
+ ...offchainOutput
286
+ };
287
+ }
288
+ /**
289
+ * Resolves a contract address to a human-readable name via PXE, if available.
290
+ * @param address - The contract address to resolve.
291
+ */ async getContractName(address) {
292
+ const instance = await this.pxe.getContractInstance(address);
293
+ if (!instance) {
294
+ return undefined;
295
+ }
296
+ const artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
297
+ return artifact?.name;
298
+ }
299
+ contextualizeError(err, ...context) {
300
+ let contextStr = '';
301
+ if (context.length > 0) {
302
+ contextStr = `\nContext:\n${context.join('\n')}`;
303
+ }
304
+ if (err instanceof SimulationError) {
305
+ err.setAztecContext(contextStr);
306
+ } else {
307
+ this.log.error(err.name, err);
308
+ this.log.debug(contextStr);
309
+ }
310
+ return err;
311
+ }
312
+ executeUtility(call, opts) {
313
+ return this.pxe.executeUtility(call, {
314
+ authwits: opts.authWitnesses,
315
+ scopes: [
316
+ opts.scope
317
+ ]
318
+ });
319
+ }
320
+ async getPrivateEvents(eventDef, eventFilter) {
321
+ const pxeEvents = await this.pxe.getPrivateEvents(eventDef.eventSelector, eventFilter);
322
+ const decodedEvents = pxeEvents.map((pxeEvent)=>{
323
+ return {
324
+ event: decodeFromAbi([
325
+ eventDef.abiType
326
+ ], pxeEvent.packedEvent),
327
+ metadata: {
328
+ l2BlockNumber: pxeEvent.l2BlockNumber,
329
+ l2BlockHash: pxeEvent.l2BlockHash,
330
+ txHash: pxeEvent.txHash
331
+ }
332
+ };
333
+ });
334
+ return decodedEvents;
335
+ }
336
+ async getContractMetadata(address) {
337
+ const instance = await this.pxe.getContractInstance(address);
338
+ const initNullifier = await siloNullifier(address, address.toField());
339
+ const publiclyRegisteredContract = await this.aztecNode.getContract(address);
340
+ const initNullifierMembershipWitness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
341
+ const isContractUpdated = publiclyRegisteredContract && !publiclyRegisteredContract.currentContractClassId.equals(publiclyRegisteredContract.originalContractClassId);
342
+ return {
343
+ instance: instance ?? undefined,
344
+ isContractInitialized: !!initNullifierMembershipWitness,
345
+ isContractPublished: !!publiclyRegisteredContract,
346
+ isContractUpdated: !!isContractUpdated,
347
+ updatedContractClassId: isContractUpdated ? publiclyRegisteredContract.currentContractClassId : undefined
348
+ };
349
+ }
350
+ async getContractClassMetadata(id) {
351
+ const publiclyRegisteredContractClass = await this.aztecNode.getContractClass(id);
352
+ return {
353
+ isArtifactRegistered: !!await this.pxe.getContractArtifact(id),
354
+ isContractClassPubliclyRegistered: !!publiclyRegisteredContractClass
355
+ };
356
+ }
357
+ }
@@ -0,0 +1,3 @@
1
+ export { BaseWallet, type FeeOptions } from './base_wallet.js';
2
+ export { simulateViaNode, buildMergedSimulationResult, extractOptimizablePublicStaticCalls } from './utils.js';
3
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9iYXNlLXdhbGxldC9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEVBQUUsVUFBVSxFQUFFLEtBQUssVUFBVSxFQUFFLE1BQU0sa0JBQWtCLENBQUM7QUFDL0QsT0FBTyxFQUFFLGVBQWUsRUFBRSwyQkFBMkIsRUFBRSxtQ0FBbUMsRUFBRSxNQUFNLFlBQVksQ0FBQyJ9
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/base-wallet/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC/D,OAAO,EAAE,eAAe,EAAE,2BAA2B,EAAE,mCAAmC,EAAE,MAAM,YAAY,CAAC"}
@@ -0,0 +1,2 @@
1
+ export { BaseWallet } from './base_wallet.js';
2
+ export { simulateViaNode, buildMergedSimulationResult, extractOptimizablePublicStaticCalls } from './utils.js';
@@ -0,0 +1,49 @@
1
+ import type { AztecNode } from '@aztec/aztec.js/node';
2
+ import type { ChainInfo } from '@aztec/entrypoints/interfaces';
3
+ import type { ContractNameResolver } from '@aztec/pxe/client/lazy';
4
+ import { type FunctionCall } from '@aztec/stdlib/abi';
5
+ import type { AztecAddress } from '@aztec/stdlib/aztec-address';
6
+ import type { GasSettings } from '@aztec/stdlib/gas';
7
+ import { type BlockHeader, type ExecutionPayload, TxSimulationResult } from '@aztec/stdlib/tx';
8
+ /**
9
+ * Splits an execution payload into a leading prefix of public static calls
10
+ * (eligible for direct node simulation) and the remaining calls.
11
+ *
12
+ * Only a leading run of public static calls is eligible for optimization.
13
+ * Any non-public-static call may enqueue public state mutations
14
+ * (e.g. private calls can enqueue public calls), so all calls that follow
15
+ * must go through the normal simulation path to see the correct state.
16
+ *
17
+ */
18
+ export declare function extractOptimizablePublicStaticCalls(payload: ExecutionPayload): {
19
+ /** Leading public static calls eligible for direct node simulation. */
20
+ optimizableCalls: FunctionCall[];
21
+ /** All remaining calls. */
22
+ remainingCalls: FunctionCall[];
23
+ };
24
+ /**
25
+ * Simulates public static calls by splitting them into batches of MAX_ENQUEUED_CALLS_PER_CALL
26
+ * and sending each batch directly to the node.
27
+ *
28
+ * @param node - The Aztec node to simulate on.
29
+ * @param publicStaticCalls - Array of public static function calls to optimize.
30
+ * @param from - The account address making the calls.
31
+ * @param chainInfo - Chain information (chainId and version).
32
+ * @param gasSettings - Gas settings for the transaction.
33
+ * @param blockHeader - Block header to use as anchor.
34
+ * @param skipFeeEnforcement - Whether to skip fee enforcement during simulation.
35
+ * @returns Array of TxSimulationResult, one per batch.
36
+ */
37
+ export declare function simulateViaNode(node: AztecNode, publicStaticCalls: FunctionCall[], from: AztecAddress, chainInfo: ChainInfo, gasSettings: GasSettings, blockHeader: BlockHeader, skipFeeEnforcement: boolean | undefined, getContractName: ContractNameResolver): Promise<TxSimulationResult[]>;
38
+ /**
39
+ * Merges simulation results from the optimized (public static) and normal paths.
40
+ * Since optimized calls are always a leading prefix, return values are simply
41
+ * concatenated: optimized first, then normal.
42
+ * Stats are taken from the normal result only (the optimized path doesn't produce them).
43
+ *
44
+ * @param optimizedResults - Results from optimized public static call batches.
45
+ * @param normalResult - Result from normal simulation (null if all calls were optimized).
46
+ * @returns A single TxSimulationResult with return values in original call order.
47
+ */
48
+ export declare function buildMergedSimulationResult(optimizedResults: TxSimulationResult[], normalResult: TxSimulationResult | null): TxSimulationResult;
49
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidXRpbHMuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9iYXNlLXdhbGxldC91dGlscy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEtBQUssRUFBRSxTQUFTLEVBQUUsTUFBTSxzQkFBc0IsQ0FBQztBQUV0RCxPQUFPLEtBQUssRUFBRSxTQUFTLEVBQUUsTUFBTSwrQkFBK0IsQ0FBQztBQUkvRCxPQUFPLEtBQUssRUFBRSxvQkFBb0IsRUFBRSxNQUFNLHdCQUF3QixDQUFDO0FBR25FLE9BQU8sRUFBRSxLQUFLLFlBQVksRUFBb0IsTUFBTSxtQkFBbUIsQ0FBQztBQUN4RSxPQUFPLEtBQUssRUFBRSxZQUFZLEVBQUUsTUFBTSw2QkFBNkIsQ0FBQztBQUNoRSxPQUFPLEtBQUssRUFBRSxXQUFXLEVBQUUsTUFBTSxtQkFBbUIsQ0FBQztBQVFyRCxPQUFPLEVBQ0wsS0FBSyxXQUFXLEVBQ2hCLEtBQUssZ0JBQWdCLEVBT3JCLGtCQUFrQixFQUNuQixNQUFNLGtCQUFrQixDQUFDO0FBRTFCOzs7Ozs7Ozs7R0FTRztBQUNILHdCQUFnQixtQ0FBbUMsQ0FBQyxPQUFPLEVBQUUsZ0JBQWdCLEdBQUc7SUFDOUUsdUVBQXVFO0lBQ3ZFLGdCQUFnQixFQUFFLFlBQVksRUFBRSxDQUFDO0lBQ2pDLDJCQUEyQjtJQUMzQixjQUFjLEVBQUUsWUFBWSxFQUFFLENBQUM7Q0FDaEMsQ0FPQTtBQXVHRDs7Ozs7Ozs7Ozs7O0dBWUc7QUFDSCx3QkFBc0IsZUFBZSxDQUNuQyxJQUFJLEVBQUUsU0FBUyxFQUNmLGlCQUFpQixFQUFFLFlBQVksRUFBRSxFQUNqQyxJQUFJLEVBQUUsWUFBWSxFQUNsQixTQUFTLEVBQUUsU0FBUyxFQUNwQixXQUFXLEVBQUUsV0FBVyxFQUN4QixXQUFXLEVBQUUsV0FBVyxFQUN4QixrQkFBa0IscUJBQWdCLEVBQ2xDLGVBQWUsRUFBRSxvQkFBb0IsR0FDcEMsT0FBTyxDQUFDLGtCQUFrQixFQUFFLENBQUMsQ0F3Qi9CO0FBRUQ7Ozs7Ozs7OztHQVNHO0FBQ0gsd0JBQWdCLDJCQUEyQixDQUN6QyxnQkFBZ0IsRUFBRSxrQkFBa0IsRUFBRSxFQUN0QyxZQUFZLEVBQUUsa0JBQWtCLEdBQUcsSUFBSSxHQUN0QyxrQkFBa0IsQ0FvQnBCIn0=
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/base-wallet/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAEtD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAI/D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAGnE,OAAO,EAAE,KAAK,YAAY,EAAoB,MAAM,mBAAmB,CAAC;AACxE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAQrD,OAAO,EACL,KAAK,WAAW,EAChB,KAAK,gBAAgB,EAOrB,kBAAkB,EACnB,MAAM,kBAAkB,CAAC;AAE1B;;;;;;;;;GASG;AACH,wBAAgB,mCAAmC,CAAC,OAAO,EAAE,gBAAgB,GAAG;IAC9E,uEAAuE;IACvE,gBAAgB,EAAE,YAAY,EAAE,CAAC;IACjC,2BAA2B;IAC3B,cAAc,EAAE,YAAY,EAAE,CAAC;CAChC,CAOA;AAuGD;;;;;;;;;;;;GAYG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,SAAS,EACf,iBAAiB,EAAE,YAAY,EAAE,EACjC,IAAI,EAAE,YAAY,EAClB,SAAS,EAAE,SAAS,EACpB,WAAW,EAAE,WAAW,EACxB,WAAW,EAAE,WAAW,EACxB,kBAAkB,qBAAgB,EAClC,eAAe,EAAE,oBAAoB,GACpC,OAAO,CAAC,kBAAkB,EAAE,CAAC,CAwB/B;AAED;;;;;;;;;GASG;AACH,wBAAgB,2BAA2B,CACzC,gBAAgB,EAAE,kBAAkB,EAAE,EACtC,YAAY,EAAE,kBAAkB,GAAG,IAAI,GACtC,kBAAkB,CAoBpB"}
@@ -0,0 +1,131 @@
1
+ import { MAX_ENQUEUED_CALLS_PER_CALL } from '@aztec/constants';
2
+ import { makeTuple } from '@aztec/foundation/array';
3
+ import { Fr } from '@aztec/foundation/curves/bn254';
4
+ import { displayDebugLogs } from '@aztec/pxe/client/lazy';
5
+ import { generateSimulatedProvingResult } from '@aztec/pxe/simulator';
6
+ import { ClaimedLengthArray, CountedPublicCallRequest, PrivateCircuitPublicInputs, PublicCallRequest } from '@aztec/stdlib/kernel';
7
+ import { ChonkProof } from '@aztec/stdlib/proofs';
8
+ import { HashedValues, PrivateCallExecutionResult, PrivateExecutionResult, Tx, TxContext, TxSimulationResult } from '@aztec/stdlib/tx';
9
+ /**
10
+ * Splits an execution payload into a leading prefix of public static calls
11
+ * (eligible for direct node simulation) and the remaining calls.
12
+ *
13
+ * Only a leading run of public static calls is eligible for optimization.
14
+ * Any non-public-static call may enqueue public state mutations
15
+ * (e.g. private calls can enqueue public calls), so all calls that follow
16
+ * must go through the normal simulation path to see the correct state.
17
+ *
18
+ */ export function extractOptimizablePublicStaticCalls(payload) {
19
+ const splitIndex = payload.calls.findIndex((call)=>!call.isPublicStatic());
20
+ const boundary = splitIndex === -1 ? payload.calls.length : splitIndex;
21
+ return {
22
+ optimizableCalls: payload.calls.slice(0, boundary),
23
+ remainingCalls: payload.calls.slice(boundary)
24
+ };
25
+ }
26
+ /**
27
+ * Simulates a batch of public static calls by bypassing account entrypoint and private execution,
28
+ * directly constructing a minimal Tx and calling node.simulatePublicCalls.
29
+ *
30
+ * @param node - The Aztec node to simulate on.
31
+ * @param publicStaticCalls - Array of public static function calls (max MAX_ENQUEUED_CALLS_PER_CALL).
32
+ * @param from - The account address making the calls.
33
+ * @param chainInfo - Chain information (chainId and version).
34
+ * @param gasSettings - Gas settings for the transaction.
35
+ * @param blockHeader - Block header to use as anchor.
36
+ * @param skipFeeEnforcement - Whether to skip fee enforcement during simulation.
37
+ * @returns TxSimulationResult with public return values.
38
+ */ async function simulateBatchViaNode(node, publicStaticCalls, from, chainInfo, gasSettings, blockHeader, skipFeeEnforcement, getContractName) {
39
+ const txContext = new TxContext(chainInfo.chainId, chainInfo.version, gasSettings);
40
+ const publicFunctionCalldata = [];
41
+ for (const call of publicStaticCalls){
42
+ const calldata = await HashedValues.fromCalldata([
43
+ call.selector.toField(),
44
+ ...call.args
45
+ ]);
46
+ publicFunctionCalldata.push(calldata);
47
+ }
48
+ const publicCallRequests = makeTuple(MAX_ENQUEUED_CALLS_PER_CALL, (i)=>{
49
+ const call = publicStaticCalls[i];
50
+ if (!call) {
51
+ return CountedPublicCallRequest.empty();
52
+ }
53
+ const publicCallRequest = new PublicCallRequest(from, call.to, call.isStatic, publicFunctionCalldata[i].hash);
54
+ // Counter starts at 1 (minRevertibleSideEffectCounter) so all calls are revertible
55
+ return new CountedPublicCallRequest(publicCallRequest, i + 1);
56
+ });
57
+ const publicCallRequestsArray = new ClaimedLengthArray(publicCallRequests, publicStaticCalls.length);
58
+ const publicInputs = PrivateCircuitPublicInputs.from({
59
+ ...PrivateCircuitPublicInputs.empty(),
60
+ anchorBlockHeader: blockHeader,
61
+ txContext: txContext,
62
+ publicCallRequests: publicCallRequestsArray,
63
+ startSideEffectCounter: new Fr(0),
64
+ endSideEffectCounter: new Fr(publicStaticCalls.length + 1)
65
+ });
66
+ // Minimal entrypoint structure — no real private execution, just public call requests
67
+ const emptyEntrypoint = new PrivateCallExecutionResult(Buffer.alloc(0), Buffer.alloc(0), new Map(), publicInputs, [], new Map(), [], [], [], [], []);
68
+ const privateResult = new PrivateExecutionResult(emptyEntrypoint, Fr.random(), publicFunctionCalldata);
69
+ const provingResult = await generateSimulatedProvingResult(privateResult, (_contractAddress, _functionSelector)=>Promise.resolve(''), node, 1);
70
+ provingResult.publicInputs.feePayer = from;
71
+ const tx = await Tx.create({
72
+ data: provingResult.publicInputs,
73
+ chonkProof: ChonkProof.empty(),
74
+ contractClassLogFields: [],
75
+ publicFunctionCalldata: publicFunctionCalldata
76
+ });
77
+ const publicOutput = await node.simulatePublicCalls(tx, skipFeeEnforcement);
78
+ if (publicOutput.revertReason) {
79
+ throw publicOutput.revertReason;
80
+ }
81
+ // Display debug logs from the public simulation.
82
+ await displayDebugLogs(publicOutput.debugLogs, getContractName);
83
+ return new TxSimulationResult(privateResult, provingResult.publicInputs, publicOutput, undefined);
84
+ }
85
+ /**
86
+ * Simulates public static calls by splitting them into batches of MAX_ENQUEUED_CALLS_PER_CALL
87
+ * and sending each batch directly to the node.
88
+ *
89
+ * @param node - The Aztec node to simulate on.
90
+ * @param publicStaticCalls - Array of public static function calls to optimize.
91
+ * @param from - The account address making the calls.
92
+ * @param chainInfo - Chain information (chainId and version).
93
+ * @param gasSettings - Gas settings for the transaction.
94
+ * @param blockHeader - Block header to use as anchor.
95
+ * @param skipFeeEnforcement - Whether to skip fee enforcement during simulation.
96
+ * @returns Array of TxSimulationResult, one per batch.
97
+ */ export async function simulateViaNode(node, publicStaticCalls, from, chainInfo, gasSettings, blockHeader, skipFeeEnforcement = true, getContractName) {
98
+ const batches = [];
99
+ for(let i = 0; i < publicStaticCalls.length; i += MAX_ENQUEUED_CALLS_PER_CALL){
100
+ batches.push(publicStaticCalls.slice(i, i + MAX_ENQUEUED_CALLS_PER_CALL));
101
+ }
102
+ const results = [];
103
+ for (const batch of batches){
104
+ const result = await simulateBatchViaNode(node, batch, from, chainInfo, gasSettings, blockHeader, skipFeeEnforcement, getContractName);
105
+ results.push(result);
106
+ }
107
+ return results;
108
+ }
109
+ /**
110
+ * Merges simulation results from the optimized (public static) and normal paths.
111
+ * Since optimized calls are always a leading prefix, return values are simply
112
+ * concatenated: optimized first, then normal.
113
+ * Stats are taken from the normal result only (the optimized path doesn't produce them).
114
+ *
115
+ * @param optimizedResults - Results from optimized public static call batches.
116
+ * @param normalResult - Result from normal simulation (null if all calls were optimized).
117
+ * @returns A single TxSimulationResult with return values in original call order.
118
+ */ export function buildMergedSimulationResult(optimizedResults, normalResult) {
119
+ const optimizedReturnValues = optimizedResults.flatMap((r)=>r.publicOutput?.publicReturnValues ?? []);
120
+ const normalReturnValues = normalResult?.publicOutput?.publicReturnValues ?? [];
121
+ const allReturnValues = [
122
+ ...optimizedReturnValues,
123
+ ...normalReturnValues
124
+ ];
125
+ const baseResult = normalResult ?? optimizedResults[0];
126
+ const mergedPublicOutput = baseResult.publicOutput ? {
127
+ ...baseResult.publicOutput,
128
+ publicReturnValues: allReturnValues
129
+ } : undefined;
130
+ return new TxSimulationResult(baseResult.privateExecutionResult, baseResult.publicInputs, mergedPublicOutput, normalResult?.stats);
131
+ }