@aztec/wallet-sdk 0.0.1-commit.3469e52 → 0.0.1-commit.350e0a4d

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 (103) hide show
  1. package/README.md +318 -270
  2. package/dest/base-wallet/base_wallet.d.ts +115 -40
  3. package/dest/base-wallet/base_wallet.d.ts.map +1 -1
  4. package/dest/base-wallet/base_wallet.js +345 -105
  5. package/dest/base-wallet/get_gas_limits.d.ts +36 -0
  6. package/dest/base-wallet/get_gas_limits.d.ts.map +1 -0
  7. package/dest/base-wallet/get_gas_limits.js +55 -0
  8. package/dest/base-wallet/index.d.ts +4 -2
  9. package/dest/base-wallet/index.d.ts.map +1 -1
  10. package/dest/base-wallet/index.js +2 -0
  11. package/dest/base-wallet/utils.d.ts +52 -0
  12. package/dest/base-wallet/utils.d.ts.map +1 -0
  13. package/dest/base-wallet/utils.js +137 -0
  14. package/dest/crypto.d.ts +97 -50
  15. package/dest/crypto.d.ts.map +1 -1
  16. package/dest/crypto.js +290 -108
  17. package/dest/emoji_alphabet.d.ts +35 -0
  18. package/dest/emoji_alphabet.d.ts.map +1 -0
  19. package/dest/emoji_alphabet.js +299 -0
  20. package/dest/extension/handlers/background_connection_handler.d.ts +168 -0
  21. package/dest/extension/handlers/background_connection_handler.d.ts.map +1 -0
  22. package/dest/extension/handlers/background_connection_handler.js +294 -0
  23. package/dest/extension/handlers/content_script_connection_handler.d.ts +57 -0
  24. package/dest/extension/handlers/content_script_connection_handler.d.ts.map +1 -0
  25. package/dest/extension/handlers/content_script_connection_handler.js +193 -0
  26. package/dest/extension/handlers/index.d.ts +12 -0
  27. package/dest/extension/handlers/index.d.ts.map +1 -0
  28. package/dest/extension/handlers/index.js +10 -0
  29. package/dest/extension/handlers/internal_message_types.d.ts +65 -0
  30. package/dest/extension/handlers/internal_message_types.d.ts.map +1 -0
  31. package/dest/extension/handlers/internal_message_types.js +24 -0
  32. package/dest/extension/provider/extension_provider.d.ts +107 -0
  33. package/dest/extension/provider/extension_provider.d.ts.map +1 -0
  34. package/dest/extension/provider/extension_provider.js +160 -0
  35. package/dest/extension/provider/extension_wallet.d.ts +152 -0
  36. package/dest/extension/provider/extension_wallet.d.ts.map +1 -0
  37. package/dest/{providers/extension → extension/provider}/extension_wallet.js +134 -103
  38. package/dest/extension/provider/index.d.ts +3 -0
  39. package/dest/extension/provider/index.d.ts.map +1 -0
  40. package/dest/{providers/extension → extension/provider}/index.js +0 -2
  41. package/dest/iframe/handlers/iframe_connection_handler.d.ts +122 -0
  42. package/dest/iframe/handlers/iframe_connection_handler.d.ts.map +1 -0
  43. package/dest/iframe/handlers/iframe_connection_handler.js +239 -0
  44. package/dest/iframe/handlers/index.d.ts +2 -0
  45. package/dest/iframe/handlers/index.d.ts.map +1 -0
  46. package/dest/iframe/handlers/index.js +1 -0
  47. package/dest/iframe/provider/iframe_discovery.d.ts +25 -0
  48. package/dest/iframe/provider/iframe_discovery.d.ts.map +1 -0
  49. package/dest/iframe/provider/iframe_discovery.js +167 -0
  50. package/dest/iframe/provider/iframe_provider.d.ts +65 -0
  51. package/dest/iframe/provider/iframe_provider.d.ts.map +1 -0
  52. package/dest/iframe/provider/iframe_provider.js +257 -0
  53. package/dest/iframe/provider/iframe_wallet.d.ts +85 -0
  54. package/dest/iframe/provider/iframe_wallet.d.ts.map +1 -0
  55. package/dest/iframe/provider/iframe_wallet.js +269 -0
  56. package/dest/iframe/provider/index.d.ts +4 -0
  57. package/dest/iframe/provider/index.d.ts.map +1 -0
  58. package/dest/iframe/provider/index.js +3 -0
  59. package/dest/manager/index.d.ts +2 -8
  60. package/dest/manager/index.d.ts.map +1 -1
  61. package/dest/manager/index.js +0 -6
  62. package/dest/manager/types.d.ts +92 -9
  63. package/dest/manager/types.d.ts.map +1 -1
  64. package/dest/manager/types.js +17 -1
  65. package/dest/manager/wallet_manager.d.ts +50 -7
  66. package/dest/manager/wallet_manager.d.ts.map +1 -1
  67. package/dest/manager/wallet_manager.js +203 -43
  68. package/dest/types.d.ts +104 -11
  69. package/dest/types.d.ts.map +1 -1
  70. package/dest/types.js +32 -2
  71. package/package.json +21 -10
  72. package/src/base-wallet/base_wallet.ts +449 -167
  73. package/src/base-wallet/get_gas_limits.ts +88 -0
  74. package/src/base-wallet/index.ts +8 -1
  75. package/src/base-wallet/utils.ts +248 -0
  76. package/src/crypto.ts +341 -113
  77. package/src/emoji_alphabet.ts +317 -0
  78. package/src/extension/handlers/background_connection_handler.ts +456 -0
  79. package/src/extension/handlers/content_script_connection_handler.ts +264 -0
  80. package/src/extension/handlers/index.ts +25 -0
  81. package/src/extension/handlers/internal_message_types.ts +71 -0
  82. package/src/extension/provider/extension_provider.ts +233 -0
  83. package/src/{providers/extension → extension/provider}/extension_wallet.ts +151 -120
  84. package/src/extension/provider/index.ts +7 -0
  85. package/src/iframe/handlers/iframe_connection_handler.ts +341 -0
  86. package/src/iframe/handlers/index.ts +7 -0
  87. package/src/iframe/provider/iframe_discovery.ts +185 -0
  88. package/src/iframe/provider/iframe_provider.ts +331 -0
  89. package/src/iframe/provider/iframe_wallet.ts +323 -0
  90. package/src/iframe/provider/index.ts +3 -0
  91. package/src/manager/index.ts +2 -10
  92. package/src/manager/types.ts +95 -8
  93. package/src/manager/wallet_manager.ts +223 -45
  94. package/src/types.ts +116 -10
  95. package/dest/providers/extension/extension_provider.d.ts +0 -63
  96. package/dest/providers/extension/extension_provider.d.ts.map +0 -1
  97. package/dest/providers/extension/extension_provider.js +0 -124
  98. package/dest/providers/extension/extension_wallet.d.ts +0 -155
  99. package/dest/providers/extension/extension_wallet.d.ts.map +0 -1
  100. package/dest/providers/extension/index.d.ts +0 -6
  101. package/dest/providers/extension/index.d.ts.map +0 -1
  102. package/src/providers/extension/extension_provider.ts +0 -167
  103. package/src/providers/extension/index.ts +0 -5
