### Install @walletconnect/web3wallet Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/packages/web3wallet/README.md Install the Web3Wallet SDK using npm. This is the first step to integrating the SDK into your wallet project. ```bash npm install @walletconnect/web3wallet ``` -------------------------------- ### Install @walletconnect/ethereum-provider Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/providers/ethereum-provider/README.md Installs the @walletconnect/ethereum-provider package using npm. This is the first step to integrate WalletConnect into your Ethereum project. ```bash npm i @walletconnect/ethereum-provider ``` -------------------------------- ### Run All Package Checks Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/README.md Executes lint, build, and test commands for all packages within the monorepo. Requires a valid TEST_PROJECT_ID obtained from WalletConnect Cloud. ```zsh TEST_PROJECT_ID=YOUR_PROJECT_ID npm run check ``` -------------------------------- ### WalletConnect Monorepo Commands and Troubleshooting Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/README.md Comprehensive list of commands for managing the WalletConnect monorepo, including package operations, checks, and troubleshooting for Xcode command line tools. ```APIDOC Command Overview: - `clean` - Description: Removes build folders from all packages. - `lint` - Description: Runs eslint checks across all packages. - `prettier` - Description: Runs prettier checks for code formatting. - `build` - Description: Builds all packages in the monorepo. - `test` - Description: Executes tests for all packages. - `check` - Description: Shorthand command to run lint, build, and test. - `reset` - Description: Shorthand command to run clean and check. Troubleshooting Xcode Command Line Tools: - `sudo xcode-select --switch /Library/Developer/CommandLineTools` - Description: Switches the active Xcode command line tools path to the specified directory. Use this if you encounter issues with the current toolchain. - `sudo xcode-select --reset` - Description: Resets the Xcode command line tools to their default installation path. Useful for resolving path-related problems. ``` -------------------------------- ### Update Session Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/packages/web3wallet/README.md Update the namespaces of an active session, for example, to add support for new chains or methods. This requires the dapp to also agree to the updated namespaces. ```javascript await web3wallet.updateSession({ topic, namespaces: newNs }); ``` -------------------------------- ### Manage Default Chain in Universal Provider Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/providers/universal-provider/README.md Illustrates how to manage the default blockchain context for the provider. It shows how to get the current chain ID and how to set a new default chain, which affects subsequent requests if no specific chain is provided. ```typescript const web3 = new Web3(provider); // default chainId is the FIRST chain during setup const chainId = await web3.eth.getChainId(); // set the default chain to 56 provider.setDefaultChain(`eip155:56`, rpcUrl?: string | undefined); // get the updated default chainId const updatedDefaultChainId = await web3.eth.getChainId(); ``` -------------------------------- ### Web3Wallet Initialization Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/packages/web3wallet/README.md Initialize the Web3Wallet SDK by providing a shared Core instance and metadata for your wallet. This sets up the connection to the WalletConnect network. ```javascript import { Core } from "@walletconnect/core"; import { Web3Wallet } from "@walletconnect/web3wallet"; const core = new Core({ projectId: process.env.PROJECT_ID, }); const web3wallet = await Web3Wallet.init({ core, // <- pass the shared `core` instance metadata: { name: "Demo app", description: "Demo Client as Wallet/Peer", url: "www.walletconnect.com", icons: [], }, }); ``` -------------------------------- ### Initialize EthereumProvider Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/providers/ethereum-provider/README.md Demonstrates the initialization of the EthereumProvider. It outlines the required and optional configuration parameters such as projectId, chains, optionalChains, showQrModal, methods, events, rpcMap, metadata, and storage options. ```typescript import { EthereumProvider } from "@walletconnect/ethereum-provider"; const provider = await EthereumProvider.init({ projectId, // REQUIRED your projectId chains, // DEPRECATED, use `optionalChains` instead optionalChains, // REQUIRED optional chain ids e.g. 1 (Ethereum), 10 (Optimism), 42161 (Arbitrum) showQrModal, // REQUIRED set to "true" to use @walletconnect/modal, methods, // OPTIONAL ethereum methods events, // OPTIONAL ethereum events rpcMap, // OPTIONAL rpc urls for each chain metadata, // OPTIONAL metadata of your app storage, // OPTIONAL custom storage implementation storageOptions, // OPTIONAL storage config options qrModalOptions // OPTIONAL - `undefined` by default }); ``` -------------------------------- ### Initialize and Connect Universal Provider Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/providers/universal-provider/README.md Demonstrates how to initialize the Universal Provider with configuration options like logger, relayUrl, projectId, and metadata. It also shows how to connect to a specific namespace, defining supported methods, chains, and RPC endpoints. ```typescript import { ethers } from "ethers"; import UniversalProvider from "@walletconnect/universal-provider"; // Initialize the provider const provider = await UniversalProvider.init({ logger: "info", relayUrl: "ws://", projectId: "12345678", metadata: { name: "React App", description: "React App for WalletConnect", url: "https://walletconnect.com/", icons: ["https://avatars.githubusercontent.com/u/37784886"], }, client: undefined, // optional instance of @walletconnect/sign-client }); // create sub providers for each namespace/chain await provider.connect({ namespaces: { eip155: { methods: [ "eth_sendTransaction", "eth_signTransaction", "eth_sign", "personal_sign", "eth_signTypedData", ], chains: ["eip155:80001"], events: ["chainChanged", "accountsChanged"], rpcMap: { 80001: "https://rpc.walletconnect.org?chainId=eip155:80001&projectId=", }, }, pairingTopic: "<123...topic>", // optional topic to connect to skipPairing: false, // optional to skip pairing ( later it can be resumed by invoking .pair()) }, }); // Create Web3 Provider const web3Provider = new ethers.providers.Web3Provider(provider); ``` -------------------------------- ### SIWE with a Dapp Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/packages/web3wallet/README.md Integrate Sign-In with Ethereum (SIWE) by formatting a message, prompting the user to sign it, and responding to the dapp with the signature. ```javascript const iss = `did:pkh:eip155:1:${address}`; web3wallet.on("auth_request", async (event) => { // format the payload const message = web3wallet.formatMessage(event.params.cacaoPayload, iss); // prompt the user to sign the message const signature = await wallet.signMessage(message); // respond await web3wallet.respondAuthRequest( { id: args.id, signature: { s: signature, t: "eip191", }, }, iss, ); }); await web3wallet.core.pairing.pair({ uri: request.uri, activatePairing: true }); ``` -------------------------------- ### Handle Session Proposal and Approval Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/packages/web3wallet/README.md Listen for session proposals and approve them with the necessary namespaces. This is a key step in establishing a connection between the wallet and a dapp. ```javascript web3wallet.on("session_proposal", async (proposal) => { const session = await web3wallet.approveSession({ id: proposal.id, namespaces, }); }); ``` -------------------------------- ### Connect with QR Modal or Handle Connection URI Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/providers/ethereum-provider/README.md Shows two methods for establishing a connection: enabling the WalletConnect modal which displays a QR code, or subscribing to the 'display_uri' event to handle the connection URI manually. Both methods can be followed by `provider.connect()` or `provider.enable()`. ```typescript // WalletConnectModal is disabled by default, enable it during init() to display a QR code modal await provider.connect({ chains, // OPTIONAL chain ids rpcMap, // OPTIONAL rpc urls pairingTopic, // OPTIONAL pairing topic }); // or await provider.enable(); ``` ```typescript // If you are not using WalletConnectModal, // you can subscribe to the `display_uri` event and handle the URI yourself. provider.on("display_uri", (uri: string) => { // ... custom logic }); await provider.connect(); // or await provider.enable(); ``` -------------------------------- ### Handle Multiple Session Events Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/packages/web3wallet/README.md Set up handlers for various session-related events to manage the lifecycle and interactions of wallet sessions. ```javascript web3wallet.on("session_proposal", handler); web3wallet.on("session_request", handler); web3wallet.on("session_delete", handler); ``` -------------------------------- ### Web3Wallet Session Management Methods Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/packages/web3wallet/README.md This section details the core methods for managing sessions within the Web3Wallet SDK, including approving, rejecting, disconnecting, updating, and extending sessions, as well as emitting session events. ```APIDOC Web3Wallet: // Event Handlers on("session_proposal", handler) - Listens for new session proposal events from dapps. on("session_request", handler) - Listens for session-specific requests (e.g., signing, sending transactions). on("session_delete", handler) - Listens for session termination events. on("auth_request", handler) - Listens for authentication requests, typically for SIWE. // Session Management approveSession(params: { id: string, namespaces: NamespaceConfig }): Promise - Approves a pending session proposal. - Parameters: - id: The ID of the session proposal. - namespaces: The namespaces to approve, defining supported chains and methods. - Returns: The established session object. rejectSession(params: { id: string, reason: Error }): Promise - Rejects a pending session proposal. - Parameters: - id: The ID of the session proposal. - reason: The reason for rejection (e.g., USER_REJECTED_METHODS). - Returns: A promise that resolves when the rejection is processed. disconnectSession(params: { topic: string, reason: Error }): Promise - Disconnects an active session. - Parameters: - topic: The topic of the session to disconnect. - reason: The reason for disconnection (e.g., USER_DISCONNECTED). - Returns: A promise that resolves when the disconnection is processed. updateSession(params: { topic: string, namespaces: NamespaceConfig }): Promise - Updates the namespaces of an active session. - Parameters: - topic: The topic of the session to update. - namespaces: The new namespaces configuration. - Returns: A promise that resolves when the update is processed. extendSession(params: { topic: string }): Promise - Extends the expiry of an active session. - Parameters: - topic: The topic of the session to extend. - Returns: A promise that resolves when the extension is processed. emitSessionEvent(params: { topic: string, event: { name: string, data: any }, chainId: string }): Promise - Emits a custom event for an active session. - Parameters: - topic: The topic of the session. - event: An object containing the event name and data. - chainId: The chain ID associated with the event. - Returns: A promise that resolves when the event is emitted. respondSessionRequest(params: { id: string, result?: any, error?: Error }): Promise - Responds to a session request (e.g., signature, transaction). - Parameters: - id: The ID of the session request. - result: The successful result of the request. - error: The error object if the request failed. - Returns: A promise that resolves when the response is sent. // SIWE Integration formatMessage(payload: CacaoPayload, iss: string): string - Formats a message payload for Sign-In with Ethereum (SIWE). - Parameters: - payload: The Cacao payload object. - iss: The issuer identifier (e.g., DID). - Returns: The formatted SIWE message string. respondAuthRequest(params: { id: string, signature: Signature }, iss: string): Promise - Responds to an authentication request with a signature. - Parameters: - id: The ID of the auth request. - signature: The signature object (e.g., { s: string, t: 'eip191' }). - iss: The issuer identifier. - Returns: A promise that resolves when the response is sent. // Pairing core.pairing.pair(params: { uri: string, activatePairing?: boolean }): Promise - Initiates a pairing with a dapp using a URI. - Parameters: - uri: The pairing URI. - activatePairing: Whether to activate the pairing immediately. - Returns: A promise that resolves when the pairing is initiated. ``` -------------------------------- ### Handle Auth Events Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/packages/web3wallet/README.md Listen for authentication requests from dapps, which are typically used for Sign-In with Ethereum (SIWE) flows. ```javascript web3wallet.on("auth_request", handler); ``` -------------------------------- ### Subscribe to Universal Provider Events Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/providers/universal-provider/README.md Shows how to subscribe to various events emitted by the Universal Provider. This includes display URI for QR codes, session pings, session events, session updates, and session deletions. ```typescript // Subscribe for pairing URI provider.on("display_uri", (uri) => { console.log(uri); }); // Subscribe to session ping provider.on("session_ping", ({ id, topic }) => { console.log(id, topic); }); // Subscribe to session event provider.on("session_event", ({ event, chainId }) => { console.log(event, chainId); }); // Subscribe to session update provider.on("session_update", ({ topic, params }) => { console.log(topic, params); }); // Subscribe to session delete provider.on("session_delete", ({ id, topic }) => { console.log(id, topic); }); ``` -------------------------------- ### Respond to Session Requests Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/packages/web3wallet/README.md Handle incoming session requests from dapps, such as signing messages or transactions, and respond with the result or an error. ```javascript web3wallet.on("session_request", async (event) => { const { id, method, params } = event.request; await web3wallet.respondSessionRequest({ id, result: response }); }); ``` -------------------------------- ### Next.js Page with Dynamic Import for WalletConnect Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/providers/ethereum-provider/README.md Demonstrates how to dynamically import a client-side component that uses the WalletConnect Ethereum Provider in a Next.js application. This prevents the provider from being initialized on the server, avoiding SSR errors. ```typescript // src/app/page.tsx (or your main layout/page) "use client"; // Required if the page itself uses the dynamic import directly import dynamic from 'next/dynamic'; import { Suspense } from 'react'; // Optional: Add loading UI // Dynamically import the component that uses EthereumProvider const WalletConnectLogic = dynamic( () => import('@/components/WalletConnectLogic'), // Path to your client component { ssr: false, // This is crucial to prevent server-side execution // Optional: Display a loading state while the component is loading // loading: () =>

