@walletmesh/aztec-rpc-wallet 0.3.1 → 0.4.0

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 (185) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +290 -228
  3. package/dist/.tsbuildinfo +1 -1
  4. package/dist/client/aztec-dapp-wallet.d.ts +401 -0
  5. package/dist/client/aztec-dapp-wallet.d.ts.map +1 -0
  6. package/dist/client/aztec-dapp-wallet.js +705 -0
  7. package/dist/client/aztec-router-provider.d.ts +58 -0
  8. package/dist/client/aztec-router-provider.d.ts.map +1 -0
  9. package/dist/client/aztec-router-provider.js +62 -0
  10. package/dist/client/helpers.d.ts +44 -0
  11. package/dist/client/helpers.d.ts.map +1 -0
  12. package/dist/client/helpers.js +79 -0
  13. package/dist/client/register-serializers.d.ts +41 -0
  14. package/dist/client/register-serializers.d.ts.map +1 -0
  15. package/dist/client/register-serializers.js +97 -0
  16. package/dist/contractArtifactCache.d.ts +49 -32
  17. package/dist/contractArtifactCache.d.ts.map +1 -1
  18. package/dist/contractArtifactCache.js +47 -34
  19. package/dist/errors.d.ts +50 -8
  20. package/dist/errors.d.ts.map +1 -1
  21. package/dist/errors.js +50 -10
  22. package/dist/index.d.ts +53 -40
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +52 -17
  25. package/dist/types.d.ts +345 -270
  26. package/dist/types.d.ts.map +1 -1
  27. package/dist/types.js +10 -8
  28. package/dist/wallet/create-node.d.ts +73 -0
  29. package/dist/wallet/create-node.d.ts.map +1 -0
  30. package/dist/wallet/create-node.js +99 -0
  31. package/dist/wallet/handlers/account.d.ts +67 -0
  32. package/dist/wallet/handlers/account.d.ts.map +1 -0
  33. package/dist/wallet/handlers/account.js +85 -0
  34. package/dist/wallet/handlers/contract-interaction.d.ts +77 -0
  35. package/dist/wallet/handlers/contract-interaction.d.ts.map +1 -0
  36. package/dist/wallet/handlers/contract-interaction.js +219 -0
  37. package/dist/wallet/handlers/contract.d.ts +96 -0
  38. package/dist/wallet/handlers/contract.d.ts.map +1 -0
  39. package/dist/wallet/handlers/contract.js +146 -0
  40. package/dist/wallet/handlers/event.d.ts +62 -0
  41. package/dist/wallet/handlers/event.d.ts.map +1 -0
  42. package/dist/wallet/handlers/event.js +85 -0
  43. package/dist/wallet/handlers/index.d.ts +88 -0
  44. package/dist/wallet/handlers/index.d.ts.map +1 -0
  45. package/dist/wallet/handlers/index.js +47 -0
  46. package/dist/wallet/handlers/node.d.ts +117 -0
  47. package/dist/wallet/handlers/node.d.ts.map +1 -0
  48. package/dist/wallet/handlers/node.js +196 -0
  49. package/dist/wallet/handlers/senders.d.ts +70 -0
  50. package/dist/wallet/handlers/senders.d.ts.map +1 -0
  51. package/dist/wallet/handlers/senders.js +92 -0
  52. package/dist/wallet/handlers/transaction.d.ts +123 -0
  53. package/dist/wallet/handlers/transaction.d.ts.map +1 -0
  54. package/dist/wallet/handlers/transaction.js +191 -0
  55. package/dist/wallet/serializers.d.ts +75 -0
  56. package/dist/wallet/serializers.d.ts.map +1 -0
  57. package/dist/wallet/serializers.js +501 -0
  58. package/docs/README.md +290 -229
  59. package/docs/classes/AztecDappWallet.md +1304 -0
  60. package/docs/classes/AztecRouterProvider.md +1058 -0
  61. package/docs/classes/AztecWalletError.md +124 -47
  62. package/docs/classes/ContractArtifactCache.md +48 -31
  63. package/docs/functions/connectAztec.md +62 -0
  64. package/docs/functions/createAztecWallet.md +46 -0
  65. package/docs/functions/createAztecWalletNode.md +96 -0
  66. package/docs/functions/registerAztecSerializers.md +61 -0
  67. package/docs/functions/registerWalletAztecSerializers.md +39 -0
  68. package/docs/globals.md +16 -14
  69. package/docs/interfaces/AztecHandlerContext.md +54 -0
  70. package/docs/interfaces/AztecWalletContext.md +50 -0
  71. package/docs/interfaces/AztecWalletMethodMap.md +470 -477
  72. package/docs/type-aliases/AztecChainId.md +16 -3
  73. package/docs/variables/ALL_AZTEC_METHODS.md +20 -0
  74. package/docs/variables/AztecWalletErrorMap.md +9 -4
  75. package/docs/variables/AztecWalletSerializer.md +45 -0
  76. package/package.json +9 -9
  77. package/src/client/aztec-dapp-wallet.test.ts +628 -0
  78. package/src/client/aztec-dapp-wallet.ts +879 -0
  79. package/src/client/aztec-router-provider.test.ts +235 -0
  80. package/src/client/aztec-router-provider.ts +64 -0
  81. package/src/client/helpers.test.ts +187 -0
  82. package/src/client/helpers.ts +91 -0
  83. package/src/client/register-serializers.ts +108 -0
  84. package/src/contractArtifactCache.test.ts +21 -10
  85. package/src/contractArtifactCache.ts +54 -35
  86. package/src/errors.ts +58 -10
  87. package/src/index.test.ts +2 -6
  88. package/src/index.ts +73 -37
  89. package/src/types.ts +379 -217
  90. package/src/wallet/create-node.test.ts +332 -0
  91. package/src/wallet/create-node.ts +120 -0
  92. package/src/wallet/handlers/account.test.ts +172 -0
  93. package/src/wallet/handlers/account.ts +99 -0
  94. package/src/wallet/handlers/contract-interaction.test.ts +248 -0
  95. package/src/wallet/handlers/contract-interaction.ts +269 -0
  96. package/src/wallet/handlers/contract.test.ts +245 -0
  97. package/src/wallet/handlers/contract.ts +174 -0
  98. package/src/wallet/handlers/event.test.ts +216 -0
  99. package/src/wallet/handlers/event.ts +99 -0
  100. package/src/wallet/handlers/index.ts +84 -0
  101. package/src/wallet/handlers/node.test.ts +304 -0
  102. package/src/wallet/handlers/node.ts +230 -0
  103. package/src/wallet/handlers/senders.test.ts +172 -0
  104. package/src/wallet/handlers/senders.ts +106 -0
  105. package/src/wallet/handlers/transaction.test.ts +371 -0
  106. package/src/wallet/handlers/transaction.ts +239 -0
  107. package/src/wallet/serializers.test.ts +253 -0
  108. package/src/wallet/serializers.ts +586 -0
  109. package/typedoc.json +23 -1
  110. package/dist/aztecRemoteWallet.d.ts +0 -70
  111. package/dist/aztecRemoteWallet.d.ts.map +0 -1
  112. package/dist/aztecRemoteWallet.js +0 -335
  113. package/dist/chainProvider.d.ts +0 -56
  114. package/dist/chainProvider.d.ts.map +0 -1
  115. package/dist/chainProvider.js +0 -98
  116. package/dist/handlers/aztecAccountWallet.d.ts +0 -4
  117. package/dist/handlers/aztecAccountWallet.d.ts.map +0 -1
  118. package/dist/handlers/aztecAccountWallet.js +0 -295
  119. package/dist/handlers/transactions.d.ts +0 -21
  120. package/dist/handlers/transactions.d.ts.map +0 -1
  121. package/dist/handlers/transactions.js +0 -98
  122. package/dist/handlers.d.ts +0 -27
  123. package/dist/handlers.d.ts.map +0 -1
  124. package/dist/handlers.js +0 -55
  125. package/dist/provider.d.ts +0 -105
  126. package/dist/provider.d.ts.map +0 -1
  127. package/dist/provider.js +0 -160
  128. package/dist/serializers/account.d.ts +0 -164
  129. package/dist/serializers/account.d.ts.map +0 -1
  130. package/dist/serializers/account.js +0 -244
  131. package/dist/serializers/contract.d.ts +0 -62
  132. package/dist/serializers/contract.d.ts.map +0 -1
  133. package/dist/serializers/contract.js +0 -130
  134. package/dist/serializers/index.d.ts +0 -21
  135. package/dist/serializers/index.d.ts.map +0 -1
  136. package/dist/serializers/index.js +0 -154
  137. package/dist/serializers/log.d.ts +0 -66
  138. package/dist/serializers/log.d.ts.map +0 -1
  139. package/dist/serializers/log.js +0 -222
  140. package/dist/serializers/note.d.ts +0 -124
  141. package/dist/serializers/note.d.ts.map +0 -1
  142. package/dist/serializers/note.js +0 -208
  143. package/dist/serializers/transaction.d.ts +0 -99
  144. package/dist/serializers/transaction.d.ts.map +0 -1
  145. package/dist/serializers/transaction.js +0 -275
  146. package/dist/wallet.d.ts +0 -62
  147. package/dist/wallet.d.ts.map +0 -1
  148. package/dist/wallet.js +0 -77
  149. package/docs/classes/AztecChainProvider.md +0 -553
  150. package/docs/classes/AztecChainWallet.md +0 -409
  151. package/docs/classes/AztecProvider.md +0 -1112
  152. package/docs/interfaces/AztecWalletBaseMethodMap.md +0 -135
  153. package/docs/interfaces/AztecWalletEventMap.md +0 -17
  154. package/docs/type-aliases/AztecChainWalletMiddleware.md +0 -13
  155. package/docs/type-aliases/AztecWalletContext.md +0 -29
  156. package/docs/type-aliases/AztecWalletMethodHandler.md +0 -37
  157. package/docs/type-aliases/AztecWalletMiddleware.md +0 -13
  158. package/docs/type-aliases/AztecWalletRouterClient.md +0 -13
  159. package/docs/type-aliases/TransactionFunctionCall.md +0 -33
  160. package/docs/type-aliases/TransactionParams.md +0 -27
  161. package/src/aztecRemoteWallet.test.ts +0 -505
  162. package/src/aztecRemoteWallet.ts +0 -467
  163. package/src/chainProvider.test.ts +0 -401
  164. package/src/chainProvider.ts +0 -116
  165. package/src/handlers/aztecAccountWallet.test.ts +0 -650
  166. package/src/handlers/aztecAccountWallet.ts +0 -531
  167. package/src/handlers/transactions.ts +0 -124
  168. package/src/handlers.test.ts +0 -270
  169. package/src/handlers.ts +0 -70
  170. package/src/provider.test.ts +0 -277
  171. package/src/provider.ts +0 -189
  172. package/src/serializers/account.test.ts +0 -125
  173. package/src/serializers/account.ts +0 -301
  174. package/src/serializers/contract.test.ts +0 -24
  175. package/src/serializers/contract.ts +0 -183
  176. package/src/serializers/index.test.ts +0 -136
  177. package/src/serializers/index.ts +0 -191
  178. package/src/serializers/log.test.ts +0 -286
  179. package/src/serializers/log.ts +0 -292
  180. package/src/serializers/note.test.ts +0 -125
  181. package/src/serializers/note.ts +0 -250
  182. package/src/serializers/transaction.test.ts +0 -320
  183. package/src/serializers/transaction.ts +0 -409
  184. package/src/wallet.test.ts +0 -275
  185. package/src/wallet.ts +0 -94