@@ -1,14 +1,23 @@
1
- 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';
1
+ import { NO_FROM } from '@aztec/aztec.js/account';
2
+ import { NO_WAIT, extractOffchainOutput } from '@aztec/aztec.js/contracts';
3
+ import { waitForTx } from '@aztec/aztec.js/node';
4
+ import { ContractInitializationStatus, TxSimulationResultWithAppOffset } from '@aztec/aztec.js/wallet';
2
5
  import { AccountFeePaymentMethodOptions } from '@aztec/entrypoints/account';
6
+ import { DefaultEntrypoint } from '@aztec/entrypoints/default';
3
7
  import { Fr } from '@aztec/foundation/curves/bn254';
4
8
  import { createLogger } from '@aztec/foundation/log';
9
+ import { displayDebugLogs } from '@aztec/pxe/client/lazy';
5
10
  import { decodeFromAbi } from '@aztec/stdlib/abi';
6
- import { computePartialAddress, getContractClassFromArtifact } from '@aztec/stdlib/contract';
11
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
12
+ import { computePartialAddress } from '@aztec/stdlib/contract';
7
13
  import { SimulationError } from '@aztec/stdlib/errors';
8
- import { Gas, GasSettings } from '@aztec/stdlib/gas';
9
- 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';
10
17
  import { mergeExecutionPayloads } from '@aztec/stdlib/tx';
11
18
  import { inspect } from 'util';
