### Complete WalletKit JS Example Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/quick-start.md A comprehensive example demonstrating the setup of WalletKit JS, including initialization, event listeners for session proposals, requests, and deletions, and an example of pairing with a URI. ```typescript import { Core } from "@walletconnect/core"; import { WalletKit } from "@reown/walletkit"; async function main() { // Setup const core = new Core({ projectId: process.env.WALLETCONNECT_PROJECT_ID, }); const walletkit = await WalletKit.init({ core, metadata: { name: "Example Wallet", description: "A sample Web3 wallet", url: "https://example.com", icons: ["https://example.com/icon.png"], }, }); // Event listeners walletkit.on("session_proposal", async (proposal) => { console.log(`Proposal from ${proposal.params.proposer.metadata.name}`); const session = await walletkit.approveSession({ id: proposal.id, namespaces: { eip155: { chains: ["eip155:1"], methods: ["eth_sendTransaction", "personal_sign"], events: ["chainChanged", "accountsChanged"], accounts: ["eip155:1:0xab16..."], }, }, }); console.log(`Session approved: ${session.topic}`); }); walletkit.on("session_request", async (event) => { console.log(`Request: ${event.params.request.method}`); // Handle request... }); walletkit.on("session_delete", (event) => { console.log(`Session disconnected: ${event.topic}`); }); // Example: Pair with a URI // const walletConnectUri = "wc:..."; // await walletkit.pair({ uri: walletConnectUri }); console.log("Wallet ready for connections"); } main().catch(console.error); ``` -------------------------------- ### Example WalletConnectPay Initialization and Usage Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/types.md Demonstrates initializing WalletKit and using the pay client to get payment options. Ensure the walletkit instance has a 'pay' property. ```typescript const walletkit = await WalletKit.init({ /* ... */ }); if (walletkit.pay) { const options = await walletkit.pay.getPaymentOptions({ paymentLink: "...", accounts: ["eip155:1:0x..."], }); } ``` -------------------------------- ### Install @reown/walletkit Source: https://github.com/reown-com/reown-walletkit-js/blob/main/packages/walletkit/README.md Install the WalletKit SDK using npm. ```bash npm install @reown/walletkit ``` -------------------------------- ### Initialize WalletKit with Core Configuration Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/configuration.md Provides a complete example of initializing WalletKit, including WalletConnect core setup and application metadata. Ensure your WalletConnect project ID is valid. ```typescript import { Core } from "@walletconnect/core"; import { WalletKit } from "@reown/walletkit"; const core = new Core({ projectId: "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6", // From WalletConnect Cloud logger: "info", }); const walletkit = await WalletKit.init({ // Required core, metadata: { name: "Example Wallet", description: "A powerful Web3 wallet", url: "https://example-wallet.com", icons: [ "https://example-wallet.com/logo-192.png", "https://example-wallet.com/logo-512.png", ], }, // Optional name: "ExampleWallet", signConfig: { // Any SignClient-specific configuration }, payConfig: { // Any Pay-specific configuration }, }); // WalletKit is now ready to use walletkit.on("session_proposal", async (proposal) => { // Handle proposals }); ``` -------------------------------- ### Basic Usage Example Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/README.md A general usage example for WalletKit, intended to be used with context. ```typescript // Usage example with context ``` -------------------------------- ### Install Reown WalletKit and WalletConnect Core Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/INDEX.md Use npm to install the necessary packages for Reown WalletKit and WalletConnect Core. ```bash npm install @reown/walletkit @walletconnect/core ``` -------------------------------- ### Example Wallet Metadata Configuration Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/configuration.md Provides an example of how to configure the metadata object for a wallet application. This includes the wallet's name, description, URL, and icons. ```typescript const metadata: CoreTypes.Metadata = { name: "My Wallet", description: "A secure mobile wallet for Web3", url: "https://mywallet.example.com", icons: [ "https://mywallet.example.com/icon-192x192.png", "https://mywallet.example.com/icon-512x512.png", ], }; ``` -------------------------------- ### Initialize WalletKit with Minimal Configuration Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/configuration.md Use this basic setup for initializing WalletKit when only essential parameters are needed. Ensure you replace 'YOUR_PROJECT_ID' with your actual project ID. ```typescript const walletkit = await WalletKit.init({ core: new Core({ projectId: "YOUR_PROJECT_ID" }), metadata: { name: "My Wallet", description: "My wallet", url: "https://example.com", icons: [], }, }); ``` -------------------------------- ### Get Metadata Example Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/types.md Example of how to use the `getMetadata` method from the `INotifications` interface to retrieve peer (dapp) metadata using a session topic. ```typescript const metadata = await WalletKit.notifications.getMetadata({ topic: "wc:abc123...", }); console.log(metadata.name); // Dapp name ``` -------------------------------- ### Parameter Table Example Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/README.md Shows the structure of a parameter table used for documenting function arguments. ```markdown | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| ``` -------------------------------- ### Initialize WalletKit with Payment Support Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/configuration.md Configure WalletKit to include payment functionalities. This setup requires additional `payConfig` and allows checking for the availability of payment features. ```typescript const walletkit = await WalletKit.init({ core: new Core({ projectId: "YOUR_PROJECT_ID" }), metadata: { name: "My Wallet", description: "My wallet with payment support", url: "https://example.com", icons: ["https://example.com/icon.png"], }, payConfig: { // Payment configuration if needed }, }); if (walletkit.pay) { // Use payment features } ``` -------------------------------- ### WalletKit Constructor Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/walletkit-client.md Initializes a new WalletKit instance. The constructor does not start the internal engine; call `initialize()` implicitly through `init()` or manually. ```APIDOC ## constructor(opts: WalletKitTypes.Options) ### Description Initializes a new WalletKit instance. The constructor does not start the internal engine; call `initialize()` implicitly through `init()` or manually. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **opts** (WalletKitTypes.Options) - Required - Configuration object with core, metadata, and optional name, signConfig, and payConfig ### Returns None ### Throws None ### Example None ``` -------------------------------- ### Method Signature Example Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/README.md Illustrates a typical TypeScript method signature with parameters and return type. ```typescript methodName(params: Type): ReturnType ``` -------------------------------- ### Options Interface Definition Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/types.md Defines the configuration options for initializing WalletKit. Includes core WalletConnect setup, metadata, and optional client-specific configurations. ```typescript interface Options { core: ICore; metadata: Metadata; name?: string; signConfig?: SignConfig; payConfig?: PayOptions; } ``` -------------------------------- ### Handle Session Proposal Event in WalletKit Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/events.md Example of how to listen for and handle the 'session_proposal' event. This snippet demonstrates approving a session with specified chains, methods, and events. ```typescript walletkit.on("session_proposal", async (proposal) => { console.log(`Dapp: ${proposal.params.proposer.metadata.name}`); console.log(`Required namespaces:`, proposal.params.requiredNamespaces); // Determine which chains to support const supportedChains = ["eip155:1", "eip155:137"]; // Ethereum, Polygon const supportedMethods = ["eth_sendTransaction", "personal_sign"]; const supportedEvents = ["chainChanged", "accountsChanged"]; // Build approved namespaces const namespaces = { eip155: { chains: supportedChains, methods: supportedMethods, events: supportedEvents, accounts: supportedChains.map(chain => `${chain}:0x123...`), }, }; try { const session = await walletkit.approveSession({ id: proposal.id, namespaces, }); console.log(`Session approved:`, session.topic); } catch (error) { console.error("Failed to approve:", error); } }); ``` -------------------------------- ### Get Payment Options Source: https://github.com/reown-com/reown-walletkit-js/blob/main/packages/walletkit/README.md Retrieve available payment options for a given payment link, including supported accounts and payment details. Set `includePaymentInfo` to true to get details like amount and expiry. ```javascript const options = await walletkit.pay.getPaymentOptions({ paymentLink: "https://pay.walletconnect.com/", accounts: ["eip155:1:0x...", "eip155:8453:0x..."], includePaymentInfo: true, }); // options.paymentId - unique payment identifier // options.options - array of payment options (different tokens/chains) // options.info - payment details (amount, merchant, expiry) ``` -------------------------------- ### Decrypt Message Example Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/types.md Example of how to use the `decryptMessage` method from the `INotifications` interface to decrypt an encrypted message using a session topic. ```typescript const message = await WalletKit.notifications.decryptMessage({ topic: "wc:abc123...", encryptedMessage: "encrypted_payload...", }); ``` -------------------------------- ### Lazy Initialization of WalletKit Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/patterns-and-best-practices.md Utilize lazy initialization to defer WalletKit setup until it's actively needed. This approach optimizes startup performance by only initializing the instance when a method call requires it. ```typescript let walletkit: WalletKit | null = null; let initPromise: Promise | null = null; export async function getOrInitWalletKit(): Promise { if (walletkit) return walletkit; if (initPromise) return initPromise; initPromise = (async () => { const core = new Core({ projectId: "..." }); walletkit = await WalletKit.init({ core, metadata: { /* ... */ } }); return walletkit; })(); return initPromise; ``` -------------------------------- ### Import Payment Detection Utility Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/utilities.md Import the `isPaymentLink` function for detecting payment-related links. No additional setup is required beyond the import statement. ```typescript // Payment detection import { isPaymentLink } from "@reown/walletkit"; ``` -------------------------------- ### Get Required Payment Actions Source: https://github.com/reown-com/reown-walletkit-js/blob/main/packages/walletkit/README.md Fetch the specific wallet RPC calls (actions) that need to be signed to confirm a payment, given the payment ID and a selected payment option ID. ```javascript const actions = await walletkit.pay.getRequiredPaymentActions({ paymentId: options.paymentId, optionId: options.options[0].id, }); // actions - array of wallet RPC calls to sign // Each action contains: { walletRpc: { chainId, method, params } } ``` -------------------------------- ### Initialize WalletKit Instance Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/walletkit-client.md Use the static `init` method to create and initialize a WalletKit instance. This is the recommended approach for instantiating WalletKit. Ensure you provide the core instance and necessary metadata. ```typescript import { Core } from "@walletconnect/core"; import { WalletKit } from "@reown/walletkit"; const core = new Core({ projectId: "YOUR_PROJECT_ID", }); const walletkit = await WalletKit.init({ core, metadata: { name: "My Wallet", description: "My wallet application", url: "https://example.com", icons: ["https://example.com/icon.png"], }, }); ``` -------------------------------- ### Initialize WalletKit Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/quick-start.md Initialize WalletKit by first setting up the WalletConnect Core with your project ID, then initializing WalletKit with the core instance and metadata. ```typescript import { Core } from "@walletconnect/core"; import { WalletKit } from "@reown/walletkit"; // 1. Initialize Core with your Project ID const core = new Core({ projectId: "YOUR_PROJECT_ID", // Get from https://cloud.walletconnect.com }); // 2. Initialize WalletKit const walletkit = await WalletKit.init({ core, metadata: { name: "My Wallet", description: "My wallet application", url: "https://mywallet.example.com", icons: ["https://mywallet.example.com/icon.png"], }, }); console.log("WalletKit initialized successfully"); ``` -------------------------------- ### Initialize WalletKit and Use Payment Methods Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/walletkit-client.md This snippet demonstrates how to initialize the WalletKit client and check for the availability of payment functionalities. It then shows how to retrieve payment options, required payment actions, and confirm a payment using WalletConnect Pay. ```typescript const walletkit = await WalletKit.init({ /* ... */ }); // Check if payment is available if (walletkit.pay) { // Get payment options for a payment link const options = await walletkit.pay.getPaymentOptions({ paymentLink: "https://pay.walletconnect.com/", accounts: ["eip155:1:0x..."], includePaymentInfo: true, }); // Get required actions to complete payment const actions = await walletkit.pay.getRequiredPaymentActions({ paymentId: options.paymentId, optionId: options.options[0].id, }); // Confirm payment after signing const result = await walletkit.pay.confirmPayment({ paymentId: options.paymentId, optionId: options.options[0].id, signatures: signedActions, }); } ``` -------------------------------- ### Initialization Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/README.md Initialize the WalletKit instance with necessary configuration. ```APIDOC ## init ### Description Initializes the WalletKit instance. ### Method Signature ```typescript WalletKit.init(options: { core: any, metadata: any }): Promise ``` ### Parameters - **options** (object) - Required - Configuration object. - **core** (any) - Required - Core configuration for WalletKit. - **metadata** (any) - Required - Metadata for the wallet. ### Request Example ```typescript const walletkit = await WalletKit.init({ core, metadata }); ``` ``` -------------------------------- ### Get Notification Metadata Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/README.md Retrieves metadata for notifications associated with a specific topic. ```typescript WalletKit.notifications.getMetadata({ topic }); ``` -------------------------------- ### Get Payment Options Source: https://github.com/reown-com/reown-walletkit-js/blob/main/packages/walletkit/README.md Retrieves available payment options for a given payment link. ```APIDOC ## Get Payment Options ### Description Retrieves available payment options for a given payment link. ### Method `walletkit.pay.getPaymentOptions(options: { paymentLink: string, accounts: string[], includePaymentInfo?: boolean }): Promise ### Parameters #### Request Body - **paymentLink** (string) - Required - The payment link. - **accounts** (string[]) - Required - The user's accounts. - **includePaymentInfo** (boolean) - Optional - Whether to include payment information. ``` -------------------------------- ### Initialization Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/INDEX.md Initializes the WalletKit instance with core and metadata configurations. ```APIDOC ## Initialization ### Description Initializes the WalletKit instance with core and metadata configurations. ### Method `WalletKit.init(options: WalletKitTypes.Options)` ### Parameters #### Request Body - **core** (ICore) - Required - The core instance for WalletKit. - **metadata** (Metadata) - Required - Metadata for the wallet. - **name** (string) - Optional - The name of the wallet. - **signConfig** (SignConfig) - Optional - Configuration for signing. - **payConfig** (PayOptions) - Optional - Configuration for payments. ``` -------------------------------- ### Run All Package Checks Source: https://github.com/reown-com/reown-walletkit-js/blob/main/README.md Execute this command from the root folder to lint, build, and test all packages. Ensure you have a TEST_PROJECT_ID from WalletConnect Cloud for tests to pass. ```zsh TEST_PROJECT_ID=YOUR_PROJECT_ID npm run check ``` -------------------------------- ### Initialize WalletKit Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/README.md Use this snippet to initialize the WalletKit instance. It requires core and metadata objects as parameters. ```typescript const walletkit = await WalletKit.init({ core, metadata }); ``` -------------------------------- ### Get Required Payment Actions Source: https://github.com/reown-com/reown-walletkit-js/blob/main/packages/walletkit/README.md Retrieves the necessary actions (e.g., RPC calls to sign) for a payment. ```APIDOC ## Get Required Payment Actions ### Description Retrieves the necessary actions (e.g., RPC calls to sign) for a payment. ### Method `walletkit.pay.getRequiredPaymentActions(options: { paymentId: string, optionId: string }): Promise ### Parameters #### Request Body - **paymentId** (string) - Required - The ID of the payment. - **optionId** (string) - Required - The ID of the selected payment option. ``` -------------------------------- ### Get Active Sessions in WalletKit Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/walletkit-client.md Retrieves all active sessions. Useful for displaying connected dapps or managing active connections. ```typescript const sessions = walletkit.getActiveSessions(); Object.entries(sessions).forEach(([topic, session]) => { console.log(`Session ${topic} with ${session.peer.metadata.name}`); }); ``` -------------------------------- ### Initialize WalletKit Source: https://github.com/reown-com/reown-walletkit-js/blob/main/packages/walletkit/README.md Initialize the WalletKit SDK with a shared Core instance and metadata. Ensure the PROJECT_ID environment variable is set. ```javascript import { Core } from "@walletconnect/core"; import { WalletKit } from "@reown/walletkit"; const core = new Core({ projectId: process.env.PROJECT_ID, }); const walletkit = await WalletKit.init({ core, // <- pass the shared `core` instance metadata: { name: "Demo app", description: "Demo Client as Wallet/Peer", url: "www.walletconnect.com", icons: [], }, }); ``` -------------------------------- ### WalletKit.init Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/walletkit-client.md Factory method to create and initialize a WalletKit instance. This is the recommended way to instantiate WalletKit. ```APIDOC ## WalletKit.init(opts: WalletKitTypes.Options): Promise ### Description Factory method that creates and initializes a WalletKit instance. This is the recommended way to instantiate WalletKit. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **opts** (WalletKitTypes.Options) - Required - Configuration object (see Options below) ### Returns - **Promise** - An initialized and ready-to-use WalletKit instance ### Throws Logs and re-throws any initialization errors ### Example ```typescript import { Core } from "@walletconnect/core"; import { WalletKit } from "@reown/walletkit"; const core = new Core({ projectId: "YOUR_PROJECT_ID", }); const walletkit = await WalletKit.init({ core, metadata: { name: "My Wallet", description: "My wallet application", url: "https://example.com", icons: ["https://example.com/icon.png"], }, }); ``` ``` -------------------------------- ### Initialize WalletKit with PayConfig Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/configuration.md Initialize WalletKit with optional WalletConnect Pay configuration. Pay is automatically initialized if payConfig is provided and the Pay service is available. ```typescript const walletkit = await WalletKit.init({ core, metadata, payConfig: { // Payment configuration options // See @walletconnect/pay documentation }, }); ``` -------------------------------- ### Get Pending Session Proposals in WalletKit Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/walletkit-client.md Retrieves all pending session proposals that are awaiting a response. Use this to display pending connection requests to the user. ```typescript const proposals = walletkit.getPendingSessionProposals(); Object.entries(proposals).forEach(([id, proposal]) => { console.log(`Proposal ${id} from ${proposal.proposer.metadata.name}`); }); ``` -------------------------------- ### Initialize WalletKit with Custom Storage and Logger Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/configuration.md Set up WalletKit with custom storage solutions and logging levels. This advanced configuration allows for greater control over data persistence and debugging. ```typescript const core = new Core({ projectId: "YOUR_PROJECT_ID", logger: "debug", storage: customStorage, customStoragePrefix: "myapp:", }); const walletkit = await WalletKit.init({ core, metadata: { name: "Advanced Wallet", description: "Wallet with custom storage", url: "https://example.com", icons: [], }, name: "AdvancedWallet", }); ``` -------------------------------- ### Initialize WalletKit with Custom Storage Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/configuration.md Shows how to initialize WalletKit with a custom storage implementation for the WalletConnect Core. This allows you to manage session data using your own storage backend. ```typescript // Example: Custom storage implementation const customStorage = { getItem: async (key: string) => { // Retrieve from your storage backend return await db.get(key); }, setItem: async (key: string, value: string) => { // Store in your storage backend await db.set(key, value); }, removeItem: async (key: string) => { // Remove from your storage backend await db.delete(key); }, }; const core = new Core({ projectId: "...", storage: customStorage, customStoragePrefix: "myapp:", }); const walletkit = await WalletKit.init({ core, metadata: { /* ... */ }, }); ``` -------------------------------- ### WalletKit.init Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/api-methods-reference.md Factory method to create and initialize a WalletKit instance. It returns a Promise that resolves with the initialized WalletKit instance. ```APIDOC ## WalletKit.init(opts: WalletKitTypes.Options): Promise ### Description Factory method to create and initialize a WalletKit instance. ### Parameters #### Path Parameters - **opts.core** (ICore) - Required - The core instance for WalletKit. - **opts.metadata** (CoreTypes.Metadata) - Required - Metadata for the WalletKit instance. - **opts.name** (string) - Optional - The name of the WalletKit instance. - **opts.signConfig** (SignClientTypes.Options["signConfig"]) - Optional - Configuration for signing. - **opts.payConfig** (WalletConnectPayOptions) - Optional - Configuration for payment. ### Returns - **Promise** - A Promise that resolves with the initialized WalletKit instance. ### Throws - Error if initialization fails. ``` -------------------------------- ### Query Wallet State Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/INDEX.md Retrieve active sessions, pending session proposals, and pending session requests. Use these to get the current status of wallet interactions. ```typescript const sessions = walletkit.getActiveSessions(); const proposals = walletkit.getPendingSessionProposals(); const requests = walletkit.getPendingSessionRequests(); ``` -------------------------------- ### Configure Core with Environment Variables Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/configuration.md Demonstrates how to configure the WalletConnect Core with environment variables for project ID and an optional custom relay URL. Ensure environment variables are set. ```typescript const core = new Core({ projectId: process.env.WALLETCONNECT_PROJECT_ID || "", relayUrl: process.env.RELAY_URL, }); ``` -------------------------------- ### WalletKit Initialization Source: https://github.com/reown-com/reown-walletkit-js/blob/main/packages/walletkit/README.md Initializes the WalletKit SDK with a shared Core instance and metadata. ```APIDOC ## WalletKit Initialization ### Description Initializes the WalletKit SDK with a shared Core instance and metadata. ### Method `WalletKit.init(options: { core: Core, metadata: Metadata }) ### Parameters #### Request Body - **core** (Core) - Required - The shared Core instance from WalletConnect. - **metadata** (Metadata) - Required - Metadata about the wallet application. ``` -------------------------------- ### Get Pending Session Requests in WalletKit Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/walletkit-client.md Retrieves all pending session requests that require a response. This is useful for displaying pending actions or method calls from connected dapps. ```typescript const pendingRequests = walletkit.getPendingSessionRequests(); pendingRequests.forEach((request) => { console.log(`Pending request ${request.id}: ${request.request.method}`); }); ``` -------------------------------- ### Initialize WalletKit with SignConfig Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/configuration.md Initialize WalletKit, passing optional SignClient configuration through to the underlying WalletConnect SignClient. Common options include disabling history tracking or setting a fallback URL. ```typescript const walletkit = await WalletKit.init({ core, metadata, signConfig: { // Optional SignClient-specific settings // See @walletconnect/types for available options }, }); ``` -------------------------------- ### Decrypt Notification and Get Metadata with WalletKit Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/walletkit-client.md Use WalletKit.notifications.decryptMessage to decrypt encrypted notifications and WalletKit.notifications.getMetadata to retrieve peer session metadata. Both require a topic, storage, and optionally a custom storage prefix. ```typescript const message = await WalletKit.notifications.decryptMessage({ topic: "wc:...", encryptedMessage: "...", storage: myStorage, customStoragePrefix: "custom:", }); ``` ```typescript const metadata = await WalletKit.notifications.getMetadata({ topic: "wc:...", storage: myStorage, customStoragePrefix: "custom:", }); ``` -------------------------------- ### Initialize WalletConnect Core Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/configuration.md Initialize the WalletConnect Core instance with your project ID. Optional parameters include logger level, relay URL, custom storage, and storage prefix. ```typescript import { Core } from "@walletconnect/core"; const core = new Core({ projectId: process.env.WALLETCONNECT_PROJECT_ID, // Optional: configure logger level logger: "info", // "error", "warn", "info", "debug", "trace" // Optional: custom relay URL relayUrl: "wss://relay.walletconnect.com", // default // Optional: custom storage storage: myCustomStorage, // Optional: custom storage prefix customStoragePrefix: "my-wallet:", }); const walletkit = await WalletKit.init({ core, metadata: { /* ... */ }, }); ``` -------------------------------- ### Configuration with Inferred WalletKit Types Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/types.md Sets up WalletKit initialization options with inferred types for core and metadata. Requires 'Core' to be imported. ```typescript const options: WalletKitTypes.Options = { core: new Core({ projectId: "..." }), metadata: { name: "My Wallet", description: "My wallet app", url: "https://example.com", icons: [], }, }; const walletkit = await WalletKit.init(options); ``` -------------------------------- ### WalletConnect Pay Methods Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/walletkit-client.md Provides access to WalletConnect Pay functionality, allowing users to check for payment availability, retrieve payment options, get required payment actions, and confirm payments. ```APIDOC ## WalletConnect Pay ### Description The `pay` property provides access to WalletConnect Pay functionality, enabling users to initiate and manage payments directly from their wallet. ### Type `IWalletKitPay` (alias for `WalletConnectPay` instance) ### Methods #### `getPaymentOptions(params: { paymentLink: string, accounts: string[], includePaymentInfo?: boolean }): Promise Retrieves available payment options for a given payment link and user accounts. **Parameters**: - **paymentLink** (string) - Required - The URL of the payment link. - **accounts** (string[]) - Required - An array of user account addresses. - **includePaymentInfo** (boolean) - Optional - Whether to include additional payment information. **Returns**: `Promise` #### `getRequiredPaymentActions(params: { paymentId: string, optionId: string }): Promise Gets the necessary actions (e.g., signing) required to complete a selected payment option. **Parameters**: - **paymentId** (string) - Required - The ID of the payment. - **optionId** (string) - Required - The ID of the selected payment option. **Returns**: `Promise` #### `confirmPayment(params: { paymentId: string, optionId: string, signatures: any }): Promise Confirms the payment after the user has signed the required actions. **Parameters**: - **paymentId** (string) - Required - The ID of the payment. - **optionId** (string) - Required - The ID of the selected payment option. - **signatures** (any) - Required - The signatures obtained from the required payment actions. **Returns**: `Promise` ### Usage Example ```typescript const walletkit = await WalletKit.init({ /* ... */ }); if (walletkit.pay) { // Get payment options const options = await walletkit.pay.getPaymentOptions({ paymentLink: "https://pay.walletconnect.com/...", accounts: ["eip155:1:0x..."], includePaymentInfo: true, }); // Get required actions const actions = await walletkit.pay.getRequiredPaymentActions({ paymentId: options.paymentId, optionId: options.options[0].id, }); // Confirm payment after signing const result = await walletkit.pay.confirmPayment({ paymentId: options.paymentId, optionId: options.options[0].id, signatures: signedActions, // Assume signedActions is obtained after user interaction }); console.log("Payment confirmed:", result); } ``` ``` -------------------------------- ### session_authenticate Event Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/events.md Handles the `session_authenticate` event emitted by the WalletKit when a dapp requests multi-chain authentication, typically using Sign In With Ethereum (SIWE). It outlines the event structure, key properties, and provides an example of how to process and respond to authentication requests. ```APIDOC ## `session_authenticate` Event ### Description Emitted when a dapp initiates a multi-chain authentication request (typically SIWE - Sign In With Ethereum). ### Event Arguments ```typescript interface SessionAuthenticate extends BaseEventArgs { id: number; topic: string; params: { id: number; requester: { publicKey: string; metadata: Metadata; }; authPayload: AuthPayload; expiryMs: number; }; } ``` ### Key Properties - `id` - Authentication request ID - `topic` - Pairing or session topic - `params.requester` - Dapp metadata and public key - `params.authPayload` - Authentication details (messages to sign, etc.) - `params.expiryMs` - Request expiry in milliseconds ### Lifecycle Emitted once per auth request; expires after the specified expiryMs. ### Typical Response Call `approveSessionAuthenticate()` or `rejectSessionAuthenticate()`. ### Example ```typescript walletkit.on("session_authenticate", async (event) => { const { id, params } = event; const { authPayload, requester } = params; console.log(`Auth request from: ${requester.metadata.name}`); console.log(`Auth payload:`, authPayload); try { // Format the message for signing const message = walletkit.formatAuthMessage({ request: authPayload, iss: "did:pkh:eip155:1:0x123...", // User's DID }); // Sign the message const signature = await wallet.signMessage(message); // Approve authentication await walletkit.approveSessionAuthenticate({ id, signature, // Additional parameters as needed }); } catch (error) { // Reject authentication await walletkit.rejectSessionAuthenticate({ id, reason: getSdkError("USER_REJECTED"), }); } }); ``` ``` -------------------------------- ### Get Peer Metadata - TypeScript Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/utilities.md Retrieve dapp metadata from a session topic using stored session data. This is helpful for displaying dapp information when handling offline notifications. The function may throw an error if the session is not found or storage is inaccessible. ```typescript import { WalletKit } from "@reown/walletkit"; // When receiving a notification and needing dapp info const sessionTopic = "wc:abc123..."; try { const dappMetadata = await WalletKit.notifications.getMetadata({ topic: sessionTopic, // Optional: specify custom storage // storage: customStorage, }); console.log(`Request from: ${dappMetadata.name}`); console.log(`URL: ${dappMetadata.url}`); console.log(`Icons: ${dappMetadata.icons}`); // Use metadata to display notification UI showNotification({ title: `${dappMetadata.name} is requesting your attention`, icon: dappMetadata.icons[0], }); } catch (error) { console.error("Failed to get metadata:", error.message); } ``` -------------------------------- ### Multi-Tenant Wallet Initialization Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/configuration.md Create isolated WalletKit instances for different tenants by providing a custom storage prefix. This ensures that each tenant's data and configuration are kept separate. ```typescript async function createWalletForTenant(tenantId: string) { const core = new Core({ projectId: process.env.WALLETCONNECT_PROJECT_ID, customStoragePrefix: `tenant-${tenantId}:`, }); const walletkit = await WalletKit.init({ core, metadata: { name: `${tenantId} Wallet`, description: "Multi-tenant wallet", url: "https://example.com", icons: ["https://example.com/icon.png"], }, name: `WalletKit-${tenantId}`, }); return walletkit; } // Each tenant has isolated storage const wallet1 = await createWalletForTenant("tenant-1"); const wallet2 = await createWalletForTenant("tenant-2"); ``` -------------------------------- ### WalletKit Client Class Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Reference for the main WalletKit client class, including its constructor, static methods, and instance methods for managing wallet sessions and interactions. ```APIDOC ## WalletKit Client Class Reference This section details the `WalletKit` class, which is the primary interface for interacting with the wallet. ### Constructor Initializes a new instance of the WalletKit client. ### Static Methods - **`WalletKit.init()`** Initializes the WalletKit library. This is a required first step before using other WalletKit functionalities. - **`WalletKit.notifications.decryptMessage(encryptedMessage: string, key: string): string`** Decrypts an encrypted message using the provided key. - **`WalletKit.notifications.getMetadata(metadata: any): any`** Retrieves metadata from a given object. ### Instance Methods - **`pair(): Promise`** Initiates the pairing process with a wallet. - **`approveSession(sessionId: string, response: any): Promise`** Approves a pending session request for a given session ID. - **`rejectSession(sessionId: string, reason: any): Promise`** Rejects a pending session request for a given session ID. - **`updateSession(sessionId: string, session: any): Promise`** Updates an existing session with new information. - **`extendSession(sessionId: string): Promise`** Extends the expiry time of an active session. - **`respondSessionRequest(requestId: string, response: any): Promise`** Responds to a specific session request. - **`disconnectSession(sessionId: string): Promise`** Disconnects an active session. - **`emitSessionEvent(sessionId: string, event: string, data: any): Promise`** Emits a custom event for a specific session. - **`getActiveSessions(): Promise`** Retrieves a list of all currently active sessions. - **`getPendingSessionProposals(): Promise`** Retrieves a list of pending session proposals. - **`getPendingSessionRequests(): Promise`** Retrieves a list of pending session requests. - **`approveSessionAuthenticate(sessionId: string, authResponse: any): Promise`** Approves an authentication request for a session. - **`rejectSessionAuthenticate(sessionId: string, reason: any): Promise`** Rejects an authentication request for a session. - **`formatAuthMessage(options: any): string`** Formats a message for authentication purposes. - **`registerDeviceToken(token: string): Promise`** Registers a device token for push notifications. - **`on(event: string, listener: Function): void`** Subscribes to a specific event. - **`once(event: string, listener: Function): void`** Subscribes to an event that will be triggered only once. - **`off(event: string, listener: Function): void`** Unsubscribes from a specific event. - **`removeListener(event: string, listener: Function): void`** Removes a previously added event listener. ``` -------------------------------- ### Handle WalletKit Initialization Errors Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/configuration.md Implement error handling for WalletKit initialization to gracefully manage potential issues like missing project IDs, network problems, or invalid metadata. The `try-catch` block helps in logging and responding to these errors. ```typescript try { const walletkit = await WalletKit.init({ core: new Core({ projectId: process.env.WALLETCONNECT_PROJECT_ID }), metadata: { /* ... */ }, }); } catch (error) { console.error("WalletKit initialization failed:", error.message); // Common errors: // - Missing projectId: "project ID is required" // - Network issues: "Failed to connect to relay" // - Invalid metadata: "Metadata validation failed" } ``` -------------------------------- ### Mock WalletKit for Unit Tests Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/patterns-and-best-practices.md Provides a mock implementation of the WalletKit for use in unit tests. This allows testing components that interact with WalletKit without needing a live instance. ```typescript // __mocks__/walletkit.ts import { vi } from "vitest"; export const mockWalletKit = { init: vi.fn(), on: vi.fn().mockReturnThis(), once: vi.fn().mockReturnThis(), off: vi.fn().mockReturnThis(), removeListener: vi.fn().mockReturnThis(), pair: vi.fn(), approveSession: vi.fn(), rejectSession: vi.fn(), updateSession: vi.fn(), extendSession: vi.fn(), respondSessionRequest: vi.fn(), emitSessionEvent: vi.fn(), disconnectSession: vi.fn(), getActiveSessions: vi.fn().mockReturnValue({}), getPendingSessionProposals: vi.fn().mockReturnValue({}), getPendingSessionRequests: vi.fn().mockReturnValue([]), }; vi.mock("@reown/walletkit", () => ({ WalletKit: mockWalletKit, })); ``` -------------------------------- ### Pair with a Dapp using WalletConnect URI Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/walletkit-client.md Initiates a pairing with a dapp by providing a WalletConnect URI. Use this to establish a connection before session proposals are exchanged. The `activatePairing` option can be set to `true` to immediately activate the pairing. ```typescript await walletkit.pair({ uri: "wc:a1b2c3d4...", activatePairing: true, }); ``` -------------------------------- ### Define Default WalletKit Client Storage Options Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/utilities.md Specifies the default storage configuration, using an in-memory database. ```typescript export const CLIENT_STORAGE_OPTIONS = { database: ":memory:", }; ``` -------------------------------- ### Singleton Pattern for WalletKit Initialization Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/patterns-and-best-practices.md Implement the Singleton pattern to maintain a single, persistent WalletKit instance throughout your application's lifecycle. This ensures consistent state management and avoids redundant initialization. ```typescript import { Core } from "@walletconnect/core"; import { WalletKit } from "@reown/walletkit"; let walletkit: WalletKit | null = null; export async function initializeWalletKit(): Promise { if (walletkit) { return walletkit; } const core = new Core({ projectId: process.env.WALLETCONNECT_PROJECT_ID, logger: "info", }); walletkit = await WalletKit.init({ core, metadata: { name: "My Wallet", description: "My secure wallet", url: "https://example.com", icons: ["https://example.com/icon.png"], }, }); return walletkit; } export function getWalletKit(): WalletKit { if (!walletkit) { throw new Error("WalletKit not initialized"); } return walletkit; } ``` -------------------------------- ### Monitor WalletKit Events for Session Proposals and Requests Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/patterns-and-best-practices.md Implement a monitor class to subscribe to and log key WalletKit events like session proposals, requests, and deletions. This helps in debugging and understanding wallet interactions. ```typescript // monitoring.ts export class WalletKitMonitor { constructor(private walletkit: WalletKit) { this.setupMonitoring(); } private setupMonitoring() { this.walletkit.on("session_proposal", (proposal) => { console.log("[SESSION_PROPOSAL]", { id: proposal.id, dapp: proposal.params.proposer.metadata.name, timestamp: new Date().toISOString(), }); }); this.walletkit.on("session_request", (event) => { console.log("[SESSION_REQUEST]", { id: event.id, method: event.params.request.method, timestamp: new Date().toISOString(), }); }); this.walletkit.on("session_delete", (event) => { console.log("[SESSION_DELETE]", { topic: event.topic, timestamp: new Date().toISOString(), }); }); // Send to monitoring service this.sendToMonitoringService(); } private sendToMonitoringService() { // Implementation: send events to your monitoring service } } ``` -------------------------------- ### IWalletKitEngine Abstract Class Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/types.md The IWalletKitEngine abstract class defines the core interface for interacting with the WalletKit engine. It includes methods for managing sessions, handling multi-chain authentication, registering device tokens for push notifications, and subscribing to various engine events. ```APIDOC ## Abstract Class: IWalletKitEngine ### Description This abstract class defines the fundamental interface for the WalletKit engine, providing methods for session management, multi-chain authentication, push notifications, and event handling. It serves as the base for concrete engine implementations. ### Methods #### Session Management - **init()**: `Promise` - Initializes the engine. - **pair(params: { uri: string; activatePairing?: boolean })**: `Promise` - Initiates a pairing process with a given URI. - **approveSession(params: ApproveSessionParams)**: `Promise` - Approves a pending session proposal. - **rejectSession(params: { id: number; reason: ErrorResponse })**: `Promise` - Rejects a pending session proposal. - **updateSession(params: { topic: string; namespaces: SessionTypes.Namespaces })**: `Promise<{ acknowledged: () => Promise }>` - Updates the namespaces for an active session. - **extendSession(params: { topic: string })**: `Promise<{ acknowledged: () => Promise }>` - Extends the expiry of an active session. - **respondSessionRequest(params: { topic: string; response: JsonRpcResponse })**: `Promise` - Responds to a session request. - **emitSessionEvent(params: { topic: string; event: any; chainId: string })**: `Promise` - Emits a session event. - **disconnectSession(params: { topic: string; reason: ErrorResponse })**: `Promise` - Disconnects an active session. - **getActiveSessions()**: `Record` - Retrieves all active sessions. - **getPendingSessionProposals()**: `Record` - Retrieves all pending session proposals. - **getPendingSessionRequests()**: `PendingRequestTypes.Struct[]` - Retrieves all pending session requests. #### Multi-chain Auth - **approveSessionAuthenticate(params: AuthTypes.ApproveSessionAuthenticateParams)**: `Promise<{ session: SessionTypes.Struct | undefined }>` - Approves a session authentication request. - **formatAuthMessage(params: { request: AuthTypes.BaseAuthRequestParams; iss: string })**: `string` - Formats an authentication message. - **rejectSessionAuthenticate(params: { id: number; reason: ErrorResponse })**: `Promise` - Rejects a session authentication request. #### Push - **registerDeviceToken(params: EchoClientTypes.RegisterDeviceTokenParams)**: `Promise` - Registers a device token for push notifications. #### Events - **on(event, listener)**: `EventEmitter` - Subscribes to an event. - **once(event, listener)**: `EventEmitter` - Subscribes to an event once. - **off(event, listener)**: `EventEmitter` - Unsubscribes from an event. - **removeListener(event, listener)**: `EventEmitter` - Removes an event listener. ``` -------------------------------- ### pair Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/walletkit-client.md Establishes a pairing with a dapp using a WalletConnect URI. This method initiates the connection before session proposals are sent. ```APIDOC ## pair ### Description Establishes a pairing with a dapp using a WalletConnect URI. This initiates the connection before session proposals are sent. ### Method `pair(params: { uri: string; activatePairing?: boolean }): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **params** (Object) - Required - Configuration object * **params.uri** (string) - Required - WalletConnect URI (e.g., `wc://...`) * **params.activatePairing** (boolean) - Optional - Whether to immediately activate this pairing (default: `false`) ### Request Example ```typescript await walletkit.pair({ uri: "wc:a1b2c3d4...", activatePairing: true, }); ``` ### Response #### Success Response (200) `Promise` - Resolves when pairing is complete #### Response Example None explicitly provided, resolves to void. ``` -------------------------------- ### WalletKit Configuration Type Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/INDEX.md Defines the options required for initializing WalletKit, including core, metadata, and optional configuration for signing and payments. ```typescript interface WalletKitTypes.Options { core: ICore; metadata: Metadata; name?: string; signConfig?: SignConfig; payConfig?: PayOptions; } ``` -------------------------------- ### Access Notification Utilities - TypeScript Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/utilities.md Import and access the static notification utilities from the WalletKit library. ```typescript import { WalletKit } from "@reown/walletkit"; // Access notification utilities const { decryptMessage, getMetadata } = WalletKit.notifications; ``` -------------------------------- ### Import WalletKit Constants Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/utilities.md Import various constants provided by the WalletKit package for client-side configurations and protocol details. These constants are useful for setting up and managing client interactions. ```typescript // Constants import { CLIENT_CONTEXT, PROTOCOL, PROTOCOL_VERSION, CLIENT_STORAGE_PREFIX, CLIENT_STORAGE_OPTIONS, REQUEST_CONTEXT, } from "@reown/walletkit"; ``` -------------------------------- ### Handle WalletKit Events Source: https://github.com/reown-com/reown-walletkit-js/blob/main/packages/walletkit/README.md Set up event handlers for various WalletKit events like session proposals, requests, and deletions. ```javascript walletkit.on("session_proposal", handler); walletkit.on("session_request", handler); walletkit.on("session_delete", handler); ``` -------------------------------- ### Import and Use WalletKit Notifications Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/utilities.md Import the `WalletKit` class to access notification functionalities, such as decrypting messages. Ensure the `WalletKit` class is correctly instantiated or used statically as shown. ```typescript // Notifications and constants import { WalletKit } from "@reown/walletkit"; WalletKit.notifications.decryptMessage({ /* ... */ }); ``` -------------------------------- ### Define PayOptions Type Source: https://github.com/reown-com/reown-walletkit-js/blob/main/_autodocs/types.md Configuration options for WalletConnect Pay, passed in WalletKitTypes.Options.payConfig. ```typescript type PayOptions = WalletConnectPayOptions; ```