Loading WalletConnect...

, } ); export default function Home() { return (
{/* Other page content */} Loading WalletConnect...

}> {/* Optional Suspense boundary */}
{/* Other page content */}
); } ``` -------------------------------- ### Handle Session Rejection Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/packages/web3wallet/README.md Listen for session proposals and reject them with a specific reason. This allows the wallet to inform the dapp why the connection was not established. ```javascript web3wallet.on("session_proposal", async (proposal) => { const session = await web3wallet.rejectSession({ id: proposal.id, reason: getSdkError("USER_REJECTED_METHODS"), }); }); ``` -------------------------------- ### Event Subscriptions Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/providers/ethereum-provider/README.md Details the various events that can be subscribed to on the provider instance. These include chain changes, account changes, session connection and disconnection, session events, and the display of connection URIs. ```typescript // chain changed provider.on("chainChanged", handler); // accounts changed provider.on("accountsChanged", handler); // session established provider.on("connect", handler); // session event - chainChanged/accountsChanged/custom events provider.on("session_event", handler); // connection uri provider.on("display_uri", handler); // session disconnect provider.on("disconnect", handler); ``` -------------------------------- ### WalletConnect Ethereum Provider Client Component Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/providers/ethereum-provider/README.md A React client component that initializes and manages the WalletConnect Ethereum Provider. It handles connection, account changes, and displays connection status, ensuring all WalletConnect logic executes only on the client. ```typescript // src/components/WalletConnectLogic.tsx "use client"; // Mark this component as client-side only import { EthereumProvider } from "@walletconnect/ethereum-provider"; import { useEffect, useState, useCallback } from "react"; // Your WalletConnect Project ID const projectId = process.env.NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID!; let provider: Awaited> | null = null; export default function WalletConnectLogic() { const [account, setAccount] = useState(null); // ... other state (isConnected, chainId, etc.) const initialize = useCallback(async () => { if (!projectId) { throw new Error("Missing NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID"); } if (provider) return; // Already initialized try { provider = await EthereumProvider.init({ projectId: projectId, optionalChains: [1, 10, 137], // Example chains showQrModal: true, metadata: { /* ... your metadata ... */ } // ... other options }); // --- Add event listeners --- provider.on("connect", (info: { chainId: string }) => { console.log("connect", info); // Set initial account/chain state }); provider.on("accountsChanged", (accounts: string[]) => { console.log("accountsChanged", accounts); setAccount(accounts[0] ?? null); }); // ... other listeners (disconnect, chainChanged) // Check for existing session if (provider.session && provider.accounts.length > 0) { setAccount(provider.accounts[0]); // set chainId, isConnected etc. } } catch (error) { console.error("Failed to initialize WalletConnect Provider", error); } }, []); useEffect(() => { // Initialize provider on component mount (client-side) initialize(); // Optional: Cleanup listeners on unmount return () => { // provider?.off(...); }; }, [initialize]); const connectWallet = useCallback(async () => { if (!provider) { console.error("Provider not initialized"); return; } try { await provider.connect(); } catch (error) { console.error("Failed to connect:", error); } }, []); // ... other functions (disconnect, signMessage, etc.) return (
{/* Your Connect/Disconnect buttons, account display, etc. */} {!account ? ( ) : (

Connected: {account}

)} {/* ... */}
); } ``` -------------------------------- ### Universal Provider Request Method Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/providers/universal-provider/README.md Details the `request` method for sending JSON RPC requests through the Universal Provider. It accepts a `RequestArguments` object containing the method and optional parameters, and an optional chain identifier. ```APIDOC RequestArguments: method: string params?: any[] | undefined provider.request(payload: RequestArguments, chain: string | undefined) - Sends JSON RPC requests to the connected wallet. - Parameters: - payload: An object conforming to RequestArguments, specifying the RPC method and its parameters. - chain: Optionally specify which chain should handle this request in the format `:` e.g. `eip155:1`. - Returns: The result of the JSON RPC request. ``` -------------------------------- ### Sending Ethereum Requests Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/providers/ethereum-provider/README.md Illustrates how to send requests to the connected Ethereum provider. Supports both Promise-based asynchronous calls using `provider.request` and callback-based asynchronous calls using `provider.sendAsync`. ```typescript const result = await provider.request({ method: "eth_requestAccounts" }); // OR provider.sendAsync({ method: "eth_requestAccounts" }, CallBackFunction); ``` -------------------------------- ### Emit Session Events Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/packages/web3wallet/README.md Emit custom events for an active session, such as account changes or network updates. This keeps the dapp informed about relevant wallet state changes. ```javascript await web3wallet.emitSessionEvent({ topic, event: { name: "accountsChanged", data: ["0xab16a96D359eC26a11e2C2b3d8f8B8942d5Bfcdb"], }, chainId: "eip155:1", }); ``` -------------------------------- ### Disconnect Session Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/packages/web3wallet/README.md Disconnect an active session with a specified topic and reason. This is used when the user or wallet decides to terminate the connection. ```javascript await web3wallet.disconnectSession({ topic, reason: getSdkError("USER_DISCONNECTED"), }); ``` -------------------------------- ### Extend Session Source: https://github.com/walletconnect/walletconnect-monorepo/blob/v2.0/packages/web3wallet/README.md Extend the expiry of an active session. This is typically done periodically to keep the session alive without requiring re-authentication. ```javascript await web3wallet.extendSession({ topic }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.