19
+ import { assertGasLimitsWithinNetworkLimits } from './get_gas_limits.js';
20
+ import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simulateViaNode } from './utils.js';
12
21
  /**
13
22
  * A base class for Wallet implementations
14
23
  */ export class BaseWallet {
@@ -17,14 +26,39 @@ import { inspect } from 'util';
17
26
  log;
18
27
  minFeePadding;
19
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;
20
35
  // Protected because we want to force wallets to instantiate their own PXE.
21
- constructor(pxe, aztecNode){
36
+ constructor(pxe, aztecNode, log = createLogger('wallet-sdk:base_wallet')){
22
37
  this.pxe = pxe;
23
38
  this.aztecNode = aztecNode;
24
- this.log = createLogger('wallet-sdk:base_wallet');
39
+ this.log = log;
25
40
  this.minFeePadding = 0.5;
26
41
  this.cancellableTransactions = false;
27
42
  }
43
+ scopesFrom(from, additionalScopes = []) {
44
+ const allScopes = from === NO_FROM ? additionalScopes : [
45
+ from,
46
+ ...additionalScopes
47
+ ];
48
+ const scopeSet = new Set(allScopes.map((address)=>address.toString()));
49
+ return [
50
+ ...scopeSet
51
+ ].map(AztecAddress.fromStringUnsafe);
52
+ }
53
+ /**
54
+ * Picks the sender address PXE should tag private messages with. Returns `undefined` when there is no signing
55
+ * account (`from === NO_FROM`) and no explicit override; in that case any private log emitted by the tx using
56
+ * the wallet-supplied default sender will fail the "Sender for tags is not set" assertion.
57
+ * @param from - Tx sender, or `NO_FROM`.
58
+ * @param sendMessagesAs - Explicit override.
59
+ */ senderForTagsFrom(from, sendMessagesAs) {
60
+ return sendMessagesAs ?? (from === NO_FROM ? undefined : from);
61
+ }
28
62
  /**
29
63
  * Returns the list of aliased contacts associated with the wallet.
30
64
  * This base implementation directly returns PXE's senders, but note that in general contacts are a superset of senders.
@@ -32,39 +66,85 @@ import { inspect } from 'util';
32
66
  * - Contacts: more general concept akin to a phone's contact list.
33
67
  * @returns The aliased collection of AztecAddresses that form this wallet's address book
34
68
  */ async getAddressBook() {
35
- const senders = await this.pxe.getSenders();
36
- return senders.map((sender)=>({
37
- item: sender,
69
+ const sources = await this.pxe.getTaggingSecretSources({
70
+ kind: 'address-derived'
71
+ });
72
+ return sources.map((source)=>({
73
+ item: source.sender,
38
74
  alias: ''
39
75
  }));
40
76
  }
77
+ /**
78
+ * Fetches and caches the node info for the wallet's lifetime, since a wallet talks to a single network and
79
+ * node info never changes. A rejected fetch clears the cache so the next call retries instead of replaying
80
+ * the cached rejection forever — important because the gas-limit fill-in and validation (run on every send)
81
+ * depend on it.
82
+ */ getNodeInfo() {
83
+ if (!this.nodeInfoPromise) {
84
+ this.nodeInfoPromise = this.aztecNode.getNodeInfo().catch((err)=>{
85
+ this.nodeInfoPromise = undefined;
86
+ throw err;
87
+ });
88
+ }
89
+ return this.nodeInfoPromise;
90
+ }
41
91
  async getChainInfo() {
42
- const { l1ChainId, rollupVersion } = await this.aztecNode.getNodeInfo();
92
+ const { l1ChainId, rollupVersion } = await this.getNodeInfo();
43
93
  return {
44
94
  chainId: new Fr(l1ChainId),
45
95
  version: new Fr(rollupVersion)
46
96
  };
47
97
  }
98
+ /**
99
+ * Returns the maximum gas limits a single transaction may declare on this wallet's network (the
100
+ * node-advertised `txsLimits.gas`). Internal helper used to fill in default gas limits when sending a
101
+ * transaction without explicit limits, and to validate caller-provided limits before sending. Backed by
102
+ * the cached node info, since a wallet talks to a single network.
103
+ */ async getMaxTxGasLimits() {
104
+ const { txsLimits } = await this.getNodeInfo();
105
+ return new Gas(txsLimits.gas.daGas, txsLimits.gas.l2Gas);
106
+ }
48
107
  async createTxExecutionRequestFromPayloadAndFee(executionPayload, from, feeOptions) {
49
108
  const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
50
- const executionOptions = {
51
- txNonce: Fr.random(),
52
- cancellable: this.cancellableTransactions,
53
- feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions
54
- };
55
109
  const finalExecutionPayload = feeExecutionPayload ? mergeExecutionPayloads([
56
110
  feeExecutionPayload,
57
111
  executionPayload
58
112
  ]) : executionPayload;
59
- const fromAccount = await this.getAccountFromAddress(from);
60
113
  const chainInfo = await this.getChainInfo();
61
- return fromAccount.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo, executionOptions);
114
+ if (from === NO_FROM) {
115
+ const entrypoint = new DefaultEntrypoint();
116
+ return entrypoint.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo);
117
+ } else {
118
+ const fromAccount = await this.getAccountFromAddress(from);
119
+ const executionOptions = {
120
+ txNonce: Fr.random(),
121
+ cancellable: this.cancellableTransactions,
122
+ // If from is an address, feeOptions include the way the account contract should handle the fee payment
123
+ feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions
124
+ };
125
+ return fromAccount.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo, executionOptions);
126
+ }
62
127
  }
63
128
  async createAuthWit(from, messageHashOrIntent) {
64
129
  const account = await this.getAccountFromAddress(from);
65
130
  const chainInfo = await this.getChainInfo();
66
131
  return account.createAuthWit(messageHashOrIntent, chainInfo);
67
132
  }
133
+ /**
134
+ * Request capabilities from the wallet.
135
+ *
136
+ * This method is wallet-implementation-dependent and must be provided by classes extending BaseWallet.
137
+ * Embedded wallets typically don't support capability-based authorization (no user authorization flow),
138
+ * while external wallets (browser extensions, hardware wallets) implement this to reduce authorization
139
+ * friction by allowing apps to request permissions upfront.
140
+ *
141
+ * TODO: Consider making it abstract so implementing it is a conscious decision. Leaving it as-is
142
+ * while the feature stabilizes.
143
+ *
144
+ * @param _manifest - Application capability manifest declaring what operations the app needs
145
+ */ requestCapabilities(_manifest) {
146
+ throw new Error('Not implemented');
147
+ }
68
148
  async batch(methods) {
69
149
  const results = [];
70
150
  for (const method of methods){
@@ -86,26 +166,50 @@ import { inspect } from 'util';
86
166
  }
87
167
  /**
88
168
  * Completes partial user-provided fee options with wallet defaults.
89
- * @param from - The address where the transaction is being sent from
90
- * @param feePayer - The address paying for fees (if any fee payment method is embedded in the execution payload)
91
- * @param gasSettings - User-provided partial gas settings
92
- * @returns - Complete fee options that can be used to create a transaction execution request
93
- */ async completeFeeOptions(from, feePayer, gasSettings) {
94
- const maxFeesPerGas = gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentMinFees()).mul(1 + this.minFeePadding);
169
+ * @param config - Fee completion config.
170
+ */ async completeFeeOptions(config) {
171
+ const { from, feePayer, gasSettings, forEstimation, congestionEstimate } = config;
172
+ const maxFeesPerGas = gasSettings?.maxFeesPerGas ?? (await this.getMinFees(congestionEstimate)).mul(1 + this.minFeePadding);
95
173
  let accountFeePaymentMethodOptions;
96
- // The transaction does not include a fee payment method, so we set the flag
97
- // for the account to use its fee juice balance
98
- if (!feePayer) {
99
- accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
174
+ // If from is an address, we need to determine the appropriate fee payment method options for the
175
+ // account contract entrypoint to use
176
+ if (from !== NO_FROM) {
177
+ if (!feePayer) {
178
+ // The transaction does not include a fee payment method, so we set the flag
179
+ // for the account to use its fee juice balance
180
+ accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
181
+ } else {
182
+ // The transaction includes fee payment method, so we check if we are the fee payer for it
183
+ // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
184
+ accountFeePaymentMethodOptions = from.equals(feePayer) ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM : AccountFeePaymentMethodOptions.EXTERNAL;
185
+ }
186
+ }
187
+ const gasSettingsOverrides = {
188
+ gasLimits: gasSettings?.gasLimits ? Gas.from(gasSettings.gasLimits) : undefined,
189
+ teardownGasLimits: gasSettings?.teardownGasLimits ? Gas.from(gasSettings.teardownGasLimits) : undefined,
190
+ maxFeesPerGas,
191
+ maxPriorityFeesPerGas: gasSettings?.maxPriorityFeesPerGas ?? GasFees.empty()
192
+ };
193
+ // When estimating gas (simulation), use high limits so the simulation doesn't run out of gas.
194
+ // When sending for real without explicit limits, declare the most a single tx may use on this network
195
+ // (the node's per-tx admission limit), so the proposer does not skip the tx for over-declaring gas.
196
+ let fullGasSettings;
197
+ if (forEstimation) {
198
+ // Estimation deliberately uses very high internal limits and skips tx validation, so we do not
199
+ // validate against the network admission limit here.
200
+ fullGasSettings = GasSettings.forEstimation(gasSettingsOverrides);
100
201
  } else {
101
- // The transaction includes fee payment method, so we check if we are the fee payer for it
102
- // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
103
- accountFeePaymentMethodOptions = from.equals(feePayer) ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM : AccountFeePaymentMethodOptions.EXTERNAL;
202
+ const maxTxGasLimits = await this.getMaxTxGasLimits();
203
+ // If the caller declared explicit gas limits, reject them up front when they exceed the network's
204
+ // per-tx admission limit (mirroring the node's GasLimitsValidator). Otherwise fill in the limit.
205
+ if (gasSettingsOverrides.gasLimits) {
206
+ assertGasLimitsWithinNetworkLimits(gasSettingsOverrides.gasLimits, maxTxGasLimits);
207
+ }
208
+ fullGasSettings = GasSettings.fallback({
209
+ ...gasSettingsOverrides,
210
+ gasLimits: gasSettingsOverrides.gasLimits ?? maxTxGasLimits
211
+ });
104
212
  }
105
- const fullGasSettings = GasSettings.default({
106
- ...gasSettings,
107
- maxFeesPerGas
108
- });
109
213
  this.log.debug(`Using L2 gas settings`, fullGasSettings);
110
214
  return {
111
215
  gasSettings: fullGasSettings,
@@ -114,75 +218,161 @@ import { inspect } from 'util';
114
218
  };
115
219
  }
116
220
  /**
117
- * Completes partial user-provided fee options with unreasonably high gas limits
118
- * for gas estimation. Uses the same logic as completeFeeOptions but sets high limits
119
- * to avoid running out of gas during estimation.
120
- * @param from - The address where the transaction is being sent from
121
- * @param feePayer - The address paying for fees (if any fee payment method is embedded in the execution payload)
122
- * @param gasSettings - User-provided partial gas settings
123
- */ async completeFeeOptionsForEstimation(from, feePayer, gasSettings) {
124
- const defaultFeeOptions = await this.completeFeeOptions(from, feePayer, gasSettings);
125
- const { gasSettings: { maxFeesPerGas, maxPriorityFeesPerGas } } = defaultFeeOptions;
126
- // Use unrealistically high gas limits for estimation to avoid running out of gas.
127
- // They will be tuned down after the simulation.
128
- 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);
129
- return {
130
- ...defaultFeeOptions,
131
- gasSettings: gasSettingsForEstimation
132
- };
133
- }
134
- registerSender(address, _alias = '') {
135
- return this.pxe.registerSender(address);
136
- }
137
- async registerContract(instance, artifact, secretKey) {
138
- const existingInstance = await this.pxe.getContractInstance(instance.address);
139
- if (existingInstance) {
140
- // Instance already registered in the wallet
141
- if (artifact) {
142
- const thisContractClass = await getContractClassFromArtifact(artifact);
143
- if (!thisContractClass.id.equals(existingInstance.currentContractClassId)) {
144
- // wallet holds an outdated version of this contract
145
- await this.pxe.updateContract(instance.address, artifact);
146
- instance.currentContractClassId = thisContractClass.id;
147
- }
221
+ * Returns the worst-case min fee across predicted future slots.
222
+ * Falls back to getCurrentMinFees if the node doesn't support getPredictedMinFees.
223
+ * @param estimate - The mana usage estimate to use for fee prediction. Defaults to Limit for conservative estimation.
224
+ */ async getMinFees(estimate = ManaUsageEstimate.Limit) {
225
+ try {
226
+ const predicted = await this.aztecNode.getPredictedMinFees(estimate);
227
+ if (predicted.length === 0) {
228
+ return this.aztecNode.getCurrentMinFees();
148
229
  }
149
- // If no artifact provided, we just use the existing registration
150
- } else {
151
- // Instance not registered yet
152
- if (!artifact) {
153
- // Try to get the artifact from the wallet's contract class storage
154
- artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
155
- if (!artifact) {
156
- 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()}`);
157
- }
230
+ return predicted.reduce((worst, fees)=>fees.feePerL2Gas > worst.feePerL2Gas ? fees : worst);
231
+ } catch (err) {
232
+ // Fallback for old nodes that don't support getPredictedMinFees.
233
+ // Only fall back on method-not-found errors (JSON-RPC code -32601); rethrow others.
234
+ if (err?.cause?.code === -32601 || err?.message?.includes('Method not found')) {
235
+ return this.aztecNode.getCurrentMinFees();
158
236
  }
159
- await this.pxe.registerContract({
160
- artifact,
161
- instance
162
- });
237
+ throw err;
238
+ }
239
+ }
240
+ async registerSender(address, _alias = '') {
241
+ await this.pxe.registerTaggingSecretSource({
242
+ kind: 'address-derived',
243
+ sender: address
244
+ });
245
+ return address;
246
+ }
247
+ async registerContract(instance, artifact, secretKeyOrKeys) {
248
+ // Classes and instances are registered independently: register the artifact (if provided) then the instance.
249
+ // Neither call validates that the artifact matches the class the instance runs, a missing artifact only surfaces
250
+ // when the contract is later simulated.
251
+ if (artifact) {
252
+ await this.pxe.registerContractClass(artifact);
163
253
  }
164
- if (secretKey) {
165
- await this.pxe.registerAccount(secretKey, await computePartialAddress(instance));
254
+ const contractAddress = await this.pxe.registerContract(instance);
255
+ if (secretKeyOrKeys) {
256
+ // PXE never receives the account seed (from which the message-signing/fallback secret keys could be re-derived):
257
+ // the wallet derives the keys here. Of these, PXE only reads and stores the four privacy secret keys and the
258
+ // message-signing and fallback *public* keys — it never touches the message-signing or fallback secret keys.
259
+ //
260
+ // Since PXE recomputes the address from those keys, we assert it matches the instance's address: a mismatch means
261
+ // the provided keys don't correspond to this account.
262
+ const derivedKeys = secretKeyOrKeys instanceof Fr ? await deriveKeys(secretKeyOrKeys) : await deriveKeysFromMasterSecretKeys(secretKeyOrKeys);
263
+ const { address } = await this.pxe.registerAccount(derivedKeys, await computePartialAddress(instance));
264
+ if (!address.equals(contractAddress)) {
265
+ 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.`);
266
+ }
166
267
  }
167
- return instance;
168
268
  }
169
- async simulateTx(executionPayload, opts) {
170
- 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);
171
- const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
172
- return this.pxe.simulateTx(txRequest, true, opts?.skipTxValidation, opts?.skipFeeEnforcement ?? true);
269
+ registerContractClass(artifact) {
270
+ return this.pxe.registerContractClass(artifact);
271
+ }
272
+ /**
273
+ * Simulates calls through the standard PXE path (account entrypoint).
274
+ * @param executionPayload - The execution payload to simulate.
275
+ * @param opts - Simulation options.
276
+ */ async simulateViaEntrypoint(executionPayload, opts) {
277
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, opts.feeOptions);
278
+ const result = await this.pxe.simulateTx(txRequest, {
279
+ simulatePublic: true,
280
+ skipTxValidation: opts.skipTxValidation,
281
+ skipFeeEnforcement: opts.skipFeeEnforcement,
282
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
283
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
284
+ overrides: opts.overrides
285
+ });
286
+ const appCallOffset = await this.computeAppCallOffset(opts.from, opts.feeOptions);
287
+ return TxSimulationResultWithAppOffset.fromResultAndOffset(result, appCallOffset);
288
+ }
289
+ /**
290
+ * Computes the index where the app's calls begin in the flattened array of calls (0 = entrypoint/root, 1..N = fee
291
+ * calls, N+1 = app).
292
+ * @param from - The sender address, or NO_FROM for the default entrypoint.
293
+ * @param feeOptions - Fee options containing the wallet fee payment method.
294
+ */ async computeAppCallOffset(from, feeOptions) {
295
+ if (from === NO_FROM) {
296
+ return 0;
297
+ }
298
+ const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
299
+ return (feeExecutionPayload?.calls.length ?? 0) + 1; // +1 for entrypoint
300
+ }
301
+ /**
302
+ * Simulates a transaction, optimizing leading public static calls by running them directly
303
+ * on the node while sending the remaining calls through the standard PXE path.
304
+ * Return values from both paths are merged back in original call order.
305
+ * @param executionPayload - The execution payload to simulate.
306
+ * @param opts - Simulation options (from address, fee settings, etc.).
307
+ * @returns The merged simulation result.
308
+ */ async simulateTx(executionPayload, opts) {
309
+ const feeOptions = await this.completeFeeOptions({
310
+ from: opts.from,
311
+ feePayer: executionPayload.feePayer,
312
+ gasSettings: opts.fee?.gasSettings,
313
+ forEstimation: true,
314
+ congestionEstimate: opts.fee?.congestionEstimate
315
+ });
316
+ const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
317
+ const remainingPayload = {
318
+ ...executionPayload,
319
+ calls: remainingCalls
320
+ };
321
+ const chainInfo = await this.getChainInfo();
322
+ let blockHeader;
323
+ // PXE might not be synced yet, so we pull the latest header from the node
324
+ // To keep things consistent, we'll always try with PXE first
325
+ try {
326
+ blockHeader = await this.pxe.getSyncedBlockHeader();
327
+ } catch {
328
+ blockHeader = (await this.aztecNode.getBlockData('latest')).header;
329
+ }
330
+ const simulationOrigin = opts.from === NO_FROM ? AztecAddress.ZERO : opts.from;
331
+ const [optimizedResults, normalResult] = await Promise.all([
332
+ optimizableCalls.length > 0 ? simulateViaNode(this.aztecNode, optimizableCalls, simulationOrigin, chainInfo, feeOptions.gasSettings, blockHeader, opts.skipFeeEnforcement ?? true, this.getContractName.bind(this), opts.overrides) : Promise.resolve([]),
333
+ remainingCalls.length > 0 ? this.simulateViaEntrypoint(remainingPayload, {
334
+ from: opts.from,
335
+ feeOptions,
336
+ additionalScopes: opts.additionalScopes,
337
+ skipTxValidation: opts.skipTxValidation,
338
+ skipFeeEnforcement: opts.skipFeeEnforcement ?? true,
339
+ sendMessagesAs: opts.sendMessagesAs,
340
+ overrides: opts.overrides
341
+ }) : Promise.resolve(null)
342
+ ]);
343
+ return buildMergedSimulationResult(optimizedResults, normalResult);
173
344
  }
174
345
  async profileTx(executionPayload, opts) {
175
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
346
+ const feeOptions = await this.completeFeeOptions({
347
+ from: opts.from,
348
+ feePayer: executionPayload.feePayer,
349
+ gasSettings: opts.fee?.gasSettings,
350
+ congestionEstimate: opts.fee?.congestionEstimate
351
+ });
176
352
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
177
- return this.pxe.profileTx(txRequest, opts.profileMode, opts.skipProofGeneration ?? true);
353
+ return this.pxe.profileTx(txRequest, {
354
+ profileMode: opts.profileMode,
355
+ skipProofGeneration: opts.skipProofGeneration ?? true,
356
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
357
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs)
358
+ });
178
359
  }
179
360
  async sendTx(executionPayload, opts) {
180
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
361
+ const feeOptions = await this.completeFeeOptions({
362
+ from: opts.from,
363
+ feePayer: executionPayload.feePayer,
364
+ gasSettings: opts.fee?.gasSettings,
365
+ congestionEstimate: opts.fee?.congestionEstimate
366
+ });
181
367
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
182
- const provenTx = await this.pxe.proveTx(txRequest);
368
+ const provenTx = await this.pxe.proveTx(txRequest, {
369
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
370
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs)
371
+ });
372
+ const offchainOutput = extractOffchainOutput(provenTx.getOffchainEffects(), provenTx.publicInputs.constants.anchorBlockHeader.globalVariables.timestamp);
183
373
  const tx = await provenTx.toTx();
184
374
  const txHash = tx.getTxHash();
185
- if (await this.aztecNode.getTxEffect(txHash)) {
375
+ if ((await this.aztecNode.getTxReceipt(txHash)).isMined()) {
186
376
  throw new Error(`A settled tx with equal hash ${txHash.toString()} exists.`);
187
377
  }
188
378
  this.log.debug(`Sending transaction ${txHash}`);
@@ -190,7 +380,43 @@ import { inspect } from 'util';
190
380
  throw this.contextualizeError(err, inspect(tx));
191
381
  });
192
382
  this.log.info(`Sent transaction ${txHash}`);
193
- return txHash;
383
+ // If wait is NO_WAIT, return txHash immediately
384
+ if (opts.wait === NO_WAIT) {
385
+ return {
386
+ txHash,
387
+ ...offchainOutput
388
+ };
389
+ }
390
+ // Otherwise, wait for the full receipt (default behavior on wait: undefined)
391
+ const callerWaitOpts = typeof opts.wait === 'object' ? opts.wait : undefined;
392
+ const waitOpts = this.defaultWaitInterval !== undefined && callerWaitOpts?.interval === undefined ? {
393
+ ...callerWaitOpts,
394
+ interval: this.defaultWaitInterval
395
+ } : callerWaitOpts;
396
+ const receipt = await waitForTx(this.aztecNode, txHash, waitOpts);
397
+ // Display debug logs from public execution if present (served in test mode only)
398
+ if (receipt.isMined() && receipt.debugLogs?.length) {
399
+ await displayDebugLogs(receipt.debugLogs, this.getContractName.bind(this));
400
+ }
401
+ return {
402
+ receipt,
403
+ ...offchainOutput
404
+ };
405
+ }
406
+ /**
407
+ * Resolves a contract address to a human-readable name via PXE, if available.
408
+ * @param address - The contract address to resolve.
409
+ */ async getContractName(address) {
410
+ const instance = await this.pxe.getContractInstance(address);
411
+ if (!instance) {
412
+ return undefined;
413
+ }
414
+ // Contract names are class-stable (an upgrade preserves the contract name), so the original class artifact is a
415
+ // sufficient source for the display name without resolving the current class against the node.
416
+ // TODO: if a contract were to be upgraded and its original artifact never registered, then this would fail and we'd
417
+ // want to fallback to the current class.
418
+ const artifact = await this.pxe.getContractArtifact(instance.originalContractClassId);
419
+ return artifact?.name;
194
420
  }
195
421
  contextualizeError(err, ...context) {
196
422
  let contextStr = '';
@@ -205,11 +431,11 @@ import { inspect } from 'util';
205
431
  }
206
432
  return err;
207
433
  }