@@ -0,0 +1,371 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { createTransactionHandlers } from './transaction.js';
3
+ import type { AccountWallet, PXE, AztecAddress, TxHash, AuthWitness } from '@aztec/aztec.js';
4
+ import type { TxExecutionRequest, Tx, TxReceipt } from '@aztec/aztec.js';
5
+ // import type { FeeOptions, TxExecutionOptions } from '@aztec/entrypoints/interfaces'; // Unused
6
+ // import type { ExecutionPayload } from '@aztec/entrypoints/payload'; // Unused
7
+ import type { AztecHandlerContext } from './index.js';
8
+ import type { ContractArtifactCache } from '../../contractArtifactCache.js';
9
+ import { Fr } from '@aztec/aztec.js';
10
+ import type {
11
+ PrivateExecutionResult,
12
+ TxProvingResult,
13
+ TxSimulationResult,
14
+ TxProfileResult,
15
+ UtilitySimulationResult,
16
+ } from '@aztec/stdlib/tx';
17
+
18
+ // Mock dependencies
19
+ const createMockWallet = () =>
20
+ ({
21
+ createTxExecutionRequest: vi.fn(),
22
+ proveTx: vi.fn(),
23
+ sendTx: vi.fn(),
24
+ getTxReceipt: vi.fn(),
25
+ simulateTx: vi.fn(),
26
+ profileTx: vi.fn(),
27
+ simulateUtility: vi.fn(),
28
+ }) as unknown as AccountWallet;
29
+
30
+ const createMockPXE = () =>
31
+ ({
32
+ // No specific methods needed for transaction handlers
33
+ }) as unknown as PXE;
34
+
35
+ const createMockContext = (wallet: AccountWallet, pxe: PXE): AztecHandlerContext => ({
36
+ wallet,
37
+ pxe,
38
+ cache: {} as ContractArtifactCache,
39
+ });
40
+
41
+ describe('Transaction Handlers', () => {
42
+ let mockWallet: AccountWallet;
43
+ let mockPXE: PXE;
44
+ let context: AztecHandlerContext;
45
+ let handlers: ReturnType<typeof createTransactionHandlers>;
46
+
47
+ beforeEach(() => {
48
+ mockWallet = createMockWallet();
49
+ mockPXE = createMockPXE();
50
+ context = createMockContext(mockWallet, mockPXE);
51
+ handlers = createTransactionHandlers();
52
+ });
53
+
54
+ describe('aztec_proveTx', () => {
55
+ it('should prove transaction with request and execution result', async () => {
56
+ const txRequest = {
57
+ txRequest: { exec: { calls: [] } },
58
+ } as unknown as TxExecutionRequest;
59
+ const privateExecutionResult = {
60
+ executionResults: [],
61
+ gasUsed: { l2Gas: 50000, daGas: 2500 },
62
+ entrypoint: undefined,
63
+ firstNullifier: undefined,
64
+ publicFunctionCalldata: undefined,
65
+ getSimulationBlockNumber: vi.fn(),
66
+ } as unknown as PrivateExecutionResult;
67
+
68
+ const expectedTx = {
69
+ hash: '0xabcdef1234567890',
70
+ data: Buffer.from('proven transaction data'),
71
+ privateExecutionResult: {},
72
+ publicInputs: {},
73
+ toTx: vi.fn(),
74
+ } as unknown as TxProvingResult;
75
+
76
+ vi.mocked(mockWallet.proveTx).mockResolvedValue(expectedTx);
77
+
78
+ const result = await handlers.aztec_proveTx(context, [txRequest, privateExecutionResult]);
79
+
80
+ expect(mockWallet.proveTx).toHaveBeenCalledWith(txRequest, privateExecutionResult);
81
+ expect(result).toBe(expectedTx);
82
+ });
83
+
84
+ it('should propagate errors from wallet.proveTx', async () => {
85
+ const txRequest = {} as unknown as TxExecutionRequest;
86
+ const privateExecutionResult = {} as unknown as PrivateExecutionResult;
87
+ const error = new Error('Failed to prove transaction');
88
+ vi.mocked(mockWallet.proveTx).mockRejectedValue(error);
89
+
90
+ await expect(handlers.aztec_proveTx(context, [txRequest, privateExecutionResult])).rejects.toThrow(
91
+ 'Failed to prove transaction',
92
+ );
93
+ expect(mockWallet.proveTx).toHaveBeenCalledWith(txRequest, privateExecutionResult);
94
+ });
95
+ });
96
+
97
+ describe('aztec_sendTx', () => {
98
+ it('should send transaction and return transaction hash', async () => {
99
+ const tx = {
100
+ getTxHash: () => '0xabcdef1234567890' as unknown as TxHash,
101
+ data: Buffer.from('transaction data'),
102
+ toJSON: () => ({
103
+ hash: '0xabcdef1234567890',
104
+ data: 'transaction data',
105
+ }),
106
+ } as unknown as Tx;
107
+
108
+ const expectedTxHash = '0xabcdef1234567890' as unknown as TxHash;
109
+ vi.mocked(mockWallet.sendTx).mockResolvedValue(expectedTxHash);
110
+
111
+ const result = await handlers.aztec_sendTx(context, [tx]);
112
+
113
+ expect(mockWallet.sendTx).toHaveBeenCalledWith(tx);
114
+ expect(result).toBe(expectedTxHash);
115
+ });
116
+
117
+ it('should propagate errors from wallet.sendTx', async () => {
118
+ const tx = {
119
+ getTxHash: () => '0xabcdef1234567890' as unknown as TxHash,
120
+ toJSON: () => ({
121
+ hash: '0xabcdef1234567890',
122
+ }),
123
+ } as unknown as Tx;
124
+ const error = new Error('Failed to send transaction');
125
+ vi.mocked(mockWallet.sendTx).mockRejectedValue(error);
126
+
127
+ await expect(handlers.aztec_sendTx(context, [tx])).rejects.toThrow('Failed to send transaction');
128
+ expect(mockWallet.sendTx).toHaveBeenCalledWith(tx);
129
+ });
130
+ });
131
+
132
+ describe('aztec_getTxReceipt', () => {
133
+ it('should get transaction receipt for given hash', async () => {
134
+ const txHash = '0xabcdef1234567890' as unknown as TxHash;
135
+ const expectedReceipt = {
136
+ txHash,
137
+ status: 'mined',
138
+ blockNumber: 42,
139
+ blockHash: '0x1234567890abcdef',
140
+ } as unknown as TxReceipt;
141
+
142
+ vi.mocked(mockWallet.getTxReceipt).mockResolvedValue(expectedReceipt);
143
+
144
+ const result = await handlers.aztec_getTxReceipt(context, [txHash]);
145
+
146
+ expect(mockWallet.getTxReceipt).toHaveBeenCalledWith(txHash);
147
+ expect(result).toBe(expectedReceipt);
148
+ });
149
+
150
+ it('should handle null receipt for pending transaction', async () => {
151
+ const txHash = '0xabcdef1234567890' as unknown as TxHash;
152
+ vi.mocked(mockWallet.getTxReceipt).mockResolvedValue(null as unknown as TxReceipt);
153
+
154
+ const result = await handlers.aztec_getTxReceipt(context, [txHash]);
155
+
156
+ expect(mockWallet.getTxReceipt).toHaveBeenCalledWith(txHash);
157
+ expect(result).toBe(null);
158
+ });
159
+
160
+ it('should propagate errors from wallet.getTxReceipt', async () => {
161
+ const txHash = '0xabcdef1234567890' as unknown as TxHash;
162
+ const error = new Error('Failed to get transaction receipt');
163
+ vi.mocked(mockWallet.getTxReceipt).mockRejectedValue(error);
164
+
165
+ await expect(handlers.aztec_getTxReceipt(context, [txHash])).rejects.toThrow(
166
+ 'Failed to get transaction receipt',
167
+ );
168
+ expect(mockWallet.getTxReceipt).toHaveBeenCalledWith(txHash);
169
+ });
170
+ });
171
+
172
+ describe('aztec_simulateTx', () => {
173
+ it('should simulate transaction with all parameters', async () => {
174
+ const txRequest = {
175
+ txRequest: { exec: { calls: [] } },
176
+ } as unknown as TxExecutionRequest;
177
+ const simulatePublic = true;
178
+ const msgSender = '0x1234567890abcdef' as unknown as AztecAddress;
179
+ const skipTxValidation = true;
180
+ const skipFeeEnforcement = true;
181
+
182
+ const expectedSimulation = {
183
+ txRequest,
184
+ publicOutput: {},
185
+ gasUsed: { l2Gas: 50000, daGas: 2500 },
186
+ } as unknown as TxSimulationResult;
187
+
188
+ vi.mocked(mockWallet.simulateTx).mockResolvedValue(expectedSimulation);
189
+
190
+ const result = await handlers.aztec_simulateTx(context, [
191
+ txRequest,
192
+ simulatePublic,
193
+ msgSender,
194
+ skipTxValidation,
195
+ skipFeeEnforcement,
196
+ ]);
197
+
198
+ expect(mockWallet.simulateTx).toHaveBeenCalledWith(
199
+ txRequest,
200
+ simulatePublic,
201
+ msgSender,
202
+ skipTxValidation,
203
+ skipFeeEnforcement,
204
+ );
205
+ expect(result).toBe(expectedSimulation);
206
+ });
207
+
208
+ it('should simulate transaction with default parameters', async () => {
209
+ const txRequest = {
210
+ txRequest: { exec: { calls: [] } },
211
+ } as unknown as TxExecutionRequest;
212
+
213
+ const expectedSimulation = {
214
+ txRequest,
215
+ publicOutput: {},
216
+ gasUsed: { l2Gas: 50000, daGas: 2500 },
217
+ } as unknown as TxSimulationResult;
218
+
219
+ vi.mocked(mockWallet.simulateTx).mockResolvedValue(expectedSimulation);
220
+
221
+ const result = await handlers.aztec_simulateTx(context, [
222
+ txRequest,
223
+ undefined,
224
+ undefined,
225
+ undefined,
226
+ undefined,
227
+ ]);
228
+
229
+ expect(mockWallet.simulateTx).toHaveBeenCalledWith(txRequest, false, undefined, undefined, false);
230
+ expect(result).toBe(expectedSimulation);
231
+ });
232
+
233
+ it('should propagate errors from wallet.simulateTx', async () => {
234
+ const txRequest = {} as unknown as TxExecutionRequest;
235
+ const error = new Error('Simulation failed');
236
+ vi.mocked(mockWallet.simulateTx).mockRejectedValue(error);
237
+
238
+ await expect(
239
+ handlers.aztec_simulateTx(context, [txRequest, undefined, undefined, undefined, undefined]),
240
+ ).rejects.toThrow('Simulation failed');
241
+ expect(mockWallet.simulateTx).toHaveBeenCalledOnce();
242
+ });
243
+ });
244
+
245
+ describe('aztec_profileTx', () => {
246
+ it('should profile transaction with all parameters', async () => {
247
+ const txRequest = {
248
+ txRequest: { exec: { calls: [] } },
249
+ } as unknown as TxExecutionRequest;
250
+ const profileMode = 'full' as const;
251
+ const skipProofGeneration = true;
252
+ const msgSender = '0x1234567890abcdef' as unknown as AztecAddress;
253
+
254
+ const expectedProfile = {
255
+ txRequest,
256
+ executionSteps: [],
257
+ timings: { totalTime: 1000 },
258
+ profile: { totalTime: 1000, gates: 50000 },
259
+ } as unknown as TxProfileResult;
260
+
261
+ vi.mocked(mockWallet.profileTx).mockResolvedValue(expectedProfile);
262
+
263
+ const result = await handlers.aztec_profileTx(context, [
264
+ txRequest,
265
+ profileMode,
266
+ skipProofGeneration,
267
+ msgSender,
268
+ ]);
269
+
270
+ expect(mockWallet.profileTx).toHaveBeenCalledWith(
271
+ txRequest,
272
+ profileMode,
273
+ skipProofGeneration,
274
+ msgSender,
275
+ );
276
+ expect(result).toBe(expectedProfile);
277
+ });
278
+
279
+ it('should profile transaction with default parameters', async () => {
280
+ const txRequest = {
281
+ txRequest: { exec: { calls: [] } },
282
+ } as unknown as TxExecutionRequest;
283
+
284
+ const expectedProfile = {
285
+ txRequest,
286
+ executionSteps: [],
287
+ timings: {},
288
+ profile: { gates: 50000 },
289
+ } as unknown as TxProfileResult;
290
+
291
+ vi.mocked(mockWallet.profileTx).mockResolvedValue(expectedProfile);
292
+
293
+ const result = await handlers.aztec_profileTx(context, [txRequest, undefined, undefined, undefined]);
294
+
295
+ expect(mockWallet.profileTx).toHaveBeenCalledWith(txRequest, 'gates', undefined, undefined);
296
+ expect(result).toBe(expectedProfile);
297
+ });
298
+
299
+ it('should propagate errors from wallet.profileTx', async () => {
300
+ const txRequest = {} as unknown as TxExecutionRequest;
301
+ const error = new Error('Profiling failed');
302
+ vi.mocked(mockWallet.profileTx).mockRejectedValue(error);
303
+
304
+ await expect(
305
+ handlers.aztec_profileTx(context, [txRequest, undefined, undefined, undefined]),
306
+ ).rejects.toThrow('Profiling failed');
307
+ expect(mockWallet.profileTx).toHaveBeenCalledOnce();
308
+ });
309
+ });
310
+
311
+ describe('aztec_simulateUtility', () => {
312
+ it('should simulate utility function with all parameters', async () => {
313
+ const functionName = 'testUtility';
314
+ const args = [new Fr(0x123n), new Fr(0x456n)];
315
+ const to = '0x1234567890abcdef' as unknown as AztecAddress;
316
+ const authWits = [{ witness: [new Fr(1n)] } as unknown as AuthWitness];
317
+ const from = '0xabcdef1234567890' as unknown as AztecAddress;
318
+
319
+ const expectedResult = {
320
+ result: new Fr(0x789n),
321
+ returnValue: new Fr(0x789n),
322
+ gasUsed: { l2Gas: 10000, daGas: 500 },
323
+ } as unknown as UtilitySimulationResult;
324
+
325
+ vi.mocked(mockWallet.simulateUtility).mockResolvedValue(expectedResult);
326
+
327
+ const result = await handlers.aztec_simulateUtility(context, [functionName, args, to, authWits, from]);
328
+
329
+ expect(mockWallet.simulateUtility).toHaveBeenCalledWith(functionName, args, to, authWits, from);
330
+ expect(result).toBe(expectedResult);
331
+ });
332
+
333
+ it('should simulate utility function with minimal parameters', async () => {
334
+ const functionName = 'simpleUtility';
335
+ const args: Fr[] = [];
336
+ const to = '0x1234567890abcdef' as unknown as AztecAddress;
337
+
338
+ const expectedResult = {
339
+ result: new Fr(0x0n),
340
+ returnValue: new Fr(0x0n),
341
+ gasUsed: { l2Gas: 5000, daGas: 250 },
342
+ } as unknown as UtilitySimulationResult;
343
+
344
+ vi.mocked(mockWallet.simulateUtility).mockResolvedValue(expectedResult);
345
+
346
+ const result = await handlers.aztec_simulateUtility(context, [
347
+ functionName,
348
+ args,
349
+ to,
350
+ undefined,
351
+ undefined,
352
+ ]);
353
+
354
+ expect(mockWallet.simulateUtility).toHaveBeenCalledWith(functionName, args, to, undefined, undefined);
355
+ expect(result).toBe(expectedResult);
356
+ });
357
+
358
+ it('should propagate errors from wallet.simulateUtility', async () => {
359
+ const functionName = 'failingUtility';
360
+ const args: Fr[] = [];
361
+ const to = '0x1234567890abcdef' as unknown as AztecAddress;
362
+ const error = new Error('Utility simulation failed');
363
+ vi.mocked(mockWallet.simulateUtility).mockRejectedValue(error);
364
+
365
+ await expect(
366
+ handlers.aztec_simulateUtility(context, [functionName, args, to, undefined, undefined]),
367
+ ).rejects.toThrow('Utility simulation failed');
368
+ expect(mockWallet.simulateUtility).toHaveBeenCalledWith(functionName, args, to, undefined, undefined);
369
+ });
370
+ });
371
+ });
@@ -0,0 +1,239 @@
1
+ import type { AztecHandlerContext } from './index.js';
2
+ import type { AztecWalletMethodMap } from '../../types.js';
3
+ import { createLogger } from '@aztec/foundation/log';
4
+
5
+ const logger = createLogger('aztec-rpc-wallet:transaction');
6
+
7
+ /**
8
+ * Creates handlers for transaction-related Aztec wallet JSON-RPC methods.
9
+ * These handlers are responsible for the core lifecycle of an Aztec transaction,
10
+ * including proving, sending, simulating, and retrieving receipts.
11
+ *
12
+ * Each handler function receives an {@link AztecHandlerContext}, providing access to the
13
+ * {@link AccountWallet} and {@link PXE} client instances necessary for these operations.
14
+ *
15
+ * @returns An object where keys are transaction-related method names
16
+ * (e.g., "aztec_proveTx", "aztec_sendTx") and values are their
17
+ * corresponding handler functions.
18
+ * @see {@link AztecWalletMethodMap} for method definitions.
19
+ */
20
+ export function createTransactionHandlers() {
21
+ return {
22
+ /**
23
+ * Handles the "aztec_proveTx" JSON-RPC method.
24
+ * Generates zero-knowledge proofs for a given {@link TxExecutionRequest}.
25
+ * If the {@link PrivateExecutionResult} is not provided, this handler will first
26
+ * simulate the private execution of the transaction to obtain it.
27
+ *
28
+ * @param ctx - The {@link AztecHandlerContext} containing the `wallet` instance.
29
+ * @param paramsTuple - A tuple containing the transaction execution request and an optional private execution result.
30
+ * Defined by {@link AztecWalletMethodMap.aztec_proveTx.params}.
31
+ * @param paramsTuple.0 - The {@link TxExecutionRequest} to prove.
32
+ * @param paramsTuple.1 - Optional: The {@link PrivateExecutionResult} from a prior private simulation.
33
+ * If not provided, a private simulation will be performed internally.
34
+ * @returns A promise that resolves to the {@link TxProvingResult}, which includes the proven transaction.
35
+ * Type defined by {@link AztecWalletMethodMap.aztec_proveTx.result}.
36
+ * @throws {Error} If `txRequest` is missing, or if simulation is needed but fails to produce a `PrivateExecutionResult`.
37
+ */
38
+ aztec_proveTx: async (
39
+ ctx: AztecHandlerContext,
40
+ paramsTuple: AztecWalletMethodMap['aztec_proveTx']['params'],
41
+ ): Promise<AztecWalletMethodMap['aztec_proveTx']['result']> => {
42
+ let [txRequest, privateExecutionResult] = paramsTuple; // privateExecutionResult can now be undefined
43
+ logger.debug(`[HANDLER] aztec_proveTx: txRequest received = ${!!txRequest}`);
44
+ if (!txRequest) {
45
+ // Only txRequest is mandatory now
46
+ throw new Error('Invalid parameters received in tuple for aztec_proveTx: txRequest is missing');
47
+ }
48
+
49
+ if (!privateExecutionResult) {
50
+ logger.debug(
51
+ '[HANDLER] aztec_proveTx: privateExecutionResult not provided, simulating transaction first.',
52
+ );
53
+ // Simulate the private part of the transaction to get the PrivateExecutionResult
54
+ // Pass false for simulatePublic, as we only need the private execution.
55
+ // Pass undefined for msgSender, skipTxValidation, skipFeeEnforcement to use defaults.
56
+ const simulationResult = await ctx.wallet.simulateTx(
57
+ txRequest,
58
+ false,
59
+ undefined,
60
+ undefined,
61
+ undefined,
62
+ );
63
+ privateExecutionResult = simulationResult.privateExecutionResult;
64
+ if (!privateExecutionResult) {
65
+ throw new Error('Failed to obtain PrivateExecutionResult from simulation for aztec_proveTx');
66
+ }
67
+ logger.debug('[HANDLER] aztec_proveTx: privateExecutionResult obtained from simulation.');
68
+ }
69
+
70
+ return await ctx.wallet.proveTx(txRequest, privateExecutionResult);
71
+ },
72
+
73
+ /**
74
+ * Handles the "aztec_sendTx" JSON-RPC method.
75
+ * Sends a proven {@link Tx} (transaction object) to the Aztec network via the
76
+ * {@link AccountWallet} in the context.
77
+ *
78
+ * This is typically the final step in submitting a transaction after it has been
79
+ * successfully proven by `aztec_proveTx`.
80
+ *
81
+ * @param ctx - The {@link AztecHandlerContext} containing the `wallet` instance.
82
+ * @param paramsTuple - A tuple containing the proven transaction.
83
+ * Defined by {@link AztecWalletMethodMap.aztec_sendTx.params}.
84
+ * @param paramsTuple.0 - The proven {@link Tx} object to send.
85
+ * @returns A promise that resolves to the {@link TxHash} of the sent transaction.
86
+ * Type defined by {@link AztecWalletMethodMap.aztec_sendTx.result}.
87
+ * @throws {Error} If the `tx` parameter is missing or invalid.
88
+ */
89
+ aztec_sendTx: async (
90
+ ctx: AztecHandlerContext,
91
+ paramsTuple: AztecWalletMethodMap['aztec_sendTx']['params'],
92
+ ): Promise<AztecWalletMethodMap['aztec_sendTx']['result']> => {
93
+ const [tx] = paramsTuple;
94
+ logger.debug(`[HANDLER] aztec_sendTx: tx hash = ${tx?.getTxHash()?.toString()}`);
95
+ if (!tx) {
96
+ // tx is mandatory
97
+ throw new Error('Invalid tx parameter received in tuple');
98
+ }
99
+ return await ctx.wallet.sendTx(tx);
100
+ },
101
+
102
+ /**
103
+ * Handles the "aztec_getTxReceipt" JSON-RPC method.
104
+ * Retrieves the {@link TxReceipt} for a transaction identified by its {@link TxHash},
105
+ * using the {@link AccountWallet} in the context.
106
+ *
107
+ * The receipt provides information about the transaction's execution status
108
+ * (e.g., success, failure, reverted), block inclusion, and any emitted events.
109
+ *
110
+ * @param ctx - The {@link AztecHandlerContext} containing the `wallet` instance.
111
+ * @param paramsTuple - A tuple containing the transaction hash.
112
+ * Defined by {@link AztecWalletMethodMap.aztec_getTxReceipt.params}.
113
+ * @param paramsTuple.0 - The {@link TxHash} of the transaction.
114
+ * @returns A promise that resolves to the {@link TxReceipt}.
115
+ * Type defined by {@link AztecWalletMethodMap.aztec_getTxReceipt.result}.
116
+ * @throws {Error} If the `txHash` parameter is missing or invalid.
117
+ */
118
+ aztec_getTxReceipt: async (
119
+ ctx: AztecHandlerContext,
120
+ paramsTuple: AztecWalletMethodMap['aztec_getTxReceipt']['params'],
121
+ ): Promise<AztecWalletMethodMap['aztec_getTxReceipt']['result']> => {
122
+ const [txHash] = paramsTuple;
123
+ logger.debug(`[HANDLER] aztec_getTxReceipt: txHash = ${txHash?.toString()}`);
124
+ if (!txHash) {
125
+ // txHash is mandatory
126
+ throw new Error('Invalid txHash parameter received in tuple');
127
+ }
128
+ return await ctx.wallet.getTxReceipt(txHash);
129
+ },
130
+
131
+ /**
132
+ * Handles the "aztec_simulateTx" JSON-RPC method.
133
+ * Simulates the execution of a {@link TxExecutionRequest} without actually proving
134
+ * or sending it to the network. This is useful for estimating gas, verifying
135
+ * correctness, or debugging.
136
+ *
137
+ * @param ctx - The {@link AztecHandlerContext} containing the `wallet` instance.
138
+ * @param paramsTuple - A tuple containing the parameters for simulation.
139
+ * Defined by {@link AztecWalletMethodMap.aztec_simulateTx.params}.
140
+ * @param paramsTuple.0 - The {@link TxExecutionRequest} to simulate.
141
+ * @param paramsTuple.1 - Optional: Boolean indicating whether to simulate public parts of the transaction. Defaults to `false`.
142
+ * @param paramsTuple.2 - Optional: The {@link AztecAddress} of the message sender for simulation context.
143
+ * @param paramsTuple.3 - Optional: Boolean flag to skip transaction validation during simulation.
144
+ * @param paramsTuple.4 - Optional: Boolean flag to skip fee enforcement during simulation.
145
+ * @returns A promise that resolves to the {@link TxSimulationResult}.
146
+ * Type defined by {@link AztecWalletMethodMap.aztec_simulateTx.result}.
147
+ * @throws {Error} If the `txRequest` parameter is missing or invalid.
148
+ */
149
+ aztec_simulateTx: async (
150
+ ctx: AztecHandlerContext,
151
+ paramsTuple: AztecWalletMethodMap['aztec_simulateTx']['params'],
152
+ ): Promise<AztecWalletMethodMap['aztec_simulateTx']['result']> => {
153
+ const [
154
+ txRequest,
155
+ simulatePublicInput, // simulatePublic is optional in PXE interface
156
+ msgSender,
157
+ skipTxValidation,
158
+ skipFeeEnforcementInput, // skipFeeEnforcement is optional in PXE interface
159
+ ] = paramsTuple;
160
+ // Handle optional params with defaults if necessary, matching PXE behavior
161
+ const simulatePublic = simulatePublicInput === undefined ? false : simulatePublicInput;
162
+ const skipFeeEnforcement = skipFeeEnforcementInput === undefined ? false : skipFeeEnforcementInput;
163
+
164
+ logger.debug(`[HANDLER] aztec_simulateTx: txRequest received = ${!!txRequest}`);
165
+ if (!txRequest) {
166
+ // txRequest is mandatory
167
+ throw new Error('Invalid txRequest parameter received in tuple');
168
+ }
169
+ return await ctx.wallet.simulateTx(
170
+ txRequest,
171
+ simulatePublic,
172
+ msgSender,
173
+ skipTxValidation,
174
+ skipFeeEnforcement,
175
+ );
176
+ },
177
+
178
+ /**
179
+ * Handles the "aztec_profileTx" JSON-RPC method.
180
+ * Profiles a {@link TxExecutionRequest} to gather performance metrics, such as
181
+ * gate counts and execution steps, without sending it to the network.
182
+ *
183
+ * @param ctx - The {@link AztecHandlerContext} containing the `wallet` instance.
184
+ * @param paramsTuple - A tuple containing the parameters for profiling.
185
+ * Defined by {@link AztecWalletMethodMap.aztec_profileTx.params}.
186
+ * @param paramsTuple.0 - The {@link TxExecutionRequest} to profile.
187
+ * @param paramsTuple.1 - Optional: The profiling mode ('gates', 'execution-steps', or 'full'). Defaults to 'gates'.
188
+ * @param paramsTuple.2 - Optional: Boolean flag to skip proof generation during profiling.
189
+ * @param paramsTuple.3 - Optional: The {@link AztecAddress} of the message sender for profiling context.
190
+ * @returns A promise that resolves to the {@link TxProfileResult}.
191
+ * Type defined by {@link AztecWalletMethodMap.aztec_profileTx.result}.
192
+ * @throws {Error} If the `txRequest` parameter is missing or invalid.
193
+ */
194
+ aztec_profileTx: async (
195
+ ctx: AztecHandlerContext,
196
+ paramsTuple: AztecWalletMethodMap['aztec_profileTx']['params'],
197
+ ): Promise<AztecWalletMethodMap['aztec_profileTx']['result']> => {
198
+ const [txRequest, profileModeInput, skipProofGeneration, msgSender] = paramsTuple;
199
+ const profileMode = profileModeInput === undefined ? 'gates' : profileModeInput; // Default for optional
200
+
201
+ logger.debug(`[HANDLER] aztec_profileTx: txRequest received = ${!!txRequest}`);
202
+ if (!txRequest) {
203
+ // txRequest is mandatory
204
+ throw new Error('Invalid txRequest parameter received in tuple');
205
+ }
206
+ return await ctx.wallet.profileTx(txRequest, profileMode, skipProofGeneration, msgSender);
207
+ },
208
+
209
+ /**
210
+ * Handles the "aztec_simulateUtility" JSON-RPC method.
211
+ * Simulates a call to a utility (view) function on a contract. Utility functions
212
+ * are read-only and do not modify state or require a transaction.
213
+ *
214
+ * @param ctx - The {@link AztecHandlerContext} containing the `wallet` instance.
215
+ * @param paramsTuple - A tuple containing the parameters for the utility function call.
216
+ * Defined by {@link AztecWalletMethodMap.aztec_simulateUtility.params}.
217
+ * @param paramsTuple.0 - The name of the utility function to call.
218
+ * @param paramsTuple.1 - An array of arguments for the function call.
219
+ * @param paramsTuple.2 - The {@link AztecAddress} of the contract or account to call.
220
+ * @param paramsTuple.3 - Optional: An array of {@link AuthWitness} for authorization, if needed.
221
+ * @param paramsTuple.4 - Optional: The {@link AztecAddress} of the sender, if relevant for the utility call.
222
+ * @returns A promise that resolves to the {@link UtilitySimulationResult}.
223
+ * Type defined by {@link AztecWalletMethodMap.aztec_simulateUtility.result}.
224
+ * @throws {Error} If required parameters like `functionName`, `args`, or `to` are missing or invalid.
225
+ */
226
+ aztec_simulateUtility: async (
227
+ ctx: AztecHandlerContext,
228
+ paramsTuple: AztecWalletMethodMap['aztec_simulateUtility']['params'],
229
+ ): Promise<AztecWalletMethodMap['aztec_simulateUtility']['result']> => {
230
+ const [functionName, args, to, authWits, from] = paramsTuple;
231
+ logger.debug(`[HANDLER] aztec_simulateUtility: functionName = ${functionName}, to = ${to?.toString()}`);
232
+ if (!functionName || !args || !to) {
233
+ // Mandatory params
234
+ throw new Error('Invalid parameters received in tuple for aztec_simulateUtility');
235
+ }
236
+ return await ctx.wallet.simulateUtility(functionName, args, to, authWits, from);
237
+ },
238
+ };
239
+ }