### Getting Started: Install, Build, and Preview Aztec Wallet Source: https://github.com/walletmesh/walletmesh-packages/blob/main/aztec/example-wallet/README.md These commands guide you through setting up and running the Aztec example wallet. They cover installing project dependencies, building the application, and starting a local preview server for development and testing. ```bash pnpm install ``` ```bash pnpm build ``` ```bash pnpm preview ``` -------------------------------- ### Set Up and Run Aztec Example DApp Locally Source: https://github.com/walletmesh/walletmesh-packages/blob/main/aztec/example-dapp/README.md Instructions for installing dependencies, building the project, and starting the development server for the Aztec example dApp on a local machine. Requires Node.js and pnpm. ```bash pnpm install pnpm build pnpm dev ``` -------------------------------- ### Start Aztec Sandbox with Docker Compose Source: https://github.com/walletmesh/walletmesh-packages/blob/main/aztec/example/README.md Instructions to start the Aztec Sandbox using Docker Compose, specifically for the example project, bypassing standard Aztec instructions. This command navigates to the sandbox directory and brings up the containers in detached mode. ```bash cd /path/to/packages/example/sandbox docker compose up -d -f docker-compose.yaml ``` -------------------------------- ### Build and Run WalletMesh Example DApp Source: https://github.com/walletmesh/walletmesh-packages/blob/main/aztec/example/README.md Commands to build the example DApp and run it using `vite preview`. This method is required due to web worker limitations encountered with Vite's development server, ensuring the application is served correctly. ```bash pnpm build pnpm preview ``` -------------------------------- ### Example Usage of Context7 MCP Commands (TypeScript) Source: https://github.com/walletmesh/walletmesh-packages/blob/main/CLAUDE.md This TypeScript example demonstrates how to programmatically use the Context7 MCP commands. It shows the two-step process of first resolving a library's ID and then using that ID to fetch its documentation, including how to specify a particular topic like React hooks. ```TypeScript // When you need Vitest documentation: // 1. Call: mcp__context7__resolve-library-id("vitest") // 2. Call: mcp__context7__get-library-docs("/vitest-dev/vitest") // When you need React hooks documentation: // 1. Call: mcp__context7__resolve-library-id("react") // 2. Call: mcp__context7__get-library-docs("/facebook/react", { topic: "hooks" }) ``` -------------------------------- ### WalletMesh Debugging Code Examples Source: https://github.com/walletmesh/walletmesh-packages/blob/main/CLAUDE.md Provides code examples for common debugging practices in WalletMesh TypeScript projects, including structured logging for better traceability and focused test execution for efficient development. ```TypeScript console.log('[PackageName:Function]', data) test.only() ``` -------------------------------- ### Build and Run Aztec Example DApp with Docker Source: https://github.com/walletmesh/walletmesh-packages/blob/main/aztec/example-dapp/README.md Commands to containerize and deploy the Aztec example dApp using Docker. This process builds a Docker image from the provided Dockerfile and runs it, making the dApp accessible on port 8080. ```bash docker build -f aztec/example-dapp/Dockerfile -t aztec-example-dapp . docker run -p 8080:80 aztec-example-dapp ``` -------------------------------- ### Install @walletmesh/aztec-helpers package Source: https://github.com/walletmesh/walletmesh-packages/blob/main/aztec/helpers/docs/README.md Instructions to install the @walletmesh/aztec-helpers package using pnpm, a fast, disk space efficient package manager. ```bash pnpm add @walletmesh/aztec-helpers ``` -------------------------------- ### Install WalletMesh Aztec Helpers Package Source: https://github.com/walletmesh/walletmesh-packages/blob/main/aztec/helpers/README.md Instructions for installing the @walletmesh/aztec-helpers package using the pnpm package manager. ```bash pnpm add @walletmesh/aztec-helpers ``` -------------------------------- ### Example: Initialize and Connect AztecRouterProvider Source: https://github.com/walletmesh/walletmesh-packages/blob/main/aztec/rpc-wallet/docs/classes/AztecRouterProvider.md Demonstrates how to create an instance of `AztecRouterProvider`, connect to an Aztec chain with specific permissions, and then use it to create an `AztecDappWallet`. This setup automatically handles serialization of Aztec-specific types for JSON-RPC communication, simplifying dApp interactions. ```typescript import { AztecRouterProvider, createAztecWallet } from '@walletmesh/aztec-rpc-wallet'; import { MyCustomTransport } from './my-custom-transport'; // Assuming a custom transport // 1. Create a JSON-RPC transport const transport = new MyCustomTransport(); // 2. Create the AztecRouterProvider instance const provider = new AztecRouterProvider(transport); // 3. Connect to the Aztec chain (e.g., testnet) and request permissions await provider.connect({ 'aztec:testnet': ['aztec_getAddress', 'aztec_sendTx'] }); // 4. Create an AztecDappWallet instance using the provider const wallet = await createAztecWallet(provider, 'aztec:testnet'); // Now, calls made through 'wallet' will automatically handle Aztec type serialization: const address = await wallet.getAddress(); // AztecAddress instance // const txRequest = ...; // const txHash = await wallet.sendTx(await wallet.proveTx(txRequest)); // Tx, TxHash instances ``` -------------------------------- ### Initialize WalletMesh Router and Provider for Ethereum Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/router/docs/README.md This TypeScript example demonstrates the setup of a `WalletRouter` and `WalletRouterProvider`. It initializes an Ethereum wallet as a `JSONRPCNode` to handle RPC communication, registers a method (`eth_accounts`), and then configures the router with a transport layer and a permissive permissions manager. Finally, it shows how to connect to the provider, request specific method permissions for 'eip155:1' (Ethereum mainnet), and make a sample `eth_accounts` call through the established session. ```typescript import { WalletRouter, WalletRouterProvider, PermissivePermissionsManager, type JSONRPCWallet } from '@walletmesh/router'; import { JSONRPCNode } from '@walletmesh/jsonrpc'; // Initialize a basic Ethereum wallet as a JSONRPCNode // This node handles JSON-RPC communication for Ethereum mainnet const ethereumWallet: JSONRPCWallet = new JSONRPCNode({ send: async (message) => { // Forward JSON-RPC messages to the injected Ethereum provider const result = await window.ethereum.request(message); // Send response back through the transport ethereumWallet.receiveMessage({ jsonrpc: '2.0', id: message.id, result }); }, onMessage: (handler) => { // Setup message handler for responses } }); // Register wallet methods etherneumWallet.registerMethod('eth_accounts', async () => { return window.ethereum.request({ method: 'eth_accounts' }); }); // Initialize the router with transport layer, wallets, and permission manager // The router coordinates communication between the application and wallets const router = new WalletRouter( { send: (msg) => Promise.resolve(window.postMessage(msg, '*')), onMessage: (handler) => window.addEventListener('message', (e) => handler(e.data)) }, new Map([['eip155:1', ethereumWallet]]), // For development, use the permissive permission manager new PermissivePermissionsManager() ); // Initialize the provider that applications use to interact with wallets // The provider offers a high-level interface for wallet operations const provider = new WalletRouterProvider({ send: async (msg) => window.postMessage(msg, '*'), onMessage: (handler) => window.addEventListener('message', (e) => handler(e.data)) }); // Connect to Ethereum mainnet and request method permissions // This establishes a session and requests access to specific RPC methods const { sessionId, permissions } = await provider.connect({ 'eip155:1': ['eth_accounts', 'eth_sendTransaction'] }, 5000); // Optional timeout in milliseconds // The permissions are in a human-readable format for display to users console.log('Approved permissions:', permissions); // The connect method returns the session ID for future requests console.log('Connected with session:', sessionId); // Call a wallet method using the established session // The router will validate permissions and route the call to the appropriate wallet const accounts = await provider.call('eip155:1', { method: 'eth_accounts' }, 5000); // Optional timeout in milliseconds ``` -------------------------------- ### Vitest Fake Timers Setup and Usage Source: https://github.com/walletmesh/walletmesh-packages/blob/main/CLAUDE.md Demonstrates the correct setup and usage of fake timers in Vitest tests to prevent slow execution. It includes `beforeEach` and `afterEach` hooks for timer management and an example of advancing time in an asynchronous test. This practice is crucial for efficient and reliable unit testing. ```javascript // Setup beforeEach(() => { vi.useFakeTimers(); }); afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); }); // In tests it('should retry after delay', async () => { const promise = someAsyncOperation(); // Advance fake timers instead of waiting await vi.advanceTimersByTimeAsync(1000); await expect(promise).resolves.toBe(expectedValue); }); ``` -------------------------------- ### Discover Wallets in dApps Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/discovery/README.md Example demonstrating how dApps can discover available wallets using `createDiscoveryListener`. It shows how to start listening for announcements and retrieve the list of discovered wallets. ```typescript import { createDiscoveryListener } from '@walletmesh/discovery'; const listener = createDiscoveryListener(['ethereum', 'evm'], (wallet) => { console.log('Discovered wallet:', wallet); }); listener.start(); // Get all discovered wallets const wallets = listener.wallets; ``` -------------------------------- ### Basic JSON-RPC Node Setup with TypeScript Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/jsonrpc/README.md Illustrates the foundational steps for setting up a JSON-RPC node, including defining type maps for methods and events, creating a custom context, and implementing a transport layer for message communication. This example demonstrates the type-safe initialization of the `JSONRPCNode`. ```TypeScript // Define your types type MethodMap = { add: { params: { a: number; b: number }; result: number }; greet: { params: { name: string }; result: string }; }; type EventMap = { userJoined: { username: string; timestamp: number }; statusUpdate: { status: 'online' | 'offline'; lastSeen?: number }; }; type Context = JSONRPCContext & { userId?: string; sessionData?: Record; // Add any other custom context properties customValue?: number; }; // Implement a transport (e.g., using a WebSocket-like object 'ws') const transport: JSONRPCTransport = { send: async (message) => { // Send messages to remote node // await ws.send(JSON.stringify(message)); console.log('Node sending message:', message); }, onMessage: (callback) => { // Receive messages from remote node // ws.on('message', data => { // callback(JSON.parse(data.toString())); // }); console.log('Node onMessage registered.'); } }; // Create a node instance with the transport and optional initial context const node = new JSONRPCNode(transport, { customValue: 123 }); ``` -------------------------------- ### Install WalletMesh Discovery Package Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/discovery/README.md Instructions for installing the `@walletmesh/discovery` package using common Node.js package managers like npm, pnpm, or yarn. ```bash npm install @walletmesh/discovery # or pnpm add @walletmesh/discovery # or yarn add @walletmesh/discovery ``` -------------------------------- ### Install @walletmesh/jsonrpc package Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/jsonrpc/README.md Instructions to install the `@walletmesh/jsonrpc` package using the pnpm package manager. ```bash pnpm add @walletmesh/jsonrpc ``` -------------------------------- ### Example: Get Supported Methods for WalletMesh Provider Source: https://github.com/walletmesh/walletmesh-packages/blob/main/aztec/rpc-wallet/docs/classes/AztecRouterProvider.md Demonstrates how to use the `getSupportedMethods` API to query supported methods for specific chains or the router itself, and how to check for specific capabilities. ```typescript // Get methods for multiple chains const methods = await provider.getSupportedMethods(['eip155:1', 'eip155:137']); if (methods['eip155:1'].includes('eth_signMessage')) { // Ethereum mainnet wallet supports message signing } // Get router's supported methods const routerMethods = await provider.getSupportedMethods(); ``` -------------------------------- ### Install @walletmesh/discovery Package Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/discovery/docs/index.html Instructions for installing the @walletmesh/discovery package using npm, pnpm, or yarn. This package provides a cross-origin wallet discovery protocol implementation for WalletMesh. ```Shell npm install @walletmesh/discovery # or pnpm add @walletmesh/discovery # or yarn add @walletmesh/discovery ``` -------------------------------- ### WalletMesh Discovery Development Commands Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/discovery/README.md Common development commands for the `@walletmesh/discovery` package, including installing dependencies, running tests, building the project, and generating documentation. ```bash # Install dependencies pnpm install # Run tests pnpm test # Build pnpm build # Generate docs pnpm docs ``` -------------------------------- ### Development Commands for @walletmesh/discovery Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/discovery/docs/index.html Common development commands for the @walletmesh/discovery package, including installing dependencies, running tests, building the project, and generating documentation using pnpm. ```Shell # Install dependencies pnpm install # Run tests pnpm test # Build pnpm build # Generate docs pnpm docs ``` -------------------------------- ### Install @walletmesh/router with pnpm Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/router/docs/README.md This command installs the `@walletmesh/router` package using pnpm, a fast and efficient package manager, making it available for use in your project. ```bash pnpm add @walletmesh/router ``` -------------------------------- ### Install @walletmesh/router package Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/router/README.md This command installs the @walletmesh/router package using pnpm, a fast, disk-space efficient package manager. ```bash pnpm add @walletmesh/router ``` -------------------------------- ### Install WalletMesh Router with pnpm Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/router/docs/README.md Instructions for installing the `@walletmesh/router` package using the pnpm package manager, a fast and efficient way to manage project dependencies. ```bash pnpm add @walletmesh/router ``` -------------------------------- ### Install @walletmesh/jsonrpc Package Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/jsonrpc/docs/README.md This snippet shows how to install the `@walletmesh/jsonrpc` package using pnpm, a fast, disk space efficient package manager. ```bash pnpm add @walletmesh/jsonrpc ``` -------------------------------- ### Example Usage of createAztecWallet in TypeScript Source: https://github.com/walletmesh/walletmesh-packages/blob/main/aztec/rpc-wallet/docs/functions/createAztecWallet.md Demonstrates how to use the `createAztecWallet` function to initialize an Aztec wallet. This example includes setting up a `dAppTransport`, creating an `AztecRouterProvider`, connecting it, and then using `createAztecWallet` to obtain a usable wallet instance. ```typescript const dAppTransport = { send: ..., onMessage: ... }; // User-defined transport const provider = new AztecRouterProvider(dAppTransport); await provider.connect({ 'aztec:mainnet': ['aztec_getAddress'] }); // Connect first const wallet = await createAztecWallet(provider, 'aztec:mainnet'); const address = wallet.getAddress(); // Now usable ``` -------------------------------- ### DApp Integration Example with Aztec RPC Wallet Source: https://github.com/walletmesh/walletmesh-packages/blob/main/aztec/rpc-wallet/docs/README.md Provides a practical example of how a dApp can connect to and interact with the Aztec wallet using `AztecRouterProvider` and `connectAztecWithWallet`. It demonstrates initializing the provider, establishing a session, and making a basic wallet call like `getAddress()`. ```typescript import { AztecRouterProvider, connectAztecWithWallet, createAztecWallet } from '@walletmesh/aztec-rpc-wallet'; // Initialize the Aztec-specific router provider const provider = new AztecRouterProvider(dAppTransportToRouter); // Connect and get an initialized wallet instance const { sessionId, wallet } = await connectAztecWithWallet(provider, 'aztec:testnet'); // 'wallet' is now an AztecDappWallet instance, ready for use const address = wallet.getAddress(); ``` -------------------------------- ### Initialize Page Theme and Display Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/discovery/docs/functions/client.createExtensionWalletAnnouncer.html These JavaScript snippets handle initial page setup, including setting the theme from local storage and managing the display of the body element to prevent flash of unstyled content (FOUC) during page load. ```JavaScript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; ``` ```JavaScript document.body.style.display="none"; ``` ```JavaScript setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Get Supported Methods for WalletMesh Provider Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/router/docs/index/classes/WalletRouterProvider.md This TypeScript example demonstrates how to use the `provider.getSupportedMethods()` function to query the methods supported by a WalletMesh provider for specific chains or for the router itself. It shows how to check if a particular method, like `eth_signMessage`, is supported on a given chain. ```typescript // Get methods for multiple chains const methods = await provider.getSupportedMethods(['eip155:1', 'eip155:137']); if (methods['eip155:1'].includes('eth_signMessage')) { // Ethereum mainnet wallet supports message signing } // Get router's supported methods const routerMethods = await provider.getSupportedMethods(); ``` -------------------------------- ### Chain Multiple Wallet Operations with WalletMesh Provider Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/router/docs/index/classes/WalletRouterProvider.md This TypeScript example demonstrates the use of the `provider.chain` method to create a fluent API for chaining multiple wallet method calls. It shows how to build a sequence of calls and execute them to get combined results. ```typescript const [balance, code] = await provider .chain('eip155:1') .call('eth_getBalance', ['0x123...']) .call('eth_getCode', ['0x456...']) .execute(); ``` -------------------------------- ### Initialize Documentation Page Display and Theme Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/discovery/docs/variables/constants.WmDiscovery.Request.html This JavaScript snippet handles the initial display and theme loading for the documentation page. It retrieves the theme from local storage or system preferences, temporarily hides the page body to prevent unstyled content, and then reveals it after a delay or when the application is ready. ```JavaScript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Initialize and Configure LocalTransport for WalletRouter in TypeScript Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/router/docs/index/classes/LocalTransport.md This example demonstrates how to create a bidirectional local transport pair using `createLocalTransportPair()`, set up a `JSONRPCNode` server with a wallet implementation, and integrate the client transport with a `WalletRouter` for local communication. It showcases the basic setup for connecting a wallet to a router without network overhead. ```typescript // Create a bidirectional local transport pair const [clientTransport, serverTransport] = createLocalTransportPair(); // Create server with wallet implementation const server = new JSONRPCNode(serverTransport, walletContext); server.registerMethod('eth_accounts', async () => ['0x...']); // Use client transport directly with router const router = new WalletRouter(transport, new Map([ ['eip155:1', clientTransport] ]), permissionManager); ``` -------------------------------- ### Initialize Theme and Display Application Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/discovery/docs/interfaces/types.WebWalletInfo.html This JavaScript snippet initializes the theme based on local storage or defaults to 'os', hides the body to prevent Flash of Unstyled Content (FOUC), and then displays the application after a short delay, ensuring the app is ready and styled. ```JavaScript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os";document.body.style.display="none";setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Example: Setting up Aztec Wallet Node with WalletRouter Source: https://github.com/walletmesh/walletmesh-packages/blob/main/aztec/rpc-wallet/docs/functions/createAztecWalletNode.md Illustrates how to initialize an Aztec AccountWallet and PXE, create a local transport pair, instantiate the Aztec wallet node, and configure it with a WalletRouter for dApp communication. This setup allows dApps to connect to the router and send requests to the Aztec node. ```typescript import { createAztecWalletNode } from '@walletmesh/aztec-rpc-wallet'; import { WalletRouter, createLocalTransportPair } from '@walletmesh/router'; import { MyAccountWallet, MyPXE, MyRouterTransport, MyPermissionManager } from './my-setup'; // User's setup // 1. Initialize Aztec AccountWallet and PXE const accountWallet = new MyAccountWallet(); const pxe = new MyPXE(); // 2. Create a local transport pair for communication between router and wallet node const [routerSideTransport, walletNodeSideTransport] = createLocalTransportPair(); // 3. Create the Aztec Wallet Node const aztecNode = createAztecWalletNode(accountWallet, pxe, walletNodeSideTransport); // aztecNode will start listening for requests on walletNodeSideTransport // 4. Create and configure the WalletRouter const routerTransport = new MyRouterTransport(); // Transport for dApp to router communication const permissionManager = new MyPermissionManager(); const router = new WalletRouter( routerTransport, new Map([['aztec:testnet', routerSideTransport]]), // Route 'aztec:testnet' to our node permissionManager ); // The system is now set up. DApps can connect to 'routerTransport' // and send requests to 'aztec:testnet', which will be handled by 'aztecNode'. ``` -------------------------------- ### Set up a WalletMesh Router with Ethereum Wallet Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/router/README.md This comprehensive example demonstrates how to initialize a WalletRouter, integrate an Ethereum wallet using JSONRPCNode, manage permissions, and establish a connection to call wallet methods. It covers setting up message transport, registering RPC methods, and handling session management for multi-chain interactions. ```typescript import { WalletRouter, WalletRouterProvider, PermissivePermissionsManager, type JSONRPCWallet } from '@walletmesh/router'; import { JSONRPCNode } from '@walletmesh/jsonrpc'; // Initialize a basic Ethereum wallet as a JSONRPCNode // This node handles JSON-RPC communication for Ethereum mainnet const ethereumWallet: JSONRPCWallet = new JSONRPCNode({ send: async (message) => { // Forward JSON-RPC messages to the injected Ethereum provider const result = await window.ethereum.request(message); // Send response back through the transport ethereumWallet.receiveMessage({ jsonrpc: '2.0', id: message.id, result }); }, onMessage: (handler) => { // Setup message handler for responses } }); // Register wallet methods etherneumWallet.registerMethod('eth_accounts', async () => { return window.ethereum.request({ method: 'eth_accounts' }); }); // Initialize the router with transport layer, wallets, and permission manager // The router coordinates communication between the application and wallets const router = new WalletRouter( { send: (msg) => Promise.resolve(window.postMessage(msg, '*')), onMessage: (handler) => window.addEventListener('message', (e) => handler(e.data)) }, new Map([['eip155:1', ethereumWallet]]), // For development, use the permissive permission manager new PermissivePermissionsManager() ); // Initialize the provider that applications use to interact with wallets // The provider offers a high-level interface for wallet operations const provider = new WalletRouterProvider({ send: async (msg) => window.postMessage(msg, '*'), onMessage: (handler) => window.addEventListener('message', (e) => handler(e.data)) }); // Connect to Ethereum mainnet and request method permissions // This establishes a session and requests access to specific RPC methods const { sessionId, permissions } = await provider.connect({ 'eip155:1': ['eth_accounts', 'eth_sendTransaction'] }, 5000); // Optional timeout in milliseconds // The permissions are in a human-readable format for display to users console.log('Approved permissions:', permissions); // The connect method returns the session ID for future requests console.log('Connected with session:', sessionId); // Call a wallet method using the established session // The router will validate permissions and route the call to the appropriate wallet const accounts = await provider.call('eip155:1', { method: 'eth_accounts' }, 5000); // Optional timeout in milliseconds ``` -------------------------------- ### Initialize WalletRouter Instance (TypeScript) Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/router/docs/index/classes/WalletRouter.md This example demonstrates the basic initialization of the WalletRouter, showing how to provide it with necessary dependencies like a transport, a map of chain-specific wallets, a permission manager, and a session store. The router then autonomously manages session validation, permission checks, method routing, and event forwarding. ```typescript // Initialize router with wallets and permission manager const router = new WalletRouter( transport, new Map([ ['eip155:1', ethereumWallet], ['solana:mainnet', solanaWallet] ]), permissionManager, sessionStore ); // Router automatically handles: // - Session validation // - Permission checks // - Method routing // - Event forwarding ``` -------------------------------- ### Initialize Theme and Control Page Display with JavaScript Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/discovery/docs/interfaces/types.ExtensionWalletInfo.html This JavaScript snippet sets the document's theme based on local storage or defaults to 'os', hides the body initially, and then reveals it after a short delay, potentially showing a page via a global `app` object. ```JavaScript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Initialize TSDoc Theme and Page Display Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/discovery/docs/variables/constants.WmDiscovery.Ready.html This JavaScript snippet initializes the theme for TSDoc documentation pages based on local storage or defaults to 'os'. It then hides the body initially and shows the page after a delay, potentially using a global 'app' object, ensuring a smooth loading experience. ```javascript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Browser-to-Browser JSON-RPC Communication using postMessage Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/jsonrpc/README.md This example illustrates a bidirectional JSON-RPC communication setup between two distinct web origins (e.g., a parent window and an iframe, or two separate windows) using `window.postMessage` as the transport layer. `website-a.com` acts as a client, initiating RPC calls, while `website-b.com` acts as a server, registering and handling methods. Both sides implement origin validation for security and utilize the `@walletmesh/jsonrpc` library for structured messaging, type safety, and error handling. ```typescript // website-a.com import { JSONRPCNode, JSONRPCError } from '@walletmesh/jsonrpc'; type Methods = { getData: { params: { id: string }; result: { data: string } }; }; // Create node for Website A with bidirectional transport const nodeA = new JSONRPCNode({ send: async message => { // Send to Website B's iframe const iframe = document.querySelector('#website-b-frame'); if (iframe?.contentWindow) { iframe.contentWindow.postMessage(message, 'https://website-b.com'); } else { throw new Error('Target iframe not found'); } }, onMessage: callback => { // Listen for messages from Website B with origin validation window.addEventListener('message', event => { if (event.origin === 'https://website-b.com') { callback(event.data); } }); } }); // Use the node with error handling try { const result = await nodeA.callMethod('getData', { id: '123' }, 5); console.log('Data:', result); } catch (error) { if (error instanceof JSONRPCError) { console.error('RPC Error:', error.message, error.data); } } ``` ```typescript // website-b.com import { JSONRPCNode, JSONRPCError } from '@walletmesh/jsonrpc'; type Methods = { getData: { params: { id: string }; result: { data: string } }; }; // Create node for Website B with bidirectional transport const nodeB = new JSONRPCNode({ send: async message => { // Send to parent window (Website A) window.parent.postMessage(message, 'https://website-a.com'); }, onMessage: callback => { // Listen for messages from Website A with origin validation window.addEventListener('message', event => { if (event.origin === 'https://website-a.com') { callback(event.data); } }); } }); // Register method with validation nodeB.registerMethod('getData', async (context, { id }) => { if (typeof id !== 'string' || !id) { throw new JSONRPCError(-32602, 'Invalid ID', { expected: 'non-empty string', received: id }); } return { data: `Data for ${id}` }; }); ``` -------------------------------- ### Common Development Commands for WalletMesh Monorepo Source: https://github.com/walletmesh/walletmesh-packages/blob/main/CLAUDE.md Provides a quick reference for frequently used `pnpm` commands to manage the WalletMesh monorepo. This includes commands for building, testing, linting, and type-checking all packages, as well as specific commands for individual packages. A full validation sequence for pre-commit checks is also provided. ```bash # Development workflow pnpm build # Build all packages pnpm test # Run all tests pnpm lint # Check lint issues pnpm type-check # Check TypeScript # Package-specific pnpm -F @walletmesh/jsonrpc test # Test specific package pnpm -F @walletmesh/jsonrpc build # Build specific package # Full validation before commit pnpm format:fix && pnpm lint && pnpm type-check && pnpm test ``` -------------------------------- ### Initialize Documentation Page Theme and Display Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/discovery/docs/interfaces/client.DiscoveryAnnouncerOptions.html This JavaScript snippet initializes the documentation page's theme based on local storage or OS preference and manages the initial display of the page content, showing it after a brief delay or when the application is ready. ```JavaScript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os";document.body.style.display="none";setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Deploy and Interact with Aztec Counter Contract (Alternative Method) Source: https://github.com/walletmesh/walletmesh-packages/blob/main/aztec/example/README.md Shows an alternative method for deploying and interacting with an Aztec Counter contract using direct `Contract.deploy` and `.send()` calls. While functional, this approach provides less context to the wallet regarding the transaction's intent compared to the preferred methods. ```javascript // Deployment using Contract.deploy const deploySentTx = await Contract.deploy(wallet, CounterContractArtifact, [0, ownerAddress]).send(); const counter = await deploySentTx.deployed(); // Interaction using direct method calls const counterContract = await Contract.at(counterAddress, CounterContractArtifact, wallet); const tx = await counterContract.methods.increment(account, account).send(); await tx.wait(); ``` -------------------------------- ### TypeScript Example: Using wrapHandler Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/jsonrpc/docs/functions/wrapHandler.md An example demonstrating how to use the `wrapHandler` function to wrap a simple handler, ensuring consistent error handling and response formatting. ```typescript const handler = (context, params) => params.a + params.b; const wrapped = wrapHandler(handler, 'add'); ``` -------------------------------- ### Deploy and Interact with Aztec Token Contract (Preferred Method) Source: https://github.com/walletmesh/walletmesh-packages/blob/main/aztec/example/README.md Demonstrates the recommended approach for deploying and interacting with an Aztec Token contract using WalletMesh's `wallet.wmDeployContract` and `wallet.wmExecuteContract`. This method provides the wallet with a higher-level view of the transaction, enabling better display of details and enhanced security. ```javascript // Deployment using wallet.wmDeployContract const deploySentTx = await wallet.wmDeployContract(TokenContractArtifact, [ownerAddress, 'TokenName', 'TKN', 18]); const token = await deploySentTx.deployed(); // Interaction using wallet.wmExecuteContract const tokenContract = await Contract.at(tokenAddress, TokenContractArtifact, wallet); const interaction = tokenContract.methods.mint_to_public(account, 10000000000000000000000n); const sentTx = await wallet.wmExecuteContract(interaction); const receipt = await sentTx.wait(); ``` -------------------------------- ### Install WalletMesh Router via pnpm Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/router/README.md This snippet provides the command-line instruction for installing the WalletMesh Router package using pnpm, a fast, disk-space efficient package manager. ```bash pnpm add @walletmesh/router ``` -------------------------------- ### Setting Up WalletRouter with Local Transports Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/router/CLAUDE.md Demonstrates how to initialize a `WalletRouter` by creating local transport pairs for different blockchain networks (Ethereum, Polygon) and associating them with wallet instances. It shows how to map client-side transports to chain IDs for multi-chain routing within the WalletMesh ecosystem. ```typescript // Create transports for your wallets const [ethClientTransport, ethWalletTransport] = createLocalTransportPair(); const [polygonClientTransport, polygonWalletTransport] = createLocalTransportPair(); // Initialize wallets with the wallet-side transports const ethWallet = createEthereumWallet(ethWalletTransport); const polygonWallet = createPolygonWallet(polygonWalletTransport); // Create the router with client-side transports const router = new WalletRouter( routerTransport, new Map([ ['eip155:1', ethClientTransport], // Ethereum mainnet ['eip155:137', polygonClientTransport] // Polygon ]), permissionManager, { sessionStore: new LocalStorageSessionStore() } ); ``` -------------------------------- ### Implementing JSON-RPC Middleware Examples in TypeScript Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/jsonrpc/docs/type-aliases/JSONRPCMiddleware.md This snippet provides examples of implementing various JSON-RPC middleware functions in TypeScript. It demonstrates common patterns such as request logging with timing, user authentication with role checking, and API rate limiting based on IP address, showcasing how middleware can intercept and modify requests or responses within a JSON-RPC system. ```typescript // Logging middleware with timing const loggingMiddleware: JSONRPCMiddleware = async (context, request, next) => { const startTime = Date.now(); console.log(`[${startTime}] Request:`, request); try { const response = await next(); console.log(`[${Date.now()}] Response (${Date.now() - startTime}ms):`, response); return response; } catch (error) { console.error(`[${Date.now()}] Error (${Date.now() - startTime}ms):`, error); throw error; } }; // Authentication middleware with role checking const authMiddleware: JSONRPCMiddleware = async (context, request, next) => { if (!context.isAuthorized) { return { jsonrpc: '2.0', error: { code: -32600, message: 'Unauthorized', data: { requiredRole: 'admin' } }, id: request.id }; } return next(); }; // Rate limiting middleware const rateLimitMiddleware: JSONRPCMiddleware = async (context, request, next) => { const { ip } = context; const limit = await rateLimit.check(ip); if (!limit.success) { return { jsonrpc: '2.0', error: { code: -32000, message: 'Rate limit exceeded', data: { retryAfter: limit.resetTime, limit: limit.max, remaining: limit.remaining } }, id: request.id }; } return next(); }; ``` -------------------------------- ### WalletMesh Discovery Package Build and Test Commands Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/discovery/CLAUDE.md Common `pnpm` commands for building, testing, linting, formatting, type checking, and generating documentation for the `@walletmesh/discovery` package. These commands facilitate development and maintenance workflows. ```Shell pnpm build ``` ```Shell pnpm test ``` ```Shell pnpm test -- src/path/to/file.test.ts ``` ```Shell pnpm test:watch -- src/path/to/file.test.ts ``` ```Shell pnpm coverage ``` ```Shell pnpm lint ``` ```Shell pnpm lint:fix ``` ```Shell pnpm format ``` ```Shell pnpm format:fix ``` ```Shell pnpm type-check ``` ```Shell pnpm type-check:build ``` ```Shell pnpm docs ``` -------------------------------- ### Example JSONRPCSerializedData Usage in TypeScript Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/jsonrpc/docs/type-aliases/JSONRPCSerializedData.md Demonstrates how to declare and initialize a `JSONRPCSerializedData` object in TypeScript. This example shows how a `Date` object can be serialized into a JSON string and assigned to the `serialized` property. ```typescript const serialized: JSONRPCSerializedData = { serialized: JSON.stringify({ date: new Date().toISOString() }) }; ``` -------------------------------- ### Initialize TSDoc Theme and Page Display Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/discovery/docs/variables/constants.WmDiscovery.Response.html This JavaScript snippet initializes the theme for TSDoc documentation pages by retrieving it from local storage or defaulting to 'os'. It also hides the document body initially and then reveals it after a 500ms delay, allowing time for page rendering or application loading. ```javascript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Install WalletMesh Aztec RPC Wallet Package Source: https://github.com/walletmesh/walletmesh-packages/blob/main/aztec/rpc-wallet/README.md Installs the `@walletmesh/aztec-rpc-wallet` package using pnpm, a fast and efficient package manager, making it available for use in your project. ```bash pnpm add @walletmesh/aztec-rpc-wallet ``` -------------------------------- ### Install @walletmesh/aztec-rpc-wallet with pnpm Source: https://github.com/walletmesh/walletmesh-packages/blob/main/aztec/rpc-wallet/docs/README.md This command installs the `@walletmesh/aztec-rpc-wallet` package using the pnpm package manager. It adds the necessary dependency to your project for integrating Aztec wallets with dApps via WalletMesh. ```bash pnpm add @walletmesh/aztec-rpc-wallet ``` -------------------------------- ### Initialize UI Theme and Display with JavaScript Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/discovery/docs/variables/constants.CONFIG.readyDebounceMs.html This JavaScript snippet sets the document's theme from local storage or defaults to 'os'. It initially hides the body to prevent a flash of unstyled content, then uses a 500ms timeout to either show the application page via `window.app.showPage()` or simply remove the display hiding property. ```javascript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os";document.body.style.display="none";setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Initialize and Use WalletRouterProvider in TypeScript Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/router/docs/index/classes/WalletRouterProvider.md Demonstrates how to initialize the `WalletRouterProvider` with a custom transport, connect to a chain with specific permissions, listen for wallet state change events, and call a method to retrieve accounts. This example showcases basic interaction patterns with the multi-chain router. ```typescript const provider = new WalletRouterProvider({ send: async (message) => { // Send message to router await fetch('/api/wallet', { method: 'POST', body: JSON.stringify(message) }); } }); // Connect to a chain const { sessionId, permissions } = await provider.connect({ 'eip155:1': ['eth_accounts', 'eth_sendTransaction'] }); // Listen for wallet state changes provider.on('wm_walletStateChanged', ({ chainId, changes }) => { console.log(`Wallet state changed for ${chainId}:`, changes); }); // Call methods const accounts = await provider.call('eip155:1', { method: 'eth_accounts' }); ``` -------------------------------- ### Example JSON-RPC Error Object in TypeScript Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/jsonrpc/docs/interfaces/JSONRPCErrorInterface.md Demonstrates the structure of a JSON-RPC 2.0 error object as defined by `JSONRPCErrorInterface`, including `code`, `message`, and optional `data` for additional details. This example shows an 'Invalid Request' error. ```typescript const error: JSONRPCErrorInterface = { code: -32600, message: 'Invalid Request', data: { details: 'Missing required parameter' } }; ``` -------------------------------- ### Example Usage of Aztec PXE Helper Functions Source: https://github.com/walletmesh/walletmesh-packages/blob/main/aztec/helpers/docs/README.md Demonstrates how to import and use the Aztec PXE helper functions to fetch contract artifacts, function artifacts, and function parameter information from a given contract address. ```typescript import { getContractArtifactFromContractAddress, getFunctionArtifactFromContractAddress, getFunctionParameterInfoFromContractAddress } from '@walletmesh/aztec-helpers'; // Example: Fetch contract artifact const artifact = await getContractArtifactFromContractAddress(pxe, '0xabc...'); // Example: Fetch function artifact const functionArtifact = await getFunctionArtifactFromContractAddress(pxe, '0xabc...', 'transfer'); // Example: Get function parameter info const params = await getFunctionParameterInfoFromContractAddress(pxe, '0xabc...', 'transfer'); console.log(params); // [{ name: 'to', type: 'AztecAddress' }, { name: 'amount', type: 'field' }] ``` -------------------------------- ### TypeScript Example: Extending WalletMethodMap for Ethereum Methods Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/router/docs/index/interfaces/WalletMethodMap.md This TypeScript example demonstrates how to define a type, `EthereumMethods`, that extends `WalletMethodMap` to include specific Ethereum JSON-RPC methods like `eth_accounts` and `eth_sendTransaction`, detailing their expected parameters and return types. ```typescript // Ethereum wallet methods type EthereumMethods = { eth_accounts: { params: undefined; result: string[] }; eth_sendTransaction: { params: [{ to: string; value: string; data?: string }]; result: string }; } & WalletMethodMap; ``` -------------------------------- ### WalletMesh Discovery Package (@walletmesh/discovery) API Reference Source: https://github.com/walletmesh/walletmesh-packages/blob/main/CLAUDE.md Comprehensive documentation for the `@walletmesh/discovery` package, detailing its purpose in wallet discovery and announcement. It outlines key files, core components like `DiscoveryAnnouncer` and `DiscoveryListener`, and the underlying event-based communication protocol. ```APIDOC Package: @walletmesh/discovery Purpose: Wallet discovery and announcement across origins Modify for: Adding new wallet discovery methods, changing announcement protocol Key files: src/client.ts (announcer), src/server.ts (listener) Key Components: - DiscoveryAnnouncer - Located in src/client.ts - Factory methods: createWebWalletAnnouncer and createExtensionWalletAnnouncer - Used by wallets to announce their presence across origins - DiscoveryListener - Located in src/server.ts - Factory method: createDiscoveryListener - Used by dApps to discover available wallets - Event-based communication system - Protocol events defined in src/constants.ts - Standard events: ready, request, response, acknowledgment - Secure cross-origin communication ``` -------------------------------- ### Example JSON-RPC 2.0 Event Messages in TypeScript Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/jsonrpc/docs/interfaces/JSONRPCEvent.md Demonstrates how to construct `JSONRPCEvent` objects for different event types, such as user joining or status updates, adhering to the JSON-RPC 2.0 event specification. These examples illustrate the `jsonrpc`, `event`, and `params` properties. ```typescript // User joined event const joinEvent: JSONRPCEvent = { jsonrpc: '2.0', event: 'userJoined', params: { username: 'Alice', timestamp: Date.now() } }; // Status update event const statusEvent: JSONRPCEvent = { jsonrpc: '20', event: 'statusUpdate', params: { user: 'Bob', status: 'away', lastSeen: Date.now() } }; ``` -------------------------------- ### Initialize Theme and Control App Display Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/discovery/docs/modules/constants.WmDiscovery.html This JavaScript snippet initializes the theme preference from local storage, defaulting to 'os' (operating system) if not found. It then hides the document body temporarily and uses a timeout to either show the application page via `window.app.showPage()` or remove the display property from the body, ensuring a controlled loading experience. ```JavaScript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Example Initialization of Wallets Type Alias Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/router/docs/index/type-aliases/Wallets.md This TypeScript example demonstrates how to create an instance of the `Wallets` map. It shows the mapping of specific chain identifiers, like 'aztec:testnet' and 'eip155:1', to their respective transport objects, which are essential for routing operations. ```typescript const wallets = new Map([ ['aztec:testnet', aztecTransport], ['eip155:1', ethereumTransport] ]); ``` -------------------------------- ### TypeScript Example for isJSONRPCSerializedData Type Guard Source: https://github.com/walletmesh/walletmesh-packages/blob/main/core/jsonrpc/docs/functions/isJSONRPCSerializedData.md This example demonstrates how to use the `isJSONRPCSerializedData` type guard in TypeScript to check if various values conform to the `JSONRPCSerializedData` structure. It shows cases that return true and false based on the presence and type of the `serialized` property. ```typescript isJSONRPCSerializedData({ serialized: "data" }); // true isJSONRPCSerializedData({ serialized: 123 }); // false isJSONRPCSerializedData({ data: "string" }); // false ```