208
- simulateUtility(call, authwits) {
209
- return this.pxe.simulateUtility(call, authwits);
210
- }
211
- getTxReceipt(txHash) {
212
- return this.aztecNode.getTxReceipt(txHash);
434
+ executeUtility(call, opts) {
435
+ return this.pxe.executeUtility(call, {
436
+ authwits: opts.authWitnesses,
437
+ scopes: opts.scopes
438
+ });
213
439
  }
214
440
  async getPrivateEvents(eventDef, eventFilter) {
215
441
  const pxeEvents = await this.pxe.getPrivateEvents(eventDef.eventSelector, eventFilter);
@@ -227,20 +453,34 @@ import { inspect } from 'util';
227
453
  });
228
454
  return decodedEvents;
229
455
  }
230
- async getContractMetadata(address) {
456
+ /**
457
+ * Returns metadata about a contract, including whether it has been initialized, published, and updated.
458
+ * @param address - The contract address to query.
459
+ */ async getContractMetadata(address) {
231
460
  const instance = await this.pxe.getContractInstance(address);
232
- const initNullifier = await siloNullifier(address, address.toField());
233
- const publiclyRegisteredContract = await this.aztecNode.getContract(address);
234
- const [initNullifierMembershipWitness, publiclyRegisteredContractClass] = await Promise.all([
235
- this.aztecNode.getNullifierMembershipWitness('latest', initNullifier),
236
- publiclyRegisteredContract ? this.aztecNode.getContractClass(publiclyRegisteredContract.currentContractClassId || instance?.currentContractClassId) : undefined
237
- ]);
461
+ const publiclyRegisteredContractPromise = this.aztecNode.getContract(address);
462
+ let initializationStatus;
463
+ if (instance) {
464
+ // We have the instance, so we can compute the private initialization nullifier (which includes init_hash and is
465
+ // emitted by both private and public initializers) and get a definitive INITIALIZED/UNINITIALIZED answer.
466
+ const initNullifier = await computeSiloedPrivateInitializationNullifier(address, instance.initializationHash);
467
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
468
+ initializationStatus = witness ? ContractInitializationStatus.INITIALIZED : ContractInitializationStatus.UNINITIALIZED;
469
+ } else {
470
+ // Without the instance we lack the init_hash needed for the private nullifier. We fall back to checking the
471
+ // public initialization nullifier (computed from address alone). Not all contracts emit it (only those with
472
+ // public functions that require initialization checks), so its absence doesn't mean the contract is
473
+ // uninitialized.
474
+ const publicNullifier = await computeSiloedPublicInitializationNullifier(address);
475
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', publicNullifier);
476
+ initializationStatus = witness ? ContractInitializationStatus.INITIALIZED : ContractInitializationStatus.UNKNOWN;
477
+ }
478
+ const publiclyRegisteredContract = await publiclyRegisteredContractPromise;
238
479
  const isContractUpdated = publiclyRegisteredContract && !publiclyRegisteredContract.currentContractClassId.equals(publiclyRegisteredContract.originalContractClassId);
239
480
  return {
240
481
  instance: instance ?? undefined,
241
- isContractInitialized: !!initNullifierMembershipWitness,
482
+ initializationStatus,
242
483
  isContractPublished: !!publiclyRegisteredContract,
243
- isContractClassPubliclyRegistered: !!publiclyRegisteredContractClass,
244
484
  isContractUpdated: !!isContractUpdated,
245
485
  updatedContractClassId: isContractUpdated ? publiclyRegisteredContract.currentContractClassId : undefined
246
486
  };
@@ -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"}