@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
@@ -1,270 +0,0 @@
1
- import { describe, expect, it, vi, beforeEach } from 'vitest';
2
- import type { AccountWallet, PXE, TxHash, AztecAddress } from '@aztec/aztec.js';
3
- import { Fr } from '@aztec/aztec.js';
4
- import { handler } from './handlers.js';
5
- import { AztecWalletError } from './errors.js';
6
- import { ContractArtifactCache } from './contractArtifactCache.js';
7
- import type {
8
- AztecWalletContext,
9
- AztecWalletMethodMap,
10
- TransactionParams,
11
- TransactionFunctionCall,
12
- } from './types.js';
13
-
14
- // Mock Contract.at and NoFeePaymentMethod at the top level
15
- // Mock Aztec.js dependencies
16
- vi.mock('@aztec/aztec.js', async () => {
17
- const actual = await vi.importActual('@aztec/aztec.js');
18
- return {
19
- ...actual,
20
- Contract: {
21
- at: vi.fn(),
22
- },
23
- NoFeePaymentMethod: class {},
24
- AztecAddress: {
25
- fromString: vi.fn().mockImplementation((str) => ({
26
- toString: () => str,
27
- toField: () => new Fr(1),
28
- equals: () => false,
29
- isZero: () => false,
30
- })),
31
- },
32
- AuthWitness: {
33
- fromString: vi.fn().mockImplementation((str) => ({
34
- toString: () => str,
35
- })),
36
- },
37
- GasSettings: {
38
- default: vi.fn().mockReturnValue({
39
- maxFeePerGas: BigInt(1000),
40
- maxPriorityFeePerGas: BigInt(100),
41
- }),
42
- },
43
- };
44
- });
45
-
46
- // Mock circuits.js dependencies
47
- vi.mock('@aztec/circuits.js', () => ({
48
- GasSettings: {
49
- default: vi.fn().mockReturnValue({
50
- maxFeePerGas: BigInt(1000),
51
- maxPriorityFeePerGas: BigInt(100),
52
- }),
53
- },
54
- }));
55
-
56
- describe('RPC Handlers', () => {
57
- let context: AztecWalletContext;
58
- let pxe: PXE;
59
- // Define a type for our mocked wallet that includes the methods we need
60
- type MockedWallet = AccountWallet & {
61
- sendTransaction: ReturnType<typeof vi.fn>;
62
- simulateTransaction: ReturnType<typeof vi.fn>;
63
- getContractInstance: ReturnType<typeof vi.fn>;
64
- getContractArtifact: ReturnType<typeof vi.fn>;
65
- getCurrentBaseFees: ReturnType<typeof vi.fn>;
66
- createTxExecutionRequest: ReturnType<typeof vi.fn>;
67
- simulateTx: ReturnType<typeof vi.fn>;
68
- proveTx: ReturnType<typeof vi.fn>;
69
- sendTx: ReturnType<typeof vi.fn>;
70
- };
71
- let wallet: MockedWallet;
72
- let contractArtifactCache: ContractArtifactCache;
73
-
74
- beforeEach(() => {
75
- // Mock wallet with common methods
76
- wallet = {
77
- getAddress: vi.fn().mockResolvedValue('mockAddress'),
78
- getContractInstance: vi.fn().mockResolvedValue(undefined),
79
- getContractArtifact: vi.fn().mockResolvedValue(undefined),
80
- sendTransaction: vi.fn(),
81
- simulateTransaction: vi.fn(),
82
- getCurrentBaseFees: vi.fn().mockResolvedValue(BigInt(1000)),
83
- createTxExecutionRequest: vi.fn().mockResolvedValue({
84
- id: 'mockTxId',
85
- data: new Uint8Array(),
86
- }),
87
- simulateTx: vi.fn().mockResolvedValue({
88
- privateExecutionResult: {
89
- success: true,
90
- data: new Uint8Array(),
91
- },
92
- }),
93
- proveTx: vi.fn().mockResolvedValue({
94
- toTx: () => ({ id: 'mockTxId' }),
95
- }),
96
- sendTx: vi.fn().mockResolvedValue({
97
- toString: () => 'txHash',
98
- } as unknown as TxHash),
99
- } as unknown as MockedWallet;
100
-
101
- // Mock PXE
102
- pxe = {
103
- // Add PXE methods as needed
104
- } as unknown as PXE;
105
-
106
- // Create contract artifact cache
107
- contractArtifactCache = new ContractArtifactCache(wallet);
108
-
109
- // Setup context
110
- context = {
111
- pxe,
112
- wallet,
113
- contractArtifactCache,
114
- };
115
- });
116
-
117
- describe('Base wallet methods', () => {
118
- it('handles wm_getSupportedMethods', async () => {
119
- const result = await handler(context, 'wm_getSupportedMethods', []);
120
- expect(Array.isArray(result)).toBe(true);
121
- expect(result.length).toBeGreaterThan(0);
122
- expect(result).toContain('aztec_connect');
123
- expect(result).toContain('aztec_getAccount');
124
- });
125
-
126
- it('handles aztec_connect', async () => {
127
- const result = await handler(context, 'aztec_connect', []);
128
- expect(result).toBe(true);
129
- });
130
-
131
- it('handles aztec_getAccount', async () => {
132
- const result = await handler(context, 'aztec_getAccount', []);
133
- expect(result).toBe('mockAddress');
134
- expect(wallet.getAddress).toHaveBeenCalled();
135
- });
136
- });
137
-
138
- describe('Transaction methods', () => {
139
- // Create a valid AztecAddress for testing
140
- // Create a valid hex string for AztecAddress (32 bytes = 64 hex chars)
141
- const mockAddressHex = `0x${'1'.repeat(64)}`;
142
- const mockAddress = {
143
- toString: () => mockAddressHex,
144
- toField: () => new Fr(1),
145
- equals: () => false,
146
- isZero: () => false,
147
- _hex: mockAddressHex,
148
- } as unknown as AztecAddress;
149
-
150
- const mockFunctionCall: TransactionFunctionCall = {
151
- contractAddress: mockAddress.toString(),
152
- functionName: 'test',
153
- args: ['arg1', 'arg2'],
154
- };
155
-
156
- const mockTxParams: TransactionParams = {
157
- functionCalls: [mockFunctionCall],
158
- authwits: [],
159
- };
160
-
161
- beforeEach(async () => {
162
- // Mock contract instance with proper request data
163
- const mockContract = {
164
- methods: {
165
- test: vi.fn().mockReturnValue({
166
- simulate: vi.fn().mockResolvedValue({
167
- success: true,
168
- returnValue: '0x123',
169
- }),
170
- request: vi.fn().mockResolvedValue({
171
- contractAddress: mockAddress,
172
- functionData: new Uint8Array([1, 2, 3]), // Non-empty function data
173
- functionSignature: 'test(uint256,uint256)',
174
- args: ['arg1', 'arg2'],
175
- }),
176
- }),
177
- },
178
- address: mockAddress,
179
- };
180
-
181
- // Configure Contract.at mock
182
- const { Contract } = await import('@aztec/aztec.js');
183
- (Contract.at as ReturnType<typeof vi.fn>).mockResolvedValue(mockContract);
184
-
185
- // Configure mock return values for contract artifact cache
186
- const mockArtifact = {
187
- functions: {
188
- test: {
189
- name: 'test',
190
- parameters: [
191
- { name: 'arg1', type: 'uint256' },
192
- { name: 'arg2', type: 'uint256' },
193
- ],
194
- },
195
- },
196
- };
197
-
198
- // Mock contract artifact cache methods
199
- contractArtifactCache.getContractArtifact = vi.fn().mockResolvedValue(mockArtifact);
200
- });
201
-
202
- it('handles aztec_sendTransaction', async () => {
203
- const result = await handler(context, 'aztec_sendTransaction', mockTxParams);
204
- expect(result).toBe('txHash');
205
- expect(contractArtifactCache.getContractArtifact).toHaveBeenCalled();
206
- expect(wallet.createTxExecutionRequest).toHaveBeenCalled();
207
- expect(wallet.simulateTx).toHaveBeenCalled();
208
- expect(wallet.proveTx).toHaveBeenCalled();
209
- expect(wallet.sendTx).toHaveBeenCalled();
210
- });
211
-
212
- it('handles aztec_simulateTransaction', async () => {
213
- const result = await handler(context, 'aztec_simulateTransaction', mockFunctionCall);
214
- expect(result).toEqual({
215
- success: true,
216
- returnValue: '0x123',
217
- });
218
- expect(contractArtifactCache.getContractArtifact).toHaveBeenCalled();
219
- });
220
-
221
- it('handles transaction errors', async () => {
222
- wallet.createTxExecutionRequest.mockRejectedValue(new Error('Transaction failed'));
223
- await expect(handler(context, 'aztec_sendTransaction', mockTxParams)).rejects.toThrow(AztecWalletError);
224
- });
225
- });
226
-
227
- describe('Error handling', () => {
228
- it('throws error for unsupported method', async () => {
229
- await expect(handler(context, 'unsupported_method' as keyof AztecWalletMethodMap, [])).rejects.toThrow(
230
- AztecWalletError,
231
- );
232
- });
233
-
234
- it('throws error for invalid parameters', async () => {
235
- await expect(
236
- handler(context, 'aztec_sendTransaction', [] as unknown as TransactionParams),
237
- ).rejects.toThrow(AztecWalletError);
238
- });
239
-
240
- it('handles null context values', async () => {
241
- // Mock the handler to wrap errors
242
- const mockHandler = async () => {
243
- try {
244
- await handler(
245
- { pxe, wallet: null, contractArtifactCache } as unknown as AztecWalletContext,
246
- 'aztec_getAccount',
247
- [],
248
- );
249
- } catch (error) {
250
- if (error instanceof Error) {
251
- throw new AztecWalletError('unknownInternalError', error.message);
252
- }
253
- throw error;
254
- }
255
- };
256
-
257
- await expect(mockHandler()).rejects.toThrow(AztecWalletError);
258
- });
259
- });
260
-
261
- describe('Account wallet methods', () => {
262
- // Add tests for account wallet specific methods
263
- // These would test the routing to accountWalletHandler
264
- it('routes account wallet methods correctly', async () => {
265
- // Mock an account wallet method
266
- const accountMethod = 'aztec_getBlock';
267
- await expect(handler(context, accountMethod, { number: 1 })).rejects.toThrow(); // Should attempt to route to accountWalletHandler
268
- });
269
- });
270
- });
package/src/handlers.ts DELETED
@@ -1,70 +0,0 @@
1
- /**
2
- * @module handlers
3
- *
4
- * This module provides the core RPC method handling logic for the Aztec wallet.
5
- * It routes incoming RPC requests to appropriate specialized handlers based on the method type.
6
- *
7
- * The handlers are organized into categories:
8
- * - Base wallet methods (connect, getAccount, etc.)
9
- * - Account wallet methods (chain operations, contract management, etc.)
10
- * - Transaction methods (send, simulate)
11
- *
12
- * Each method handler validates inputs, performs the requested operation through the wallet,
13
- * and returns properly formatted responses.
14
- */
15
-
16
- import type { AztecWalletMethodMap } from './types.js';
17
- import { type AztecWalletContext, BASE_WALLET_METHODS } from './types.js';
18
- import { AztecWalletError } from './errors.js';
19
- import { sendTransaction, simulateTransaction } from './handlers/transactions.js';
20
- import { aztecWalletHandler, AZTEC_WALLET_METHODS } from './handlers/aztecAccountWallet.js';
21
-
22
- /**
23
- * Main handler function that routes RPC method calls to appropriate specialized handlers.
24
- *
25
- * @param context - The wallet context containing PXE and wallet instances
26
- * @param method - The RPC method being called
27
- * @param params - Parameters passed to the method
28
- * @returns Result from the method handler
29
- * @throws {AztecWalletError} If method not supported or handler fails
30
- */
31
-
32
- export async function handler<M extends keyof AztecWalletMethodMap>(
33
- context: AztecWalletContext,
34
- method: M,
35
- params: AztecWalletMethodMap[M]['params'],
36
- ): Promise<AztecWalletMethodMap[M]['result']> {
37
- if (AZTEC_WALLET_METHODS.includes(method)) {
38
- return aztecWalletHandler(context, method, params);
39
- }
40
- switch (method) {
41
- // Base wallet methods
42
- case 'wm_getSupportedMethods': {
43
- // Return combined list of supported methods from all handlers
44
- return [...BASE_WALLET_METHODS, ...AZTEC_WALLET_METHODS] as string[];
45
- }
46
- case 'aztec_connect': {
47
- // Basic connection validation
48
- // Note: Main connection logic handled by provider
49
- return true;
50
- }
51
- // Core wallet methods
52
- case 'aztec_getAccount':
53
- return (await context.wallet.getAddress()).toString();
54
-
55
- // Transaction methods
56
- case 'aztec_sendTransaction':
57
- return await sendTransaction(
58
- context,
59
- params as AztecWalletMethodMap['aztec_sendTransaction']['params'],
60
- );
61
- case 'aztec_simulateTransaction':
62
- return await simulateTransaction(
63
- context,
64
- params as AztecWalletMethodMap['aztec_simulateTransaction']['params'],
65
- );
66
-
67
- default:
68
- throw new AztecWalletError('invalidRequest', `Method not supported: ${String(method)}`);
69
- }
70
- }
@@ -1,277 +0,0 @@
1
- import { describe, test, expect, vi, beforeEach } from 'vitest';
2
- import { AztecProvider } from './provider.js';
3
- import { AztecWalletError, AztecWalletErrorType } from './errors.js';
4
- import type { ContractInstanceWithAddress, AztecAddress, ContractArtifact } from '@aztec/aztec.js';
5
- import { WalletRouterProvider } from '@walletmesh/router';
6
- import type { OperationBuilder } from '@walletmesh/router';
7
- import type { Mock } from 'vitest';
8
-
9
- const createMockTransport = () => ({
10
- send: vi.fn(),
11
- on: vi.fn(),
12
- off: vi.fn(),
13
- close: vi.fn(),
14
- });
15
-
16
- describe('AztecProvider', () => {
17
- let provider: AztecProvider;
18
- let mockTransport: ReturnType<typeof createMockTransport>;
19
- let mockChainBuilder: {
20
- chainId: string;
21
- provider: WalletRouterProvider;
22
- calls: unknown[];
23
- call: Mock;
24
- execute: Mock;
25
- };
26
-
27
- beforeEach(() => {
28
- mockTransport = createMockTransport();
29
- provider = new AztecProvider(mockTransport);
30
-
31
- // Setup chain builder mock after provider creation
32
- mockChainBuilder = {
33
- chainId: 'aztec:testnet',
34
- provider: provider,
35
- calls: [],
36
- call: vi.fn(),
37
- execute: vi.fn(),
38
- };
39
-
40
- // Setup mock chain builder
41
- mockChainBuilder.call.mockImplementation(() => mockChainBuilder);
42
- mockChainBuilder.execute.mockImplementation(() => Promise.resolve());
43
-
44
- // Setup additional mocks
45
- vi.spyOn(provider as WalletRouterProvider, 'sessionId', 'get').mockReturnValue('test-session-id');
46
- vi.spyOn(provider, 'chain').mockImplementation((chainId) => {
47
- mockChainBuilder.chainId = chainId;
48
- mockChainBuilder.call.mockImplementation((method, params) => {
49
- mockChainBuilder.calls.push({ method, params });
50
- return mockChainBuilder;
51
- });
52
- mockChainBuilder.execute.mockImplementation(async () => {
53
- const result = await Promise.resolve(null);
54
- if (result === null) {
55
- throw new AztecWalletError(AztecWalletErrorType.invalidResponse, 'Invalid response');
56
- }
57
- return result;
58
- });
59
- return mockChainBuilder as unknown as OperationBuilder;
60
- });
61
- });
62
-
63
- describe('constructor', () => {
64
- test('registers event handlers', () => {
65
- // Create a spy on the on method before creating provider
66
- const onSpy = vi.spyOn(WalletRouterProvider.prototype, 'on');
67
-
68
- // Create a new provider
69
- new AztecProvider(mockTransport);
70
-
71
- expect(onSpy).toHaveBeenCalledWith('wm_walletStateChanged', expect.any(Function));
72
- expect(onSpy).toHaveBeenCalledWith('wm_sessionTerminated', expect.any(Function));
73
-
74
- onSpy.mockRestore();
75
- });
76
-
77
- test('initializes with empty chain sets', () => {
78
- expect(provider.getSupportedChains()).toEqual([]);
79
- });
80
- });
81
-
82
- describe('handleWalletStateChanged', () => {
83
- test('adds chain when accounts become available', () => {
84
- const chainId = 'aztec:testnet';
85
- provider['requestedChains'].add(chainId);
86
-
87
- provider['handleWalletStateChanged']({
88
- chainId,
89
- changes: { accounts: ['0x123'] },
90
- });
91
-
92
- expect(provider.getSupportedChains()).toContain(chainId);
93
- });
94
-
95
- test('removes chain when accounts become unavailable', () => {
96
- const chainId = 'aztec:testnet';
97
- provider['requestedChains'].add(chainId);
98
- provider['connectedChains'].add(chainId);
99
-
100
- provider['handleWalletStateChanged']({
101
- chainId,
102
- changes: { accounts: [] },
103
- });
104
-
105
- expect(provider.getSupportedChains()).not.toContain(chainId);
106
- });
107
-
108
- test('ignores events for non-requested chains', () => {
109
- const chainId = 'aztec:testnet';
110
- // Chain not added to requestedChains
111
-
112
- provider['handleWalletStateChanged']({
113
- chainId,
114
- changes: { accounts: ['0x123'] },
115
- });
116
-
117
- expect(provider.getSupportedChains()).not.toContain(chainId);
118
- });
119
- });
120
-
121
- describe('handleSessionTerminated', () => {
122
- test('clears chains when session matches', () => {
123
- const chainId = 'aztec:testnet';
124
- provider['requestedChains'].add(chainId);
125
- provider['connectedChains'].add(chainId);
126
-
127
- provider['handleSessionTerminated']({
128
- sessionId: 'test-session-id',
129
- reason: 'test termination',
130
- });
131
-
132
- expect(provider.getSupportedChains()).toEqual([]);
133
- expect(provider['requestedChains'].size).toBe(0);
134
- });
135
-
136
- test('ignores termination for different sessions', () => {
137
- const chainId = 'aztec:testnet';
138
- provider['requestedChains'].add(chainId);
139
- provider['connectedChains'].add(chainId);
140
-
141
- provider['handleSessionTerminated']({
142
- sessionId: 'different-session',
143
- reason: 'test termination',
144
- });
145
-
146
- expect(provider.getSupportedChains()).toContain(chainId);
147
- expect(provider['requestedChains'].has(chainId)).toBe(true);
148
- });
149
- });
150
-
151
- describe('getAccount', () => {
152
- test('returns account address on success', async () => {
153
- const expectedAddress = '0x123';
154
- mockChainBuilder.execute.mockResolvedValueOnce(expectedAddress);
155
-
156
- const result = await provider.getAccount('aztec:testnet');
157
- expect(result).toBe(expectedAddress);
158
- });
159
-
160
- test('throws on invalid response', async () => {
161
- mockChainBuilder.execute.mockResolvedValueOnce(null);
162
-
163
- await expect(provider.getAccount('aztec:testnet')).rejects.toThrowError(
164
- new AztecWalletError(AztecWalletErrorType.invalidResponse, 'Invalid account address returned'),
165
- );
166
- });
167
- });
168
-
169
- describe('sendTransaction', () => {
170
- const mockTxParams = {
171
- functionCalls: [
172
- {
173
- contractAddress: '0x456',
174
- functionName: 'transfer',
175
- args: ['0x789', 100],
176
- },
177
- ],
178
- };
179
-
180
- test('returns transaction hash on success', async () => {
181
- const expectedHash = '0xabc';
182
- mockChainBuilder.execute.mockResolvedValueOnce(expectedHash);
183
-
184
- const result = await provider.sendTransaction('aztec:testnet', mockTxParams);
185
- expect(result).toBe(expectedHash);
186
- });
187
-
188
- test('throws on invalid response', async () => {
189
- mockChainBuilder.execute.mockResolvedValueOnce(null);
190
-
191
- await expect(provider.sendTransaction('aztec:testnet', mockTxParams)).rejects.toThrowError(
192
- new AztecWalletError(AztecWalletErrorType.invalidResponse, 'Invalid transaction hash returned'),
193
- );
194
- });
195
- });
196
-
197
- describe('simulateTransaction', () => {
198
- const mockSimParams = {
199
- contractAddress: '0x456',
200
- functionName: 'transfer',
201
- args: ['0x789', 100],
202
- };
203
-
204
- test('returns simulation result on success', async () => {
205
- const expectedResult = { success: true, gas: 1000 };
206
- mockChainBuilder.execute.mockResolvedValueOnce(expectedResult);
207
-
208
- const result = await provider.simulateTransaction('aztec:testnet', mockSimParams);
209
- expect(result).toEqual(expectedResult);
210
- });
211
-
212
- test('throws on invalid response', async () => {
213
- mockChainBuilder.execute.mockResolvedValueOnce(null);
214
-
215
- await expect(provider.simulateTransaction('aztec:testnet', mockSimParams)).rejects.toThrowError(
216
- new AztecWalletError(AztecWalletErrorType.invalidResponse, 'Invalid simulation result returned'),
217
- );
218
- });
219
- });
220
-
221
- describe('registration methods', () => {
222
- test('registerContract executes without error', async () => {
223
- mockChainBuilder.execute.mockResolvedValueOnce(undefined);
224
-
225
- await expect(
226
- provider.registerContract('aztec:testnet', {
227
- instance: {
228
- address: '0x123' as unknown as AztecAddress,
229
- version: 1,
230
- salt: '0x0' as unknown as AztecAddress,
231
- deployer: '0x0' as unknown as AztecAddress,
232
- contractClassId: '0x0' as unknown as AztecAddress,
233
- contractClassVersion: 1,
234
- publicKey: '0x0' as unknown as AztecAddress,
235
- } as unknown as ContractInstanceWithAddress,
236
- artifact: {
237
- name: 'TestContract',
238
- bytecode: '0x',
239
- functionSelectors: {},
240
- functions: {},
241
- outputs: {},
242
- storageLayout: {},
243
- events: {},
244
- } as unknown as ContractArtifact,
245
- }),
246
- ).resolves.not.toThrow();
247
- });
248
-
249
- test('registerContractClass executes without error', async () => {
250
- mockChainBuilder.execute.mockResolvedValueOnce(undefined);
251
-
252
- await expect(
253
- provider.registerContractClass('aztec:testnet', {
254
- artifact: {
255
- name: 'TestContract',
256
- bytecode: '0x',
257
- functionSelectors: {},
258
- functions: {},
259
- outputs: {},
260
- storageLayout: {},
261
- events: {},
262
- } as unknown as ContractArtifact,
263
- }),
264
- ).resolves.not.toThrow();
265
- });
266
-
267
- test('registerSender executes without error', async () => {
268
- mockChainBuilder.execute.mockResolvedValueOnce(undefined);
269
-
270
- await expect(
271
- provider.registerSender('aztec:testnet', {
272
- sender: '0x123' as unknown as AztecAddress,
273
- }),
274
- ).resolves.not.toThrow();
275
- });
276
- });
277
- });