@walletmesh/aztec-rpc-wallet 0.3.1 → 0.4.1

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 +26 -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 +498 -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 +11 -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 +584 -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
package/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # @walletmesh/aztec-rpc-wallet
2
2
 
3
+ ## 0.4.1
4
+
5
+ ### Patch Changes
6
+
7
+ - c22c977: Minor build fixes
8
+
9
+ ## 0.4.0
10
+
11
+ ### Minor Changes
12
+
13
+ - cb714b7: This release marks a major architectural overhaul of the Aztec RPC wallet to provide a more robust, secure, and developer-friendly integration with `aztec.js`.
14
+
15
+ - **BREAKING CHANGE**: The previous `AztecChainWallet` and `AztecProvider` classes have been removed.
16
+ - Introduced `AztecDappWallet`, a new client-side `Wallet` implementation that conforms to the standard `aztec.js` interface, ensuring seamless integration with the Aztec ecosystem.
17
+ - Added `createAztecWalletNode`, a new server-side factory for creating a `JSONRPCNode` that serves an `AccountWallet` instance.
18
+ - Introduced `connectAztec` and `createAztecWallet` helpers to simplify dApp connection and initialization flows.
19
+ - Added high-level `wmExecuteTx` and `wmDeployContract` methods to `AztecDappWallet`, which provide the wallet with more transaction context for improved security and user experience.
20
+ - Introduced `AztecRouterProvider`, which extends the base `WalletRouterProvider` to automatically handle serialization for all Aztec-specific types.
21
+
22
+ ### Patch Changes
23
+
24
+ - Updated dependencies [cb714b7]
25
+ - Updated dependencies [cb714b7]
26
+ - @walletmesh/jsonrpc@0.5.0
27
+ - @walletmesh/router@0.5.0
28
+
3
29
  ## 0.3.1
4
30
 
5
31
  ### Patch Changes
package/README.md CHANGED
@@ -1,260 +1,322 @@
1
- # WalletMesh Aztec RPC Wallet Library
1
+ # @walletmesh/aztec-rpc-wallet
2
2
 
3
- [@walletmesh/aztec-rpc-wallet](https://github.com/WalletMesh/walletmesh-packages/tree/main/aztec/aztec-rpc-wallet) provides a type-safe RPC interface for interacting with [Aztec](https://aztec.network) wallets. It consists of three main components:
3
+ JSON-RPC wallet integration for Aztec Protocol, built on WalletMesh router for multi-chain support.
4
4
 
5
- - **AztecProvider**: Client-side provider for dApps to communicate with Aztec wallets
6
- - **AztecChainWallet**: Server-side implementation that handles RPC requests using an Aztec wallet instance
7
- - **AztecOperationBuilder**: Fluent API for chaining multiple RPC method calls
5
+ ## Overview
8
6
 
9
- The library is built on [@walletmesh/jsonrpc](https://github.com/WalletMesh/walletmesh-packages/tree/main/core/jsonrpc#readme) and [@walletmesh/router](https://github.com/WalletMesh/walletmesh-packages/tree/main/core/router#readme).
7
+ This package provides an integration between Aztec wallets and dApps using the WalletMesh router system. It implements the aztec.js `Wallet` interface while leveraging WalletRouter for session management, permissions, and multi-chain support.
10
8
 
11
- ## Features
9
+ ## Architecture
12
10
 
13
- - Connect to multiple Aztec chains simultaneously
14
- - Flexible chain ID support (any string with 'aztec:' prefix)
15
- - Type-safe RPC interfaces with comprehensive TypeScript definitions
16
- - Efficient batching of multiple method calls
17
- - Fluent chaining API for bulk operations
18
- - Comprehensive error handling
19
- - Contract artifact caching
20
- - Event handling for wallet state changes
21
- - Serialization support for all Aztec data types
22
- - Support for encrypted and unencrypted events/logs
11
+ ```mermaid
12
+ graph LR
13
+ subgraph DApp Side
14
+ DApp[DApp Code] --> AztecDappWallet[AztecDappWallet]
15
+ AztecDappWallet --> AztecRouterProvider[AztecRouterProvider]
16
+ end
17
+
18
+ subgraph WalletMesh Core
19
+ AztecRouterProvider -- JSON-RPC --> WalletRouter[WalletRouter]
20
+ end
21
+
22
+ subgraph Wallet Side
23
+ WalletRouter -- JSON-RPC --> AztecWalletNode[AztecWalletNode]
24
+ AztecWalletNode --> AccountWallet[AccountWallet Instance]
25
+ AztecWalletNode --> PXE[PXE Instance]
26
+ end
27
+
28
+ style DApp fill:#cde4ff,stroke:#777,stroke-width:2px
29
+ style WalletRouter fill:#e6ffcd,stroke:#777,stroke-width:2px
30
+ style AztecWalletNode fill:#ffe6cd,stroke:#777,stroke-width:2px
31
+ style AccountWallet fill:#ffe6cd,stroke:#777,stroke-width:2px
32
+ style PXE fill:#ffe6cd,stroke:#777,stroke-width:2px
33
+ ```
34
+
35
+ - **DApp Side**: The dApp uses `AztecDappWallet` (an implementation of `aztec.js` `Wallet`) which communicates through `AztecRouterProvider`.
36
+ - **WalletRouter**: The central router from `@walletmesh/router` that directs requests to the appropriate wallet node based on chain ID.
37
+ - **Wallet Side**: `createAztecWalletNode` creates a `JSONRPCNode` (referred to as `AztecWalletNode` in the diagram) that wraps the user's `AccountWallet` and `PXE` instance, handling RPC requests.
23
38
 
24
39
  ## Installation
25
40
 
26
41
  ```bash
27
- npm install @walletmesh/aztec-rpc-wallet
42
+ pnpm add @walletmesh/aztec-rpc-wallet
28
43
  ```
29
44
 
30
- ## Core RPC Methods
31
-
32
- The library supports a comprehensive set of RPC methods:
33
-
34
- ### Chain Operations
35
- - `aztec_connect`: Connect to Aztec chains
36
- - `aztec_getBlock`: Get block by number
37
- - `aztec_getBlockNumber`: Get current block number
38
- - `aztec_getProvenBlockNumber`: Get proven block number
39
- - `aztec_getChainId`: Get chain ID
40
- - `aztec_getVersion`: Get protocol version
41
- - `aztec_getNodeInfo`: Get node information
42
- - `aztec_getPXEInfo`: Get PXE information
43
- - `aztec_getCurrentBaseFees`: Get current base fees
44
-
45
- ### Account Operations
46
- - `aztec_getAccount`: Get wallet's account address
47
- - `aztec_getAddress`: Get wallet's Aztec address
48
- - `aztec_getCompleteAddress`: Get complete address details
49
- - `aztec_registerAccount`: Register a new account
50
- - `aztec_getRegisteredAccounts`: Get all registered accounts
51
-
52
- ### Transaction Operations
53
- - `aztec_sendTransaction`: Send one or more transactions
54
- - `aztec_simulateTransaction`: Simulate transaction without executing
55
- - `aztec_sendTx`: Send raw transaction
56
- - `aztec_createTxExecutionRequest`: Create transaction execution request
57
- - `aztec_proveTx`: Generate transaction proof
58
- - `aztec_getTxEffect`: Get transaction effect
59
- - `aztec_getTxReceipt`: Get transaction receipt
60
-
61
- ### Contract Operations
62
- - `aztec_registerContract`: Register contract instance
63
- - `aztec_registerContractClass`: Register contract class
64
- - `aztec_getContracts`: Get registered contracts
65
- - `aztec_getContractInstance`: Get contract instance details
66
- - `aztec_getContractClass`: Get contract class details
67
- - `aztec_getContractArtifact`: Get contract artifact
68
- - `aztec_isContractClassPubliclyRegistered`: Check if contract class is publicly registered
69
- - `aztec_isContractPubliclyDeployed`: Check if contract is publicly deployed
70
- - `aztec_isContractInitialized`: Check if contract is initialized
71
- - `aztec_getPublicStorageAt`: Get public storage value
72
-
73
- ### Authorization & Scope Management
74
- - `aztec_setScopes`: Set authorization scopes
75
- - `aztec_getScopes`: Get current scopes
76
- - `aztec_addAuthWitness`: Add authorization witness
77
- - `aztec_getAuthWitness`: Get authorization witness
78
- - `aztec_createAuthWit`: Create authorization witness
79
-
80
- ### Notes and Events
81
- - `aztec_getIncomingNotes`: Get incoming notes
82
- - `aztec_addNote`: Add note
83
- - `aztec_addNullifiedNote`: Add nullified note
84
- - `aztec_getUnencryptedLogs`: Get unencrypted logs
85
- - `aztec_getContractClassLogs`: Get contract class logs
86
- - `aztec_getEncryptedEvents`: Get encrypted events
87
- - `aztec_getUnencryptedEvents`: Get unencrypted events
88
-
89
- ### L1->L2 Bridge Operations
90
- - `aztec_isL1ToL2MessageSynced`: Check if L1->L2 message is synced
91
- - `aztec_getL1ToL2MembershipWitness`: Get L1->L2 membership witness
92
-
93
- See [src/types.ts](https://github.com/WalletMesh/walletmesh-packages/blob/main/aztec/aztec-rpc-wallet/src/types.ts) for complete method definitions and parameters.
94
-
95
- ## Usage Examples
96
-
97
- ### Basic Provider Usage
45
+ ## Quick Start
46
+
47
+ ### DApp Usage
48
+
49
+ This example demonstrates connecting to an Aztec wallet and performing a simple action.
98
50
 
99
51
  ```typescript
100
- import { AztecProvider } from '@walletmesh/aztec-rpc-wallet';
101
-
102
- // Create provider with transport
103
- const provider = new AztecProvider(transport);
104
-
105
- // Connect to chains
106
- await provider.connect(['aztec:testnet', 'aztec:devnet']);
107
-
108
- // Get account address
109
- const address = await provider.getAccount('aztec:testnet');
110
-
111
- // Send transaction
112
- const txHash = await provider.sendTransaction('aztec:testnet', {
113
- functionCalls: [{
114
- contractAddress: "0x1234...",
115
- functionName: "transfer",
116
- args: [recipient, amount]
117
- }]
118
- });
119
-
120
- // Register contract
121
- await provider.registerContract('aztec:testnet', {
122
- instance: contractInstance,
123
- artifact: contractArtifact // optional if class already registered
124
- });
125
-
126
- // Listen for chain connection events
127
- provider.on('chain:connected', ({ chainId }) => {
128
- console.log(`Connected to chain: ${chainId}`);
129
- });
130
-
131
- // Listen for chain disconnection events
132
- provider.on('chain:disconnected', ({ chainId }) => {
133
- console.log(`Disconnected from chain: ${chainId}`);
134
- });
52
+ import { AztecRouterProvider, connectAztec } from '@walletmesh/aztec-rpc-wallet';
53
+ import { Contract } from '@aztec/aztec.js'; // Assuming you have a contract instance
54
+
55
+ // Define a transport (example: window postMessage for browser extensions)
56
+ const transport = {
57
+ send: async (msg: unknown) => window.parent.postMessage(msg, '*'), // Or specific targetOrigin
58
+ onMessage: (handler: (data: unknown) => void) => {
59
+ const listener = (event: MessageEvent) => {
60
+ // Add origin check for security if applicable
61
+ // if (event.origin !== 'expected-origin') return;
62
+ handler(event.data);
63
+ };
64
+ window.addEventListener('message', listener);
65
+ // Return a cleanup function if your transport needs it
66
+ // return () => window.removeEventListener('message', listener);
67
+ },
68
+ };
69
+
70
+ async function main() {
71
+ // 1. Create AztecRouterProvider with your transport
72
+ // This provider automatically handles serialization of Aztec types.
73
+ const provider = new AztecRouterProvider(transport);
74
+
75
+ // 2. Connect to the Aztec chain and get an initialized wallet instance
76
+ // This requests permissions for all Aztec methods by default.
77
+ // Replace 'aztec:testnet' with your target chainId if different.
78
+ const { sessionId, wallet } = await connectAztec(provider, 'aztec:testnet');
79
+ console.log('Connected to Aztec wallet with session ID:', sessionId);
80
+
81
+ // 3. Use the wallet (which implements aztec.js Wallet interface)
82
+ const address = wallet.getAddress(); // Synchronous access after initialization
83
+ console.log('Wallet address:', address.toString());
84
+
85
+ // Example: Interacting with a contract (assuming 'myContract' is an aztec.js Contract instance)
86
+ const myContract = await Contract.at(contractAddress, contractArtifact, wallet);
87
+ const interaction = myContract.methods.someFunction(arg1, arg2);
88
+
89
+ // Option A: Using WalletMesh high-level execution (Wallet gets passed high-level interaction
90
+ // and can see the actual function call & arguments rather than just hashed values)
91
+ const sentTx = await wallet.wmExecuteTx(interaction);
92
+ const txHash = await sentTx.getTxHash();
93
+ console.log('Transaction sent with wmExecuteTx, hash:', txHash.toString());
94
+ const receipt = await sentTx.getReceipt();
95
+
96
+ // Option B: Using standard aztec.js flow (only implemented for Aztec.js `Wallet` interface compatibility)
97
+ const executionPayload = await interaction.request();
98
+ const txExecutionRequest = await wallet.createTxExecutionRequest(executionPayload, feeOptions, txOptions);
99
+ const provingResult = await wallet.proveTx(txExecutionRequest);
100
+ const txHashStd = await wallet.sendTx(provingResult.toTx());
101
+ console.log('Transaction sent with standard flow, hash:', txHashStd.toString());
102
+ const receiptStd = await wallet.getTxReceipt(txHashStd);
103
+
104
+ // For a read-only call
105
+ const simulateResult = await myContract.methods.balanceOf(address).simulate();
106
+ console.log('Simulate function result:', simulateResult);
107
+ }
108
+ ```
109
+
110
+ ### Wallet Implementation
111
+
112
+ ```typescript
113
+ import { createAztecWalletNode } from '@walletmesh/aztec-rpc-wallet';
114
+ import { WalletRouter } from '@walletmesh/router';
115
+
116
+ // 1. Create Aztec wallet node
117
+ const walletNode = createAztecWalletNode(
118
+ accountWallet, // Your AccountWallet instance
119
+ pxe, // Your PXE instance
120
+ transport // JSON-RPC transport
121
+ );
122
+
123
+ // 2. Register with router
124
+ const router = new WalletRouter(
125
+ routerTransport,
126
+ new Map([
127
+ ['aztec:testnet', walletNode],
128
+ // Add other chains as needed
129
+ ]),
130
+ permissionManager
131
+ );
135
132
  ```
136
133
 
137
- ### Chaining API for Bulk Operations
134
+ ## API Reference
138
135
 
139
- The provider supports a fluent chaining API for executing multiple operations efficiently:
136
+ ### DApp API
137
+
138
+ #### `AztecRouterProvider`
139
+ Extended WalletRouterProvider with built-in Aztec serialization support. Automatically handles serialization/deserialization of Aztec types (AztecAddress, CompleteAddress, Fr, etc.) when communicating through the router.
140
140
 
141
141
  ```typescript
142
- // Multiple reads in single batch
143
- const [account, contracts, blockNumber] = await provider
144
- .chain('aztec:testnet')
145
- .call('aztec_getAccount')
146
- .call('aztec_getContracts')
147
- .call('aztec_getBlockNumber')
148
- .execute();
149
-
150
- // Contract setup and interaction
151
- const [classId, instanceId, txHash] = await provider
152
- .chain('aztec:testnet')
153
- .call('aztec_registerContractClass', { artifact: contractArtifact })
154
- .call('aztec_registerContract', {
155
- instance: contractInstance,
156
- artifact: contractArtifact
157
- })
158
- .call('aztec_sendTransaction', {
159
- functionCalls: [{
160
- contractAddress: contractInstance.address,
161
- functionName: 'initialize',
162
- args: [param1, param2]
163
- }]
164
- })
165
- .execute();
166
-
167
- // Multi-chain operations
168
- const [testnetData, devnetData] = await Promise.all([
169
- provider
170
- .chain('aztec:testnet')
171
- .call('aztec_getAccount')
172
- .call('aztec_getContracts')
173
- .execute(),
174
- provider
175
- .chain('aztec:devnet')
176
- .call('aztec_getAccount')
177
- .call('aztec_getContracts')
178
- .execute()
179
- ]);
142
+ const provider = new AztecRouterProvider(transport);
143
+ // All Aztec types are automatically serialized/deserialized
180
144
  ```
181
145
 
182
- ### Error Handling
146
+ #### `createAztecWallet(provider, chainId)`
147
+ Creates an Aztec wallet instance that implements the aztec.js `Wallet` interface.
183
148
 
184
- The library provides comprehensive error handling through `AztecWalletError`:
149
+ ```typescript
150
+ const wallet = createAztecWallet(provider, 'aztec:testnet');
151
+ ```
152
+
153
+ #### `connectAztec(provider, chainId?, methods?)`
154
+ Connects to an Aztec wallet service and returns an initialized `AztecDappWallet` instance.
155
+ - `provider`: An initialized `AztecRouterProvider`.
156
+ - `chainId?`: The target `AztecChainId` (e.g., `'aztec:testnet'`). Defaults to `'aztec:mainnet'`.
157
+ - `methods?`: Optional array of method names to request permissions for. Defaults to `ALL_AZTEC_METHODS`.
158
+ Returns: `Promise<{ sessionId: string; wallet: AztecDappWallet }>`
185
159
 
186
160
  ```typescript
187
- try {
188
- await provider.sendTransaction('aztec:testnet', {
189
- functionCalls: [{
190
- contractAddress: "0x1234...",
191
- functionName: "transfer",
192
- args: [recipient, amount]
193
- }]
194
- });
195
- } catch (error) {
196
- if (error instanceof AztecWalletError) {
197
- switch (error.code) {
198
- case -32001: // User refused
199
- console.log('Transaction rejected by user');
200
- break;
201
- case -32002: // Wallet not connected
202
- console.log('Please connect wallet first');
203
- break;
204
- default:
205
- console.error('RPC error:', error.message);
206
- }
207
- }
208
- }
161
+ const { sessionId, wallet } = await connectAztec(provider, 'aztec:testnet');
162
+ const address = wallet.getAddress(); // Wallet is ready
209
163
  ```
210
164
 
211
- ### Implementing a Wallet
212
165
 
213
- Server-side implementation using `AztecWallet`:
166
+ #### `AztecDappWallet`
167
+ The main client-side wallet class that implements the `aztec.js` `Wallet` interface. It interacts with the remote wallet via the `AztecRouterProvider`. Instances are typically created using `createAztecWallet` or `connectAztec`.
168
+
169
+ **Key `Wallet` Interface Methods (implemented by `AztecDappWallet`):**
170
+
171
+ * **Account Information:**
172
+ * `getAddress(): AztecAddress` - Gets the wallet's primary Aztec address (cached after initialization).
173
+ * `getCompleteAddress(): CompleteAddress` - Gets the wallet's complete address including public keys (cached).
174
+ * `getChainId(): Fr` - Gets the chain ID (cached).
175
+ * `getVersion(): Fr` - Gets the wallet/PXE version (cached).
176
+ * Async versions for direct fetching: `getAddressAsync()`, `getCompleteAddressAsync()`, `getChainIdAsync()`, `getVersionAsync()`.
177
+
178
+ * **Transaction Lifecycle:**
179
+ * `createTxExecutionRequest(exec: ExecutionPayload, fee: FeeOptions, options: TxExecutionOptions): Promise<TxExecutionRequest>` - Creates a transaction execution request using the wallet's local entrypoint.
180
+ * `proveTx(txRequest: TxExecutionRequest, privateExecutionResult?: PrivateExecutionResult): Promise<TxProvingResult>` - Generates proofs for a transaction.
181
+ * `sendTx(tx: Tx): Promise<TxHash>` - Sends a proven transaction to the network.
182
+ * `getTxReceipt(txHash: TxHash): Promise<TxReceipt>` - Retrieves a transaction receipt.
183
+ * `simulateTx(txRequest: TxExecutionRequest, simulatePublic: boolean, msgSender?: AztecAddress, skipTxValidation?: boolean, skipFeeEnforcement?: boolean, scopes?: AztecAddress[]): Promise<TxSimulationResult>` - Simulates a transaction.
184
+ * `profileTx(txRequest: TxExecutionRequest, profileMode: 'gates' | 'execution-steps' | 'full', skipProofGeneration?: boolean, msgSender?: AztecAddress): Promise<TxProfileResult>` - Profiles a transaction.
185
+ * `simulateUtility(functionName: string, args: unknown[], to: AztecAddress, authWits?: AuthWitness[], from?: AztecAddress): Promise<UtilitySimulationResult>` - Simulates a view function call.
186
+
187
+ * **Contract Management:**
188
+ * `registerContract(contract: { artifact?: ContractArtifact; instance: ContractInstanceWithAddress }): Promise<void>` - Registers a deployed contract instance.
189
+ * `registerContractClass(artifact: ContractArtifact): Promise<void>` - Registers a contract class/artifact.
190
+ * `getContracts(): Promise<AztecAddress[]>` - Gets all registered contract addresses.
191
+ * `getContractMetadata(address: AztecAddress): Promise<ContractMetadata>` - Gets metadata for a specific contract.
192
+ * `getContractClassMetadata(id: Fr, includeArtifact?: boolean): Promise<ContractClassMetadata>` - Gets metadata for a contract class.
193
+ * `updateContract(_contractAddress: AztecAddress, artifact: ContractArtifact): Promise<void>` - Updates a contract's artifact (typically re-registers its class).
194
+
195
+ * **Authorization & Senders:**
196
+ * `createAuthWit(intent: Fr | Buffer | IntentInnerHash | IntentAction): Promise<AuthWitness>` - Creates an authorization witness.
197
+ * `registerSender(address: AztecAddress): Promise<AztecAddress>` - Registers an authorized sender.
198
+ * `getSenders(): Promise<AztecAddress[]>` - Gets all authorized senders.
199
+ * `removeSender(sender: AztecAddress): Promise<void>` - Removes an authorized sender.
200
+
201
+ * **Network & Node Information:**
202
+ * `getBlock(number: number): Promise<L2Block | undefined>` - Gets a block by its number.
203
+ * `getBlockNumber(): Promise<number>` - Gets the current block number.
204
+ * `getCurrentBaseFees(): Promise<GasFees>` - Gets current base gas fees.
205
+ * `getNodeInfo(): Promise<NodeInfo>` - Gets node information.
206
+ * `getPXEInfo(): Promise<PXEInfo>` - Gets PXE service information.
207
+
208
+ * **Event Querying:**
209
+ * `getPrivateEvents<T>(contractAddress: AztecAddress, eventMetadata: EventMetadataDefinition, from: number, numBlocks: number, recipients: AztecAddress[]): Promise<T[]>` - Queries private (encrypted) events.
210
+ * `getPublicEvents<T>(eventMetadata: EventMetadataDefinition, from: number, limit: number): Promise<T[]>` - Queries public (unencrypted) events.
211
+
212
+ **WalletMesh Extended Methods on `AztecDappWallet`:**
213
+ These methods simplify common dApp workflows by leveraging WalletMesh capabilities.
214
+ - `wmExecuteTx(interaction: ContractFunctionInteraction): Promise<SentTx>` - High-level method to execute a transaction from a `ContractFunctionInteraction`. Handles payload creation, proving, and sending via the remote wallet.
215
+ - `wmSimulateTx(interaction: ContractFunctionInteraction): Promise<TxSimulationResult>` - High-level method to simulate a transaction from a `ContractFunctionInteraction`.
216
+ - `deployContract(artifact: ContractArtifact, args: unknown[], constructorName?: string): Promise<DeploySentTx>` - High-level method to deploy a contract.
217
+
218
+ Refer to `aztec.js` documentation for detailed explanations of the standard `Wallet` interface methods.
219
+
220
+ ### Wallet API
221
+
222
+ #### `createAztecWalletNode(wallet, pxe, transport)`
223
+ Creates a JSONRPCNode configured for Aztec wallet operations.
214
224
 
215
225
  ```typescript
216
- import { AztecChainWallet } from '@walletmesh/aztec-rpc-wallet';
217
- import type { PXE, AccountWallet } from '@aztec/aztec.js';
218
-
219
- // Create wallet instance
220
- const wallet = new AztecChainWallet(
221
- pxe, // PXE instance
222
- accountWallet, // Aztec AccountWallet instance
223
- transport // Transport layer
224
- );
226
+ const walletNode = createAztecWalletNode(accountWallet, pxe, transport);
227
+ ```
228
+
229
+ ## Method Permissions
230
+
231
+ ### Default Methods
232
+ When using `connectAztec()` without specifying methods:
233
+ - `aztec_getAddress`
234
+ - `aztec_getCompleteAddress`
235
+ - `aztec_sendTx`
236
+ - `aztec_getTxReceipt`
237
+ - `aztec_createTxExecutionRequest`
238
+ - `aztec_simulateTx`
239
+ - `aztec_getNodeInfo`
240
+ - `aztec_getBlockNumber`
241
+ - `aztec_getCurrentBaseFees`
242
+
243
+ ### All Available Methods
244
+ See `ALL_AZTEC_METHODS` export for the complete list of supported methods.
245
+
246
+ ## Transport Layer
225
247
 
226
- // Handle incoming requests
227
- transport.on('message', async (request) => {
228
- const response = await wallet.handleRequest(request);
229
- // Send response back to dApp
230
- });
248
+ This library uses the `JSONRPCTransport` interface from `@walletmesh/jsonrpc` for communication:
231
249
 
232
- // Use with WalletMesh router
233
- const routerClient = wallet.asWalletRouterClient();
250
+ ```typescript
251
+ interface JSONRPCTransport {
252
+ send(data: unknown): Promise<void>;
253
+ onMessage(callback: (data: unknown) => void): void;
254
+ }
234
255
  ```
235
256
 
236
- ## Error Codes
237
-
238
- Common error codes returned by the library:
239
-
240
- - -32000: Unknown internal error
241
- - -32001: User refused transaction
242
- - -32002: Wallet not connected
243
- - -32003: Contract instance not registered
244
- - -32004: Contract class not registered
245
- - -32005: Sender not registered
246
- - -32006: Invalid response format
247
- - -32007: Not connected to any chain
248
- - -32008: Chain not supported
249
- - -32009: Invalid request format
250
- - -32010: Invalid parameters
251
- - -32011: Permission denied
252
- - -32012: Session not found
253
- - -32013: Session expired
254
- - -32014: Transaction not found
255
- - -32015: Block not found
256
- - -32016: Authorization witness not found
257
-
258
- ## Example Project
259
-
260
- See the [example project](https://github.com/WalletMesh/walletmesh-packages/tree/main/aztec/example) for a complete implementation using this library.
257
+ ## Architecture Details
258
+
259
+ ### Components
260
+
261
+ 1. **Wallet Side** (`wallet/` directory)
262
+ - `create-node.ts` - Factory for JSONRPCNode
263
+ - `handlers/` - Pure function handlers for each method
264
+ - `serializers/` - Type serialization for Aztec objects
265
+
266
+ 2. **DApp Side** (`client/` directory)
267
+ - `aztec-dapp-wallet.ts` - Implements aztec.js Wallet interface
268
+ - `helpers.ts` - Convenience functions
269
+
270
+ 3. **Shared** (`types.ts`)
271
+ - Method definitions
272
+ - Aztec-specific types
273
+
274
+ ### Handler Pattern
275
+
276
+ ```typescript
277
+ export function createAccountHandlers() {
278
+ return {
279
+ aztec_getAddress: async (
280
+ ctx: AztecHandlerContext,
281
+ _paramsTuple: AztecWalletMethodMap['aztec_getAddress']['params'],
282
+ ): Promise<AztecWalletMethodMap['aztec_getAddress']['result']> => {
283
+ return ctx.wallet.getAddress();
284
+ },
285
+ // ... more handlers
286
+ };
287
+ }
288
+ ```
289
+
290
+ ### Serializer Architecture
291
+
292
+ This package relies on Aztec's serialization mechanisms to handle complex Aztec data types over JSON-RPC. This is managed by the `AztecWalletSerializer` on the wallet-side and automatically handled by `AztecRouterProvider` on the dApp-side.
293
+
294
+ **Key Aspects:**
295
+
296
+ 1. **`AztecWalletSerializer`**:
297
+ * A single, comprehensive serializer object (see `wallet/serializers.ts`) is responsible for all Aztec methods.
298
+ * **Parameter Deserialization (Wallet Side)**: When the wallet node receives a request, `AztecWalletSerializer` uses a detailed `switch` statement for `params.deserialize`. It parses the JSON parameters and reconstructs them into their proper Aztec object types (e.g., `AztecAddress.fromString(str)`, `TxExecutionRequest.schema.parse(obj)`), leveraging Zod schemas from `@aztec/aztec.js` and `@aztec/stdlib`.
299
+ * **Result Serialization (Wallet Side)**: For results being sent back to the dApp, `AztecWalletSerializer` uses `result.serialize`. It often employs `jsonStringify` from `@aztec/foundation/json-rpc` along with Zod schemas for specific Aztec result types.
300
+ * **Parameter Serialization (Client Side via `AztecRouterProvider`)**: The `AztecRouterProvider` ensures that when the dApp calls a method on `AztecDappWallet`, the parameters (which are already proper Aztec objects) are serialized correctly before being sent. This typically involves `jsonStringify` with appropriate schemas.
301
+ * **Result Deserialization (Client Side via `AztecRouterProvider`)**: When the dApp receives a response, `AztecRouterProvider` uses the serializer to convert the JSON data back into rich Aztec objects (e.g., an `AztecAddress` instance, not just a string).
302
+
303
+ 2. **Zod Schemas**: The serialization heavily relies on Zod schemas defined within the Aztec protocol's libraries (e.g., `AztecAddress.schema`, `Tx.schema`) and some custom Zod schemas defined in this package for types not having them upstream.
304
+
305
+ 3. **Automatic Handling for dApps**: DApp developers using `AztecRouterProvider` and `AztecDappWallet` generally do not need to worry about serialization details, as it's handled transparently.
306
+
307
+ This architecture ensures type safety and data integrity when complex Aztec objects are transmitted between the dApp and the wallet.
308
+
309
+ ## DApp Usage Example
310
+
311
+ ```typescript
312
+ import { AztecRouterProvider, connectAztecWithWallet, createAztecWallet } from '@walletmesh/aztec-rpc-wallet';
313
+
314
+ // Initialize the Aztec-specific router provider
315
+ const provider = new AztecRouterProvider(dAppTransportToRouter);
316
+
317
+ // Connect and get an initialized wallet instance
318
+ const { sessionId, wallet } = await connectAztecWithWallet(provider, 'aztec:testnet');
319
+
320
+ // 'wallet' is now an AztecDappWallet instance, ready for use
321
+ const address = wallet.getAddress();
322
+ ```