# WalletConnect Agents SDK (/agents/overview) The **WalletConnect Agents SDK** is a monorepo of CLI tools and libraries that bring WalletConnect capabilities to the terminal and AI agent environments. It enables wallet connection, message signing, cross-chain bridging, and WCT staking without a browser UI. **Beta (v0.1.x)** — This project is under active development. APIs and CLI interfaces may change between releases. Not yet recommended for production use. ## Packages [#packages]
Package Description
@walletconnect/pay-cli Create and complete WalletConnect Pay payments from the terminal
@walletconnect/cli-sdk Wallet connection, signing, and cross-chain swidge for terminal apps
@walletconnect/staking-cli WCT staking on Optimism — stake, unstake, claim rewards
## Install [#install] ```bash npm install -g @walletconnect/cli-sdk @walletconnect/staking-cli ``` Get a Project ID from [WalletConnect Cloud](https://cloud.walletconnect.com), then configure it: ```bash walletconnect config set project-id # or export WALLETCONNECT_PROJECT_ID= ``` --- ## WalletConnect Pay CLI [#walletconnect-pay-cli] **Experimental** — This package is under active development. APIs, commands, and behavior may change significantly between releases. Create and complete WalletConnect Pay payments from the terminal. Supports proxy mode (no API keys needed) and direct API mode. ### Commands [#commands] ``` Usage: walletconnect-pay [options] Commands: status Check the status of a payment create Create a new payment (merchant credentials required) checkout Complete a payment using a connected wallet Options: --staging Use the staging API --proxy Proxy through frontend (no API keys needed) --help Show this help message ``` ### Authentication [#authentication] By default, the CLI proxies through the WalletConnect Pay frontend — no API keys needed. For direct API access: ```bash export WC_PAY_WALLET_API_KEY= # Required for merchant operations export WC_PAY_PARTNER_API_KEY= export WC_PAY_MERCHANT_ID= ``` ### Travel Rule compliance [#travel-rule-compliance] Some payments require Information Capture data. Provide via CLI flags or environment variables: ```bash walletconnect-pay checkout \ --name "John Doe" \ --dob "1990-01-15" \ --pob-country "US" \ --pob-address "New York, NY" ``` Or via environment variables: ```bash export WC_PAY_NAME="John Doe" export WC_PAY_DOB="1990-01-15" export WC_PAY_POB_COUNTRY="US" export WC_PAY_POB_ADDRESS="New York, NY" ``` ### Examples [#examples] ```bash # Check a payment's status walletconnect-pay status pay_abc123 --staging # Create a $10 payment (1000 = minor units / cents) walletconnect-pay create 1000 --staging # Complete a payment with a connected wallet walletconnect-pay checkout pay_abc123 --staging ``` ### Programmatic usage [#programmatic-usage] ```typescript import { createPayClient, createFrontendPayClient } from "@walletconnect/pay-cli"; // Direct API client const client = createPayClient({ walletApiKey: "your-wallet-api-key", sdkVersion: "0.5.0", staging: true, }); // Proxy through the frontend (no API keys needed) const proxyClient = createFrontendPayClient({ frontendUrl: "https://staging.pay.walletconnect.com", }); const payment = await client.getPayment("pay_abc123"); ``` --- ## WalletConnect CLI [#walletconnect-cli] Connect a wallet, sign messages, send transactions, and bridge tokens across chains from the terminal. ### Commands [#commands-1] ``` Usage: walletconnect [options] Commands: connect Connect to a wallet via QR code whoami Show current session info sign Sign a message with the connected wallet sign-typed-data Sign EIP-712 typed data (JSON string) send-transaction Send a transaction (EVM or Solana) swidge Bridge/swap tokens across chains via LI.FI disconnect Disconnect the current session config set Set a config value (e.g. project-id) config get Get a config value Options: --browser Use browser UI instead of terminal QR code --json Output as JSON (for whoami) --chain Specify chain (e.g. evm, solana, eip155:10) for connect --version Show version number --help Show this help message ``` ### Examples [#examples-1] ```bash # Connect a wallet (shows QR code in terminal) walletconnect connect # Connect using a browser-based QR code walletconnect connect --browser # Sign a message walletconnect sign "Hello from the terminal" # Check connected wallet walletconnect whoami # Send a transaction on Optimism walletconnect send-transaction '{"to":"0x...","value":"0x0","chainId":"eip155:10"}' # Disconnect walletconnect disconnect ``` ### Swidge (Cross-Chain Bridge/Swap) [#swidge-cross-chain-bridgeswap] Bridge or swap tokens across EVM chains, powered by [LI.FI](https://li.fi). The connected wallet approves and executes each transaction. ```bash # Bridge 5 WCT from Optimism to Ethereum mainnet walletconnect swidge --from-chain eip155:10 --to-chain eip155:1 \ --from-token WCT --to-token WCT --amount 5 # Swap USDC on Base to ETH on Optimism walletconnect swidge --from-chain eip155:8453 --to-chain eip155:10 \ --from-token USDC --to-token ETH --amount 10 # Bridge ETH from Ethereum to Base walletconnect swidge --from-chain eip155:1 --to-chain eip155:8453 \ --amount 0.01 ``` When sending a transaction, the CLI automatically checks if the connected wallet has sufficient ETH on the target chain. If funds are insufficient: - **Interactive (TTY):** Prompts you to bridge from another chain - **Pipe / agent mode:** Auto-bridges from the chain with the most funds ### Programmatic usage [#programmatic-usage-1] ```typescript import { WalletConnectCLI, withWallet } from "@walletconnect/cli-sdk"; // High-level helper — connect → use → cleanup await withWallet( { projectId: "your-project-id", metadata: { name: "My App", description: "...", url: "...", icons: [] }, }, async (wallet, { accounts }) => { const txHash = await wallet.request({ chainId: "eip155:1", request: { method: "eth_sendTransaction", params: [{ from: accounts[0].split(":").pop(), to: "0x...", value: "0x0" }], }, }); }, ); // Direct client usage const wallet = new WalletConnectCLI({ projectId: "your-project-id", metadata: { name: "My App", description: "...", url: "...", icons: [] }, chains: ["eip155:1", "eip155:10"], ui: "browser", // or "terminal" (default) }); const { accounts } = await wallet.connect(); const signature = await wallet.request({ chainId: "eip155:1", request: { method: "personal_sign", params: ["0x48656c6c6f", accounts[0]] }, }); await wallet.disconnect(); await wallet.destroy(); ``` --- ## WalletConnect Staking CLI [#walletconnect-staking-cli] Stake WCT tokens on Optimism, check staking positions, and claim rewards. ### Commands [#commands-2] ``` Usage: walletconnect-staking [options] Commands: stake Stake WCT (approve + createLock/updateLock) unstake Withdraw all staked WCT (after lock expires) claim Claim staking rewards status Show staking position, rewards, and APY balance Show WCT token balance Options: --address=0x... Use address directly (for read-only commands) --browser Use browser UI for wallet connection --help Show this help message ``` ### Examples [#examples-2] ```bash # Stake 1000 WCT for 52 weeks walletconnect-staking stake 1000 52 # Check staking position and rewards (read-only, no wallet needed) walletconnect-staking status --address=0x... # Check WCT balance walletconnect-staking balance --address=0x... # Claim staking rewards (requires wallet) walletconnect-staking claim # Withdraw all staked WCT (after lock expires) walletconnect-staking unstake ``` ### Programmatic usage [#programmatic-usage-2] ```typescript import { stake, status, balance, fetchStaking, formatWCT } from "@walletconnect/staking-cli"; ``` The staking package exports transaction builders, formatting utilities, and API helpers for building custom staking integrations. --- ## Agent Skills [#agent-skills] Install the accompanying Claude Code / agent skills: ```bash npx skills add WalletConnect/agent-sdk ``` This adds the `walletconnect-pay`, `walletconnect`, and `walletconnect-staking` skills to your Claude Code environment, enabling AI agents to interact with wallets and payments directly from the terminal. ## Source [#source] } href="https://github.com/walletconnect/agent-sdk"> View the source, file issues, and contribute on GitHub. # TON Connect WalletConnect Integration (/apps/guides/tonconnect-walletconnect) This guide explains how to enable WalletConnect support in your [TON Connect](https://www.npmjs.com/package/@tonconnect/sdk) application, allowing users to connect with WalletConnect-compatible wallets. ## Prerequisites [#prerequisites] Before enabling WalletConnect in your TON Connect application, ensure you have the following: ### 1. TON Connect Project [#1-ton-connect-project] You should have an existing TON Connect project initialized with the [@tonconnect/sdk](https://www.npmjs.com/package/@tonconnect/sdk) package. If you haven't set up TON Connect yet, please refer to the [TON Connect documentation](https://docs.ton.org/develop/dapps/ton-connect/overview) to get started. ### 2. WalletConnect Project ID [#2-walletconnect-project-id] Create a new project on the WalletConnect Dashboard at https://dashboard.walletconnect.com and obtain a new project ID. You will need this project ID to initialize WalletConnect in your application. ### 3. Allowlist Your Domains [#3-allowlist-your-domains] To help prevent malicious use of your project ID, you are strongly encouraged to set an allowlist of [origins](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin) where your project ID is used. You can manage your allowlist in the [WalletConnect Dashboard](https://dashboard.walletconnect.com) under the project settings. The allowlist supports a list of origins in the format `[scheme://]`. Using `localhost` (or `127.0.0.1`) is always permitted, and if the allowlist is empty, all origins are allowed. Updates take 15 minutes to apply. Examples of possible origins in the allowlist: - `example.com` - allows `https://example.com` or `http://example.com` but not `https://www.example.com` - `https://example.com` - allows `https://example.com` but not `http://example.com` - `https://*.example.com` - allows `https://www.example.com` but not `https://example.com` Requests from origins not in the allowlist will be denied. Make sure to add all domains where your app will be deployed. ## Enable WalletConnect [#enable-walletconnect] To enable WalletConnect in your TON Connect application, use the `initializeWalletConnect()` function from the `@tonconnect/sdk` package along with the `UniversalConnector` from `@reown/appkit-universal-connector`. ```typescript import { initializeWalletConnect } from '@tonconnect/sdk'; import { UniversalConnector } from '@reown/appkit-universal-connector'; initializeWalletConnect(UniversalConnector, { projectId: 'YOUR_PROJECT_ID', metadata: { name: 'My DApp', description: 'My awesome DApp', url: 'https://mydapp.com', icons: ['https://mydapp.com/icon.png'] } }); ``` ### Configuration Options [#configuration-options] The `initializeWalletConnect` function accepts the following configuration options: | Option | Type | Required | Description | |--------|------|----------|-------------| | `projectId` | `string` | Yes | Your WalletConnect project ID from the [Dashboard](https://dashboard.walletconnect.com) | | `metadata.name` | `string` | Yes | The name of your application | | `metadata.description` | `string` | Yes | A brief description of your application | | `metadata.url` | `string` | Yes | The URL of your application | | `metadata.icons` | `string[]` | Yes | An array of icon URLs for your application | ### Example Implementation [#example-implementation] Here's a complete example of integrating WalletConnect into a TON Connect application: ```typescript import { TonConnect } from '@tonconnect/sdk'; import { initializeWalletConnect } from '@tonconnect/sdk'; import { UniversalConnector } from '@reown/appkit-universal-connector'; import { TonConnectUIProvider, TonConnectButton, } from '@tonconnect/ui-react'; // Initialize WalletConnect support initializeWalletConnect(UniversalConnector, { projectId: 'YOUR_PROJECT_ID', metadata: { name: 'My TON DApp', description: 'A decentralized application on TON', url: 'https://mytonapp.com', icons: ['https://mytonapp.com/icon.png'] } }); export function App() { // Create TON Connect instance const tonConnect = new TonConnect({ manifestUrl: 'https://mytonapp.com/tonconnect-manifest.json' }); return (

WalletConnect + TON React Example

) } ``` ## Handling `ton_proof` [#handling-ton_proof] When using TON Connect with WalletConnect, `ton_proof` is requested and returned as part of the connection response using the [CAIP-222](https://chainagnostic.org/CAIPs/caip-222) authentication flow. The proof payload is passed via the `authentication` parameter during `connect()`, and the signed proof is available on `session.authentication` after the connection is established. ### Requesting `ton_proof` During Connection [#requesting-ton_proof-during-connection] To request `ton_proof` during the WalletConnect session establishment, pass the `authentication` parameter when calling `connect()` on the underlying `UniversalConnector` provider: ```typescript import { UniversalConnector } from '@reown/appkit-universal-connector'; const connector = await UniversalConnector.init({ projectId: 'YOUR_PROJECT_ID', metadata: { name: 'My TON DApp', description: 'A decentralized application on TON', url: 'https://mytonapp.com', icons: ['https://mytonapp.com/icon.png'] }, networks: [{ namespace: 'ton', chains: [tonMainnet], methods: ['ton_sendMessage', 'ton_signData'], events: [] }] }); const session = await connector.provider.connect({ optionalNamespaces: { ton: { methods: ['ton_sendMessage', 'ton_signData'], chains: ['ton:-239'], events: [] } }, authentication: [{ uri: 'https://mytonapp.com', domain: 'mytonapp.com', chains: ['ton:-239'], nonce: '', ttl: 86400, statement: '' }] }); ``` ### Reading the Proof Result [#reading-the-proof-result] After a successful connection, the proof result is available on `session.authentication` as an array of [CAIP-222 Cacao](https://chainagnostic.org/CAIPs/caip-222) objects: ```typescript const authenticationResults = session?.authentication; if (authenticationResults && authenticationResults.length > 0) { // Each result is a Cacao object containing the signed proof const proof = authenticationResults[0]; console.log('ton_proof result:', proof); } ``` The `ton_proof` result is **not** available in `onStatusChange` when using WalletConnect. You must read it from `session.authentication` directly after the connection is established. ## Next Steps [#next-steps] After integrating WalletConnect into your TON Connect application, users will be able to connect using any WalletConnect-compatible wallet. For more information about TON-specific RPC methods supported by WalletConnect, see the [TON Chain Support](/wallets/chains/ton) documentation. # WalletConnect for Apps (/apps) ## **Your Gateway to the WalletConnect Network** [#your-gateway-to-the-walletconnect-network] **We highly recommend using one of our SDK partners to integrate WalletConnect into your app.** The **WalletConnect App SDK** is the foundational gateway for apps to access the **WalletConnect Network,** the decentralized connectivity layer for the financial internet. With a single integration, developers can connect to **700+ wallets** and **65,000+ apps** across **EVM, Solana, Bitcoin**, and **any network with a CAIP-25 namespace**, while preserving privacy, composability, and user choice. **Built on open standards** and powered by a decentralized relay network, WalletConnect unlocks secure and cross-chain wallet connections for apps across devices and platforms. Whether you’re building for DeFi, gaming, payments, or identity, WalletConnect provides the essential building block for **trusted wallet-to-app experiences**, all backed by the **infrastructure that powers the financial internet**. ## **Powering leading SDKs across Web3** [#powering-leading-sdks-across-web3] The WalletConnect App SDK is already embedded in some of the most widely-used SDKs in the ecosystem - powering everything from onboarding to payments. ## **Who is it for?** [#who-is-it-for] - **App developers** who want to connect wallets quickly and securely - **SDK builders** who want a powerful foundation for wallet connectivity - **Web3 platforms** scaling across chains and wallets If your product needs to talk to wallets, the App SDK is your starting point. ## What does WalletConnect have to offer for Apps? [#what-does-walletconnect-have-to-offer-for-apps] At its core, the WalletConnect handles the most critical UX layer of any onchain app: **wallet connection**. ✅ **Prebuilt modal UX** for connecting wallets ✅ **Chain-agnostic support** across EVM, Solana, Bitcoin, and more ✅ **Built-in compatibility** with 500+ wallets ✅ **Native, embedded UI** - no iframes, no redirects ✅ **Customizable and composable** - use standalone or extend with your own flows It’s the fastest way to build reliable wallet connectivity, with none of the versioning, RPC mismatches, or fragmented logic that plague homegrown solutions. ## Demo [#demo] --- ## How to Integrate WalletConnect into your App [#how-to-integrate-walletconnect-into-your-app] There are **two core pathways to integrate WalletConnect** into your app: 1. Via an SDK partner that has already integrated WalletConnect into their SDK. 2. Standalone integration of WalletConnect. Below, you can find instructions and information for both pathways. ## Integrate WalletConnect via an SDK Partner [#integrate-walletconnect-via-an-sdk-partner] First, we need to cover what exactly is an SDK and how projects can use them to integrate WalletConnect into their app. ### What is an SDK? [#what-is-an-sdk] An SDK is a software development kit that provides a set of tools, libraries, and documentation for developers to build applications. It is a collection of code, tools, and resources that help developers build applications faster and easier. In this context, SDKs are pre-packaged developer tools that abstract away the underlying protocol, i.e. WalletConnect, and provide a simplified integration path for apps and wallets, making wallet connectivity fast, reliable, and developer-friendly. ### 🛠 Most Popular SDKs built on top of WalletConnect [#-most-popular-sdks-built-on-top-of-walletconnect] - [**Reown AppKit**](https://reown.com/appkit) - A modular UX engine for onboarding, payments, and wallet interaction. Used in 286M+ sessions and 10B+ RPC calls . - [**Privy**](https://www.privy.io/) - Secure wallet infrastructure that simplifies identity, session handling, and embedded wallets. - [**Dynamic**](https://www.dynamic.xyz/) - All-in-one authentication and wallet SDK for web3 apps across mobile and web. - [**ConnectKit**](https://family.co/connectkit) - Beautiful React components built for WalletConnect connections. - [**RainbowKit**](https://www.rainbowkit.com/) - Customizable wallet connection UI optimized for Ethereum and WalletConnect. - [**Canton dApp SDK**](https://github.com/hyperledger-labs/splice-wallet-kernel/tree/main/sdk/dapp-sdk) - Browser SDK from the [Splice Wallet Kernel](https://github.com/hyperledger-labs/splice-wallet-kernel) for building dApps on the [Canton Network](https://www.canton.network/). Implements the [CIP-103](https://github.com/canton-foundation/cips/blob/main/cip-0103/cip-0103.md) dApp API with multi-transport support (HTTP, `postMessage`) and an EIP-1193-style `window.canton` provider. These SDKs demonstrate what’s possible with the App SDK as a base layer and how it can be extended to suit your product, stack, and user flow. ### SDK Chain Compatibility [#sdk-chain-compatibility] Below you can find the chain compatibility for the most popular SDKs built on top of WalletConnect. | SDK | Networks / Chains Supported | |------------------|----------------------------------------------------| | **Reown AppKit** | EVM, Solana, Bitcoin, Polkadot, Cosmos and all other networks with a CAIP-25 namespace | | **Privy** | EVM, Solana, Bitcoin | | **Dynamic** | EVM, Solana, Bitcoin, Flow, StarkNet, Sui, Cosmos, Algorand, Spark | | **ConnectKit** | EVM | | **RainbowKit** | EVM | | **Canton dApp SDK** | Canton Network | ## Standalone Integration of WalletConnect as an App [#standalone-integration-of-walletconnect-as-an-app] If you do not wish to use an SDK partner, you can integrate WalletConnect directly into your app. Please refer to the corresponding installation guide for each framework given below. } href="/apps/react/installation"> Get started with WalletConnect as an App in React. } href="/apps/next/installation"> Get started with WalletConnect as an App in Next.js. } href="/apps/vue/installation"> Get started with WalletConnect as an App in Vue. } href="/apps/javascript/installation"> Get started with WalletConnect as an App in JavaScript. ### Chains Supported by WalletConnect [#chains-supported-by-walletconnect] Please refer to the [Chains Supported](https://docs.reown.com/cloud/chains/chain-list) page for the list of chains supported by WalletConnect. ### RPCs and Chain Specific Methods [#rpcs-and-chain-specific-methods] Please refer to the **RPC Reference** dropdown under the [Multi-Chain](https://docs.reown.com/advanced/multichain/rpc-reference/) section for the list of RPCs and chain specific methods supported by WalletConnect. # Installation (/apps/javascript/installation) WalletConnect App SDK is chain agnostic and provides seamless integration with several blockchain ecosystems. WalletConnect App SDK when combined with Universal Provider library enables compatibility across any blockchain protocol. ## Pre-requisites [#pre-requisites] This section is to inform you about the pre-requisites for integrating WalletConnect as an App with JavaScript (vanilla JS). ### Cloud Configuration [#cloud-configuration] Create a new project on WalletConnect Dashboard at https://dashboard.walletconnect.com and obtain a new project ID. You will need this project ID to initialize WalletConnect in your project (app). ### Allowlist [#allowlist] To help prevent malicious use of your project ID, you are strongly encouraged to set an allowlist of [origins](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin) where your project ID is used. You can manage your allowlist in the [WalletConnect Dashboard](https://dashboard.walletconnect.com) under the project settings. The allowlist supports a list of origins in the format `[scheme://]`. Using `localhost` (or `127.0.0.1`) is always permitted, and if the allowlist is empty, all origins are allowed. Updates take 15 minutes to apply. Examples of possible origins in the allowlist: - `example.com` - allows `https://example.com` or `http://example.com` but not `https://www.example.com` - `https://example.com` - allows `https://example.com` but not `http://example.com` - `https://*.example.com` - allows `https://www.example.com` but not `https://example.com` Requests from origins not in the allowlist will be denied. Make sure to add all domains where your app will be deployed. ## Installation [#installation] ```bash tab="npm" npm install @reown/appkit @reown/appkit-universal-connector @reown/appkit-common ethers ``` ```bash tab="Yarn" yarn add @reown/appkit @reown/appkit-universal-connector @reown/appkit-common ethers ``` ```bash tab="Bun" bun add @reown/appkit @reown/appkit-universal-connector @reown/appkit-common ethers ``` ```bash tab="pnpm" pnpm add @reown/appkit @reown/appkit-universal-connector @reown/appkit-common ethers ``` ## Implementation [#implementation] Here is a sample implementation of WalletConnect App SDK with JavaScript. You can also check the example repository below. } href="https://github.com/reown-com/appkit-web-examples/tree/main/javascript/javascript-core-universal-connector"> Check the WalletConnect App SDK JavaScript example For a quick integration of WalletConnect App SDK you can use the `UniversalConnector` class. Which simplifies the integration of WalletConnect App SDK by providing a single interface for all the blockchain protocols. You can configure the Universal Connector with the networks you want to support. For more information, please visit [RPC Reference](https://docs.reown.com/advanced/multichain/rpc-reference/cosmos-rpc) section from our docs. We recommend creating a config file to establish a singleton instance for the Universal Connector: ```tsx tab="Generic Example" import { UniversalConnector } from '@reown/appkit-universal-connector' export const projectId = import.meta.env.VITE_PROJECT_ID || "YOUR_PROJECT_ID_HERE" // Replace with your actual project ID if (!projectId || projectId === "YOUR_PROJECT_ID_HERE") { throw new Error('Project ID is not defined. Please set your project ID from the WalletConnect Dashboard.') } // you can configure your own network const suiMainnet = { id: 784, chainNamespace: 'sui', caipNetworkId: 'sui:mainnet', name: 'Sui', nativeCurrency: { name: 'SUI', symbol: 'SUI', decimals: 9 }, rpcUrls: { default: { http: ['https://fullnode.mainnet.sui.io:443'] } } } export const networks = [suiMainnet] export let universalConnector export async function getUniversalConnector() { if (!universalConnector) { universalConnector = await UniversalConnector.init({ projectId, metadata: { name: 'Universal Connector', description: 'Universal Connector', url: 'https://www.walletconnect.com', icons: ['https://www.walletconnect.com/icon.png'] }, networks: [ { methods: ['sui_signPersonalMessage'], chains: [suiMainnet], events: [], namespace: 'sui' } ] }) } return universalConnector } ``` ```tsx tab="Stacks Example" import { UniversalConnector } from '@reown/appkit-universal-connector' export const projectId = import.meta.env.VITE_PROJECT_ID || "YOUR_PROJECT_ID_HERE" // Replace with your actual project ID if (!projectId || projectId === "YOUR_PROJECT_ID_HERE") { throw new Error('Project ID is not defined. Please set your project ID from the WalletConnect Dashboard.') } // you can configure your own network const stacksMainnet = { id: 'stacks-mainnet', chainNamespace: 'stacks', caipNetworkId: 'stacks:1', name: 'Stacks Mainnet', nativeCurrency: { name: 'STX', symbol: 'STX', decimals: 6 }, rpcUrls: { default: { http: ['https://stacks-node-api.mainnet.stacks.co'] } } // Example Stacks Mainnet RPC URL } export const networks = [stacksMainnet] export let universalConnector export async function getUniversalConnector() { if (!universalConnector) { universalConnector = await UniversalConnector.init({ projectId, metadata: { name: 'Universal Connector', description: 'Universal Connector', url: 'https://www.walletconnect.com', icons: ['https://www.walletconnect.com/icon.png'] }, networks: [ { methods: ['stx_signMessage', 'stx_signTransaction', 'stx_getAccounts', 'stx_getAddresses', 'stx_callContract', 'stx_deployContract', 'sendTransfer', 'getAddresses'], chains: [stacksMainnet], events: ['stx_chainChanged', 'stx_accountsChanged'], namespace: 'stacks' } ] }) } return universalConnector } ``` ```tsx tab="TON Example" import type { AppKitNetwork } from '@reown/appkit/networks' import type { CustomCaipNetwork } from '@reown/appkit-common' import { UniversalConnector } from '@reown/appkit-universal-connector' // Get projectId from https://dashboard.walletconnect.com export const projectId = import.meta.env.VITE_PROJECT_ID || "YOUR_PROJECT_ID_HERE" // Replace with your actual project ID if (!projectId || projectId === "YOUR_PROJECT_ID_HERE") { throw new Error('Project ID is not defined. Please set your project ID from the WalletConnect Dashboard.') } const tonMainnet: CustomCaipNetwork<'ton'> = { id: -239, chainNamespace: 'ton' as const, caipNetworkId: 'ton:-239', name: 'TON', nativeCurrency: { name: 'TON', symbol: 'TON', decimals: 9 }, rpcUrls: { default: { http: ['https://toncenter.com/api/v2/jsonRPC'] } } } export const networks = [tonMainnet] as [AppKitNetwork, ...AppKitNetwork[]] export async function getUniversalConnector() { const universalConnector = await UniversalConnector.init({ projectId, metadata: { name: 'Universal Connector', description: 'Universal Connector', url: 'https://www.walletconnect.com', icons: ['https://www.walletconnect.com/icon.png'] }, networks: [ { methods: ['ton_signData'], chains: [tonMainnet as CustomCaipNetwork], events: [], namespace: 'ton' } ] }) return universalConnector } ``` ```tsx tab="TRON Example" import { UniversalConnector } from '@reown/appkit-universal-connector' export const projectId = import.meta.env.VITE_PROJECT_ID || "YOUR_PROJECT_ID_HERE" // Replace with your actual project ID if (!projectId || projectId === "YOUR_PROJECT_ID_HERE") { throw new Error('Project ID is not defined. Please set your project ID from the WalletConnect Dashboard.') } const tronMainnet = { id: '0x2b6653dc', chainNamespace: 'tron', caipNetworkId: 'tron:0x2b6653dc', name: 'Tron Mainnet', nativeCurrency: { name: 'TRX', symbol: 'TRX', decimals: 6 }, rpcUrls: { default: { http: ['https://api.trongrid.io'] } } } export const networks = [tronMainnet] export let universalConnector export async function getUniversalConnector() { if (!universalConnector) { universalConnector = await UniversalConnector.init({ projectId, metadata: { name: 'Universal Connector', description: 'Universal Connector', url: 'https://www.walletconnect.com', icons: ['https://www.walletconnect.com/icon.png'] }, networks: [ { methods: ['tron_signTransaction', 'tron_signMessage'], chains: [tronMainnet], events: [], namespace: 'tron' } ] }) } return universalConnector } ``` In the main.js file you can add: ```tsx import { getUniversalConnector } from './config/appKit.js' async function setup() { const universalConnector = await getUniversalConnector() // check if session is already connected if (universalConnector?.provider.session) { session = universalConnector?.provider.session } } setup() ``` ## Trigger the modal [#trigger-the-modal] To open the WalletConnect modal you need to call the `connect` function from the Universal Connector. For more information, please visit [RPC Reference](https://docs.reown.com/advanced/multichain/rpc-reference/cosmos-rpc) section from our docs. ```tsx ....
``` ## Smart Contract Interaction [#smart-contract-interaction] [Wagmi hooks](https://wagmi.sh/react/api/hooks/useReadContract) can help us interact with wallets and smart contracts: ```tsx import { useReadContract } from "wagmi"; import { USDTAbi } from "../abi/USDTAbi"; const USDTAddress = "0x..."; function App() { const result = useReadContract({ abi: USDTAbi, address: USDTAddress, functionName: "totalSupply", }); } ``` Read more about Wagmi hooks for smart contract interaction [here](https://wagmi.sh/react/hooks/useReadContract). [Ethers](https://docs.ethers.org/v6/) can help us interact with wallets and smart contracts: ```tsx import { useAppKitProvider, useAppKitAccount } from "@reown/appkit/react"; import { BrowserProvider, Contract, formatUnits } from "ethers"; const USDTAddress = "0x617f3112bf5397D0467D315cC709EF968D9ba546"; // The ERC-20 Contract ABI, which is a common contract interface // for tokens (this is the Human-Readable ABI format) const USDTAbi = [ "function name() view returns (string)", "function symbol() view returns (string)", "function balanceOf(address) view returns (uint)", "function transfer(address to, uint amount)", "event Transfer(address indexed from, address indexed to, uint amount)", ]; function Components() { const { address, isConnected } = useAppKitAccount(); const { walletProvider } = useAppKitProvider("eip155"); async function getBalance() { if (!isConnected) throw Error("User disconnected"); const ethersProvider = new BrowserProvider(walletProvider); const signer = await ethersProvider.getSigner(); // The Contract object const USDTContract = new Contract(USDTAddress, USDTAbi, signer); const USDTBalance = await USDTContract.balanceOf(address); console.log(formatUnits(USDTBalance, 18)); } return ; } ``` [@Solana/web3.js](https://solana.com/docs/clients/javascript) library allows for seamless interaction with wallets and smart contracts on the Solana blockchain. For a practical example of how it works, you can refer to our [lab dApp](https://lab.reown.com/appkit/?name=solana). ```tsx import { SystemProgram, PublicKey, Keypair, Transaction, TransactionInstruction, LAMPORTS_PER_SOL } from '@solana/web3.js' import { useAppKitAccount, useAppKitProvider } from '@reown/appkit/react' import { useAppKitConnection, type Provider } from '@reown/appkit-adapter-solana/react' function deserializeCounterAccount(data?: Buffer): { count: number } { if (data?.byteLength !== 8) { throw Error('Need exactly 8 bytes to deserialize counter') } return { count: Number(data[0]) } } const { address } = useAppKitAccount() const { connection } = useAppKitConnection() const { walletProvider } = useAppKitProvider('solana') async function onIncrementCounter() { const PROGRAM_ID = new PublicKey('Cb5aXEgXptKqHHWLifvXu5BeAuVLjojQ5ypq6CfQj1hy') const counterKeypair = Keypair.generate() const counter = counterKeypair.publicKey const balance = await connection.getBalance(walletProvider.publicKey) if (balance < LAMPORTS_PER_SOL / 100) { throw Error('Not enough SOL in wallet') } const COUNTER_ACCOUNT_SIZE = 8 const allocIx: TransactionInstruction = SystemProgram.createAccount({ fromPubkey: walletProvider.publicKey, newAccountPubkey: counter, lamports: await connection.getMinimumBalanceForRentExemption(COUNTER_ACCOUNT_SIZE), space: COUNTER_ACCOUNT_SIZE, programId: PROGRAM_ID }) const incrementIx: TransactionInstruction = new TransactionInstruction({ programId: PROGRAM_ID, keys: [ { pubkey: counter, isSigner: false, isWritable: true } ], data: Buffer.from([0x0]) }) const tx = new Transaction().add(allocIx).add(incrementIx) tx.feePayer = walletProvider.publicKey tx.recentBlockhash = (await connection.getLatestBlockhash('confirmed')).blockhash await walletProvider.signAndSendTransaction(tx, [counterKeypair]) const counterAccountInfo = await connection.getAccountInfo(counter, { commitment: 'confirmed' }) if (!counterAccountInfo) { throw new Error('Expected counter account to have been created') } const counterAccount = deserializeCounterAccount(counterAccountInfo?.data) if (counterAccount.count !== 1) { throw new Error('Expected count to have been 1') } console.log(`[alloc+increment] count is: ${counterAccount.count}`); } ``` # Installation (/apps/next/installation) WalletConnect App SDK is chain agnostic and provides seamless integration with several blockchain ecosystems. WalletConnect App SDK when combined with Universal Provider library enables compatibility across any blockchain protocol. ## Pre-requisites [#pre-requisites] This section is to inform you about the pre-requisites for integrating WalletConnect as an App with Next.js. ### Cloud Configuration [#cloud-configuration] Create a new project on WalletConnect Dashboard at https://dashboard.walletconnect.com and obtain a new project ID. You will need this project ID to initialize WalletConnect in your project (app). ### Allowlist [#allowlist] To help prevent malicious use of your project ID, you are strongly encouraged to set an allowlist of [origins](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin) where your project ID is used. You can manage your allowlist in the [WalletConnect Dashboard](https://dashboard.walletconnect.com) under the project settings. The allowlist supports a list of origins in the format `[scheme://]`. Using `localhost` (or `127.0.0.1`) is always permitted, and if the allowlist is empty, all origins are allowed. Updates take 15 minutes to apply. Examples of possible origins in the allowlist: - `example.com` - allows `https://example.com` or `http://example.com` but not `https://www.example.com` - `https://example.com` - allows `https://example.com` but not `http://example.com` - `https://*.example.com` - allows `https://www.example.com` but not `https://example.com` Requests from origins not in the allowlist will be denied. Make sure to add all domains where your app will be deployed. ## Installation [#installation] ```bash tab="npm" npm install @reown/appkit @reown/appkit-universal-connector @reown/appkit-common ethers ``` ```bash tab="Yarn" yarn add @reown/appkit @reown/appkit-universal-connector @reown/appkit-common ethers ``` ```bash tab="Bun" bun add @reown/appkit @reown/appkit-universal-connector @reown/appkit-common ethers ``` ```bash tab="pnpm" pnpm add @reown/appkit @reown/appkit-universal-connector @reown/appkit-common ethers ``` ## Implementation [#implementation] For a quick integration of WalletConnect App SDK you can use the `UniversalConnector` class. Which simplifies the integration of WalletConnect App SDK by providing a single interface for all the blockchain protocols. You can configure the Universal Connector with the networks you want to support. For more information, please visit [RPC Reference](https://docs.reown.com/advanced/multichain/rpc-reference/cosmos-rpc) section from our docs. We recommend creating a config file to establish a singleton instance for the Universal Connector: ```tsx tab="Generic Example" import type { AppKitNetwork } from '@reown/appkit/networks' import type { CustomCaipNetwork } from '@reown/appkit-common' import { UniversalConnector } from '@reown/appkit-universal-connector' // Get projectId from https://dashboard.walletconnect.com export const projectId = import.meta.env.VITE_PROJECT_ID || "YOUR_PROJECT_ID_HERE" // Replace with your actual project ID if (!projectId || projectId === "YOUR_PROJECT_ID_HERE") { throw new Error('Project ID is not defined. Please set your project ID from the WalletConnect Dashboard.') } // you can configure your own network const suiMainnet: CustomCaipNetwork<'sui'> = { id: 784, chainNamespace: 'sui' as const, caipNetworkId: 'sui:mainnet', name: 'Sui', nativeCurrency: { name: 'SUI', symbol: 'SUI', decimals: 9 }, rpcUrls: { default: { http: ['https://fullnode.mainnet.sui.io:443'] } } } export const networks = [suiMainnet] as [AppKitNetwork, ...AppKitNetwork[]] export async function getUniversalConnector() { const universalConnector = await UniversalConnector.init({ projectId, metadata: { name: 'Universal Connector', description: 'Universal Connector', url: 'https://www.walletconnect.com', icons: ['https://www.walletconnect.com/icon.png'] }, networks: [ { methods: ['sui_signPersonalMessage'], chains: [suiMainnet as CustomCaipNetwork], events: [], namespace: 'sui' } ] }) return universalConnector } ``` ```tsx tab="Stacks Example" import type { AppKitNetwork } from '@reown/appkit/networks' import type { InferredCaipNetwork } from '@reown/appkit-common' import { UniversalConnector } from '@reown/appkit-universal-connector' // Get projectId from https://dashboard.walletconnect.com export const projectId = import.meta.env.VITE_PROJECT_ID || "YOUR_PROJECT_ID_HERE" // Replace with your actual project ID if (!projectId || projectId === "YOUR_PROJECT_ID_HERE") { throw new Error('Project ID is not defined. Please set your project ID from the WalletConnect Dashboard.') } // you can configure your own network const stacksMainnet: InferredCaipNetwork = { id: 'stacks-mainnet', chainNamespace: 'stacks' as const, caipNetworkId: 'stacks:1', name: 'Stacks Mainnet', nativeCurrency: { name: 'STX', symbol: 'STX', decimals: 6 }, rpcUrls: { default: { http: ['https://stacks-node-api.mainnet.stacks.co'] } } // Example Stacks Mainnet RPC URL } export const networks = [stacksMainnet] as [AppKitNetwork, ...AppKitNetwork[]] export async function getUniversalConnector() { const universalConnector = await UniversalConnector.init({ projectId, metadata: { name: 'Universal Connector', description: 'Universal Connector', url: 'https://www.walletconnect.com', icons: ['https://www.walletconnect.com/icon.png'] }, networks: [ { methods: ['stx_signMessage', 'stx_signTransaction', 'stx_getAccounts', 'stx_getAddresses', 'stx_callContract', 'stx_deployContract', 'sendTransfer', 'getAddresses'], chains: [stacksMainnet as InferredCaipNetwork], events: ['stx_chainChanged', 'stx_accountsChanged'], namespace: 'stacks' } ] }) return universalConnector } ``` ```tsx tab="TON Example" import type { AppKitNetwork } from '@reown/appkit/networks' import type { CustomCaipNetwork } from '@reown/appkit-common' import { UniversalConnector } from '@reown/appkit-universal-connector' // Get projectId from https://dashboard.walletconnect.com export const projectId = import.meta.env.VITE_PROJECT_ID || "YOUR_PROJECT_ID_HERE" // Replace with your actual project ID if (!projectId || projectId === "YOUR_PROJECT_ID_HERE") { throw new Error('Project ID is not defined. Please set your project ID from the WalletConnect Dashboard.') } const tonMainnet: CustomCaipNetwork<'ton'> = { id: -239, chainNamespace: 'ton' as const, caipNetworkId: 'ton:-239', name: 'TON', nativeCurrency: { name: 'TON', symbol: 'TON', decimals: 9 }, rpcUrls: { default: { http: ['https://toncenter.com/api/v2/jsonRPC'] } } } export const networks = [tonMainnet] as [AppKitNetwork, ...AppKitNetwork[]] export async function getUniversalConnector() { const universalConnector = await UniversalConnector.init({ projectId, metadata: { name: 'Universal Connector', description: 'Universal Connector', url: 'https://www.walletconnect.com', icons: ['https://www.walletconnect.com/icon.png'] }, networks: [ { methods: ['ton_signData'], chains: [tonMainnet as CustomCaipNetwork], events: [], namespace: 'ton' } ] }) return universalConnector } ``` ```tsx tab="TRON Example" import type { AppKitNetwork } from '@reown/appkit/networks' import type { CustomCaipNetwork } from '@reown/appkit-common' import { UniversalConnector } from '@reown/appkit-universal-connector' // Get projectId from https://dashboard.walletconnect.com export const projectId = import.meta.env.VITE_PROJECT_ID || "YOUR_PROJECT_ID_HERE" // Replace with your actual project ID if (!projectId || projectId === "YOUR_PROJECT_ID_HERE") { throw new Error('Project ID is not defined. Please set your project ID from the WalletConnect Dashboard.') } const tronMainnet: CustomCaipNetwork<'tron'> = { id: '0x2b6653dc', chainNamespace: 'tron' as const, caipNetworkId: 'tron:0x2b6653dc', name: 'Tron Mainnet', nativeCurrency: { name: 'TRX', symbol: 'TRX', decimals: 6 }, rpcUrls: { default: { http: ['https://api.trongrid.io'] } } } export const networks = [tronMainnet] as [AppKitNetwork, ...AppKitNetwork[]] export async function getUniversalConnector() { const universalConnector = await UniversalConnector.init({ projectId, metadata: { name: 'Universal Connector', description: 'Universal Connector', url: 'https://www.walletconnect.com', icons: ['https://www.walletconnect.com/icon.png'] }, networks: [ { methods: ['tron_signTransaction', 'tron_signMessage'], chains: [tronMainnet as CustomCaipNetwork], events: [], namespace: 'tron' } ] }) return universalConnector } ``` In the App.tsx file you can add : ```tsx import { useState, useEffect } from 'react' import { getUniversalConnector } from './config' // previous config file import { UniversalConnector } from '@reown/appkit-universal-connector' export function App() { const [universalConnector, setUniversalConnector] = useState() const [session, setSession] = useState() // Initialize the Universal Connector on component mount useEffect(() => { getUniversalConnector().then(setUniversalConnector) }, []) // Set the session state in case it changes useEffect(() => { setSession(universalConnector?.provider.session) }, [universalConnector?.provider.session]) ``` ## Trigger the modal [#trigger-the-modal] To open the WalletConnect modal you need to call the `connect` function from the Universal Connector. ```tsx // get the session from the universal connector const handleConnect = async () => { if (!universalConnector) { return } const { session: providerSession } = await universalConnector.connect() setSession(providerSession) }; // disconnect the universal connector const handleDisconnect = async () => { if (!universalConnector) { return } await universalConnector.disconnect() setSession(null) }; ... return ( (
) ``` ## Smart Contract Interaction [#smart-contract-interaction] [Wagmi hooks](https://wagmi.sh/react/api/hooks/useReadContract) can help us interact with wallets and smart contracts: ```tsx import { useReadContract } from "wagmi"; import { USDTAbi } from "../abi/USDTAbi"; const USDTAddress = "0x..."; function App() { const result = useReadContract({ abi: USDTAbi, address: USDTAddress, functionName: "totalSupply", }); } ``` Read more about Wagmi hooks for smart contract interaction [here](https://wagmi.sh/react/hooks/useReadContract). [Ethers](https://docs.ethers.org/v6/) can help us interact with wallets and smart contracts: ```tsx import { useAppKitProvider, useAppKitAccount } from "@reown/appkit/react"; import { BrowserProvider, Contract, formatUnits } from "ethers"; const USDTAddress = "0x617f3112bf5397D0467D315cC709EF968D9ba546"; // The ERC-20 Contract ABI, which is a common contract interface // for tokens (this is the Human-Readable ABI format) const USDTAbi = [ "function name() view returns (string)", "function symbol() view returns (string)", "function balanceOf(address) view returns (uint)", "function transfer(address to, uint amount)", "event Transfer(address indexed from, address indexed to, uint amount)", ]; function Components() { const { address, isConnected } = useAppKitAccount(); const { walletProvider } = useAppKitProvider("eip155"); async function getBalance() { if (!isConnected) throw Error("User disconnected"); const ethersProvider = new BrowserProvider(walletProvider); const signer = await ethersProvider.getSigner(); // The Contract object const USDTContract = new Contract(USDTAddress, USDTAbi, signer); const USDTBalance = await USDTContract.balanceOf(address); console.log(formatUnits(USDTBalance, 18)); } return ; } ``` [@Solana/web3.js](https://solana.com/docs/clients/javascript) library allows for seamless interaction with wallets and smart contracts on the Solana blockchain. For a practical example of how it works, you can refer to our [lab dApp](https://lab.reown.com/appkit/?name=solana). ```tsx import { SystemProgram, PublicKey, Keypair, Transaction, TransactionInstruction, LAMPORTS_PER_SOL } from '@solana/web3.js' import { useAppKitAccount, useAppKitProvider } from '@reown/appkit/react' import { useAppKitConnection, type Provider } from '@reown/appkit-adapter-solana/react' function deserializeCounterAccount(data?: Buffer): { count: number } { if (data?.byteLength !== 8) { throw Error('Need exactly 8 bytes to deserialize counter') } return { count: Number(data[0]) } } const { address } = useAppKitAccount() const { connection } = useAppKitConnection() const { walletProvider } = useAppKitProvider('solana') async function onIncrementCounter() { const PROGRAM_ID = new PublicKey('Cb5aXEgXptKqHHWLifvXu5BeAuVLjojQ5ypq6CfQj1hy') const counterKeypair = Keypair.generate() const counter = counterKeypair.publicKey const balance = await connection.getBalance(walletProvider.publicKey) if (balance < LAMPORTS_PER_SOL / 100) { throw Error('Not enough SOL in wallet') } const COUNTER_ACCOUNT_SIZE = 8 const allocIx: TransactionInstruction = SystemProgram.createAccount({ fromPubkey: walletProvider.publicKey, newAccountPubkey: counter, lamports: await connection.getMinimumBalanceForRentExemption(COUNTER_ACCOUNT_SIZE), space: COUNTER_ACCOUNT_SIZE, programId: PROGRAM_ID }) const incrementIx: TransactionInstruction = new TransactionInstruction({ programId: PROGRAM_ID, keys: [ { pubkey: counter, isSigner: false, isWritable: true } ], data: Buffer.from([0x0]) }) const tx = new Transaction().add(allocIx).add(incrementIx) tx.feePayer = walletProvider.publicKey tx.recentBlockhash = (await connection.getLatestBlockhash('confirmed')).blockhash await walletProvider.signAndSendTransaction(tx, [counterKeypair]) const counterAccountInfo = await connection.getAccountInfo(counter, { commitment: 'confirmed' }) if (!counterAccountInfo) { throw new Error('Expected counter account to have been created') } const counterAccount = deserializeCounterAccount(counterAccountInfo?.data) if (counterAccount.count !== 1) { throw new Error('Expected count to have been 1') } console.log(`[alloc+increment] count is: ${counterAccount.count}`); } ``` # Installation (/apps/react/installation) WalletConnect App SDK is chain agnostic and provides seamless integration with several blockchain ecosystems. WalletConnect App SDK when combined with Universal Provider library enables compatibility across any blockchain protocol. ## Pre-requisites [#pre-requisites] This section is to inform you about the pre-requisites for integrating WalletConnect as an App with React. ### Cloud Configuration [#cloud-configuration] Create a new project on WalletConnect Dashboard at https://dashboard.walletconnect.com and obtain a new project ID. You will need this project ID to initialize WalletConnect in your project (app). ### Allowlist [#allowlist] To help prevent malicious use of your project ID, you are strongly encouraged to set an allowlist of [origins](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin) where your project ID is used. You can manage your allowlist in the [WalletConnect Dashboard](https://dashboard.walletconnect.com) under the project settings. The allowlist supports a list of origins in the format `[scheme://]`. Using `localhost` (or `127.0.0.1`) is always permitted, and if the allowlist is empty, all origins are allowed. Updates take 15 minutes to apply. Examples of possible origins in the allowlist: - `example.com` - allows `https://example.com` or `http://example.com` but not `https://www.example.com` - `https://example.com` - allows `https://example.com` but not `http://example.com` - `https://*.example.com` - allows `https://www.example.com` but not `https://example.com` Requests from origins not in the allowlist will be denied. Make sure to add all domains where your app will be deployed. ## Installation [#installation] If you are setting up your React app, please **do not use** `npx create-react-app`, as it has been deprecated. Using it may cause dependency issues. Instead, please use [Vite](https://vitejs.dev/guide/#scaffolding-your-first-vite-project) to create your React app. You can set it up by running `npm create vite@latest`. ```bash tab="npm" npm install @reown/appkit @reown/appkit-universal-connector @reown/appkit-common ethers ``` ```bash tab="Yarn" yarn add @reown/appkit @reown/appkit-universal-connector @reown/appkit-common ethers ``` ```bash tab="Bun" bun add @reown/appkit @reown/appkit-universal-connector @reown/appkit-common ethers ``` ```bash tab="pnpm" pnpm add @reown/appkit @reown/appkit-universal-connector @reown/appkit-common ethers ``` ## Implementation [#implementation] Here is a sample implementation of WalletConnect App SDK with React. You can also check the example repository below. } href="https://github.com/reown-com/appkit-web-examples/tree/main/react/react-core-universal-connector"> Check the WalletConnect App SDK React example For a quick integration of WalletConnect App SDK you can use the `UniversalConnector` class. Which simplifies the integration of WalletConnect App SDK by providing a single interface for all the blockchain protocols. You can configure the Universal Connector with the networks you want to support. For more information, please visit [RPC Reference](https://docs.reown.com/advanced/multichain/rpc-reference/cosmos-rpc) section from our docs. We recommend creating a config file to establish a singleton instance for the Universal Connector: ```tsx tab="Generic Example" import type { AppKitNetwork } from '@reown/appkit/networks' import type { CustomCaipNetwork } from '@reown/appkit-common' import { UniversalConnector } from '@reown/appkit-universal-connector' // Get projectId from https://dashboard.walletconnect.com export const projectId = import.meta.env.VITE_PROJECT_ID || "b56e18d47c72ab683b10814fe9495694" // this is a public projectId only to use on localhost if (!projectId) { throw new Error('Project ID is not defined') } // you can configure your own network const suiMainnet: CustomCaipNetwork<'sui'> = { id: 784, chainNamespace: 'sui' as const, caipNetworkId: 'sui:mainnet', name: 'Sui', nativeCurrency: { name: 'SUI', symbol: 'SUI', decimals: 9 }, rpcUrls: { default: { http: ['https://fullnode.mainnet.sui.io:443'] } } } export const networks = [suiMainnet] as [AppKitNetwork, ...AppKitNetwork[]] export async function getUniversalConnector() { const universalConnector = await UniversalConnector.init({ projectId, metadata: { name: 'Universal Connector', description: 'Universal Connector', url: 'https://www.walletconnect.com', icons: ['https://www.walletconnect.com/icon.png'] }, networks: [ { methods: ['sui_signPersonalMessage'], chains: [suiMainnet as CustomCaipNetwork], events: [], namespace: 'sui' } ] }) return universalConnector } ``` ```tsx tab="Stacks Example" import type { AppKitNetwork } from '@reown/appkit/networks' import type { InferredCaipNetwork } from '@reown/appkit-common' import { UniversalConnector } from '@reown/appkit-universal-connector' // Get projectId from https://dashboard.walletconnect.com export const projectId = import.meta.env.VITE_PROJECT_ID || "YOUR_PROJECT_ID_HERE" // Replace with your actual project ID if (!projectId || projectId === "YOUR_PROJECT_ID_HERE") { throw new Error('Project ID is not defined. Please set your project ID from the WalletConnect Dashboard.') } // you can configure your own network const stacksMainnet: InferredCaipNetwork = { id: 'stacks-mainnet', chainNamespace: 'stacks' as const, caipNetworkId: 'stacks:1', name: 'Stacks Mainnet', nativeCurrency: { name: 'STX', symbol: 'STX', decimals: 6 }, rpcUrls: { default: { http: ['https://stacks-node-api.mainnet.stacks.co'] } } // Example Stacks Mainnet RPC URL } export const networks = [stacksMainnet] as [AppKitNetwork, ...AppKitNetwork[]] export async function getUniversalConnector() { const universalConnector = await UniversalConnector.init({ projectId, metadata: { name: 'Universal Connector', description: 'Universal Connector', url: 'https://www.walletconnect.com', icons: ['https://www.walletconnect.com/icon.png'] }, networks: [ { methods: ['stx_signMessage', 'stx_signTransaction', 'stx_getAccounts', 'stx_getAddresses', 'stx_callContract', 'stx_deployContract', 'sendTransfer', 'getAddresses'], chains: [stacksMainnet as InferredCaipNetwork], events: ['stx_chainChanged', 'stx_accountsChanged'], namespace: 'stacks' } ] }) return universalConnector } ``` ```tsx tab="TON Example" import type { AppKitNetwork } from '@reown/appkit/networks' import type { CustomCaipNetwork } from '@reown/appkit-common' import { UniversalConnector } from '@reown/appkit-universal-connector' // Get projectId from https://dashboard.walletconnect.com export const projectId = import.meta.env.VITE_PROJECT_ID || "YOUR_PROJECT_ID_HERE" // Replace with your actual project ID if (!projectId || projectId === "YOUR_PROJECT_ID_HERE") { throw new Error('Project ID is not defined. Please set your project ID from the WalletConnect Dashboard.') } const tonMainnet: CustomCaipNetwork<'ton'> = { id: -239, chainNamespace: 'ton' as const, caipNetworkId: 'ton:-239', name: 'TON', nativeCurrency: { name: 'TON', symbol: 'TON', decimals: 9 }, rpcUrls: { default: { http: ['https://toncenter.com/api/v2/jsonRPC'] } } } export const networks = [tonMainnet] as [AppKitNetwork, ...AppKitNetwork[]] export async function getUniversalConnector() { const universalConnector = await UniversalConnector.init({ projectId, metadata: { name: 'Universal Connector', description: 'Universal Connector', url: 'https://www.walletconnect.com', icons: ['https://www.walletconnect.com/icon.png'] }, networks: [ { methods: ['ton_signData'], chains: [tonMainnet as CustomCaipNetwork], events: [], namespace: 'ton' } ] }) return universalConnector } ``` ```tsx tab="TRON Example" import type { AppKitNetwork } from '@reown/appkit/networks' import type { CustomCaipNetwork } from '@reown/appkit-common' import { UniversalConnector } from '@reown/appkit-universal-connector' // Get projectId from https://dashboard.walletconnect.com export const projectId = import.meta.env.VITE_PROJECT_ID || "YOUR_PROJECT_ID_HERE" // Replace with your actual project ID if (!projectId || projectId === "YOUR_PROJECT_ID_HERE") { throw new Error('Project ID is not defined. Please set your project ID from the WalletConnect Dashboard.') } const tronMainnet: CustomCaipNetwork<'tron'> = { id: '0x2b6653dc', chainNamespace: 'tron' as const, caipNetworkId: 'tron:0x2b6653dc', name: 'Tron Mainnet', nativeCurrency: { name: 'TRX', symbol: 'TRX', decimals: 6 }, rpcUrls: { default: { http: ['https://api.trongrid.io'] } } } export const networks = [tronMainnet] as [AppKitNetwork, ...AppKitNetwork[]] export async function getUniversalConnector() { const universalConnector = await UniversalConnector.init({ projectId, metadata: { name: 'Universal Connector', description: 'Universal Connector', url: 'https://www.walletconnect.com', icons: ['https://www.walletconnect.com/icon.png'] }, networks: [ { methods: ['tron_signTransaction', 'tron_signMessage'], chains: [tronMainnet as CustomCaipNetwork], events: [], namespace: 'tron' } ] }) return universalConnector } ``` In the App.tsx file you can add : ```tsx import { useState, useEffect } from 'react' import { getUniversalConnector } from './config' // previous config file import { UniversalConnector } from '@reown/appkit-universal-connector' export function App() { const [universalConnector, setUniversalConnector] = useState() const [session, setSession] = useState() // Initialize the Universal Connector on component mount useEffect(() => { getUniversalConnector().then(setUniversalConnector) }, []) // Set the session state in case it changes useEffect(() => { setSession(universalConnector?.provider.session) }, [universalConnector?.provider.session]) ``` ## Trigger the modal [#trigger-the-modal] To open the WalletConnect modal you need to call the `connect` function from the Universal Connector. ```tsx // get the session from the universal connector const handleConnect = async () => { if (!universalConnector) { return } const { session: providerSession } = await universalConnector.connect() setSession(providerSession) }; // disconnect the universal connector const handleDisconnect = async () => { if (!universalConnector) { return } await universalConnector.disconnect() setSession(null) }; ... return ( (
) ``` ## Smart Contract Interaction [#smart-contract-interaction] [Wagmi hooks](https://wagmi.sh/react/api/hooks/useReadContract) can help us interact with wallets and smart contracts: ```tsx import { useReadContract } from "wagmi"; import { USDTAbi } from "../abi/USDTAbi"; const USDTAddress = "0x..."; function App() { const result = useReadContract({ abi: USDTAbi, address: USDTAddress, functionName: "totalSupply", }); } ``` Read more about Wagmi hooks for smart contract interaction [here](https://wagmi.sh/react/hooks/useReadContract). [Ethers](https://docs.ethers.org/v6/) can help us interact with wallets and smart contracts: ```tsx import { useAppKitProvider, useAppKitAccount } from "@reown/appkit/react"; import { BrowserProvider, Contract, formatUnits } from "ethers"; const USDTAddress = "0x617f3112bf5397D0467D315cC709EF968D9ba546"; // The ERC-20 Contract ABI, which is a common contract interface // for tokens (this is the Human-Readable ABI format) const USDTAbi = [ "function name() view returns (string)", "function symbol() view returns (string)", "function balanceOf(address) view returns (uint)", "function transfer(address to, uint amount)", "event Transfer(address indexed from, address indexed to, uint amount)", ]; function Components() { const { address, isConnected } = useAppKitAccount(); const { walletProvider } = useAppKitProvider("eip155"); async function getBalance() { if (!isConnected) throw Error("User disconnected"); const ethersProvider = new BrowserProvider(walletProvider); const signer = await ethersProvider.getSigner(); // The Contract object const USDTContract = new Contract(USDTAddress, USDTAbi, signer); const USDTBalance = await USDTContract.balanceOf(address); console.log(formatUnits(USDTBalance, 18)); } return ; } ``` [@Solana/web3.js](https://solana.com/docs/clients/javascript) library allows for seamless interaction with wallets and smart contracts on the Solana blockchain. For a practical example of how it works, you can refer to our [lab dApp](https://lab.reown.com/appkit/?name=solana). ```tsx import { SystemProgram, PublicKey, Keypair, Transaction, TransactionInstruction, LAMPORTS_PER_SOL } from '@solana/web3.js' import { useAppKitAccount, useAppKitProvider } from '@reown/appkit/react' import { useAppKitConnection, type Provider } from '@reown/appkit-adapter-solana/react' function deserializeCounterAccount(data?: Buffer): { count: number } { if (data?.byteLength !== 8) { throw Error('Need exactly 8 bytes to deserialize counter') } return { count: Number(data[0]) } } const { address } = useAppKitAccount() const { connection } = useAppKitConnection() const { walletProvider } = useAppKitProvider('solana') async function onIncrementCounter() { const PROGRAM_ID = new PublicKey('Cb5aXEgXptKqHHWLifvXu5BeAuVLjojQ5ypq6CfQj1hy') const counterKeypair = Keypair.generate() const counter = counterKeypair.publicKey const balance = await connection.getBalance(walletProvider.publicKey) if (balance < LAMPORTS_PER_SOL / 100) { throw Error('Not enough SOL in wallet') } const COUNTER_ACCOUNT_SIZE = 8 const allocIx: TransactionInstruction = SystemProgram.createAccount({ fromPubkey: walletProvider.publicKey, newAccountPubkey: counter, lamports: await connection.getMinimumBalanceForRentExemption(COUNTER_ACCOUNT_SIZE), space: COUNTER_ACCOUNT_SIZE, programId: PROGRAM_ID }) const incrementIx: TransactionInstruction = new TransactionInstruction({ programId: PROGRAM_ID, keys: [ { pubkey: counter, isSigner: false, isWritable: true } ], data: Buffer.from([0x0]) }) const tx = new Transaction().add(allocIx).add(incrementIx) tx.feePayer = walletProvider.publicKey tx.recentBlockhash = (await connection.getLatestBlockhash('confirmed')).blockhash await walletProvider.signAndSendTransaction(tx, [counterKeypair]) const counterAccountInfo = await connection.getAccountInfo(counter, { commitment: 'confirmed' }) if (!counterAccountInfo) { throw new Error('Expected counter account to have been created') } const counterAccount = deserializeCounterAccount(counterAccountInfo?.data) if (counterAccount.count !== 1) { throw new Error('Expected count to have been 1') } console.log(`[alloc+increment] count is: ${counterAccount.count}`); } ``` # Installation (/apps/vue/installation) WalletConnect App SDK is chain agnostic and provides seamless integration with several blockchain ecosystems. WalletConnect App SDK when combined with Universal Provider library enables compatibility across any blockchain protocol. ## Pre-requisites [#pre-requisites] This section is to inform you about the pre-requisites for integrating WalletConnect as an App with Vue ### Cloud Configuration [#cloud-configuration] Create a new project on WalletConnect Dashboard at https://dashboard.walletconnect.com and obtain a new project ID. You will need this project ID to initialize WalletConnect in your project (app). ### Allowlist [#allowlist] To help prevent malicious use of your project ID, you are strongly encouraged to set an allowlist of [origins](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin) where your project ID is used. You can manage your allowlist in the [WalletConnect Dashboard](https://dashboard.walletconnect.com) under the project settings. The allowlist supports a list of origins in the format `[scheme://]`. Using `localhost` (or `127.0.0.1`) is always permitted, and if the allowlist is empty, all origins are allowed. Updates take 15 minutes to apply. Examples of possible origins in the allowlist: - `example.com` - allows `https://example.com` or `http://example.com` but not `https://www.example.com` - `https://example.com` - allows `https://example.com` but not `http://example.com` - `https://*.example.com` - allows `https://www.example.com` but not `https://example.com` Requests from origins not in the allowlist will be denied. Make sure to add all domains where your app will be deployed. ## Installation [#installation] ```bash tab="npm" npm install @reown/appkit @reown/appkit-universal-connector @reown/appkit-common ethers ``` ```bash tab="Yarn" yarn add @reown/appkit @reown/appkit-universal-connector @reown/appkit-common ethers ``` ```bash tab="Bun" bun add @reown/appkit @reown/appkit-universal-connector @reown/appkit-common ethers ``` ```bash tab="pnpm" pnpm add @reown/appkit @reown/appkit-universal-connector @reown/appkit-common ethers ``` ## Implementation [#implementation] Here is a sample implementation of WalletConnect App SDK with Vue. You can also check the example repository below. } href="https://github.com/reown-com/appkit-web-examples/tree/main/vue/vue-universal-connector"> Check the WalletConnect App SDK Vue example For a quick integration of WalletConnect App SDK you can use the `UniversalConnector` class. Which simplifies the integration of WalletConnect App SDK by providing a single interface for all the blockchain protocols. You can configure the Universal Connector with the networks you want to support. For more information, please visit [RPC Reference](https://docs.reown.com/advanced/multichain/rpc-reference/cosmos-rpc) section from our docs. We recommend creating a config file to establish a singleton instance for the Universal Connector: ```tsx tab="Generic Example" import type { AppKitNetwork } from '@reown/appkit/networks' import type { CustomCaipNetwork } from '@reown/appkit-common' import { UniversalConnector } from '@reown/appkit-universal-connector' // Get projectId from https://dashboard.walletconnect.com export const projectId = import.meta.env.VITE_PROJECT_ID || "YOUR_PROJECT_ID_HERE" // Replace with your actual project ID if (!projectId || projectId === "YOUR_PROJECT_ID_HERE") { throw new Error('Project ID is not defined. Please set your project ID from the WalletConnect Dashboard.') } const suiMainnet: CustomCaipNetwork<'sui'> = { id: 784, chainNamespace: 'sui' as const, caipNetworkId: 'sui:mainnet', name: 'Sui', nativeCurrency: { name: 'SUI', symbol: 'SUI', decimals: 9 }, rpcUrls: { default: { http: ['https://fullnode.mainnet.sui.io:443'] } } } export const networks = [suiMainnet] as [AppKitNetwork, ...AppKitNetwork[]] export async function getUniversalConnector() { const universalConnector = await UniversalConnector.init({ projectId, metadata: { name: 'Universal Connector', description: 'Universal Connector', url: 'https://www.walletconnect.com', icons: ['https://www.walletconnect.com/icon.png'] }, networks: [ { methods: ['sui_signPersonalMessage'], chains: [suiMainnet as CustomCaipNetwork], events: [], namespace: 'sui' } ] }) return universalConnector } ``` ```tsx tab="Stacks Example" import type { AppKitNetwork } from '@reown/appkit/networks' import type { InferredCaipNetwork } from '@reown/appkit-common' import { UniversalConnector } from '@reown/appkit-universal-connector' // Get projectId from https://dashboard.walletconnect.com export const projectId = import.meta.env.VITE_PROJECT_ID || "YOUR_PROJECT_ID_HERE" // Replace with your actual project ID if (!projectId || projectId === "YOUR_PROJECT_ID_HERE") { throw new Error('Project ID is not defined. Please set your project ID from the WalletConnect Dashboard.') } // you can configure your own network const stacksMainnet: InferredCaipNetwork = { id: 'stacks-mainnet', chainNamespace: 'stacks' as const, caipNetworkId: 'stacks:1', name: 'Stacks Mainnet', nativeCurrency: { name: 'STX', symbol: 'STX', decimals: 6 }, rpcUrls: { default: { http: ['https://stacks-node-api.mainnet.stacks.co'] } } // Example Stacks Mainnet RPC URL } export const networks = [stacksMainnet] as [AppKitNetwork, ...AppKitNetwork[]] export async function getUniversalConnector() { const universalConnector = await UniversalConnector.init({ projectId, metadata: { name: 'Universal Connector', description: 'Universal Connector', url: 'https://www.walletconnect.com', icons: ['https://www.walletconnect.com/icon.png'] }, networks: [ { methods: ['stx_signMessage', 'stx_signTransaction', 'stx_getAccounts', 'stx_getAddresses', 'stx_callContract', 'stx_deployContract', 'sendTransfer', 'getAddresses'], chains: [stacksMainnet as InferredCaipNetwork], events: ['stx_chainChanged', 'stx_accountsChanged'], namespace: 'stacks' } ] }) return universalConnector } ``` ```tsx tab="TON Example" import type { AppKitNetwork } from '@reown/appkit/networks' import type { CustomCaipNetwork } from '@reown/appkit-common' import { UniversalConnector } from '@reown/appkit-universal-connector' // Get projectId from https://dashboard.walletconnect.com export const projectId = import.meta.env.VITE_PROJECT_ID || "YOUR_PROJECT_ID_HERE" // Replace with your actual project ID if (!projectId || projectId === "YOUR_PROJECT_ID_HERE") { throw new Error('Project ID is not defined. Please set your project ID from the WalletConnect Dashboard.') } const tonMainnet: CustomCaipNetwork<'ton'> = { id: -239, chainNamespace: 'ton' as const, caipNetworkId: 'ton:-239', name: 'TON', nativeCurrency: { name: 'TON', symbol: 'TON', decimals: 9 }, rpcUrls: { default: { http: ['https://toncenter.com/api/v2/jsonRPC'] } } } export const networks = [tonMainnet] as [AppKitNetwork, ...AppKitNetwork[]] export async function getUniversalConnector() { const universalConnector = await UniversalConnector.init({ projectId, metadata: { name: 'Universal Connector', description: 'Universal Connector', url: 'https://www.walletconnect.com', icons: ['https://www.walletconnect.com/icon.png'] }, networks: [ { methods: ['ton_signData'], chains: [tonMainnet as CustomCaipNetwork], events: [], namespace: 'ton' } ] }) return universalConnector } ``` ```tsx tab="TRON Example" import type { AppKitNetwork } from '@reown/appkit/networks' import type { CustomCaipNetwork } from '@reown/appkit-common' import { UniversalConnector } from '@reown/appkit-universal-connector' // Get projectId from https://dashboard.walletconnect.com export const projectId = import.meta.env.VITE_PROJECT_ID || "YOUR_PROJECT_ID_HERE" // Replace with your actual project ID if (!projectId || projectId === "YOUR_PROJECT_ID_HERE") { throw new Error('Project ID is not defined. Please set your project ID from the WalletConnect Dashboard.') } const tronMainnet: CustomCaipNetwork<'tron'> = { id: '0x2b6653dc', chainNamespace: 'tron' as const, caipNetworkId: 'tron:0x2b6653dc', name: 'Tron Mainnet', nativeCurrency: { name: 'TRX', symbol: 'TRX', decimals: 6 }, rpcUrls: { default: { http: ['https://api.trongrid.io'] } } } export const networks = [tronMainnet] as [AppKitNetwork, ...AppKitNetwork[]] export async function getUniversalConnector() { const universalConnector = await UniversalConnector.init({ projectId, metadata: { name: 'Universal Connector', description: 'Universal Connector', url: 'https://www.walletconnect.com', icons: ['https://www.walletconnect.com/icon.png'] }, networks: [ { methods: ['tron_signTransaction', 'tron_signMessage'], chains: [tronMainnet as CustomCaipNetwork], events: [], namespace: 'tron' } ] }) return universalConnector } ``` In de App.vue file you can add : ```tsx ``` ## Trigger the modal [#trigger-the-modal] To open the WalletConnect modal you need to call the `connect` function from the Universal Connector. ```tsx ... async handleConnect() { if (!universalConnector) { return } const { session: providerSession } = await universalConnector.connect() } ``` ## Smart Contract Interaction [#smart-contract-interaction] [Wagmi actions](https://wagmi.sh/core/api/actions/readContract) can help us interact with wallets and smart contracts: ```html ``` Read more about Wagmi actions for smart contract interaction [here](https://wagmi.sh/core/actions/readContract). [Ethers](https://docs.ethers.org/v6/) can help us interact with wallets and smart contracts: ```html ``` [@Solana/web3.js](https://solana.com/docs/clients/javascript) library allows for seamless interaction with wallets and smart contracts on the Solana blockchain. For a practical example of how it works, you can refer to our [lab dApp](https://lab.reown.com/appkit/?name=solana). ```tsx import { ref } from 'vue'; import { SystemProgram, PublicKey, Keypair, Transaction, TransactionInstruction, LAMPORTS_PER_SOL } from '@solana/web3.js'; import { useAppKitAccount, useAppKitProvider } from '@reown/appkit/vue' import { useAppKitConnection, type Provider } from '@reown/appkit-adapter-solana/vue' export default { setup() { const counterMessage = ref(''); const { address } = useAppKitAccount(); const { connection } = useAppKitConnection() const { walletProvider } = useAppKitProvider('solana') function deserializeCounterAccount(data) { if (data?.byteLength !== 8) { throw Error('Need exactly 8 bytes to deserialize counter'); } return { count: Number(data[0]) }; } async function onIncrementCounter() { try { const PROGRAM_ID = new PublicKey('Cb5aXEgXptKqHHWLifvXu5BeAuVLjojQ5ypq6CfQj1hy'); const counterKeypair = Keypair.generate(); const counter = counterKeypair.publicKey; const balance = await connection.getBalance(walletProvider.publicKey); if (balance < LAMPORTS_PER_SOL / 100) { throw Error('Not enough SOL in wallet'); } const COUNTER_ACCOUNT_SIZE = 8; const allocIx = SystemProgram.createAccount({ fromPubkey: walletProvider.publicKey, newAccountPubkey: counter, lamports: await connection.getMinimumBalanceForRentExemption(COUNTER_ACCOUNT_SIZE), space: COUNTER_ACCOUNT_SIZE, programId: PROGRAM_ID }); const incrementIx = new TransactionInstruction({ programId: PROGRAM_ID, keys: [ { pubkey: counter, isSigner: false, isWritable: true } ], data: Buffer.from([0x0]) }); const tx = new Transaction().add(allocIx).add(incrementIx); tx.feePayer = walletProvider.publicKey; tx.recentBlockhash = (await connection.getLatestBlockhash('confirmed')).blockhash; await walletProvider.signAndSendTransaction(tx, [counterKeypair]); const counterAccountInfo = await connection.getAccountInfo(counter, { commitment: 'confirmed' }); if (!counterAccountInfo) { throw new Error('Expected counter account to have been created'); } const counterAccount = deserializeCounterAccount(counterAccountInfo?.data); if (counterAccount.count !== 1) { throw new Error('Expected count to have been 1'); } counterMessage.value = `[alloc+increment] count is: ${counterAccount.count}`; } catch (error) { console.error(error); counterMessage.value = `Error: ${error.message}`; } } return { onIncrementCounter, counterMessage }; } }; ``` # WalletConnect Documentation (/)
WalletConnect Ecosystem Quickstart

WalletConnect powers apps, wallets and end-users via the WalletConnect network.

    Resources
    } href="https://walletconnect.com/blog" > Read the latest news and updates from the WalletConnect team } href="https://discord.walletconnect.network/" > Discord community for WalletConnect Network and WCT Token } href="https://x.com/WalletConnect" > Follow WalletConnect on X (Twitter) to stay updated on the announcements
# License Update (/license-update) WalletConnect SDKs are now offered under the [WalletConnect Community License](https://github.com/WalletConnect/walletconnect-monorepo/blob/v2.0/LICENSE.md). The Community License keeps the same open access for developers while adding clear terms that help keep the WalletConnect experience reliable, sustainable, and consistent for developers and end users alike. Developers may still integrate, experiment, and ship freely. The Community License simply adds clear conditions (like attribution and reasonable infrastructure usage thresholds) to protect service quality and maintain a great developer experience across the WalletConnect ecosystem. For larger-scale commercial developers, there's a clear path to supplemental licenses for expanded use. These updates make it easier for everyone to build confidently on stable infrastructure. See the individual SDKs' READMEs and LICENSEs (e.g., [walletconnect-monorepo](https://github.com/WalletConnect/walletconnect-monorepo)) for more details. # WCT Smart Contracts (/network/WCT-token/contracts) Below you can find all the contract addresses for the WalletConnect Token (WCT). ## Deployment Addresses [#deployment-addresses] ### Ethereum Mainnet (Chain ID: 1) [#ethereum-mainnet-chain-id-1] | Contract | Address | Description | |----------|---------|-------------| | WCT Token | [`0xeF4461891DfB3AC8572cCf7C794664A8DD927945`](https://etherscan.io/address/0xeF4461891DfB3AC8572cCf7C794664A8DD927945) | Main WCT token contract | ### Optimism (Chain ID: 10) [#optimism-chain-id-10] | Contract | Address | Description | |----------|---------|-------------| | L2WCT Token | [`0xeF4461891DfB3AC8572cCf7C794664A8DD927945`](https://optimistic.etherscan.io/address/0xeF4461891DfB3AC8572cCf7C794664A8DD927945) | WCT token on Optimism | | Admin Timelock | [`0x61cc6aF18C351351148815c5F4813A16DEe7A7E4`](https://optimistic.etherscan.io/address/0x61cc6aF18C351351148815c5F4813A16DEe7A7E4) | Admin timelock controller | | Manager Timelock | [`0xB5EFe3783Db55B913C79CBdB81C9d2C0a993f5f0`](https://optimistic.etherscan.io/address/0xB5EFe3783Db55B913C79CBdB81C9d2C0a993f5f0) | Manager timelock controller | | WalletConnectConfig | [`0xd2f149fAA66DC4448176123f850C14Ff14f978B3`](https://optimistic.etherscan.io/address/0xd2f149fAA66DC4448176123f850C14Ff14f978B3) | Protocol configuration | | Pauser | [`0x9163de7F22A9f3ad261B3dBfbB9A42886816adE7`](https://optimistic.etherscan.io/address/0x9163de7F22A9f3ad261B3dBfbB9A42886816adE7) | Emergency pause mechanism | | StakeWeight | [`0x521B4C065Bbdbe3E20B3727340730936912DfA46`](https://optimistic.etherscan.io/address/0x521B4C065Bbdbe3E20B3727340730936912DfA46) | Manages staking positions | | StakingRewardDistributor | [`0xF368F535e329c6d08DFf0d4b2dA961C4e7F3fCAF`](https://optimistic.etherscan.io/address/0xF368F535e329c6d08DFf0d4b2dA961C4e7F3fCAF) | Handles rewards distribution | | Airdrop | [`0x4ee97a759AACa2EdF9c1445223b6Cd17c2eD3fb4`](https://optimistic.etherscan.io/address/0x4ee97a759AACa2EdF9c1445223b6Cd17c2eD3fb4) | Season 1 airdrop distribution | ### Base Mainnet (Chain ID: 8453) [#base-mainnet-chain-id-8453] | Contract | Address | Description | |----------|---------|-------------| | WCT Token | [`0xeF4461891DfB3AC8572cCf7C794664A8DD927945`](https://basescan.org/address/0xeF4461891DfB3AC8572cCf7C794664A8DD927945) | WCT token on Base | ### Solana [#solana] | Contract | Address | Description | |----------|---------|-------------| | WCT Token | [`WCTk5xWdn5SYg56twGj32sUF3W4WFQ48ogezLBuYTBY`](https://explorer.solana.com/address/WCTk5xWdn5SYg56twGj32sUF3W4WFQ48ogezLBuYTBY) | WCT token on Solana | ## Token Information [#token-information] - Total Supply: 1,000,000,000 WCT (1e27 wei) # FAQ (/network/WCT-token/faq) ## Frequently Asked Questions [#frequently-asked-questions] ### How does staking work? [#how-does-staking-work] When you stake WCT, you lock tokens in the protocol to earn rewards and voting power. Your position remains fully locked and at **constant stakeweight** until you choose to **initiate an unlock**. Once unlocking begins, your stakeweight **decays linearly** over the selected duration until your tokens become withdrawable. --- ### How do I unstake or exit? [#how-do-i-unstake-or-exit] You can exit anytime by **initiating an unlocking period**. Select one of the available durations (e.g., 4, 26, or 52 weeks). During this time, stakeweight and rewards gradually decrease. When the period ends, your tokens become **fully withdrawable**. --- ### Which unlock durations are available? [#which-unlock-durations-are-available] You can choose from predefined options: **4, 8, 12, 26, 52, 78, or 104 weeks** (≈ 1–24 months). Shorter unlocks provide flexibility; longer ones grant higher rewards. --- ### How are rewards calculated and distributed? [#how-are-rewards-calculated-and-distributed] Rewards are distributed **weekly** (Thursday–Thursday) based on your **share of total stakeweight**: $$ \text{Reward Share} = \frac{\text{Position Stakeweight}}{\text{Total Network Stakeweight}} $$ Positions created or updated after Thursday 00:00 GMT become eligible in the **next** reward cycle. --- ### How can I increase my rewards? [#how-can-i-increase-my-rewards] You can earn more by: - Staking **more WCT** - Choosing a **longer unlock duration** - **Re-staking** your weekly rewards to compound your position - Keeping your position locked (not unlocking) to maintain full stakeweight --- ### What happens if I don’t claim rewards immediately? [#what-happens-if-i-dont-claim-rewards-immediately] Unclaimed rewards **accumulate automatically** and can be claimed anytime. There’s **no expiry** or penalty for delayed claiming. --- ### Can I partially unstake my position? [#can-i-partially-unstake-my-position] No. Partial unstaking is **not supported** — you must withdraw the full position once it’s fully unlocked. --- ### Can I change or extend my staking position? [#can-i-change-or-extend-my-staking-position] Yes. While locked, you can: - **Add more WCT** to your existing position - **Change your unlock preset** to a longer duration Both actions update your stakeweight accordingly. Changes made mid-week take effect in the **next reward period**. --- ### Are there any fees? [#are-there-any-fees] Only regular **gas fees** apply for on-chain transactions such as staking, updating, claiming, or unstaking. The cost depends on current network conditions. --- ### Can I have multiple staking positions? [#can-i-have-multiple-staking-positions] Each address can hold **one active position**. If you want multiple positions with different durations, use multiple wallet accounts or addresses. --- ### Can locked tokens participate in staking? [#can-locked-tokens-participate-in-staking] Yes. Certain locked allocations (e.g., team or contributor tokens) can be staked and earn rewards even while non-transferable, under their original vesting terms. This applies only to long-term allocation contracts. --- ### What happens after my unlock finishes? [#what-happens-after-my-unlock-finishes] When the unlock period ends: - Your stakeweight and voting power drop to **0** - You can **withdraw** your full amount - To continue earning, simply **stake again** # Governance (/network/WCT-token/governance) The governance of the WalletConnect Network is structured to facilitate decentralization, transparency, and community participation. This section outlines the roles and responsibilities of the WalletConnect Foundation and the community governance model that guides the Network. ## Foundation [#foundation] The WalletConnect Foundation is tasked with stewarding the Network by promoting its adoption, use, and growth. The Foundation's responsibilities include overview of grants to stakeholders, supporting applications, sdk and wallet development teams, and managing partnerships. ## Councils [#councils] The Councils includes several curated groups of individuals who are responsible for the different functions that are either part of the foundation, core development teams, node operator teams or work independently. Envisioned Councils include: - **Technical Council** - responsible for the technology & infrastructure - **Partnerships Council** - responsible for the partnerships & growth This structure is projected to be implemented during the constitution of the community governance. ## Community Governance [#community-governance] The WalletConnect Network is designed for a fully decentralized governance model managed by community governance. Further decentralization is expected to be facilitated by approved proposals of WCT tokenholders participating in the Network governance. Optimally this transition occurs through planned, multiple phases. An example of such planned multiple phases follows, though the actual transition will depend on input and approval from WCT tokenholders: 1. **Phase 1 - TGE Preparation:** - The WalletConnect Foundation was established and began operations. - The Foundation and reown collaborate on the Network's technical, community, partnerships, and administrative governance. 2. **Phase 2 - Foundation Transition:** - The Foundation establishes different councils to eventually take over various governance functions. - The Foundation expands its programs and responsibilities over community, partnerships, and administration considerations for the Network. - The community governance arises from WCT token stakers who participate in the Network and its governance. 3. **Phase 3 - Partnerships Transition:** - The Partnerships Council, elected by the community governance, assumes a more prominent role in community initiatives, including marketing, business development, grants programs, education, developer relations, and events. 4. **Phase 4 - Technology Transition:** - The Technical Council, elected by the community governance, assumes responsibility for technical governance as the Network becomes permissionless. - The Foundation coordinates this transition. 5. **Phase 5 - Administration Transition:** - The Foundation requires community governance approval to establish annual budgets, review and elect councils, and handle other administrative responsibilities through voting by community governance delegates. Token holders can participate in governance starting in Phase 2 after TGE by staking their WCT tokens, proposing changes, and voting on key issues, thereby shaping the future of the WalletConnect Network. # WCT Token (/network/WCT-token/overview) The WCT token powers the WalletConnect ecosystem, acting as both a reward and governance mechanism. ## Token Functions [#token-functions] The WCT token has three primary functions within the WalletConnect Network: 1. **Rewards**: WCT tokens are distributed as cashback, staking rewards, and node operator rewards. 2. **Staking**: Participants can stake WCT tokens to earn rewards and participate in governance. 3. **Governance**: WCT holders can vote on proposals and changes, giving the community control over the Network's development through decentralized governance. ## WCT Allocation [#wct-allocation] WCT allocation chart showing shares for the Foundation, airdrop, team, rewards, backers and core developers The initial supply of WCT tokens is capped at 1 billion, with the following allocations: - WalletConnect Foundation: 27% - Airdrops: 18.5% - Team: 18.5% - Rewards: 17.5% - Previous Backers: 11.5% - Core Development: 7% Tokens allocated to core development, team and previous backers will be subject to a 4-year unlock including a 1 year cliff starting at the token generation event (TGE). ## Fixed Supply [#fixed-supply] The initial design of the WalletConnect Network's tokenomics does not include token inflation. The current model focuses on utilizing existing token allocations such that inflation is not envisioned within the first 3-4 years. Introduction of an inflationary design would follow only after the token holders' vote to approval following careful consideration of Network metrics, participant feedback, and overall ecosystem health, with specific parameters to be determined through Network governance processes. ## Token Flow [#token-flow] Payments represent one of the largest economic opportunities in crypto. Global card networks generate hundreds of billions in fee revenue annually — funding rewards programs, interchange, and network operations for every participant. WalletConnect Pay is designed to bring that same model onchain: generate real transaction revenue from real commerce, powered by the WalletConnect Network. The Network is the primary engine of WalletConnect Pay. The WCT token sits at the centre, connecting payment activity to staking rewards, governance weight, and long-term token value. ### How the Network Powers Value Flows [#how-the-network-powers-value-flows] Every payment powered by WalletConnect Pay generates transaction fees. Those fees flow back into the Network through multiple mechanisms. Additional mechanisms are expected to be implemented. **Rewards Distribution** — Fee revenue funds rewards across all four stakeholder groups in the payment flow: | Stakeholder | How They Earn | | --- | --- | | Wallets | Earn interchange on every payment routed through WalletConnect Pay — modelled on card network interchange | | End Users | Earn cashback-style rewards on every purchase | ### Why This Model Works [#why-this-model-works] Most alternative payment methods have failed not for technical reasons, but because they gave users no reason to switch. UK Open Banking was technically superior to cards but offered consumers zero upside. CurrentC was backed by the largest US retailers but built solely to save merchants on fees — and died before launch because users had nothing to gain. WalletConnect Pay is designed around the opposite principle: lead with incentives on every side. The result is a self-reinforcing flywheel — more payments generate more fees, more fees fund better rewards, better rewards drive more payments. WCT is what holds this flywheel together. Stakers benefit as volume grows. Governance shapes how rewards and buybacks are calibrated over time. The token is not waiting for utility — it is the connective tissue between a payments network and its community of participants. Merchants pay transaction fees — not users. The end-user experience remains frictionless by design. # Rewards (/network/WCT-token/rewards) The WalletConnect Network implements a strategic reward system to incentivize network participants and ensure the network's growth and stability. ## Reward Allocation [#reward-allocation] 17.5% of the initial token supply is allocated for rewards to incentivize Network participants over the first few years of operations. This allocation is strategically phased: - **First Year**: Only 5% will be distributed to test Network assumptions - **Subsequent Years**: The remaining 12.5% is reserved ## Phased Distribution [#phased-distribution] The reward distribution is strategically phased to allow for testing and long-term sustainability: 1. **First Year**: A conservative 5% distribution to test network assumptions and reward mechanisms. 2. **Subsequent Years**: A larger 12.5% allocation, designated as a "flexible incentive" for ongoing distribution. :::note The larger portion (12.5%) is a "flexible incentive" and may be subject to change to maintain the reward mechanism's support of Network goals and benefits to all participants. This flexibility ensures that the reward system can adapt to the evolving needs of the Network and its participants. ::: ## Purpose of Rewards [#purpose-of-rewards] The reward system is designed to: 1. Incentivize active participation in the network 2. Encourage long-term commitment from participants 3. Ensure network security and efficiency 4. Support the overall growth and sustainability of the WalletConnect ecosystem ## Types of Rewards [#types-of-rewards] The Network includes various types of rewards: 1. **Staking Rewards**: Participants can earn rewards by staking WCT tokens. 2. **Node Rewards**: Service Node operators receive rewards based on their performance and activity. 3. **Wallet Performance Rewards**: Wallets can earn rewards based on their performance and certification status. 4. **End-user Cashback**: Cashback rewards for using WalletConnect Pay. ## Related Topics [#related-topics] To learn more about specific aspects of the reward system and participation in the WalletConnect Network, please refer to the following sections: - [Staking](../wct-staking) - [Service Node Performance Rewards](./service-node-rewards) # Service Node Rewards (/network/WCT-token/service-node-rewards) The WalletConnect Network implements a carefully structured reward system for node operators, designed to incentivize high performance and long-term commitment. The node rewards budget is split into two phases, with the first phase addressing the unique challenges of the WCT token non-transferability period. ## Phase 1: Non-Transferability Period [#phase-1-non-transferability-period] During this initial phase, a fixed-base reward structure is implemented, resulting in the following token-base revenues: 1. **Initial Allocation**: 100,000 WCT are distributed as initial allocation and can be staked. These tokens are locked for the entire period of non-transferability. 2. **Performance Boost (B_n)**: A boost given to nodes to reflect their performance and activity that is not based on WCT price. ### Boost Calculation [#boost-calculation] The performance boost (B_n) is calculated as follows: $$B_n = \alpha + (weight \cdot performance score)$$ A multiplicator (M_n) is also applied: $$M_n = \frac{100000}{T}$$ Where T is the period on which the initial allocation is locked. ### Weight Distribution [#weight-distribution] The boost is based on the weight of the node relative to other nodes. Initially, if there are 15 nodes, each getting 100,000 WCT, they would each get 6.67% weight. This stake weight evolves if some nodes do not restake their boost. ## Performance-Based Rewards [#performance-based-rewards] Individual node rewards are conditional on the performance factor $U(i,t) \in [0, 1]$. In line with the performance factors for other groups, there is a set of KPIs defining this. Initially, it will be based on uptime and latency. For a detailed explanation of how these factors are calculated and weighted, please refer to the [Performance Evaluation](../service-nodes/#performance-evaluation) section. The reward structure is subject to adjustment through network governance to ensure it continues to align with the network's goals and economic sustainability. # WCT Staking (/network/WCT-token/staking) Staking WCT is the primary mechanism through which token holders engage with and support the network by locking their tokens in the protocol's smart contracts. This alignment of interests creates a more secure and participatory ecosystem. Staking WCT provides three key benefits: voting rights in protocol governance, eligibility for performance rewards programs, and weekly WCT token rewards distributions. These mechanisms allow token holders to participate actively in the protocol while earning additional rewards. The staking model now uses perpetual positions with user-triggered unlocking. You select an unlock duration up front (from a discrete set of options), but your position stays fully locked and at full stakeweight until you decide to initiate unlock. When you initiate unlock, stakeweight decays linearly over the chosen duration. ## Stake Weight [#stake-weight] Stakeweight is the measure used to determine a staker's position within the network at any given time. It is derived from two factors: the amount of WCT staked and the remaining lock time of the position. Rewards are distributed proportionally to each staker's share of total network stakeweight, and governance voting power is directly proportional to stakeweight. ### States [#states] - **Locked (Perpetual):** Your position is active and not unlocking. While locked, the remaining lock time is fixed at your selected unlock duration, so stakeweight does not decay. - **Unlocking:** You've initiated an unstake. Remaining lock time decreases linearly to zero over the selected unlock duration; stakeweight decays accordingly. When it reaches zero, the position becomes fully withdrawable. ### Calculating Stake Weight [#calculating-stake-weight] The stakeweight calculation is: $$ \text{Stakeweight} = \frac{\text{Amount of WCT} \times \text{Remaining Lock Time}}{209} $$ Where: - **Amount of WCT:** Number of WCT tokens staked. - **Remaining Lock Time:** - **Locked state:** fixed at the **selected unlock duration** (e.g., 52 weeks). - **Unlocking state:** decays linearly from the selected duration down to 0. - **209:** Normalization constant for maximum stakeweight. For example, if a user stakes **1,000 WCT** and has selected a **40-week** unlock duration: - **Locked:** $$ \text{Stakeweight} = \frac{1000 \times 40}{209} \approx 191.39 $$ - **Unlocking (halfway through, 20 weeks remaining):** $$ \text{Stakeweight} = \frac{1000 \times 20}{209} \approx 95.69 $$ While the stakeweight formula uses 209 weeks as the denominator, the current maximum unlock duration you can select is 104 weeks (≈ 2 years). Due to timestamp rounding, 104 weeks is used to represent 2 years. ### Stakeweight Decay (only during Unlocking) [#stakeweight-decay-only-during-unlocking] In the **Locked** state, stakeweight remains constant (no decay). In the **Unstaking** state, **remaining lock time**—and thus stakeweight—decays linearly week by week until it reaches 0 at the end of the unlock duration. ## How to Stake WCT [#how-to-stake-wct] To stake WCT, visit [**https://app.walletconnect.com/stake**](https://app.walletconnect.com/stake) WCT staking dashboard showing your balance, staking position and rewards Staking panel prompting you to enter the amount of WCT to stake Staking panel listing the unstaking durations and the APY for each Staking panel asking your wallet to approve a spending limit before staking The staking flow involves: - Connect your wallet. - Select **Stake**. - Enter the **amount** you want to stake. - Set the **duration** (this sets the **unstaking period** used when you later exit. The longer the duration, the higher the APY). - **Approve** the amount — sign the approval with your wallet. - **Stake** — sign the staking transaction with your wallet. Your position is perpetually locked until you initiate unstaking. Choosing the unlock duration does not exit you; it sets the duration for a future exit. ## Discrete Unlock Duration Options [#discrete-unlock-duration-options] To simplify decisions, the unlock duration must be one of: - **4, 8, 12, 26, 52, 78, or 104 weeks** (≈ 1–24 months) You can change your preset **while Locked**. The preset determines the **remaining lock time** used for stakeweight in the Locked state and the **length of the decay** once you initiate unstaking. ## Staking Rewards Eligibility [#staking-rewards-eligibility] Rewards are distributed **weekly**. Each reward period **starts and ends on Thursday (00:00 GMT)**. To be eligible for a given week: - Your position must **exist before Thursday 00:00 GMT** of that week; and - Your position must have **Remaining Lock Time > 0**: - **Locked:** always eligible. - **Unlocking:** eligible while **≥ 1 week** remains (once it hits 0, eligibility ends). ### Examples [#examples] #### Eligible (Locked) [#eligible-locked] Created on **Wednesday 23:00 GMT**, preset **4 weeks**, not unlocking yet → Eligible for the week starting Thursday 00:00 GMT (position existed before the cutoff and is Locked). #### Eligible (Unlocking with ≥ 1 week) [#eligible-unlocking-with--1-week] Initiate unlock on **Monday** with preset **12 weeks** → For subsequent Thursdays while ≥ 1 week remains, the position is eligible (with a decaying stakeweight). #### Ineligible (Too late) [#ineligible-too-late] Create a new position at **Thursday 01:00 GMT** → Not eligible for that week (created after the cutoff). ## Position Lifecycle [#position-lifecycle] ### Initiating Unstake (Exit) [#initiating-unstake-exit] When you're ready to exit: 1. Go to [**https://app.walletconnect.com/stake**](https://app.walletconnect.com/stake) 2. Connect your wallet 3. Click **Unstake** 4. After the unstaking duration ends, you will be able to withdraw your locked tokens. From that point: - Remaining lock time **decays linearly** from the unstaking duration selected when the position was created to **0**. - Stakeweight decays accordingly. - When it reaches **0**, the position becomes **fully withdrawable**. Staking dashboard showing an active WCT position with its duration and APY Unstaking panel explaining the unlock period before your WCT can be claimed ### Re-Locking (Stop Decay) [#re-locking-stop-decay] - While **Unstaking**, you can **Update** your position to return to the **Locked** state. - When updating your position, you must select a preset that is **≥ the current remaining time** (you can make it **longer**, but not shorter). - Decay stops immediately; stakeweight snaps back to the fixed value using the new preset. ### Completed Unstake [#completed-unstake] When remaining lock time reaches **0**: - Stakeweight and voting power become **0**. - The position becomes **withdrawable** (full amount; partial withdrawals are not supported). - After withdrawing, you may create a **new** staking position at any time. ## Updating Your Position [#updating-your-position] Users can update **active staking** positions at any time: ### Adding WCT [#adding-wct] Increase your position by depositing more WCT. The added tokens adopt your position's current preset. Staking panel for adding more WCT to an existing staking position ### Changing the Unlock Duration Preset [#changing-the-unlock-duration-preset] While **Staked**, you can change your duration to any of the discrete options **greater than or equal to** your current remaining time. This **does not** initiate unlocking; it only changes the **fixed remaining lock time** used for stakeweight in the Locked state and sets the future unlock duration. Panel for updating the unstaking duration of an existing WCT position ## Claiming Rewards [#claiming-rewards] Every Thursday, WCT rewards are distributed to eligible positions based on their proportional share of total network stakeweight. If your position's stakeweight represents 5% of the total, you'll receive approximately 5% of that week's distribution. $$ \text{Reward Share} = \frac{\text{Position Stakeweight}}{\text{Total Network Stakeweight}} $$ You can claim rewards on your dashboard at any time. When claiming, you may **re-stake** rewards back into the position to grow stakeweight. Checking in weekly lets you claim and optionally re-stake rewards and adjust your preset, helping you maintain optimal stakeweight. ## Migration Path (Existing Positions) [#migration-path-existing-positions] To avoid disrupting existing positions at upgrade time: - Existing positions were treated as **already unlocking** under the new contracts, so they continue to decay and become withdrawable on their original timelines without action required. - If you prefer the new **perpetual** behavior, select **Update**, choose a duration (you'll be able to select only durations **greater than or equal to** your current remaining lock), then remain **Locked** until you choose to initiate a new unlock. ## Backwards Compatibility / Optionality [#backwards-compatibility--optionality] Power users can still mimic the old behavior by **initiating unlock immediately after staking**, which starts decay from day one (as before). Otherwise, you enjoy constant stakeweight until you decide to exit. # Network (/network) The WalletConnect Network is a network of apps, wallets and chains, facilitating end-users to connect to apps using any supported wallet on any supported chain. It is chain agnostic, working across ecosystems from EVM and its L2s, to Solana, Cosmos, Polkadot, Bitcoin and more. To date, it has facilitated more than 300+ million connections for 50+ million users between over 700+ different wallets and 80,000+ applications. Since its inception in 2018, the Network's design emphasizes interoperability and composability to efficiently enable interoperability between apps, wallets, fintechs, chains and TradFi. ## Technology [#technology] The WalletConnect Network's key components include: 1. **Service Nodes**; database nodes that form the backbone of the network's storage layer. They operate on a consistent-hashing based distributed database. 2. **Gateway Nodes**; responsible for facilitating encrypted communications and data routing between wallets and applications. 3. **Relay Service**; connects users' wallets to dapps. ## Permissioned Network [#permissioned-network] The WalletConnect Network operates in a permissioned environment. This means: * Specific node operators manage the Service Nodes under service-level agreements. * The Gateway Nodes are centralized and managed by WalletConnect. This allows WalletConnect to provide a secure and reliable service for enterprise-grade apps and wallets. ## Network Participants [#network-participants] WalletConnect Network Architecture The WalletConnect Network comprises various participants, each playing a crucial role in maintaining functionality and security: 1. **Service Node Operators**: They run the service nodes (database nodes) that form the backbone of the network's storage layer. These nodes operate on a consistent-hashing based distributed database. 2. **Gateway Node Operators**: They manage the gateway nodes, which are the entry points for apps and SDKs. Gateways facilitate encrypted communications and data routing between wallets and applications. 3. **Wallets**: These allow end-users to manage their blockchain keys and interact with apps via the WalletConnect protocol. Most wallets integrate with the network using the WalletKit SDK. 4. **Apps**: These are the products and services in the web3 space that drive traffic to the network. They can integrate directly or via available SDKs. 5. **SDKs**: Software Development Kits that simplify the integration process for apps and wallets. 6. **End Users**: The consumers of all services within the network, from wallets to apps, going through the relay and database nodes. Each of these participants contributes to the ecosystem in unique ways, ensuring the network's functionality, security, and continued growth. Their roles and interactions form the foundation of the WalletConnect Network's robust and interconnected infrastructure. ## Learn more about the WalletConnect Network [#learn-more-about-the-walletconnect-network] Learn about the WalletConnect network's governance model. Learn how WCT powers the network's governance and incentivizes participants. Read more about the network's design, architecture, and core principles. Read WCT Issuer's MiCA whitepaper for admission to trading. # Service Nodes (/network/service-nodes) Service nodes form the backbone of the WalletConnect Network, serving as crucial infrastructure for persisting and managing end-to-end encrypted network messages. These nodes employ rendezvous hashing, a sophisticated method that ensures even distribution of data across the network. This approach not only enhances reliability and fault tolerance but also maintains user privacy by design - service nodes cannot decrypt or read the content of the messages they handle. ## Technical Architecture [#technical-architecture] The network's architecture is built on the premise that clients may be offline for extended periods. To address this, a "mailbox" system persists messages, allowing clients to retrieve data upon reconnection. This system is underpinned by a database utilizing rendezvous hashing, a concept that has proven its scalability in modern databases including Cassandra, DynamoDB, MongoDB, and others. The nodes are primarily constructed in Rust, chosen for its performance and safety features. For critical lower-level operations such as bloom-filters and I/O, the nodes integrate RocksDB, an industry-standard implementation maintained by Facebook/Meta. This hybrid approach leverages the strengths of custom-built solutions and battle-tested components. Current research focuses on evolving the rendezvous hashing-based database into a fully permissionless system. The next milestone is to publish a comprehensive technical design for community review, a crucial step before implementation. In the interim, node access to the network remains permissioned to ensure stability and security. ## Service Node Operators [#service-node-operators] Service Node Operators play a vital role in the WalletConnect ecosystem. Their responsibilities extend beyond mere node management to include proactive maintenance of high uptime and consistent performance optimization. The barrier to entry - staking WCT tokens - serves a dual purpose: it demonstrates the operator's commitment and aligns their interests with the network's success. The reward structure for operators is carefully designed to promote both long-term commitment and high-quality service. Staking rewards incentivize sustained participation, while performance-based incentives, calculated using key metrics like uptime and latency, encourage continuous improvement and innovation in node operation. ## Node Statuses [#node-statuses] The WalletConnect Network implements a dynamic node status system, allowing for flexible and responsive network management: - **Active**: These nodes are the workhorses of the network, directly processing user requests within their assigned region. The initial target of 15 active nodes balances network robustness with economic efficiency. - **Reserve**: Operating similarly to active nodes, reserve nodes ensure network resilience. They participate in the replication process and stand ready to step into an active role when needed, maintaining a pool of qualified nodes. - **Jailed**: This status serves as a temporary penalty for nodes that fail to meet performance standards. The 24-hour exclusion period provides operators time to address issues while protecting the network from underperforming nodes. - **Standby**: Representing potential capacity, standby nodes have staked tokens but are not actively running. This status allows the network to scale rapidly when demand increases. - **Deactivated**: This status accommodates operators who choose to cease support, ensuring an orderly exit process that protects both the operator's interests and the network's stability. | Status | Target Number | |-------------|----------------| | Active | 15 | | Reserve | 6 | | Jailed | No target | | Standby | No target | | Deactivated | No target | Target numbers are initial values and may be adjusted through governance decisions to optimize network performance and economic sustainability. ## Performance Evaluation [#performance-evaluation] The sophisticated performance evaluation system is a cornerstone of maintaining the WalletConnect Network's high standards. The performance coefficient $U(i,t) \in [0, 1]$ provides a nuanced measure of each node's contribution: $$\text{Performance} = (W_u \cdot U_i) \cdot (W_l \cdot L_i)$$ Where $U_i$ represents uptime, $L_i$ denotes latency, and $W_u$ and $W_l$ are adjustable weights. This formula allows for fine-tuning of performance priorities as the network evolves. ## Performance Verification [#performance-verification] The transition from a permissioned to a permissionless verification system represents a key evolution in the network's maturity: 1. Permissioned Network (Phase 1): * Trusted oracle nodes conduct performance verification, ensuring a controlled and stable initial environment. * The oracle node plays a crucial role within the Network. It functions as both a data collector and a regular service operator. 2. Permissionless Network (Phase 2): * All nodes engage in mutual performance measurement, creating a more decentralized and robust verification system. * Every node pings and reports on every other node operator, replacing the need for a central oracle. * This distributed approach enhances the network's resilience and reduces single points of failure. Key Transition: * Phase 1: Trusted nodes (oracles) verify performance * Phase 2: Every node participates in performance measurement This phased approach allows for gradual decentralization while maintaining network integrity throughout the transition. It enables the network to start with a controlled, easily manageable system and evolve into a more decentralized, robust structure as it matures. ## Slashing Mechanism [#slashing-mechanism] The slashing mechanism is a critical component in maintaining high network standards: 1. Performance threshold $\tau$ (where $0 < \tau < 1$) is set through governance. 2. Nodes with $U(i,t) < \tau$ trigger a slashing event. 3. The underperforming node is moved to "jailed" status and replaced by a reserve node. 4. Jailed nodes may face a reduction in staked tokens, with the percentage determined by governance. 5. After the jailing period, nodes return to standby status, with the opportunity to re-enter active service. # WalletConnect Specs (/network/specs) The WalletConnect Specs document the core WalletConnect protocol — how it's built underneath, at a level of technical detail beyond what's covered in this documentation. } href="https://specs.walletconnect.com/"> Read the protocol specification. # Wallets (/network/wallets) Wallets enable users to manage their blockchain keys and interact with applications via the WalletConnect protocol. They play a vital role in the Network by enabling end-users to securely access and utilize blockchain services on any network. Wallets are responsible for integrating with the WalletConnect Network and providing a seamless user experience for managing digital assets and performing blockchain transactions. Today, reown provides the WalletKit SDK to enable simple integrations for wallets to the Network. ## Certified Wallets [#certified-wallets] The [WalletConnect Certified](https://walletconnect.com/blog/walletguide-and-walletconnect-certified-the-future-of-digital-wallets) program offers additional incentives for wallets that meet high standards of UX and integration, further encouraging wallets to stay up-to-date with the latest network features and best practices​. ## Wallet Rewards [#wallet-rewards] Wallets participating in the WalletConnect network can earn rewards through staking and performance incentives. To qualify, wallets must stake WCT tokens, which enables them to participate in the Network's governance and earn staking rewards. For a closer look at the WalletConnect network's wallet rewards system, refer to the [Wallet Rewards](/network/WCT-token/rewards) documentation.​ # Get the payment status (/payments/api-reference/2026-02-18/get-v1-gateway-payment-id-status) # Get a payment (/payments/api-reference/2026-02-18/get-v1-gateway-payment-id) # Get the payment status (/payments/api-reference/2026-02-18/get-v1-payments-id-status) # Get payment details (/payments/api-reference/2026-02-18/get-v1-payments-id) # POST /v1/gateway/payment/{id}/cancel (/payments/api-reference/2026-02-18/post-v1-gateway-payment-id-cancel) # Confirm a payment (/payments/api-reference/2026-02-18/post-v1-gateway-payment-id-confirm) # Fetches an action (/payments/api-reference/2026-02-18/post-v1-gateway-payment-id-fetch) # Get payment options (/payments/api-reference/2026-02-18/post-v1-gateway-payment-id-options) # POST /v1/gateway/payment/{id}/transition (/payments/api-reference/2026-02-18/post-v1-gateway-payment-id-transition) # POST /v1/payments/{id}/cancel (/payments/api-reference/2026-02-18/post-v1-payments-id-cancel) # POST /v1/payments/{id}/transition (/payments/api-reference/2026-02-18/post-v1-payments-id-transition) # Create a new payment (/payments/api-reference/2026-02-18/post-v1-payments) # Binance Pay Onchain order-status webhook (/payments/api-reference/2026-02-18/post-v1-webhooks-binance-pay-onchain) # Binance Pay webhook (single callback) (/payments/api-reference/2026-02-18/post-v1-webhooks-binance-pay) # Bybit Pay PSP order webhook (/payments/api-reference/2026-02-18/post-v1-webhooks-bybit-pay) # Get the payment status (/payments/api-reference/2026-02-19.preview/get-v1-gateway-payment-id-status) # Get a payment (/payments/api-reference/2026-02-19.preview/get-v1-gateway-payment-id) # Get the payment status (/payments/api-reference/2026-02-19.preview/get-v1-payments-id-status) # Get payment details (/payments/api-reference/2026-02-19.preview/get-v1-payments-id) # POST /v1/gateway/payment/{id}/cancel (/payments/api-reference/2026-02-19.preview/post-v1-gateway-payment-id-cancel) # Confirm a payment (/payments/api-reference/2026-02-19.preview/post-v1-gateway-payment-id-confirm) # Fetches an action (/payments/api-reference/2026-02-19.preview/post-v1-gateway-payment-id-fetch) # Get payment options (/payments/api-reference/2026-02-19.preview/post-v1-gateway-payment-id-options) # POST /v1/gateway/payment/{id}/transition (/payments/api-reference/2026-02-19.preview/post-v1-gateway-payment-id-transition) # POST /v1/payments/{id}/cancel (/payments/api-reference/2026-02-19.preview/post-v1-payments-id-cancel) # POST /v1/payments/{id}/transition (/payments/api-reference/2026-02-19.preview/post-v1-payments-id-transition) # Create a new payment (/payments/api-reference/2026-02-19.preview/post-v1-payments) # Binance Pay Onchain order-status webhook (/payments/api-reference/2026-02-19.preview/post-v1-webhooks-binance-pay-onchain) # Binance Pay webhook (single callback) (/payments/api-reference/2026-02-19.preview/post-v1-webhooks-binance-pay) # Bybit Pay PSP order webhook (/payments/api-reference/2026-02-19.preview/post-v1-webhooks-bybit-pay) # Authentication (/payments/api-reference/authentication) Every request to the WalletConnect Pay API is authenticated with an API key, passed in the `Api-Key` header: ```bash curl "https://api.pay.walletconnect.com/v1/merchants" \ -H "Api-Key: $WCP_API_KEY" ``` API keys are created and managed in the [dashboard](https://merchant.pay.walletconnect.com/en/api-keys). A key is shown only once at creation — store it in a secret manager. Anyone with the key can act on behalf of your account. ## Test and live keys [#test-and-live-keys] Your account has two kinds of keys, one for each mode: | Key prefix | Mode | Behavior | |---|---|---| | `wcp_test_` | **Test** | Payments are simulated; no funds move. See [Test mode](/payments/test-mode). | | `wcp_` | **Live** | Real payments with on-chain settlement. | The key is the **only** thing that selects test or live. Both key types work against the same base URL and the same endpoints, and there is no test flag or mode parameter on any request. Responses do not say whether a resource is test or live — that's determined by the key that created it. ## Errors [#errors] | Status | Meaning | |---|---| | `401 Unauthorized` | The key is missing, malformed, or revoked. | | `403 Forbidden` | The key is valid but lacks permission for this account or resource. | ## Key safety [#key-safety] - **Never expose keys in client-side code.** All API calls should be made from your backend. - **Use test keys everywhere except production.** Development, CI, and staging should use `wcp_test_` keys. - **Rotate compromised keys immediately** from the [dashboard](https://merchant.pay.walletconnect.com/en/api-keys). # API Reference (/payments/api-reference) This section contains the full WalletConnect Pay API reference, organized by service area. ## Gateway [#gateway] Endpoints for wallets to fulfill payments (API-first / non-SDK flow): get payment options, fetch actions, confirm payments, check status, and cancel. If you're looking for the integration overview, start with **[API-first integration (Non-SDK wallets)](/payments/wallets/api-first)**. ## Payments [#payments] Merchant-facing endpoints for creating and managing payments. ## Webhooks [#webhooks] Endpoints that payment providers (Binance Pay, Binance Pay Onchain and Bybit Pay) call to report order status. Each request is verified with the provider's signature instead of an API key. To receive payment events in your own backend, see **[Webhooks](/payments/webhooks)**. # API Versioning (/payments/api-reference/versioning) The WalletConnect Pay API uses date-based versions in `YYYY-MM-DD` format. Each version is a stable snapshot of the API's behavior and response shapes. ## How it works [#how-it-works] When a merchant account is created, it gets pinned to the current API version. All requests from that account use the pinned version by default, so existing integrations keep working without any changes. You can override the version on any request with the `WCP-Version` header: ```http title="Request header" POST /v1/payments HTTP/1.1 WCP-Version: 2026-02-04 ``` If you omit the header, the request uses your account's pinned version. Overrides can only target versions newer than your pinned version. To permanently upgrade your pinned version, use the merchant dashboard. Downgrades are not supported. Use the version selector at the top of these docs to browse the API reference for a specific version. ## Preview versions [#preview-versions] Preview versions let you test upcoming changes before they reach GA. They use a `.preview` suffix: ```http title="Preview version header" WCP-Version: 2026-06-01.preview ``` Previews require an explicit header on every request. They are not covered by the same stability guarantees as GA versions, and breaking changes may land with minimal notice. ## Client compatibility requirements [#client-compatibility-requirements] For the stability guarantees to hold, your client must: - Ignore unknown fields in API responses. New fields can appear in any version. - Tolerate unknown enum values. New statuses and types ship without a version bump. - Handle unknown webhook event types without crashing. - Treat unrecognized error codes as generic errors rather than hard-failing. These are all additive, non-breaking changes that apply across versions. ## Breaking vs non-breaking changes [#breaking-vs-non-breaking-changes] Breaking changes only ship in new dated versions. A change is breaking if it removes or renames a field, changes a field's type, alters default behavior, removes an endpoint, or makes an optional parameter required. Non-breaking changes apply to all versions: new endpoints, optional parameters, response fields, enum values, webhook types, and error codes. No version bump needed. # CEX Exchange Integrations (/payments/cex-coverage) This page outlines the centralized exchanges WalletConnect Pay supports for **Pay with CEX**. When a user selects a supported exchange at checkout, WalletConnect Pay creates the payment order and deeplinks the user into the exchange app to review and approve the payment. The exchange executes the transaction internally and settles funds directly into the merchant's own exchange account. WalletConnect Pay never holds, custodies, or moves funds in this flow. Compliance, KYC, and settlement are handled end-to-end by the exchange. For merchants, enabling a CEX integration requires onboarding directly with each exchange and activating it via the WalletConnect Pay Merchant Dashboard. ## Supported Exchanges [#supported-exchanges] | Exchange | Status | Website | |----------------|---------------|----------------------------------------------| | Binance Pay | Live | [pay.binance.com](https://pay.binance.com) | | Crypto.com Pay | Coming Soon | [crypto.com](https://crypto.com) | | Bybit Pay | Coming Soon | [bybit.com](https://bybit.com) | | Coinbase | Coming Soon | [coinbase.com](https://coinbase.com) | | KuCoin Pay | Coming Soon | [kucoin.com](https://kucoin.com) | | OKX | Coming Soon | [okx.com](https://okx.com) | | Gate Pay | Coming Soon | [gate.io](https://gate.io) | | Bitget Pay | Coming Soon | [bitget.com](https://bitget.com) | | Kraken | Coming Soon | [kraken.com](https://kraken.com) | | Bitfinex | Coming Soon | [bitfinex.com](https://bitfinex.com) | | Luno | Coming Soon | [luno.com](https://luno.com) | ## Adding more Central Exchange Integrations [#adding-more-central-exchange-integrations] WalletConnect Pay can enable additional integrations based on merchant demand and expected volume. If your business needs a specific integration not listed above, [contact us](https://share.hsforms.com/19Dpp4ayYR9uriB3xNAh0JAnxw6s) and we will work with you to enable it. # Merchant API Reference (/payments/ecommerce/api-reference) ## Authentication [#authentication] Every request to the Merchant API requires the following headers: | Header | Required | Description | |--------|----------|-------------| | `Content-Type` | Conditional | Must be `application/json` for requests with a JSON body | | `Api-Key` | Yes | Partner API key from the [Merchant Dashboard](/payments/merchant/onboarding) | | `Merchant-Id` | Yes | Merchant identifier from the [Merchant Dashboard](/payments/merchant/onboarding) | Keep your `Api-Key` secret. Never expose it in client-side code — all API calls should be made from your backend server. ## Base URLs [#base-urls] | Environment | URL | |-------------|-----| | Production | `https://api.pay.walletconnect.com` | | Staging | `https://staging.api.pay.walletconnect.com` | --- ## Create Payment [#create-payment] Creates a new payment for the buyer to complete on the WalletConnect Pay checkout portal. ``` POST /v1/merchant/payment ``` ### Request Body [#request-body] | Field | Type | Required | Description | |-------|------|----------|-------------| | `amount` | object | Yes | The payment amount | | `amount.unit` | string | Yes | Currency in `iso4217/{CODE}` format (e.g., `iso4217/USD`) | | `amount.value` | string | Yes | Amount in minor units as a string (e.g., `"5000"` for $50.00) | | `referenceId` | string | Yes | Your internal order or reference identifier | | `checkout` | object | No | Checkout redirect configuration | | `checkout.successUrl` | string | No | HTTPS URL to redirect the buyer after a successful payment | | `checkout.errorUrl` | string | No | HTTPS URL to redirect the buyer after a failed payment | The `amount.value` is expressed in the currency's **minor units**. For USD, `"5000"` equals $50.00 (5000 cents). For JPY (which has no minor unit), `"5000"` equals ¥5,000. Both `successUrl` and `errorUrl` must be valid HTTPS URLs. If either is missing or invalid, the redirect feature is disabled entirely for that payment — the checkout portal will show generic terminal views instead. ### Request Example [#request-example] ```json { "amount": { "unit": "iso4217/USD", "value": "5000" }, "referenceId": "order_abc123", "checkout": { "successUrl": "https://yourstore.com/order/abc123/success", "errorUrl": "https://yourstore.com/order/abc123/failed" } } ``` ### Response [#response] | Field | Type | Description | |-------|------|-------------| | `paymentId` | string | Unique payment identifier (e.g., `pay_xxx`) | | `gatewayUrl` | string | URL to the checkout portal for this payment — use this to redirect the buyer | | `status` | string | Initial payment status (typically `pending`) | | `expiresAt` | integer | Unix timestamp (seconds) when the payment expires | | `isFinal` | boolean | Whether the payment is already in a terminal state | | `pollInMs` | integer | Suggested polling interval in milliseconds for status checks | ### Response Example [#response-example] ```json { "paymentId": "pay_abc123def456", "gatewayUrl": "https://pay.walletconnect.com/?pid=pay_abc123def456", "status": "pending", "expiresAt": 1709831400, "isFinal": false, "pollInMs": 1000 } ``` ### Code Examples [#code-examples] ```bash tab="cURL" curl -X POST https://api.pay.walletconnect.com/v1/merchant/payment \ -H "Content-Type: application/json" \ -H "Api-Key: YOUR_API_KEY" \ -H "Merchant-Id: YOUR_MERCHANT_ID" \ -d '{ "amount": { "unit": "iso4217/USD", "value": "5000" }, "referenceId": "order_abc123", "checkout": { "successUrl": "https://yourstore.com/order/abc123/success", "errorUrl": "https://yourstore.com/order/abc123/failed" } }' ``` ```typescript tab="TypeScript" const response = await fetch( "https://api.pay.walletconnect.com/v1/merchant/payment", { method: "POST", headers: { "Content-Type": "application/json", "Api-Key": process.env.WCP_API_KEY, "Merchant-Id": process.env.WCP_MERCHANT_ID, }, body: JSON.stringify({ amount: { unit: "iso4217/USD", value: String(order.totalCents), }, referenceId: order.id, checkout: { successUrl: `${process.env.BASE_URL}/order/${order.id}/success`, errorUrl: `${process.env.BASE_URL}/order/${order.id}/failed`, }, }), } ); const { paymentId, gatewayUrl } = await response.json(); ``` ### Error Responses [#error-responses] | Status Code | Description | |-------------|-------------| | `400` | Invalid request — check required fields and format | | `401` | Invalid or missing API key | | `404` | Merchant not found for the given `Merchant-Id` | | `500` | Internal server error | --- ## Verify Payment Status [#verify-payment-status] After the buyer completes (or abandons) the checkout, verify the payment status from your backend. ``` GET /v1/merchant/payment/{id}/status ``` ### Path Parameters [#path-parameters] | Parameter | Type | Description | |-----------|------|-------------| | `id` | string | The `paymentId` returned when creating the payment | ### Headers [#headers] | Header | Required | Description | |--------|----------|-------------| | `Api-Key` | Yes | Partner API key | | `Merchant-Id` | Yes | Merchant identifier | ### Response [#response-1] | Field | Type | Description | |-------|------|-------------| | `status` | string | Payment status (see below) | | `isFinal` | boolean | Whether the payment has reached a terminal state | ### Payment Statuses [#payment-statuses] | Status | Terminal | Description | |--------|----------|-------------| | `pending` | No | Payment created, waiting for buyer action | | `processing` | No | Transaction submitted, awaiting on-chain confirmation | | `succeeded` | Yes | Payment completed successfully | | `failed` | Yes | Payment failed or was rejected | | `expired` | Yes | Payment window closed without completion | ### Code Example [#code-example] ```bash tab="cURL" curl https://api.pay.walletconnect.com/v1/merchant/payment/pay_abc123def456/status \ -H "Api-Key: YOUR_API_KEY" \ -H "Merchant-Id: YOUR_MERCHANT_ID" ``` ```typescript tab="TypeScript" async function verifyPaymentStatus(paymentId: string): Promise { const response = await fetch( `https://api.pay.walletconnect.com/v1/merchant/payment/${paymentId}/status`, { headers: { "Api-Key": process.env.WCP_API_KEY, "Merchant-Id": process.env.WCP_MERCHANT_ID, }, } ); const { status, isFinal } = await response.json(); return status; } ``` # Online Checkout Integration Guide (/payments/ecommerce/integration) Integrate WalletConnect Pay into your online checkout so buyers can pay with crypto from any wallet, using the assets they already hold. ## Prerequisites [#prerequisites] Before you begin, make sure you have: - **Completed merchant onboarding** — sign up and complete KYB verification on the [Merchant Dashboard](/payments/merchant/onboarding) - **API Key** — available in your Merchant Dashboard after onboarding (used as the `Api-Key` header) - **Merchant ID** — your merchant identifier from the Merchant Dashboard - **A backend server** — all API calls must be made server-side to keep your API Key secure ## How It Works [#how-it-works] The checkout integration follows a redirect-based flow. Your backend creates a payment, redirects the buyer to the WalletConnect Pay checkout portal, and verifies the result after the buyer returns. ```mermaid sequenceDiagram participant B as Buyer participant MF as Merchant Frontend participant MB as Merchant Backend participant API as WalletConnect Pay API participant BX as Checkout Portal B->>MF: Click "Pay with Crypto" MF->>MB: Create payment request MB->>API: POST /v1/merchant/payment API-->>MB: { paymentId, gatewayUrl } MB-->>MF: gatewayUrl MF->>BX: Redirect buyer to checkout portal Note over BX,B: Buyer connects wallet,
selects payment option,
and signs the transaction alt Payment succeeds BX->>MF: Redirect to successUrl?payment_id={paymentId} else Payment fails BX->>MF: Redirect to errorUrl?payment_id={paymentId} end MF->>MB: Verify payment status MB->>API: GET /v1/merchant/payment/{paymentId}/status API-->>MB: { status: "succeeded" } MB-->>MF: Order confirmed MF->>B: Show order confirmation ``` ## Integration Steps [#integration-steps] ### Create a Payment [#create-a-payment] From your backend, call the Merchant API to create a payment with the order amount and redirect URLs. ```typescript // Server-side only const response = await fetch( "https://api.pay.walletconnect.com/v1/merchant/payment", { method: "POST", headers: { "Content-Type": "application/json", "Api-Key": process.env.WCP_API_KEY, "Merchant-Id": process.env.WCP_MERCHANT_ID, }, body: JSON.stringify({ amount: { unit: "iso4217/USD", value: String(order.totalCents), // e.g., "5000" for $50.00 }, referenceId: order.id, checkout: { successUrl: `${process.env.BASE_URL}/order/${order.id}/success`, errorUrl: `${process.env.BASE_URL}/order/${order.id}/failed`, }, }), } ); const { paymentId, gatewayUrl } = await response.json(); ``` Store the `paymentId` in your database alongside the order so you can verify the payment later. The `amount.value` is in **minor currency units** — for USD, `"5000"` equals $50.00. See the [API Reference](/payments/ecommerce/api-reference) for details. ### Redirect the Buyer [#redirect-the-buyer] Redirect the buyer to the `gatewayUrl` returned by the API. This takes them to the WalletConnect Pay checkout portal where they can connect their wallet, choose a payment option, and complete the transaction. ```typescript // Client-side: redirect to checkout portal window.location.href = gatewayUrl; ``` The checkout portal handles the entire buyer-side payment flow — no additional integration is needed on your end for this step. ### Handle the Return [#handle-the-return] After the payment completes (or fails), the checkout portal redirects the buyer back to your site: - **Success**: `{successUrl}?payment_id={paymentId}` - **Failure**: `{errorUrl}?payment_id={paymentId}` The redirect happens automatically after a 3-second countdown on the checkout portal. ```typescript const url = new URL(window.location.href); const paymentId = url.searchParams.get("payment_id"); if (!paymentId) { throw new Error("Missing payment_id in redirect URL"); } const status = await verifyPayment(paymentId); ``` **Never trust the redirect URL alone.** Always look up the expected `paymentId` for the order from your own database and verify it matches the redirect parameter. Verify the payment status server-side before fulfilling any order. ### Verify Payment Status [#verify-payment-status] From your backend, call the status endpoint to get the authoritative payment result. ```typescript const order = await getOrderByPaymentId(paymentId); const response = await fetch( `https://api.pay.walletconnect.com/v1/merchant/payment/${paymentId}/status`, { headers: { "Api-Key": process.env.WCP_API_KEY, "Merchant-Id": process.env.WCP_MERCHANT_ID, }, } ); const { status, isFinal } = await response.json(); if (status === "succeeded") { await fulfillOrder(order.id); } else if (status === "processing") { // Transaction submitted but not yet confirmed — check again shortly } else { // "failed" or "expired" — inform the buyer } ``` If `isFinal` is `false` (status is `processing`), poll the endpoint at a reasonable interval until the payment reaches a terminal state. | Status | Terminal | Action | |--------|----------|--------| | `succeeded` | Yes | Fulfill the order | | `failed` | Yes | Show error, offer retry | | `expired` | Yes | Show expiry message, offer new payment | | `processing` | No | Poll again after a short delay | See the full [API Reference](/payments/ecommerce/api-reference) for endpoint details and error codes. ## Checkout URL Requirements [#checkout-url-requirements] Both `successUrl` and `errorUrl` must be valid **HTTPS** URLs. If either is missing or fails validation, the redirect feature is disabled for that payment — the checkout portal will show a generic success or error message instead. - The checkout portal appends `?payment_id={id}` to your callback URLs automatically - There is no `cancelUrl` — if the buyer abandons the flow, they simply close the tab - Include your order reference in the URL path (e.g., `/order/{orderId}/success`) so you can correlate the redirect with the right order ## Merchant Branding [#merchant-branding] The checkout portal displays your merchant name and icon to the buyer during the payment flow. These are configured in the [Merchant Dashboard](/payments/merchant/onboarding): - **`merchant.name`** — displayed in the payment summary - **`merchant.iconUrl`** — displayed alongside your name For best results, use a square icon with a minimum size of 72x72px in PNG, SVG, or WebP format. ## Testing [#testing] Use the staging environment to test your integration before going live: | Environment | API Base URL | |-------------|-------------| | Production | `https://api.pay.walletconnect.com` | | Staging | `https://staging.api.pay.walletconnect.com` | Contact the WalletConnect team to obtain staging credentials. ## Example Implementation [#example-implementation] Complete working reference checkouts are available in the WalletConnect Pay examples repository: } href="https://github.com/WalletConnect/walletconnect-pay-examples/tree/main/gateway/headless-checkout"> Next.js checkout showing payment creation, checkout redirect, and order verification. } href="https://github.com/WalletConnect/walletconnect-pay-examples/tree/main/gateway/headless-checkout-vanilla"> Framework-neutral checkout driving the payment flow with vanilla TypeScript. The example includes: - **API client** — payment creation with checkout URLs - **Checkout route** — creates a payment and redirects the buyer - **Order confirmation page** — receives the redirect and displays order status # WalletConnect Pay for Ecommerce and Online Checkout (/payments/ecommerce/overview) WalletConnect Pay enables you to add crypto and stablecoin payments to your online checkout with a single integration, offering a familiar, wallet-based experience for customers worldwide. Before integrating, complete [merchant onboarding](/payments/merchant/onboarding) to obtain your API Key and Merchant ID. ## How It Works [#how-it-works] Your backend creates a payment via a single API call and redirects the buyer to the WalletConnect Pay checkout portal. The buyer connects their wallet, selects a payment option, and completes the transaction. After payment, the buyer is redirected back to your site and you verify the result server-side. 1. Your backend calls `POST /v1/merchant/payment` with the order amount and redirect URLs 2. You redirect the buyer to the checkout portal using the `gatewayUrl` from the response 3. The buyer connects their wallet, picks a token and network, and signs the transaction 4. The checkout portal redirects the buyer back to your `successUrl` or `errorUrl` 5. Your backend verifies the payment status via `GET /v1/merchant/payment/{id}/status` ## What does WalletConnect Pay offer for ecommerce? [#what-does-walletconnect-pay-offer-for-ecommerce] ### Any wallet. Any asset. One checkout flow. [#any-wallet-any-asset-one-checkout-flow] Let customers pay online using the wallets and assets they already use, all through a single, consistent checkout experience. ### A checkout flow that fits existing stacks [#a-checkout-flow-that-fits-existing-stacks] WalletConnect Pay is designed to fit cleanly into existing checkout and operations workflows. It can align with PSP compliance requirements (like required information capture and screening steps) and follows payment patterns customers already recognize and trust. ### Built-in incentives to encourage usage [#built-in-incentives-to-encourage-usage] WalletConnect Pay can provide rewards that give customers a reason to choose WalletConnect Pay at checkout—supporting adoption with no added effort from merchants or PSPs. ### Smarter economics for online payments [#smarter-economics-for-online-payments] Support higher-value online transactions, reduce acceptance costs, and settle faster with flexible crypto or fiat payouts. ### Bring your wallet or pay product to everyday commerce [#bring-your-wallet-or-pay-product-to-everyday-commerce] Integrate WalletConnect Pay to let your users pay across POS and ecommerce. You keep custody and control of the experience—while WalletConnect Pay handles PSP compatibility behind the scenes. ## Get Started [#get-started] } href="/payments/ecommerce/integration"> Step-by-step guide to integrate WalletConnect Pay checkout into your site. } href="/payments/ecommerce/api-reference"> Merchant API endpoint reference for creating and verifying payments. } href="/payments/merchant/onboarding"> Set up your merchant account and obtain your API credentials. } href="https://github.com/WalletConnect/walletconnect-pay-examples/tree/main/gateway/headless-checkout"> Next.js reference checkout implementation. } href="https://github.com/WalletConnect/walletconnect-pay-examples/tree/main/gateway/headless-checkout-vanilla"> Framework-neutral vanilla TypeScript checkout. # Fiat Coverage (/payments/fiat-coverage) This page outlines the fiat currencies WalletConnect Pay currently supports for **settlement via offramp**. When a merchant or customer is configured to receive fiat instead of crypto, accepted crypto is converted and paid out in one of the currencies listed below. For the tokens and chains that can be accepted from the buyer (and which combinations settle to fiat versus direct crypto), see [Token and Chain Coverage](/payments/token-and-chain-coverage). ## Supported fiat currencies [#supported-fiat-currencies] | Currency | ISO Code | Region | |----------------|----------|----------| | US Dollar | USD | Global | | Euro | EUR | Europe | | British Pound | GBP | UK | ## Coming soon [#coming-soon] The following currencies are planned and can be enabled for merchants on request, subject to expected volume. | Currency | ISO Code | Region | |----------------------|----------|---------------| | UAE Dirham | AED | UAE | | Argentine Peso | ARS | Argentina | | Australian Dollar | AUD | Australia | | Bangladeshi Taka | BDT | Bangladesh | | Brazilian Real | BRL | Brazil | | Canadian Dollar | CAD | Canada | | Chilean Peso | CLP | Chile | | Colombian Peso | COP | Colombia | | Costa Rican Colón | CRC | Costa Rica | | Ghanaian Cedi | GHS | Ghana | | Hong Kong Dollar | HKD | Hong Kong | | Indonesian Rupiah | IDR | Indonesia | | Israeli Shekel | ILS | Israel | | Indian Rupee | INR | India | | Japanese Yen | JPY | Japan | | Kenyan Shilling | KES | Kenya | | South Korean Won | KRW | South Korea | | Mexican Peso | MXN | Mexico | | Malaysian Ringgit | MYR | Malaysia | | Nigerian Naira | NGN | Nigeria | | Nepalese Rupee | NPR | Nepal | | Philippine Peso | PHP | Philippines | | Pakistani Rupee | PKR | Pakistan | | Singapore Dollar | SGD | Singapore | | Thai Baht | THB | Thailand | | Turkish Lira | TRY | Turkey | | South African Rand | ZAR | South Africa | ## Adding more currencies [#adding-more-currencies] WalletConnect Pay can enable additional fiat corridors based on merchant demand and expected volume. If your business needs a currency not listed above — for example PLN, CHF, SEK, NOK, DKK, RON, or others — [contact us](https://share.hsforms.com/19Dpp4ayYR9uriB3xNAh0JAnxw6s) with your expected monthly volume and target markets, and we will work with you to enable it. Fiat coverage will continue to expand as additional offramp corridors are activated and as new partner relationships are integrated. # How to Pay with WalletConnect Pay (/payments/for-users) WalletConnect Pay lets you pay with crypto from any wallet, any asset, and on any network. ## What you’ll see at checkout [#what-youll-see-at-checkout] When a store supports WalletConnect Pay, you’ll typically see a **“Pay with Crypto”** option and one of the following: - **A WalletConnect QR code** shown on the POS device. You can use any wallet that supports WalletConnect Pay to scan the QR code directly from within the wallet and make the payment. - **A QR code you can scan with your phone camera**, which opens a payment page on your mobile browser where you can connect your wallet with WalletConnect and make the payment. ## How paying works [#how-paying-works] 1. Scan the QR code with a mobile wallet that supports WalletConnect Pay 1. Or scan the QR code with your mobile camera to open the payment page on your mobile browser and connect your wallet. 2. Your wallet shows the **payment intent** (what you’re paying, how much, and where it’s going). 3. Choose the **token** and **network** you want to use (for example, USDC on Ethereum). 4. Approve the payment in your wallet. 5. Wait for the transaction result and confirmation. ## What to double-check before you approve [#what-to-double-check-before-you-approve] - **Amount and currency**: make sure it matches what you expect. - **Network and fees**: fees and confirmation times depend on the network you choose. - **Where you’re sending funds**: only approve if the payment details look right. ## Your security [#your-security] WalletConnect Pay never requires your seed phrase. If any page or app asks for it, don’t proceed. # WalletConnect Pay Documentation (/payments)

WalletConnect Pay

WalletConnect Pay is a complete, end-to-end stablecoin and crypto payment solution that allows PSPs and merchants to enable crypto payments from any wallet and any asset through a single, familiar integration. Choose your integration method below to quickstart.

    How does WalletConnect Pay work?
    Resources

    Learn more about WalletConnect Pay and the wider WalletConnect brand.

    } href="/payments/api-reference" > Dive into the API reference to explore more } href="https://walletconnect.com/blog" > Read the latest news and updates from the WalletConnect team
# Merchant logo specification (/payments/merchant-api/logo-specification) The `iconUrl` field on the Merchant API accepts a public HTTPS URL pointing to a merchant logo. The logo renders at the moment of payment, so dimensions and format are a direct trust signal. A stretched or pixelated logo undermines buyer confidence at the exact step where confidence matters most. This guide covers the recommended specification for the `iconUrl` field used by [`POST /v1/merchants`](/payments/api-reference/2026-02-18/post-v1-merchants) (create) and [`PATCH /v1/merchants/{merchantId}`](/payments/api-reference/2026-02-18/patch-v1-merchants-merchantid) (update). ## Where the logo appears [#where-the-logo-appears] The merchant logo is surfaced at the two main moments of the buyer's payment flow: ### Wallet payment screen [#wallet-payment-screen] When the buyer scans the WalletConnect QR code, the wallet opens a payment screen with the merchant logo as the primary visual anchor above the amount and selected payment method. Wallet payment screen showing the merchant logo above the amount and the selected payment method

Logos and brands shown are for illustrative purposes only and do not imply affiliation or endorsement.

### Buyer checkout [#buyer-checkout] On the WalletConnect Pay buyer checkout page (opened when a buyer scans the payment QR with a generic camera or QR scanner), the merchant logo anchors the "Pay X to <Merchant>" headline above the payment options. WalletConnect Pay buyer checkout page showing the merchant logo above the amount and the Pay button

Logos and brands shown are for illustrative purposes only and do not imply affiliation or endorsement.

Because the logo renders inside different container shapes across surfaces (square cards on web, rounded squares in wallets), the asset needs to work across all of them. The specification below is designed for that. ## Specification [#specification] | Field | Value | |-------|-------| | Aspect ratio | 1:1 (square), ±5% tolerance | | Minimum dimensions | 500 × 500 px | | Recommended dimensions | 1024 × 1024 px | | Maximum dimensions | 4096 × 4096 px | | Accepted formats | JPEG, PNG, WebP, AVIF | | Max file size | 2 MB | | Transparency | Allowed in PNG and WebP | ### Format guidance [#format-guidance] - **PNG** or **WebP** for logos with transparent backgrounds. - **JPEG** for flat photographic logos with no transparency. - **AVIF** if your asset pipeline already produces it; otherwise prefer PNG. - **1024 × 1024 px** is the recommended size: it gives retina headroom across surfaces while staying well under the 2 MB cap. ### Why square [#why-square] Logos render inside square and rounded-square containers across surfaces. Non-square images get center-cropped, and the result is unpredictable: a tall rectangle that looks fine in one wallet may have its bottom half clipped in another. Square assets with the ±5% tolerance render consistently everywhere. Create a merchant with a logo hosted on your own CDN: ```http POST /v1/merchants HTTP/1.1 Host: api.pay.walletconnect.com Authorization: Bearer Idempotency-Key: 9f1c2e8a-3b6d-4e2a-b1d4-2f0a7c5e8e11 Content-Type: application/json { "merchantName": "Acme Store", "merchantEmail": "billing@acme.store", "iconUrl": "https://cdn.acme.store/brand/logo-1024.png" } ``` ```http HTTP/1.1 201 Created Content-Type: application/json { "merchant": { "id": "mrch_7kBz2qR9xPvLmN4Yw", "name": "Acme Store", "email": "billing@acme.store", "status": "active", "createdAt": "2026-05-14T10:30:00.000Z" } } ``` The URL must be publicly reachable over HTTPS at the time of the call. To change the logo later, call `PATCH /v1/merchants/{merchantId}` with a new `iconUrl`. Simply swapping the asset at your CDN URL will not update what buyers see at checkout. # Merchant FAQs (/payments/merchant/faqs) # Quickstart (/payments/merchant/quickstart) This guide takes you from zero to your first payment in six steps. Every account has two modes: **test**, where payments are simulated and no funds move, and **live**, where payments execute on-chain for real. Both use the same API — the only difference is which API key you use (`wcp_test_…` vs `wcp_…`). This guide runs through the flow in **test mode first**, so you can build and verify everything safely. See [Test mode](/payments/test-mode) for the full picture. 1. **Create a test API key** in the dashboard. 2. **Authenticate** your requests with the key. 3. **Create your first merchant** via `POST /v1/merchants`. 4. **Configure crypto settlement** via `POST /v1/merchants/{merchantId}/settlements/crypto`. 5. **Create your first payment** via `POST /v1/payments`. 6. **Check the payment status** via `GET /v1/payments/{id}/status`. Don't have access to the dashboard yet? [Contact sales](https://share.hsforms.com/19Dpp4ayYR9uriB3xNAh0JAnxw6s) to get started. ## Create a test API key [#create-a-test-api-key] 1. Open [**API Keys**](https://merchant.pay.walletconnect.com/en/api-keys) in the dashboard and sign in if prompted. 2. Create a **test key** — it starts with `wcp_test_`. Copy the key — it is shown only once. 3. Store it in a secret manager. Anyone with this key can act on behalf of your account. With a test key, everything in this guide behaves like production except that no funds move. See [Test mode](/payments/test-mode) for exactly what test payments do and don't do. ## Authenticate [#authenticate] Every request to the Merchant API uses the `Api-Key` header. ```bash export WCP_API_KEY="wcp_test_…" # the test key you just created export WCP_BASE="https://api.pay.walletconnect.com" ``` A quick sanity check — list your merchants: ```bash curl "$WCP_BASE/v1/merchants" \ -H "Api-Key: $WCP_API_KEY" ``` A `200 OK` with a (possibly empty) `data` array confirms the key works. A `401` means the key is wrong; a `403` means the key is valid but lacks permission for this account. Pin requests to a specific API version with the `WCP-Version` header (for example, `WCP-Version: 2026-02-18`). Without it, your account's default version is used. See [Versioning](/payments/api-reference/versioning) for the full policy. ## Create your first merchant [#create-your-first-merchant] A **merchant** is the entity that receives payments. One account can hold many merchants — typically one per brand, storefront, or legal entity. ```bash curl -X POST "$WCP_BASE/v1/merchants" \ -H "Api-Key: $WCP_API_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "merchantName": "Acme Store", "merchantEmail": "billing@acme.store" }' ``` The response includes the merchant `id` — save it, you'll need it for every payment. ```json { "merchant": { "id": "mrch_7kBz2qR9xPvLmN4Yw", "name": "Acme Store", "email": "billing@acme.store", "status": "active", "createdAt": "2026-02-18T10:30:00.000Z" } } ``` ```bash export WCP_MERCHANT_ID="mrch_7kBz2qR9xPvLmN4Yw" ``` `Idempotency-Key` is required on this endpoint. Use a fresh UUID per merchant — replays with the same key return the original result instead of creating a duplicate. See the full schema and field reference in [Create a merchant](/payments/api-reference/latest/post-v1-merchants). ## Configure crypto settlement [#configure-crypto-settlement] Before you can accept payments, tell us where to deliver settled funds. Each settlement entry pairs a [CAIP-19](https://chainagnostic.org/CAIPs/caip-19) `asset` (the token you want to settle in) with a [CAIP-10](https://chainagnostic.org/CAIPs/caip-10) `destination` wallet on the same chain. ```bash curl -X POST "$WCP_BASE/v1/merchants/$WCP_MERCHANT_ID/settlements/crypto" \ -H "Api-Key: $WCP_API_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "settlements": [ { "asset": "eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "destination": "eip155:8453:0x1234567890abcdef1234567890abcdef12345678" } ] }' ``` The example above registers USDC on Base. For the full list of supported `asset` values and the chains we settle to, see [Token & Chain Coverage](/payments/token-and-chain-coverage). Each `(merchant, asset)` pair must be unique — registering the same asset twice returns `settlement_asset_conflict`. To change a destination, use [Update a crypto settlement](/payments/api-reference/latest/put-v1-merchants-merchantid-settlements-crypto-id) instead. See the full schema in [Create crypto settlements](/payments/api-reference/latest/post-v1-merchants-merchantid-settlements-crypto). ## Create your first payment [#create-your-first-payment] A **payment** is a request for funds against one of your merchants. You pass the merchant via the `Merchant-Id` header and your own order identifier as `referenceId`. ```bash curl -X POST "$WCP_BASE/v1/payments" \ -H "Api-Key: $WCP_API_KEY" \ -H "Merchant-Id: $WCP_MERCHANT_ID" \ -H "Content-Type: application/json" \ -d '{ "referenceId": "ORDER-123", "amount": { "unit": "iso4217/USD", "value": "100" } }' ``` The response includes the payment `id` and a link your buyer can open in any WalletConnect-compatible wallet. Hand that link to your checkout, share it directly, or render it as a QR code. ```bash export WCP_PAYMENT_ID="pay_…" # from the response above ``` ## Check the payment status [#check-the-payment-status] Poll the status endpoint to know when the payment has completed: ```bash curl "$WCP_BASE/v1/payments/$WCP_PAYMENT_ID/status" \ -H "Api-Key: $WCP_API_KEY" \ -H "Merchant-Id: $WCP_MERCHANT_ID" ``` ```json { "status": "succeeded", "isFinal": true, "pollInMs": null, "info": { "txId": "test:pay_…", "optionAmount": { "unit": "caip19/eip155:8453/erc20:0x...", "value": "1000000" } } } ``` Use `isFinal` to decide when to stop polling. While the payment is still in flight, the response returns `isFinal: false` and a `pollInMs` hint for how long to wait before polling again. Once `isFinal` is `true`, `status` is one of `succeeded`, `failed`, `cancelled`, or `expired` and `pollInMs` is `null`. In test mode the `txId` is synthetic (`test:{paymentId}`) — no transaction is executed on-chain. Live payments return a real transaction hash. See the full response schema in [Get the payment status](/payments/api-reference/latest/get-v1-payments-id-status). ## From test to live [#from-test-to-live] That's the whole flow. Repeating these same six steps with a **live key** (`wcp_` prefix) means every payment you create is a **real payment** — on-chain execution, real funds, real settlement. Nothing else changes: same API, same endpoints, same code. Test-mode data doesn't carry over, so you'll create your merchants and settlement configuration again with the live key. # How it works (/payments/psps/headless-sdk/how-it-works) Before you install anything, it helps to understand the shape of the SDK: the stages a payment moves through, how the runtime plugs into your app, and why your WCP API key never reaches the browser. ## The payment lifecycle [#the-payment-lifecycle] Whatever UI you build, the runtime moves a payment through the same stages. Your job is to render each stage and call the matching action. ### Load the payment [#load-the-payment] The buyer arrives with a payment ID (from a QR code, link, or your checkout). The runtime fetches the payment intent — amount, merchant, accepted tokens. ### Connect a wallet [#connect-a-wallet] The buyer connects a wallet through the `WalletProvider` seam. The runtime reads their accounts across the supported networks. ### Fetch payment options [#fetch-payment-options] Given the connected accounts, WCP returns the concrete ways to pay — token, network, amount, fees, and whether compliance data is required. ### Select & build [#select--build] The buyer picks an option. The runtime builds the transaction(s) and the exact wallet-RPC actions to sign. ### Sign [#sign] The `Signer` drives the wallet through the required signatures (e.g. a permit + the payment). ### Confirm & settle [#confirm--settle] Signed results are submitted to confirm the payment. The runtime then polls status until the payment succeeds, fails, or expires. ## How it fits together [#how-it-fits-together] The Headless SDK follows a **headless runtime + host** model. The payment flow lives entirely in the SDK; your application is the **host** that consumes it. The runtime reaches the outside world only through five injectable **seams** — so you can swap in your own transport, wallet, timing, and analytics, and reuse the exact same payment machine. ```mermaid flowchart TD Host["Your gateway — the host
your UI, branding, routing"] React["@walletconnect/pay-react
usePaymentSession"] State["@walletconnect/pay-state
payment runtime"] Host -->|consumes| React React -->|drives| State State -->|reaches the outside world
only through seams| Seams subgraph Seams["Injectable seams"] direction LR Transport["Transport"] Wallet["WalletProvider"] Signer["Signer"] Clock["Clock"] Telemetry["Telemetry"] end Transport --> T2["your server → WCP API"] Wallet --> W2["AppKit / your wallet"] Signer --> S2["signing strategy"] Clock --> C2["timers / polling"] Telemetry --> A2["analytics"] ``` The five seams the runtime depends on: | Seam | What it abstracts | Provided by | | ---------------- | ------------------------------------------ | ---------------------------------------------------- | | `Transport` | WCP HTTP calls | `pay-core` `createHttpTransport` → your server route | | `WalletProvider` | connect / accounts / provider / switch | `pay-appkit`, or your own wallet integration | | `Signer` | sign a payment option's wallet-RPC actions | `pay-appkit` `createAppKitSigner` — one call (wraps `pay-state`'s signing; drop to its raw strategies only for a custom, non-AppKit wallet) | | `Clock` | intervals + page visibility (for polling) | browser timers (the SDK ships a default) | | `Telemetry` | analytics breadcrumbs | your analytics pipeline (optional) | `@walletconnect/pay-state` ships browser-ready `Clock` and `Telemetry` defaults (`browserClock`, `noopTelemetry`). In practice a React/Next.js gateway wires just the `Transport` (pointed at your server route); the `WalletProvider` and `Signer` come ready-made from `pay-appkit` (`` + `createAppKitSigner`), and it reuses `browserClock` for the rest. `Telemetry` is optional. ## The WCP API key never reaches the browser [#the-wcp-api-key-never-reaches-the-browser] The WCP API is authenticated with a secret API key that **must stay server-side**. The SDK enforces this split: the browser talks to *your* server, and your server talks to WCP. ```mermaid flowchart LR Browser["Browser
Transport seam
(no secret)"] Server["Your server route
createEngineClient
(holds the API key)"] Wcp["WalletConnect Pay
API"] Browser -->|"fetch /api/wcp/payment/:id/*"| Server Server -->|"Api-Key header"| Wcp ``` `pay-core` exposes two entry points for exactly this: `createHttpTransport` for the browser (talks to *your* server) and `createEngineClient` (imported from `@walletconnect/pay-core/server`) which holds the API key and talks to WCP. In a Next.js app, your Route Handler sits in the middle. ## Next steps [#next-steps] } href="/payments/psps/headless-sdk/implementation"> Build a complete checkout in React / Next.js, step by step. } href="/payments/psps/headless-sdk/packages-reference"> The public API of pay-core, pay-state, pay-react, and pay-appkit. # Implementation (/payments/psps/headless-sdk/implementation) **Prefer to let an AI agent build this?** Install the WalletConnect Pay Headless [skill](https://github.com/WalletConnect/skills/tree/main/skills/walletconnect-pay-headless) — with it loaded, Claude Code, Cursor, Codex, and other agents can scaffold the steps below directly in your codebase: ```bash npx skills add WalletConnect/skills --skill walletconnect-pay-headless ``` This page walks through building a complete checkout on the Headless SDK, with **React / Next.js** and **JavaScript** examples side by side. New to the SDK? Read [How it works](/payments/psps/headless-sdk/how-it-works) first for the architecture and the role of each seam. Wallet connection is now **zero-config**: the SDK owns the entire Reown AppKit setup. You install only the `@walletconnect/pay-*` packages and never touch `@reown/*`, `wagmi`, or `viem` directly. You build three things: 1. A **server proxy** — routes that forward to WCP with your secret key. 2. A **browser transport** — points the runtime at those routes. 3. The **AppKit provider** — one component (`` in React) or one factory call (`createPayAppKit` in JavaScript). The wallet seam, the signer, and the clock all come from the SDK. Then `usePaymentSession` (React) or `createPaymentController` (JavaScript) ties everything together and gives you a snapshot to render. The browser never holds the WCP API key. It talks to *your* server, and your server talks to WCP — see [The WCP API key never reaches the browser](/payments/psps/headless-sdk/how-it-works#the-wcp-api-key-never-reaches-the-browser). ## Prerequisites [#prerequisites] - **Node 18+**. The React example uses **Next.js** (App Router); the JavaScript example is framework-neutral. - **Headless checkout access** on your WalletConnect Pay account — request it from **Developers → API Keys** in the [dashboard](https://merchant.pay.walletconnect.com/en/api-keys). See [Request access and collect the keys](/payments/psps/headless-sdk/overview#request-access-and-collect-the-keys). - A **Reown project ID**, shown on the **Headless checkout** card once access is granted (public). - A **Gateway wallet key** (prefix `wcw_`), created from the same card. Secret — server-side only. - A **WalletConnect Pay key** (prefix `wcp_`, or `wcp_test_` for [test mode](/payments/test-mode)) from the same **API Keys** section, for creating payments through the Merchant API. ## Install [#install] Install only the Headless SDK. Wallet connectivity (`@reown/appkit`, `wagmi`, `viem`, `@solana/web3.js`, `@tanstack/react-query`) comes transitively through `@walletconnect/pay-appkit` — you don't add or configure any of it. ```bash npm install @walletconnect/pay-core @walletconnect/pay-state \ @walletconnect/pay-appkit @walletconnect/pay-react ``` `@walletconnect/pay-react` is the React hook binding — omit it if you're not using React. ## Step 1 — Server proxy (keep the API key server-side) [#step-1--server-proxy-keep-the-api-key-server-side] Create a server-only module that constructs the WCP client once and forwards calls. The key comes from server env and never ships to the browser. This is framework-agnostic — any server works; the example uses Next.js Route Handlers. ```typescript title="lib/server/wcp.ts" import 'server-only' import { createEngineClient } from '@walletconnect/pay-core/server' const client = createEngineClient({ apiUrl: process.env.WCP_API_URL ?? 'https://staging.api.pay.walletconnect.org', apiKey: process.env.WCP_WALLET_API_KEY ?? '' // secret — server-side only }) /** Forward a browser call to WCP and return a WcpResponse-shaped Response. */ export async function callWcp( path: string, init: { method: 'GET' | 'POST'; body?: unknown } ): Promise { const paymentId = path.split('/')[4]! // /v1/gateway/payment/:id/... let result if (path.endsWith('/options')) { result = await client.getPaymentOptions(paymentId, init.body as never) } else if (path.endsWith('/fetch')) { result = await client.fetchOptionActions(paymentId, init.body as never) } else if (path.endsWith('/confirm')) { result = await client.confirmPayment(paymentId, init.body as never) } else if (path.endsWith('/status')) { result = await client.getPaymentStatus(paymentId) } else { result = await client.getPayment(paymentId) } return Response.json(result) } ``` Then expose one route per WCP call under `/api/wcp/payment/[id]`. The browser transport (Step 2) calls exactly these paths: ```typescript title="app/api/wcp/payment/[id]/options/route.ts" import { callWcp } from '@/lib/server/wcp' export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) { const { id } = await params const body = await req.json() return callWcp(`/v1/gateway/payment/${id}/options`, { method: 'POST', body }) } ``` ```typescript title="app/api/wcp/payment/[id]/status/route.ts" import { callWcp } from '@/lib/server/wcp' export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) { const { id } = await params return callWcp(`/v1/gateway/payment/${id}/status`, { method: 'GET' }) } ``` Create the same handler for each route the transport uses: | Route Handler | Method | WCP call | | -------------------------------------- | ------ | ------------------- | | `app/api/wcp/payment/[id]/route.ts` | `GET` | `getPayment` | | `app/api/wcp/payment/[id]/options/route.ts` | `POST` | `getPaymentOptions` | | `app/api/wcp/payment/[id]/fetch/route.ts` | `POST` | `fetchOptionActions` | | `app/api/wcp/payment/[id]/confirm/route.ts` | `POST` | `confirmPayment` | | `app/api/wcp/payment/[id]/status/route.ts` | `GET` | `getPaymentStatus` | These proxy routes are a **starting point**, not production-ready — add your own origin allowlist, rate limiting, and auth before shipping. Their only job here is to keep the WCP key off the browser. ## Step 2 — Browser transport [#step-2--browser-transport] On the client, point the runtime at your proxy. `createHttpTransport` issues requests to `${baseUrl}/payment/:id/...`, matching the routes above. ```typescript import { createHttpTransport } from '@walletconnect/pay-core' const transport = createHttpTransport({ baseUrl: '/api/wcp' }) ``` That's the entire `Transport` seam. It speaks the same five methods as the server client, but routes through your origin — no key, no CORS. ## Step 3 — Set up AppKit (zero-config) [#step-3--set-up-appkit-zero-config] The SDK constructs the AppKit instance, the Wagmi/Solana adapters, and the WalletConnect-owned network set for you, in headless mode (no built-in modal — you render your own wallet picker). You supply only your `projectId` and `metadata`. In **React**, render `` once near the root. It owns AppKit's client-only construction, the `WagmiProvider` + `QueryClientProvider` tree, and an SSR-safe context. In **JavaScript**, call `createPayAppKit` and `await` its async construction. ```tsx tab="React — components/providers.tsx" 'use client' import { PayAppKitProvider } from '@walletconnect/pay-appkit/react' const projectId = process.env.NEXT_PUBLIC_APPKIT_PROJECT_ID ?? '' export function Providers({ children }: { children: React.ReactNode }) { return ( {children} ) } ``` ```typescript tab="JavaScript — appkit.ts" import { createPayAppKit } from '@walletconnect/pay-appkit' const payAppKit = createPayAppKit({ projectId: import.meta.env.VITE_APPKIT_PROJECT_ID ?? '', metadata: { name: 'Acme Pay', description: 'Headless checkout', url: window.location.origin, icons: [] } }) // Construction is client-only and async — await it before reading the instance. await payAppKit.whenReady() export const appKit = payAppKit.getInstance() ``` `` accepts an optional `queryClient` (a host with its own passes it to share one cache; omit it for a fully internal one) and optional `themeVariables` (e.g. a host font). Both `createPayAppKit` and the provider load the Reown modules through a client-only dynamic import, so AppKit's UI never enters your SSR bundle. ## Step 4 — Build the checkout [#step-4--build-the-checkout] Assemble the seams and drive the session. The **wallet seam** comes from the SDK's wallet-list hook/controller, and the **signer** is a single built-in call — `createAppKitSigner(wallet)` — so you no longer wire up signing strategies by hand. `clock` is `browserClock`. In React, `useAppKitWalletProvider` turns the AppKit instance into the `WalletProvider` seam **and** a ready-made picker controller (list, search, pagination, the pairing QR URI). Read the instance from `getPayAppKitInstance()` once `usePayAppKit().isReady` is true. In JavaScript, `createAppKitWalletList` is the framework-neutral equivalent. ```tsx tab="React — components/checkout.tsx" 'use client' import { createHttpTransport } from '@walletconnect/pay-core' import { createAppKitSigner } from '@walletconnect/pay-appkit' import { getPayAppKitInstance, useAppKitWalletProvider, usePayAppKit } from '@walletconnect/pay-appkit/react' import { browserClock } from '@walletconnect/pay-state' import { usePaymentSession } from '@walletconnect/pay-react' import { useMemo } from 'react' export function Checkout({ paymentId }: { paymentId: string }) { // The provider constructs AppKit asynchronously; read the instance once it's ready. const { isReady } = usePayAppKit() const appKit = isReady ? getPayAppKitInstance() : undefined // The wallet seam + a ready-made picker (list, search, pagination, QR URI). const { wallet, wallets, wcUri, getWcUri } = useAppKitWalletProvider(appKit, { wcPayUrl: typeof window !== 'undefined' ? window.location.href : undefined }) // Assemble the runtime seams. The signer is one built-in call. const seams = useMemo( () => ({ transport: createHttpTransport({ baseUrl: '/api/wcp' }), clock: browserClock, signer: createAppKitSigner(wallet) }), [wallet] ) const { snapshot, connectWallet, disconnectWallet, selectOption, confirmSelection, submitInfoCapture } = usePaymentSession({ paymentId, seams, wallet }) return
{/* render per snapshot.state — see Step 5 */}
} ``` ```typescript tab="JavaScript — main.ts" import { createHttpTransport } from '@walletconnect/pay-core' import { createAppKitSigner, createAppKitWalletList } from '@walletconnect/pay-appkit' import { browserClock, createPaymentController } from '@walletconnect/pay-state' import { appKit } from './appkit' // The framework-neutral wallet-list controller: list / search / paginate / QR URI / // connect — and `walletList.wallet`, the seam the runtime drives. const walletList = createAppKitWalletList(appKit, { wcPayUrl: window.location.href }) const wallet = walletList.wallet const controller = createPaymentController({ paymentId, wallet, seams: { transport: createHttpTransport({ baseUrl: '/api/wcp' }), clock: browserClock, signer: createAppKitSigner(wallet) } }) controller.subscribe(() => render(controller.getSnapshot())) controller.start() ``` In React, render the checkout from a route wrapped in your providers: ```tsx title="app/[paymentId]/page.tsx" import { Checkout } from '@/components/checkout' import { Providers } from '@/components/providers' export default async function PaymentPage({ params }: { params: Promise<{ paymentId: string }> }) { const { paymentId } = await params return } ``` ## Step 5 — Render the snapshot [#step-5--render-the-snapshot] `snapshot.state` is a single string you switch on. Each state maps to one piece of UI; the named actions advance the flow. The logic is the same for React and JavaScript — the only difference is where the snapshot comes from (`usePaymentSession` vs `controller.getSnapshot()`). ```tsx switch (snapshot.state) { case 'ReadyForWallet': // Show the QR (from getWcUri/wcUri) and a wallet picker. On pick: return connectWallet(w, w.namespaces[0])} /> case 'ConnectingWallet': return case 'LoadingOptions': return case 'OptionsReady': return ( selectOption(opt, rank)} /> ) case 'NoOptions': return case 'InformationCapture': // Render snapshot.collectData.fields, then: return case 'OptionSelected': case 'RequiresApproval': return ( ) case 'AwaitingWalletApproval': return case 'WaitingForConfirmation': return case 'Succeeded': return case 'Failed': case 'PaymentExpired': case 'PaymentCancelled': case 'InvalidPayment': case 'SanctionedUser': return } ``` That's a full gateway. Connect → options → (optional KYC) → confirm → sign → settle, all driven by the runtime; you only render and call actions. Once a wallet is connected, `disconnectWallet(namespace?)` drops one namespace or all of them. ## Environment variables [#environment-variables] ```bash title=".env.local" # Reown project ID from the Headless checkout card — wallet connection / QR pairing (public) NEXT_PUBLIC_APPKIT_PROJECT_ID= # Gateway wallet key (wcw_…) — server-side only, NEVER exposed to the browser WCP_API_URL=https://staging.api.pay.walletconnect.org WCP_WALLET_API_KEY= ``` In a Vite / non-Next.js host, expose the project ID under that toolchain's client env convention (e.g. `VITE_APPKIT_PROJECT_ID`) and keep `WCP_WALLET_API_KEY` on the server only. ## Reference apps [#reference-apps] } href="https://github.com/WalletConnect/walletconnect-pay-examples/tree/main/gateway/headless-checkout"> The full React checkout — `` + `usePaymentSession`, no `@reown/*` in the app. } href="https://github.com/WalletConnect/walletconnect-pay-examples/tree/main/gateway/headless-checkout-vanilla"> The same checkout with no framework — `createPaymentController` + manual subscribe + imperative render. ## Next steps [#next-steps] } href="/payments/psps/headless-sdk/packages-reference"> The full public API of pay-core, pay-state, pay-react, and pay-appkit. } href="/payments/api-reference/index"> The Gateway and Payments endpoints behind the SDK. # Headless SDK (/payments/psps/headless-sdk/overview) **Building with an AI coding agent?** Install the WalletConnect Pay Headless [skill](https://github.com/WalletConnect/skills/tree/main/skills/walletconnect-pay-headless) and your agent (Claude Code, Cursor, Codex, and others) can scaffold this integration for you: ```bash npx skills add WalletConnect/skills --skill walletconnect-pay-headless ``` The Headless SDK is a set of framework-agnostic [`@walletconnect/pay-*`](https://www.npmjs.com/org/walletconnect) packages that own the WalletConnect Pay (WCP) payment flow while you own the UI. It's the exact runtime that powers our own hosted Buyer Experience — extracted so you can build a fully branded, fully owned checkout on the same runtime. You get the payment state machine, WCP API client, and wallet orchestration; you bring your own UI, branding, routing, and infrastructure. **Beta (v0.1.x)** — The Headless SDK is under active development. Public APIs may change between minor releases until 1.0. [Talk to us](https://share.hsforms.com/1XsMCkUxFT2Cte8SCeAh89wnxw6s) before going to production. ## Who is it for? [#who-is-it-for] - **Payment Service Providers & Acquirers** who want crypto checkout inside their own product, with their own design system and domain — not a redirect to a third-party page. - **Platforms & marketplaces** embedding pay-with-crypto directly into an existing checkout flow. - **Teams that need control** over every step of the UX: wallet selection, network/token choice, compliance prompts, success and error states. If you just want to accept payments with the least effort, use the [hosted gateway](/payments) or the [Ecommerce integration](/payments/ecommerce/overview) instead. Reach for the Headless SDK when you need to **own the experience**. ## What you get [#what-you-get] }> The full payment state machine (load → connect → quote → sign → confirm → settle), fully framework-agnostic. No UI imposed. }> A zero-dependency client for the WalletConnect Pay API, with the secret API key safely held server-side. }> A single `usePaymentSession` hook that projects the runtime into a clean, serializable snapshot plus named actions — zero state-machine internals leak into your components. }> A ready-made adapter over [Reown AppKit](https://reown.com/appkit) for wallet connection across EVM and Solana — or bring your own. ## Supported networks & tokens [#supported-networks--tokens] The Headless SDK supports the full WalletConnect Pay token and network coverage — USDC, USDT, EURC, PYUSD and more across Ethereum, Polygon, Base, Optimism, Arbitrum (and Solana, rolling out). See [Token & chain coverage](/payments/token-and-chain-coverage) for the live list. ## Request access and collect the keys [#request-access-and-collect-the-keys] The Headless SDK is gated. Access is granted per account from the [WalletConnect Pay dashboard](https://merchant.pay.walletconnect.com/). ### Open Developers → API Keys [#open-developers--api-keys] Go to **Developers → API Keys** in the dashboard and sign in if prompted. ### Request access on the Headless checkout card [#request-access-on-the-headless-checkout-card] Find the **Headless checkout** card and click **Request access**. The WalletConnect Pay team reviews the request and gets back to you. ### Collect your credentials [#collect-your-credentials] Once access is granted, the **Headless checkout** card exposes the credentials for embedding the SDK: - A **Reown project ID** — used to configure the Headless feature in Reown AppKit. It is public. - A **Gateway wallet key** button — each key (prefix `wcw_`) authenticates your server against the WalletConnect Pay API. ### Grab your WalletConnect Pay key [#grab-your-walletconnect-pay-key] In the same **API Keys** section, copy your **WalletConnect Pay key** (prefix `wcp_` for live, `wcp_test_` for test) — the Merchant API key used to create payments. See [Test mode](/payments/test-mode) for the difference between the two. With the Reown project ID, a Gateway wallet key, and a WalletConnect Pay key, you have everything needed to run the Headless SDK end to end. Map them to environment variables as shown in [Implementation](/payments/psps/headless-sdk/implementation#environment-variables). ## Full example [#full-example] The fastest way to learn the SDK is to read the reference checkout it's extracted from. Every snippet in these docs comes from it. } href="https://github.com/WalletConnect/walletconnect-pay-examples/tree/main/gateway/headless-checkout"> A complete, branded Next.js checkout built on the four packages. ## Next steps [#next-steps] } href="/payments/psps/headless-sdk/how-it-works"> The payment lifecycle, the host + seams model, and how the API key stays server-side. } href="/payments/psps/headless-sdk/implementation"> Build a complete checkout in React / Next.js, step by step. # Packages Reference (/payments/psps/headless-sdk/packages-reference) The runtime is split into layered packages. Each is independently consumable, and lower layers never depend on higher ones — so you can take only what you need.
Package Role Depends on
@walletconnect/pay-core WCP API client — contract types, CAIP utilities, the browser Transport seam (createHttpTransport), and the server-side createEngineClient that holds your API key. The foundation. —
@walletconnect/pay-state The headless runtime — the payment state machine, orchestration, the injectable seam contracts, the session factory, and the public PaymentSnapshot view-model. No React, no HTTP client, no wallet SDK. pay-core
@walletconnect/pay-react Thin React binding — usePaymentSession returns the snapshot plus domain actions. Zero state-machine leak. pay-state
@walletconnect/pay-appkit Reown AppKit adapter — implements the WalletProvider seam over a Reown AppKit instance (plus the Solana web3 loader). A /react subpath ships the wallet-connection hook. pay-state
## `@walletconnect/pay-core` [#walletconnectpay-core] The foundation: WCP contract types, CAIP utilities, and the `Transport` seam. Zero runtime dependencies. Two entry points — a browser-safe main entry and a server-only `/server` entry that holds the key. ### Browser entry — `@walletconnect/pay-core` [#browser-entry--walletconnectpay-core] ```typescript import { createHttpTransport, type Transport, type HttpTransportConfig } from '@walletconnect/pay-core' interface HttpTransportConfig { baseUrl?: string // default '/api/wcp' fetch?: typeof fetch timeoutMs?: number // default 30_000 } function createHttpTransport(config?: HttpTransportConfig): Transport ``` The `Transport` contract (the seam the runtime depends on) — five methods, each resolving to a `WcpResponse` envelope (never throwing): ```typescript interface Transport { getPayment(paymentId): Promise> getPaymentOptions(paymentId, request): Promise> fetchOptionActions(paymentId, request): Promise> confirmPayment(paymentId, request): Promise> getPaymentStatus(paymentId): Promise> } ``` Also exported: all WCP contract types (`GetPaymentResponse`, `PaymentOptionExtended`, `Amount`, `CollectData`, `PaymentStatus`, …), CAIP utilities (`parseCaip2`, `parseCaip10`, …), and transport error helpers (`TRANSPORT_ERROR_CODES`, `isAbortError`, `DEFAULT_TIMEOUT_MS`). ### Server entry — `@walletconnect/pay-core/server` [#server-entry--walletconnectpay-coreserver] ```typescript import { createEngineClient, type EngineClient, type EngineClientConfig, DEFAULT_VERSION } from '@walletconnect/pay-core/server' interface EngineClientConfig { apiUrl: string // e.g. https://staging.api.pay.walletconnect.org (no trailing slash) apiKey: string // your Gateway Api-Key — keep secret, server-side only version?: string // WCP API version; defaults to DEFAULT_VERSION fetch?: typeof fetch timeoutMs?: number // default 30_000 } function createEngineClient(config: EngineClientConfig): EngineClient ``` `EngineClient` exposes the same five methods as `Transport`, but attaches the secret `Api-Key` and `Wcp-Version` headers and calls WCP directly. Use it only on the server. ## `@walletconnect/pay-state` [#walletconnectpay-state] The headless runtime: the payment state machine, the injectable seam contracts, the framework-agnostic `PaymentController`, the signing strategies, and the public `PaymentSnapshot` view-model. ### `createPaymentController` [#createpaymentcontroller] The framework-agnostic binding (the React hook wraps this). Use it directly in a non-React host. ```typescript import { createPaymentController, type PaymentController, type PaymentControllerOptions } from '@walletconnect/pay-state' interface PaymentControllerOptions { paymentId: string seams: PaymentSessionSeams // { transport, clock, signer?, telemetry? } wallet: WalletProvider initialPayment?: GetPaymentResponse signingTimeoutMs?: number onMachineEvent?: MachineEventObserver // read-only analytics observer } function createPaymentController(options: PaymentControllerOptions): PaymentController ``` ```typescript interface PaymentController { getSnapshot(): PaymentSnapshot subscribe(listener: () => void): () => void start(): void destroy(): void // domain actions (see the React hook below for the full list) connectWallet(wallet, namespace?, options?): void // … } ``` ### Seams [#seams] The runtime reaches the outside world only through these contracts: ```typescript interface PaymentSessionSeams { transport: Transport // WCP calls (from pay-core) clock: Clock // intervals + page visibility (for status polling) signer?: Signer // signing capability — required for an end-to-end payment telemetry?: Telemetry // optional analytics breadcrumbs } interface WalletProvider { getAccounts(): Partial> getProvider(network: Caip2 & { namespace: T }): ProviderForNamespace | null connect(wallet: WalletRef, namespace: Namespace, options?: WalletConnectOptions): Promise disconnect(namespace?: Namespace): Promise switchNetwork(caipNetworkId: string): Promise subscribe(listener: () => void): () => void } interface Signer { signActions(option: PaymentOptionExtended, range?: ActionRange): Promise } ``` Browser defaults are provided so you only have to inject `transport`, `wallet`, and `signer`: ```typescript import { browserClock, noopTelemetry, browserDefaults } from '@walletconnect/pay-state' ``` ### Signing strategies [#signing-strategies] AppKit hosts don't need these directly — `@walletconnect/pay-appkit` exports a zero-config `createAppKitSigner(wallet)` that wraps them with the bundled Solana codec. These are the low-level primitives, for a custom wallet integration. ```typescript import { EvmSigningStrategy, SolanaSigningStrategy, signOptionActions } from '@walletconnect/pay-state' // Dispatch each of an option's actions to the matching strategy: signOptionActions(option: PaymentOptionExtended, strategies: SigningStrategy[], range?: ActionRange): Promise ``` ### `PaymentSnapshot` [#paymentsnapshot] The public, serializable view-model. `state` is one of: | Group | States | | ----------- | ---------------------------------------------------------------------------------------- | | Loading | `Initializing` | | Wallet | `ReadyForWallet`, `ConnectingWallet` | | Options | `LoadingOptions`, `OptionsReady`, `NoOptions`, `OptionSelected` | | Compliance | `InformationCapture` | | Approval | `RequiresApproval`, `AwaitingWalletApproval`, `WaitingForConfirmation` | | Terminal | `Succeeded`, `Failed`, `PaymentExpired`, `PaymentCancelled`, `InvalidPayment`, `SanctionedUser` | ```typescript interface PaymentSnapshot { state: PaymentState payment?: GetPaymentResponse options: PaymentOptionExtended[] selectedOption?: PaymentOptionExtended collectData?: CollectData | null wallet: { isConnected: boolean; accounts: string[] } requiresApproval: boolean signingError?: { code: string; message?: string } isQuoteExpired: boolean profileId?: string profileNotFound: boolean // …diagnostic fields } ``` ## `@walletconnect/pay-react` [#walletconnectpay-react] A single hook — `usePaymentSession` — a `useSyncExternalStore`-based binding over the controller. SSR-safe, tear-free, zero XState leak. ```typescript import { usePaymentSession, type UsePaymentSessionOptions, type PaymentSessionApi } from '@walletconnect/pay-react' function usePaymentSession(options: UsePaymentSessionOptions): PaymentSessionApi ``` `UsePaymentSessionOptions` matches `PaymentControllerOptions` (`paymentId`, `seams`, `wallet`, `initialPayment?`, `signingTimeoutMs?`, `onMachineEvent?`). The return is `{ snapshot }` plus the named actions: | Action | Drives | | ----------------------------------------------- | ----------------------------------------------- | | `connectWallet(wallet, namespace?, options?)` | Begin connecting a wallet | | `disconnectWallet(namespace?)` | Disconnect one namespace, or all | | `selectOption(option, rank)` | Pick a payment option | | `confirmSelection()` | Confirm and move toward signing | | `unselectOption()` | Return to the option list | | `submitInfoCapture(data)` | Submit collected KYC/contact data | | `navigateBack()` | Step back | Plus a **host-orchestration channel** for signals the runtime can't observe itself — `refreshOptions`, `notifyQuoteExpired`, `acknowledgeQuoteExpiry`, `markUserSanctioned`, `setProfileLookup`, `notifyPaymentExpired`, `failWalletConnection`. Most gateways won't need these to start. ## `@walletconnect/pay-appkit` [#walletconnectpay-appkit] The Reown AppKit adapter — it owns the entire AppKit setup so a host stays `@reown/*`-free. It constructs the instance, implements the `WalletProvider` seam over it, provides a zero-config `Signer`, and ships a headless wallet-picker controller. The main entry is framework-neutral; the React provider + hooks live on `/react`. ### Main entry — `@walletconnect/pay-appkit` [#main-entry--walletconnectpay-appkit] ```typescript import { createPayAppKit, // ({ projectId, metadata, themeVariables? }) => PayAppKit (one-call setup) createAppKitSigner, // (wallet) => Signer (zero-config, bundles the Solana codec) createAppKitWalletList, // (appKit, options?) => AppKitWalletList (framework-neutral picker) createAppKitWalletProvider, // (appKit, options?) => WalletProvider SUPPORTED_NETWORKS, EVM_NETWORKS, // the WC-owned network set (baked in, not host config) loadSolanaWeb3, // lazy @solana/web3.js codec loader for the Solana signing strategy applyPlacements, resolvePlacements, // wallet-ordering helpers type AppKit, // re-exported AppKit instance type — don't import @reown/appkit directly type PayAppKit, type CreatePayAppKitOptions, type PayAppKitMetadata, type WalletListItem, type ConnectedWallet, type WalletListState, type WalletListOptions } from '@walletconnect/pay-appkit' ``` `createPayAppKit` builds the instance with the WC-owned networks + adapters in headless mode. It's **client-only and async** — `await payAppKit.whenReady()`, then read `getInstance()` / `getWagmiConfig()` / `getHooks()` / `getError()` / `isInitialized()`. `createAppKitWalletList` returns a controller — `wallet` (the seam), `getState()`, `subscribe()`, `fetchWallets()`, `search()`, `loadMore()`, `getWcUri()` — for non-React hosts. ### React entry — `@walletconnect/pay-appkit/react` [#react-entry--walletconnectpay-appkitreact] The zero-config provider that owns AppKit's construction + the Wagmi/Query tree + an SSR-safe context, plus the state hook and the imperative instance accessor: ```typescript import { PayAppKitProvider, // usePayAppKit, // SSR-safe hook: isReady / account / network / walletConnection / connect / disconnect / … getPayAppKitInstance, // module-level accessor to the same AppKit instance (for non-hook consumers) useAppKitWalletProvider, type AppKitWalletProviderHandle, type UseAppKitWalletProviderOptions } from '@walletconnect/pay-appkit/react' function useAppKitWalletProvider(appKit: AppKit | undefined, options?: UseAppKitWalletProviderOptions): AppKitWalletProviderHandle ``` `useAppKitWalletProvider`'s handle extends `WalletListState` and adds `wallet` (the seam to hand `usePaymentSession`), `searchQuery`/`setSearchQuery` (debounced), `fetchWallets`, `loadMore`, and `getWcUri` for the pairing QR. ## Next steps [#next-steps] } href="/payments/psps/headless-sdk/implementation"> The step-by-step React / Next.js walkthrough. } href="/payments/api-reference/index"> The Gateway and Payments endpoints behind the SDK. # WalletConnect Pay for PSPs (/payments/psps/overview) WalletConnect Pay lets Payment Service Providers, acquirers, and platforms accept crypto payments on the same runtime that powers our hosted gateway. You choose how much of the experience you own — from a redirect to a hosted page, all the way to a fully branded checkout built inside your own product. ## Two ways to integrate [#two-ways-to-integrate] }> Send buyers to `pay.walletconnect.com` and let WalletConnect Pay handle the whole experience — wallet selection, quoting, signing, and settlement. The fastest path to accepting payments, with no UI to build. } href="/payments/psps/headless-sdk/overview"> Build a **fully branded, fully owned checkout** inside your own product. You get the payment runtime, WCP client, and wallet orchestration as framework-agnostic packages; you bring the UI, branding, and domain. ## Which one is for me? [#which-one-is-for-me] Reach for the **hosted gateway** if you want to accept payments with the least effort and are happy to send buyers to a WalletConnect-hosted page. See the [hosted gateway overview](/payments) or the [Ecommerce integration](/payments/ecommerce/overview). Reach for the **Headless SDK** when you need to **own the experience** end to end — wallet selection, network and token choice, compliance prompts, success and error states — all inside your own design system and domain, with no redirect to a third-party page. The Headless SDK is gated: request access from **Developers → API Keys** in the [dashboard](https://merchant.pay.walletconnect.com/en/api-keys) — see [Request access and collect the keys](/payments/psps/headless-sdk/overview#request-access-and-collect-the-keys). Both paths run on the same WCP backend and share the same token and network coverage. You can start with the hosted gateway and move to the Headless SDK later without re-doing your backend integration. ## Who is it for? [#who-is-it-for] - **Payment Service Providers & Acquirers** offering crypto checkout inside their own product, with their own design system and domain. - **Platforms & marketplaces** embedding pay-with-crypto directly into an existing checkout flow. - **Teams that need control** over every step of the UX. ## Next steps [#next-steps] } href="/payments/psps/headless-sdk/overview"> Own the full checkout experience with the `@walletconnect/pay-*` packages. } href="/payments/api-reference/index"> The Gateway and Payments endpoints behind WalletConnect Pay. }> Are you a PSP or acquirer? Tell us what you're building and we'll help you get set up. # Report an Issue (/payments/report-an-issue) The WalletConnect Pay Dashboard is your single place to report bugs and share feedback. ## How to Report an Issue [#how-to-report-an-issue] Follow these steps to get in touch with our support team: ### Log in to the WalletConnect Pay Dashboard [#log-in-to-the-walletconnect-pay-dashboard] Go to [merchant.pay.walletconnect.com](https://merchant.pay.walletconnect.com/) and log in with your account. ### Open the Help Center [#open-the-help-center] Once logged in, click the chat bubble in the bottom-right corner of the page, or choose **Report a bug** from the Help Center sidebar. Help Center chat bubble in the WalletConnect Dashboard ### Report the issue [#report-the-issue] From the help desk modal, select: - **File a bug report** - Submit the issue to our support team. - **Check our docs** - Browse through our documentation for answers. Our team will review your submission and get back to you as soon as possible. ## Support Response Times [#support-response-times] We don't offer guaranteed response times. Our team answers general issues as capacity allows, so replies may take anywhere from a few hours to several days. Thanks for your patience. # Test mode (/payments/test-mode) Every WalletConnect Pay account has two modes: **test** and **live**. Test mode lets you build and verify your full integration — merchants, settlement configuration, and payments — without executing anything on-chain. Throughout these docs and on the hosted payment page, purple indicates test mode. In the dashboard, the **Test / Live** selector at the top shows which mode you're working in. ## How test mode works [#how-test-mode-works] Test and live are separated at the **account level**, and you choose the mode by **which API key you use**. There is no `test` flag or mode parameter on any request — a payment created with a test key is a test payment, and a payment created with a live key is a live payment. ```mermaid flowchart LR subgraph test ["Test mode"] TK["wcp_test_… key"] --> TP["Test payment"] TP --> TS["Synthetic settlement
(no on-chain execution)"] end subgraph live ["Live mode"] LK["wcp_… key"] --> LP["Live payment"] LP --> LS["Real on-chain settlement"] end API["Same API
api.pay.walletconnect.com"] --> TK API --> LK style test fill:#F5F3FF,stroke:#7C3AED,color:#5B21B6 style TK fill:#EDE9FE,stroke:#7C3AED,color:#5B21B6 style TP fill:#EDE9FE,stroke:#7C3AED,color:#5B21B6 style TS fill:#EDE9FE,stroke:#7C3AED,color:#5B21B6 ``` Both modes use the **same API, the same base URL, and the same endpoints**. Nothing about your code changes between test and live except the key. | | Test mode | Live mode | |---|---|---| | **API key prefix** | `wcp_test_` | `wcp_` | | **Base URL** | `https://api.pay.walletconnect.com` | `https://api.pay.walletconnect.com` | | **On-chain execution** | None — settlement is simulated | Real transactions | | **Transaction hash** | Synthetic (`test:{paymentId}`) | Real on-chain hash | | **Payment limit** | None | Pilot limit until your account goes live | | **Data** | Fully separate from live data | Fully separate from test data | ## Test API keys [#test-api-keys] Test keys are created in the [dashboard](https://merchant.pay.walletconnect.com/en/api-keys), alongside live keys. You can tell them apart by the prefix: test keys always start with `wcp_test_`. ```bash export WCP_API_KEY="wcp_test_…" # test key — safe to experiment with export WCP_BASE="https://api.pay.walletconnect.com" ``` Merchants, settlement configurations, and payments created with a test key exist only in test mode. They are never visible to live requests, and vice versa. API responses do **not** say whether a resource is test or live. The mode is determined entirely by the key that created the resource — if you need to tell test and live data apart in your systems, track which key produced it. ## What test payments do [#what-test-payments-do] A test payment moves through the same lifecycle as a live payment — created, processing, succeeded — so you can exercise your full integration, including status polling. The differences: - **No funds move.** Nothing is executed on-chain and no settlement is delivered. - **The transaction hash is synthetic.** Completed test payments report a `txId` of the form `test:{paymentId}` instead of a real on-chain hash. - **Amounts are realistic.** Payment options are quoted from the amount you request, converted per token at current exchange rates — the same way live payments are priced. ## Test mode in the dashboard [#test-mode-in-the-dashboard] You can run the whole test flow from the [dashboard](https://merchant.pay.walletconnect.com) without writing any code. ### Create a test payment [#create-a-test-payment] 1. Switch the dashboard to **Test** with the selector in the top-right corner. 2. If you don't have any merchants in test mode yet, open **Merchants** and click **Create merchant** — give it a name and a contact email. Merchants are separate between test and live, so your live merchants don't appear in test. 3. Open **Payments** and click **Create payment**. 4. Select a merchant and enter any amount — test mode has no payment limit. 5. Click **Create payment**, then **Copy link** to share the payment link or open it yourself.
![Create payment dialog in test mode with a merchant selected and an amount of 10 USD entered](/images/test-mode-create-payment.png)
Create payment in test mode (note the selector on Test, top right) — pick a merchant and enter any amount.
### Simulate status changes [#simulate-status-changes] Test payments don't move through their lifecycle on their own — you drive them, from either of two places: - **The hosted payment page** — open the generated payment link. In test mode the page shows a purple banner ("You're in test mode. No real funds move.") and lets you pay with a simulated **Test Wallet**. A floating **Test Console** lets you simulate the transition: **Confirm success**, **Simulate failure**, **Expire payment**, or **Cancel payment**. - **The dashboard payments list** — in test mode, each payment row has a **Simulation actions** menu (three dots): pick **Mark as [status]** to transition it.
![Hosted payment page in test mode showing the purple test-mode banner, a Test Wallet payment option, and the Test Console button](/images/test-mode-payment-page.png)
The hosted payment page in test mode — purple banner, Test Wallet, and the Test Console at the bottom.
![Test Console panel titled Simulate transition, showing a test payment with Expire payment and Cancel payment actions](/images/test-mode-test-console.png)
The Test Console — available actions depend on the payment's current status.
![Dashboard payments list in test mode with the Simulation actions menu open on a processing payment, showing Mark as Succeeded, Mark as Failed, and Mark as Expired options](/images/test-mode-simulation-actions.png)
Simulation actions in the dashboard — a processing payment can be marked as succeeded, failed, or expired.
### Allowed status transitions [#allowed-status-transitions] Whichever surface you use, a test payment can only move along these paths: ```mermaid stateDiagram-v2 direction LR requires_action --> processing requires_action --> expired requires_action --> cancelled processing --> succeeded processing --> failed processing --> expired ``` Terminal states (`succeeded`, `failed`, `expired`, `cancelled`) have no further actions. This lets you exercise every status your integration needs to handle — including the failure paths that are hard to produce on demand with real payments. ## The pilot limit [#the-pilot-limit] Test mode has no payment limit — build and verify as much as you need. **Live mode** starts in **pilot**: live payments are real, but they count toward a total payment limit until your account is taken off pilot. In live mode, the dashboard home shows a **Pilot to Live** card with the limit you have left. When you're ready to process real volume, click **Request to go live** — our team reviews the request and removes the limit. Switching from test to live is just a key swap: create a **live key** (prefix `wcp_`) in the [dashboard](https://merchant.pay.walletconnect.com/en/api-keys) and use it instead — same API, same endpoints, no code changes. Test-mode data does not carry over, so re-create your merchants and settlement configuration with the live key. ## Next steps [#next-steps] } href="/payments/merchant/quickstart"> Create your first test payment in six steps. } href="/payments/api-reference/authentication"> How API keys and the Api-Key header work. # Token and Chain Coverage (/payments/token-and-chain-coverage) This page outlines the tokens and blockchains currently supported in General Availability within WalletConnect Pay. It provides a clear view of: - **Acceptance** — whether a token on a given chain can be accepted from the buyer. - **Settlement** — what the merchant or customer receives after acceptance, either direct crypto or fiat via an offramp, depending on the customer configuration. This list will be updated over time as assets move from beta into General Availability and as settlement coverage expands. ## Supported tokens and chains [#supported-tokens-and-chains] When creating crypto settlements, use the CAIP-19 token identifier below when specifying the settlement token contract. See the [Create crypto settlements](/payments/api-reference/2026-02-18/post-v1-merchants-merchantid-settlements-crypto) endpoint for details. | Token | Chain | CAIP-19 | Acceptance | Settlement | |---------|-----------------|---------|:----------:|------------| | USDC | Arbitrum | `eip155:42161/erc20:0xaf88d065e77c8cC2239327C5EDb3A432268e5831` | ✅ | Direct Crypto or Fiat (USD, EUR) | | USDC | Base | `eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` | ✅ | Direct Crypto or Fiat (USD, EUR) | | USDC | Polygon | `eip155:137/erc20:0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359` | ✅ | Direct Crypto or Fiat (USD, EUR) | | USDC | Ethereum | `eip155:1/erc20:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48` | ✅ | Direct Crypto or Fiat (USD, EUR) | | USDC | Optimism | `eip155:10/erc20:0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85` | ✅ | Direct Crypto | | USDC | BSC | `eip155:56/erc20:0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d` | ✅ | Direct Crypto | | USDC | Celo | `eip155:42220/erc20:0xcebA9300f2b948710d2653dD7B07f33A8B32118C` | ✅ | Direct Crypto | | USDC | Monad | `eip155:143/erc20:0x754704Bc059F8C67012fEd69BC8A327a5aafb603` | ✅ | Direct Crypto | | USDC | Arc | `eip155:5042/erc20:0x3600000000000000000000000000000000000000` | ✅ | Direct Crypto | | USDC | Solana | `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/token:EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` | ✅ | Direct Crypto or Fiat (USD, EUR) | | USDC | Stellar | `stellar:pubnet/asset:USDC-GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN` | ✅ | Direct Crypto | | EURC | Base | `eip155:8453/erc20:0x60a3E35Cc302bFA44Cb288Bc5a4F316Fdb1adb42` | ✅ | Direct Crypto or Fiat (USD, EUR) | | EURC | Ethereum | `eip155:1/erc20:0x1aBaEA1f7C830bD89Acc67eC4af516284b1bC33c` | ✅ | Direct Crypto or Fiat (USD, EUR) | | EURC | Solana | `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/token:HzwqbKZw8HxMN6bF2yFZNrht3c2iXXzpKcFu7uBEDKtr` | ✅ | Direct Crypto | | EURe | Polygon | `eip155:137/erc20:0xE0aEa583266584DafBB3f9C3211d5588c73fEa8d` | ✅ | Direct Crypto | | EURAU | Ethereum | `eip155:1/erc20:0x4933A85b5b5466Fbaf179F72D3DE273c287EC2c2` | ✅ | Direct Crypto | | EURAU | Polygon | `eip155:137/erc20:0x4933A85b5b5466Fbaf179F72D3DE273c287EC2c2` | ✅ | Direct Crypto | | EURAU | Base | `eip155:8453/erc20:0x4933A85b5b5466Fbaf179F72D3DE273c287EC2c2` | ✅ | Direct Crypto | | EURAU | Arbitrum | `eip155:42161/erc20:0x4933A85b5b5466Fbaf179F72D3DE273c287EC2c2` | ✅ | Direct Crypto | | EURAU | Optimism | `eip155:10/erc20:0x4933A85b5b5466Fbaf179F72D3DE273c287EC2c2` | ✅ | Direct Crypto | | CHFAU | Ethereum | `eip155:1/erc20:0xBD4DfC058eb95b8De5ceAF39966A1a70F5556F78` | ✅ | Direct Crypto | | CHFAU | Polygon | `eip155:137/erc20:0xBD4DfC058eb95b8De5ceAF39966A1a70F5556F78` | ✅ | Direct Crypto | | CHFAU | Base | `eip155:8453/erc20:0xBD4DfC058eb95b8De5ceAF39966A1a70F5556F78` | ✅ | Direct Crypto | | AUSD | Ethereum | `eip155:1/erc20:0x00000000eFE302BEAA2b3e6e1b18d08D69a9012a` | ✅ | Direct Crypto | | AUSD | Arbitrum | `eip155:42161/erc20:0x00000000eFE302BEAA2b3e6e1b18d08D69a9012a` | ✅ | Direct Crypto | | AUSD | Base | `eip155:8453/erc20:0x00000000eFE302BEAA2b3e6e1b18d08D69a9012a` | ✅ | Direct Crypto | | AUSD | BSC | `eip155:56/erc20:0x00000000eFE302BEAA2b3e6e1b18d08D69a9012a` | ✅ | Direct Crypto | | USDG | Ethereum | `eip155:1/erc20:0xe343167631d89B6Ffc58B88d6b7fB0228795491D` | ✅ | Direct Crypto | | USDG | Robinhood Chain | `eip155:4663/erc20:0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168` | ✅ | Direct Crypto | | OUSD | Ethereum | `eip155:1/erc20:0x9f6F3991D525015a6F8CaF062C83b62fD3AC4436` | ✅ | Direct Crypto | | OUSD | Base | `eip155:8453/erc20:0xB2000000000000000000002fEb517dFeC7415344` | ✅ | Direct Crypto | | PYUSD | Ethereum | `eip155:1/erc20:0x6c3ea9036406852006290770bedfcaba0e23a0e8` | ✅ | Direct Crypto | | PYUSD | Arbitrum | `eip155:42161/erc20:0x46850ad61c2b7d64d08c9c754f45254596696984` | ✅ | Direct Crypto | | SoFiUSD | Ethereum | `eip155:1/erc20:0x0CB6d03B0aC88A463F67B7Ad99f9f3ec4678092E` | ✅ | Direct Crypto | | USAT | Ethereum | `eip155:1/erc20:0x07041776f5007ACa2A54844F50503a18A72A8b68` | ✅ | Direct Crypto | | USDT | Ethereum | `eip155:1/erc20:0xdAC17F958D2ee523a2206206994597C13D831ec7` | ✅ | Direct Crypto or Fiat (USD, EUR) | | USDT | Polygon | `eip155:137/erc20:0xc2132D05D31c914a87C6611C10748AEb04B58e8F` | ✅ | Direct Crypto or Fiat (USD, EUR) | | USDT | Arbitrum | `eip155:42161/erc20:0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9` | ✅ | Direct Crypto | | USDT | BSC | `eip155:56/erc20:0x55d398326f99059fF775485246999027B3197955` | ✅ | Direct Crypto | | USDT | Solana | `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/token:Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB` | ✅ | Direct Crypto or Fiat (USD, EUR) | | USDT | Tron | `tron:0x2b6653dc/trc20:TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t` | ✅ | Direct Crypto | | ETH | Ethereum | `eip155:1/slip44:60` | ✅ | Direct Crypto | | ETH | Optimism | `eip155:10/slip44:60` | ✅ | Direct Crypto | | ETH | Base | `eip155:8453/slip44:60` | ✅ | Direct Crypto | | ETH | Arbitrum | `eip155:42161/slip44:60` | ✅ | Direct Crypto | | ETH | Robinhood Chain | `eip155:4663/slip44:60` | ✅ | Direct Crypto | | BNB | BSC | `eip155:56/slip44:714` | ✅ | Direct Crypto | | POL | Polygon | `eip155:137/slip44:966` | ✅ | Direct Crypto | | MON | Monad | `eip155:143/slip44:268435779` | ✅ | Direct Crypto | | SOL | Solana | `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/slip44:501` | ✅ | Direct Crypto | | WETH | Ethereum | `eip155:1/erc20:0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2` | ✅ | Direct Crypto | | WETH | Optimism | `eip155:10/erc20:0x4200000000000000000000000000000000000006` | ✅ | Direct Crypto | | WETH | Base | `eip155:8453/erc20:0x4200000000000000000000000000000000000006` | ✅ | Direct Crypto | | WETH | Arbitrum | `eip155:42161/erc20:0x82aF49447D8a07e3bd95BD0d56f35241523fBab1` | ✅ | Direct Crypto | | WPOL | Polygon | `eip155:137/erc20:0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270` | ✅ | Direct Crypto | | WCT | Ethereum | `eip155:1/erc20:0xeF4461891DfB3AC8572cCf7C794664A8DD927945` | ✅ | Direct Crypto | | WCT | Optimism | `eip155:10/erc20:0xeF4461891DfB3AC8572cCf7C794664A8DD927945` | ✅ | Direct Crypto | | WCT | Base | `eip155:8453/erc20:0xeF4461891DfB3AC8572cCf7C794664A8DD927945` | ✅ | Direct Crypto | | WCT | Solana | `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/token:WCTk5xWdn5SYg56twGj32sUF3W4WFQ48ogezLBuYTBY` | ✅ | Direct Crypto | ## Definitions [#definitions] ### Acceptance [#acceptance] WalletConnect Pay accepts the token on the specified chain from the buyer as part of the payment flow. ### Settlement [#settlement] After acceptance, WalletConnect Pay delivers funds to the merchant or customer in one of the following ways: - **Direct Crypto** — the payment is settled in crypto to the merchant's or customer's wallet. Settlement may involve bridging or swapping before delivery. - **Fiat (USD, EUR)** — the accepted token can be converted (offramp) into fiat currency (USD or EUR) via partners, with fiat then delivered to the merchant. Fiat settlement availability depends on offramp partner support per token and chain. Over time, fiat coverage will expand as WalletConnect Pay introduces internal swaps, allowing a broader set of tokens to be converted into supported offramp assets before payout. # Wallet Coverage (/payments/wallet-coverage) WalletConnect Pay works with **every WalletConnect-compatible wallet**. Any wallet that has integrated WalletConnect — over 700 today — can be used by a buyer to pay a WCP merchant. For the full, always-current directory, point your customers at [WalletGuide](https://walletguide.walletconnect.network/). ## Top wallets by usage and volume [#top-wallets-by-usage-and-volume] The wallets below cover the majority of WCP buyer activity today across EVM, Solana, and Bitcoin ecosystems. - [MetaMask](https://metamask.io/) - [Trust Wallet](https://trustwallet.com/) - [Binance Web3 Wallet](https://www.binance.com/en/web3wallet) - [Kraken Wallet](https://www.kraken.com/wallet) - [Ledger](https://www.ledger.com/) - [SafePal](https://www.safepal.com/) - [Rainbow](https://rainbow.me/) - [TokenPocket](https://www.tokenpocket.pro/) - [Timeless X](https://timelesswallet.xyz/) - [Safe](https://safe.global/) - [Zerion](https://zerion.io/) - [1inch Wallet](https://1inch.io/wallet/) - [Crypto.com DeFi Wallet](https://crypto.com/defi-wallet) - [Ronin Wallet](https://roninchain.com/) - [OKX Wallet](https://www.okx.com/web3) - [Bitget Wallet](https://web3.bitget.com/) - [Uniswap Wallet](https://wallet.uniswap.org/) - [Bybit Wallet](https://www.bybit.com/web3) - [imToken](https://token.im/) - [Fireblocks](https://www.fireblocks.com/) - [CTRL](https://ctrl.xyz/) - [Blockchain.com Wallet](https://www.blockchain.com/wallet) - [Rakuten Wallet](https://wallet.rakuten.co.jp/) - [BitPay](https://bitpay.com/wallet/) - [xPortal](https://xportal.com/) - [Bitcoin.com Wallet](https://www.bitcoin.com/wallet) - [Bifrost](https://bifrostwallet.com/) - [Best Wallet](https://bestwallet.com/) - [Phantom](https://phantom.com/) - [Solflare](https://www.solflare.com/) ## Wallet support is chain-dependent [#wallet-support-is-chain-dependent] Wallet support is chain-dependent. Even when a wallet is listed on WalletGuide, it only works on the chains the wallet itself supports. When picking a wallet for a specific buyer cohort, always check the wallet's chain coverage against the chains your merchant accepts. See [Token and Chain Coverage](/payments/token-and-chain-coverage) for the chains WCP accepts today. ## Find a wallet [#find-a-wallet] } href="https://walletguide.walletconnect.network/"> Browse 700+ WalletConnect-compatible wallets and filter by chain or device. # API-first integration (Non-SDK wallets) (/payments/wallets/api-first) If you're integrating WalletConnect Pay into a wallet **without using the Wallet Pay SDK**, you can use an API-first approach via the **Gateway API**. This flow is centered around **three Gateway calls**: - **Get payment options**: list options the user can complete with their wallet/accounts - **Fetch an action**: resolve "build" actions into wallet RPC actions when needed - **Confirm a payment**: submit the selected option and the executed action results ## Prerequisites [#prerequisites] - **API key**: request access from WalletConnect - You can do this by filling out [**this form**](https://share.hsforms.com/19Dpp4ayYR9uriB3xNAh0JAnxw6s) and getting in touch with our team. - **Required headers** on each request: - `Api-Key` — your API key ## Payment flow [#payment-flow] The payment flow mirrors the SDK flow, but you call the Gateway API directly: **Get Options → (Collect Data) → (Fetch Actions) → Execute Wallet RPC → Confirm Payment** ```mermaid sequenceDiagram participant User participant Wallet participant Gateway as WalletConnect Pay (Gateway API) participant Chain as Wallet RPC / Chain User->>Wallet: Scan QR / Open payment link Wallet->>Gateway: POST /v1/gateway/payment/{id}/options (accounts) Gateway-->>Wallet: options[] (+ optional info/collectData) Wallet->>User: Display payment options User->>Wallet: Select payment option alt Selected option requires data collection Wallet->>User: Load selectedOption.collectData.url in WebView User->>Wallet: Fill form & accept T&C (IC_COMPLETE) end alt Option includes a build action Wallet->>Gateway: POST /v1/gateway/payment/{id}/fetch (optionId, data) Gateway-->>Wallet: actions[] (walletRpc) end Wallet->>User: Request signature(s) / transaction(s) User->>Wallet: Approve Wallet->>Chain: Execute wallet RPC actions (in order) Chain-->>Wallet: Results (e.g., signature(s) / tx hash(es)) Wallet->>Gateway: POST /v1/gateway/payment/{id}/confirm (optionId, results, collectedData?) Gateway-->>Wallet: status + isFinal (+ pollInMs) Wallet->>User: Show result / status ``` ## Understanding `actions` [#understanding-actions] Payment options can include an `actions[]` array. Each action tells your wallet what needs to happen next. - **`walletRpc` actions** - The Gateway gives you a wallet RPC payload (`chain_id`, `method`, `params`) - Your wallet should execute it (sign / send), then record the output to submit in `results[]` - **`build` actions** - The action is not directly executable by the wallet - Call **Fetch an action** to convert the `build` payload into one or more **`walletRpc`** actions Maintain action ordering. The `results[]` you submit in **Confirm a payment** must correspond to the actions you executed, in order. ## High-level steps [#high-level-steps] ### 1) Get payment options [#1-get-payment-options] Call **Get payment options** for the given `paymentId`, passing a list of accounts (CAIP-10 / chain namespace format as provided by your wallet). - Use this response to render: - payment details (optionally, if `includePaymentInfo=true`) - available `options[]` the user can pick from - required `actions[]` for the chosen option ### 2) Fetch an action (only if required) [#2-fetch-an-action-only-if-required] If an option contains an action of type **`build`**, call **Fetch an action** with that `optionId` and the `data` payload to resolve it into one or more executable actions (typically `walletRpc`). ### 3) Confirm a payment [#3-confirm-a-payment] After your wallet executes the required `walletRpc` actions (sign/submit), call **Confirm a payment** with: - the selected `optionId` - `results[]`: the output from each executed action (in the same order you performed them) - optional `collectedData` if the options response requested additional user info If you used the **WebView-based data collection** flow (i.e., displayed `collectData.url` in a WebView), there is no need to send `collectedData` in the confirm request — the WebView submits user data directly to the backend. If `isFinal` is `false`, the response may include `pollInMs`. Use it to decide when to check again (see the API Reference for status/polling behavior). The WalletConnect Pay SDKs support **WebView-based data collection**. Each payment option may have its own `collectData.url`. When present on a selected option, wallets can display this URL in a WebView instead of building native forms. The WebView handles form rendering, validation, and T&C acceptance, and submits data directly to the backend. See the [platform-specific SDK documentation](/payments/wallets/overview) for implementation details. ## Integration guidelines [#integration-guidelines] These guidelines reflect the patterns used internally by the WalletConnect Pay SDK. Following them ensures a smooth, reliable UX. ### Payment link detection [#payment-link-detection] Payment links can arrive in several formats. Your wallet should detect and extract the `paymentId` from: | Format | Example | |--------|---------| | WC Pay URL (path) | `https://pay.walletconnect.com/pay_123` | | WC Pay URL (query) | `https://pay.walletconnect.com/?pid=pay_123` | | `wc:` URI with `pay=` param | `wc:abc@2?pay=https%3A%2F%2Fpay.walletconnect.com%2F%3Fpid%3Dpay_123` | | Bare payment ID | `pay_123` | Only trust `pay.walletconnect.com` and `*.pay.walletconnect.com` as valid WC Pay hosts. Always validate the domain before extracting a payment ID. Check for payment links **before** handling generic URLs or WalletConnect pairing URIs. Payment links are HTTPS URLs that would otherwise open in a browser. ### Providing accounts [#providing-accounts] Pass all of the user's accounts in **CAIP-10 format** (`eip155:{chainId}:{address}`) when calling **Get payment options**. Include accounts for every supported chain to maximize the number of payment options returned. ### Resolving `build` actions [#resolving-build-actions] When an option's `actions[]` contains a `build` action, it cannot be executed directly. Call **Fetch an action** (`POST /v1/gateway/payment/{id}/fetch`) with the `optionId` and the build action's `data` string. The response will contain one or more `walletRpc` actions that your wallet can execute. A single `build` action may resolve into multiple `walletRpc` actions. Always iterate over the full response. ### Executing wallet RPC actions [#executing-wallet-rpc-actions] Each `walletRpc` action contains: - `chain_id` — the chain to execute on (CAIP-2 format, e.g., `eip155:8453`) - `method` — the RPC method (e.g., `eth_signTypedData_v4`, `eth_sendTransaction`, `personal_sign`) - `params` — JSON-encoded parameters Execute each action in order using your wallet's signing or transaction implementation. For signing methods (e.g., `eth_signTypedData_v4`), collect the signature hex string. For transaction methods (e.g., `eth_sendTransaction`), collect the transaction hash. Store each result for submission. Payment options may include multiple actions with different RPC methods. For example, a Permit2 payment where the user lacks sufficient token allowance for Permit2 returns two actions: an `eth_sendTransaction` to approve the token allowance, followed by an `eth_signTypedData_v4` to sign the Permit2 transfer. Your wallet must check each action's `method` field and dispatch to the appropriate handler. For full implementation guidance, see [USDT support](/payments/wallets/token-chain-support/usdt-support). Actions are not limited to the `eip155` (EVM) namespace. **Solana** actions arrive as `walletRpc` actions with `chain_id` in the `solana:` namespace and `method: solana_signTransaction`. Route each action by the namespace in its `chain_id`, sign with the matching wallet, and return the **base64-encoded signed transaction** (not a detached signature) in `results[]`. Do not broadcast — the backend submits the transaction. For full implementation guidance, see [Solana support](/payments/wallets/token-chain-support/solana-support). ### Submitting results [#submitting-results] When calling **Confirm a payment**, wrap each signature as a `walletRpc` result: ```json { "optionId": "opt_123", "results": [ { "type": "walletRpc", "data": ["0x"] }, { "type": "walletRpc", "data": ["0x"] } ] } ``` The `results[]` array **must** match the `actions[]` array in both length and order. Misalignment causes payment failures. ### Polling for final status [#polling-for-final-status] After **Confirm a payment** returns, check the `isFinal` field: - **`isFinal: true`** — the payment has reached a terminal state (`succeeded`, `failed`, or `expired`). No further action needed. - **`isFinal: false`** — the payment is still processing. Use the `pollInMs` value from the response as the delay before your next confirm call. Use the `maxPollMs` query parameter on the confirm request to enable **server-side long-polling** — the server will hold the connection and return as soon as the status changes or the timeout expires, reducing the number of round-trips. ``` POST /v1/gateway/payment/{id}/confirm?maxPollMs=30000 ``` ### Retry strategy [#retry-strategy] Implement retries with **exponential backoff and jitter** for resilience: - **Retry only on** server errors (5xx) and network failures (connection refused, timeout) - **Do not retry** client errors (4xx) — these indicate invalid input and won't succeed on retry - **Recommended**: 3 retries with 100ms initial backoff, doubling each attempt, plus random jitter ### Data collection [#data-collection] Data collection is per-option — each payment option may independently have a `collectData` object. When the user selects an option, check `option.collectData`: | Response `collectData` | `option.collectData` | Behavior | |---|---|---| | present | present | Option requires IC — use `option.collectData.url` | | present | `null` | Option does NOT require IC (others might) — skip IC for this option | | `null` | `null` | No IC needed for any option | If the selected option's `collectData` has a `url` field, display it in a WebView before confirming. The URL is already scoped to that option's account. The WebView handles form rendering, validation, and T&C acceptance. When the WebView signals completion (`IC_COMPLETE` via JS bridge), proceed to confirm — no need to include `collectedData` in the request. If you choose not to use the WebView and instead build your own form, use the `collectData.schema` JSON schema to determine the required fields, collect the values, and pass them as `collectedData` in the confirm request. ### Expiration handling [#expiration-handling] Payments have an expiration timestamp (`expiresAt` in the payment info). Display a countdown or warning to the user when time is running low, and prevent submission after expiry. If a payment or route expires mid-flow, the API returns a `410` (payment expired) or `409` (route expired) error. Handle these gracefully by informing the user and offering to start over if a new payment link is available. ## API Reference [#api-reference] For request/response schemas and examples for each Gateway endpoint, see the **[API Reference](/payments/api-reference)**. # WalletConnect Pay - Wallet Integration (/payments/wallets/overview) Your users hold crypto and stablecoins. WalletConnect Pay gives them somewhere to spend it. One integration connects your wallet to a global network of PSPs and merchants — online and in-store. You control the experience. WalletConnect Pay handles the rest: payment execution, compliance, settlement, and gas. What's included - Consistent, compliant payment flows across ecommerce and point of sale - Interchange revenue for your wallet on every eligible transaction, settled in $WCT - Cashback in $WCT for your users on every purchase - Check [Token and Chain coverage](/payments/token-and-chain-coverage) for supported tokens and chains WalletConnect provides three integration approaches for enabling WalletConnect Pay in your wallet: ## Integration Options [#integration-options] ### Integrate using the Wallet SDK (Recommended) [#integrate-using-the-wallet-sdk-recommended] If your wallet already uses the WalletConnect Wallet SDK (WalletKit), WalletConnect Pay is automatically available when you initialize WalletKit. This is the recommended approach as it provides a unified API and automatic configuration. } href="/payments/wallets/walletkit/kotlin"> WalletKit integration for Android wallets. } href="/payments/wallets/walletkit/swift"> WalletKit integration for iOS wallets. } href="/payments/wallets/walletkit/react-native"> WalletKit integration for React Native wallets. } href="/payments/wallets/walletkit/flutter"> WalletKit integration for Flutter wallets. } href="/payments/wallets/walletkit/web"> WalletKit integration for Web/Node.js wallets. ### Standalone Integration [#standalone-integration] For wallets that don't currently use the WalletConnect Wallet SDK, you can integrate the standalone Pay SDK directly. This approach requires configuring the SDK with your WalletConnect Project ID. } href="/payments/wallets/standalone/kotlin"> Standalone Pay SDK for Android wallets. } href="/payments/wallets/standalone/swift"> Standalone Pay SDK for iOS wallets. } href="/payments/wallets/standalone/react-native"> Standalone Pay SDK for React Native wallets. } href="/payments/wallets/standalone/flutter"> Standalone Pay SDK for Flutter wallets. } href="/payments/wallets/standalone/web"> Standalone Pay SDK for Web/Node.js wallets. ### API-First Integration [#api-first-integration] For wallets that prefer direct API integration without using an SDK, you can use the Gateway API directly. } href="/payments/wallets/api-first"> Integrate WalletConnect Pay using the Gateway API. ### WebView Integration [#webview-integration] For apps that want to embed the full WalletConnect Pay checkout UI inside a native WebView — without redirecting to an external browser. The hosted checkout handles everything; your app supplies two query parameters and listens for bridge messages. } href="/payments/wallets/webview"> Embed the checkout portal in a native WebView (iOS, Android, React Native, Flutter). ## Getting Started [#getting-started] To get started with WalletConnect Pay integration: 1. **Get a Project ID**: Create a wallet project at the [WalletConnect Dashboard](https://dashboard.walletconnect.com) to obtain your Project ID. 2. **Choose your integration approach**: Select either the WalletKit integration (if you already use WalletKit) or the standalone Pay SDK integration. 3. **Follow the platform-specific guide**: Use the documentation for your platform to implement the payment flow. ## Payment Flow Overview [#payment-flow-overview] Regardless of which integration approach you choose, the payment flow follows the same pattern: 1. **Detect Payment Link**: Identify when a user scans or opens a WalletConnect Pay link 2. **Get Payment Options**: Fetch available payment options based on user's accounts 3. **Collect User Data** (if required for selected option): If the selected payment option requires compliance information, display a WebView for the user to provide it. This must happen **before** fetching the required actions — the WebView submits the data directly to the backend 4. **Get Required Actions**: Retrieve the signing actions for the selected payment option 5. **Sign Actions**: Sign the required permits/transactions using your wallet's signing infrastructure 6. **Confirm Payment**: Submit the wallet RPC results (`data`) and complete the payment ## Recommended Implementation [#recommended-implementation] For best user experience, follow the recommended implementation below. ## Testing [#testing] Test your WalletConnect Pay integration with the Point-of-Sale app in the WalletConnect Dashboard. To enable the app, configure a mock-merchant recipient address. Payments will arrive to this address and you won't lose any testing funds. On Solana, payment options for non-native tokens only appear once this address has an associated token account (ATA) for that token. The easiest way to create one is to send a small amount of the token to this address — the transfer covers the SOL needed to create the account. Alternatively, send a create-account transaction and pay for it with SOL. ## Earn Revenue [#earn-revenue] Wallets can earn interchange-like revenue on eligible WalletConnect Pay payments. To activate, make sure to complete a successful payment with your integration, then submit the Form found in the WalletConnect Dashboard. We will review the submission and confirm the results to the submitted contact email. Earn Revenue panel in the WalletConnect Dashboard with a link to the submission form ## User Information FAQs [#user-information-faqs] No. The process is optimised so users don't have to re-enter information for each transaction. Once collected, the information will be reused. Wallets that already have verified user PII (e.g. a neobank, a card issuing wallet) can prefill the WebView form by appending a `?prefill=` query parameter to the WebView URL. The `required` list from the `collectDataAction.schema` tells you which fields the form expects (e.g., `fullName`, `dob`, `pobAddress`). The user will still see the form but with pre-populated fields, reducing friction. When processing a payment: 1. Call `getPaymentOptions` and display all available options to the user 2. When the user selects an option, check `selectedOption.collectData` — if it has a `url` field, data collection is required for that specific option 3. Display the URL in a WebView — the hosted form handles rendering, validation, and T&C acceptance 4. The WebView communicates completion via JavaScript bridge messages (`IC_COMPLETE` / `IC_ERROR`) 5. When the WebView completes, proceed to confirm the payment — no `collectedData` needs to be passed since the WebView submits data directly WalletConnect Pay complies with Travel Rule regulations to ensure the payment flow is scalable and future-proof across all regions. This requires capturing some user information like name and date of birth. The WebView-based data collection form handles Terms & Conditions and Privacy Policy acceptance as part of the form flow. The user must accept these before the form can be submitted. SDKs support a WebView-based approach for collecting user information. When `selectedOption.collectData.url` is present on a payment option, wallets display this URL in a WebView instead of building native forms. The hosted form handles: - Form rendering and field validation - Terms & Conditions and Privacy Policy acceptance - Data submission directly to the backend The WebView communicates with the wallet via JavaScript bridge messages (`IC_COMPLETE` when done, `IC_ERROR` on failure). See the platform-specific documentation for implementation details. We strongly recommend using the WebView-based flow over building custom native UI. Data collection requirements are driven by regulation and can evolve. The hosted WebView form is maintained and updated centrally so that wallets can automatically pick up changes. No. Information capture (IC) is per-option — some payment options may require it while others don't. Each payment option has its own `collectData` field. When `option.collectData` is present, the user must complete data collection before confirming that option. When it's `null`, no IC is needed for that option. Wallets should display all options upfront and show a visual indicator (e.g., "Info required" badge) on options that require data collection. Only open the WebView when the user selects an option with `collectData` present. Yes, with a caveat. Wallets that choose to implement custom UI assume responsibility for keeping their forms in sync with these changes. When changes are rolled out, wallets must implement them immediately. If the provided data is not what is requested, users in the relevant jurisdiction(s) will be unable to pay until the custom integration is updated. The WebView approach eliminates this overhead and ensures a consistent, up-to-date experience with minimal integration effort. Wallets also must ensure the user has accepted: - [WalletConnect Terms and Conditions](https://walletconnect.com/terms) - [WalletConnect Privacy Policy](https://walletconnect.com/privacy) The required user information can be sent to WalletConnect using schema in the `collect_data` object. We strongly recommend using the WebView-based flow over building custom native UI. Data collection requirements are driven by regulation and can evolve. The hosted WebView form is maintained and updated centrally so that wallets can automatically pick up changes. Yes. Wallets can pre-fill user information and it will be shown in the WebView form. If wallets choose to skip the WebView form, they must ensure the user has accepted: - [WalletConnect Terms and Conditions](https://walletconnect.com/terms) - [WalletConnect Privacy Policy](https://walletconnect.com/privacy) Yes. The hosted form accepts two optional appearance parameters on its URL: - `theme=light` or `theme=dark` — sets the form's base color mode. Match it to your wallet's active mode. - `themeVariables=` — overrides design tokens (font, font size, some colors, button border radius, and input border radius). Generate and export this value from the [WalletConnect Pay Dashboard](https://dashboard.walletconnect.com) and append it to the form URL verbatim. Both are optional and independent — when omitted, the form uses its default styling. See your platform's integration guide for the URL-building code. # WalletConnect Pay SDK - Flutter (/payments/wallets/standalone/flutter) The WalletConnect Pay SDK allows wallet users to pay merchants using their crypto assets. The SDK handles payment option discovery, permit signing coordination, and payment confirmation while leveraging your wallet's existing signing infrastructure. ## Sample Wallet [#sample-wallet] For a complete working example, check out our sample wallet implementation: } href="https://github.com/reown-com/reown_flutter/tree/develop/packages/reown_walletkit/example"> A reference Flutter wallet app demonstrating WalletConnect Pay integration. ## Requirements [#requirements] - Flutter 3.0+ - iOS 13.0+ - Android API 23+ - `walletconnect_pay` 1.1.0 or later ## Installation [#installation] Add `walletconnect_pay` package to your `pubspec.yaml` or simply run: ```bash flutter pub add walletconnect_pay ``` ## Initialization [#initialization] Initialize the `WalletConnectPay` client with your WCP ID and client ID or API key: ```dart import 'package:walletconnect_pay/walletconnect_pay.dart'; // Initialize WalletConnect Pay. Either apiKey or appId must be passed final payClient = WalletConnectPay( apiKey: 'YOUR_API_KEY', // Optional appId: 'YOUR_WCP_ID', // Optional clientId: 'OPTIONAL_CLIENT_ID', // Optional baseUrl: 'https://api.pay.walletconnect.com', // Optional ); // Initialize the SDK try { await payClient.init(); } on PayInitializeError catch (e) { // Handle initialization error } ``` **Configuration Parameters** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `apiKey` | `String?` | No* | WalletConnect Pay API key | | `appId` | `String?` | No* | WCP ID | | `clientId` | `String?` | No | Client identifier | | `baseUrl` | `String?` | No | Base URL for the API (defaults to production) | Either `apiKey` or `appId` must be provided for authentication. Don't have a project ID? Create one at the [WalletConnect Dashboard](https://dashboard.walletconnect.com) by signing up and creating a new project. ## Supported Networks & Tokens [#supported-networks--tokens] WalletConnect Pay currently supports the following tokens and networks: | Token | Network | Chain ID | CAIP-10 Format | |-------|---------|----------|----------------| | USDC | Arbitrum | 42161 | `eip155:42161:{address}` | | USDC | Base | 8453 | `eip155:8453:{address}` | | USDC | Polygon | 137 | `eip155:137:{address}` | | USDC | Ethereum | 1 | `eip155:1:{address}` | | USDC | Optimism | 10 | `eip155:10:{address}` | | USDC | Monad | 143 | `eip155:143:{address}` | | USDC | Celo | 42220 | `eip155:42220:{address}` | | USDC | BSC | 56 | `eip155:56:{address}` | | EURC | Ethereum | 1 | `eip155:1:{address}` | | EURC | Base | 8453 | `eip155:8453:{address}` | | USDT0 | Arbitrum | 42161 | `eip155:42161:{address}` | | PYUSD | Ethereum | 1 | `eip155:1:{address}` | | PYUSD | Arbitrum | 42161 | `eip155:42161:{address}` | | USDG | Ethereum | 1 | `eip155:1:{address}` | | USDT | Ethereum | 1 | `eip155:1:{address}` | | USDT | Polygon | 137 | `eip155:137:{address}` | | USDT | BSC | 56 | `eip155:56:{address}` | Include accounts for all supported networks to maximize payment options for your users. ## Payment Flow [#payment-flow] The payment flow consists of five main steps: **Get Options -> Collect Data (if required) -> Get Actions -> Sign Actions -> Confirm Payment** ```mermaid sequenceDiagram participant User participant Wallet participant PaySDK as Pay SDK participant Backend as WalletConnect Pay participant WebView User->>Wallet: Scan QR / Open payment link Wallet->>PaySDK: getPaymentOptions(link, accounts) PaySDK->>Backend: Fetch payment options Backend-->>PaySDK: Payment options + merchant info PaySDK-->>Wallet: PaymentOptionsResponse Wallet->>User: Display payment options User->>Wallet: Select payment option alt Data collection required Wallet->>WebView: Load collectDataAction.url in WebView WebView->>User: Display data collection form User->>WebView: Fill form & accept T&C WebView-->>Wallet: IC_COMPLETE message end Wallet->>PaySDK: getRequiredPaymentActions(paymentId, optionId) PaySDK->>Backend: Get signing actions Backend-->>PaySDK: Required wallet RPC actions PaySDK-->>Wallet: List of actions to sign Wallet->>User: Request signature(s) User->>Wallet: Approve & sign Wallet->>PaySDK: confirmPayment(data) PaySDK->>Backend: Submit payment Backend-->>PaySDK: Payment status PaySDK-->>Wallet: ConfirmPaymentResponse Wallet->>User: Show result ``` ### Get Payment Options [#get-payment-options] Retrieve available payment options for a payment link: ```dart final request = GetPaymentOptionsRequest( paymentLink: 'https://pay.walletconnect.com/pay_123', accounts: ['eip155:1:0x...', 'eip155:137:0x...'], // User's wallet CAIP-10 accounts includePaymentInfo: true, // Include payment details in response ); final response = await payClient.getPaymentOptions(request: request); // Access payment information print('Payment ID: ${response.paymentId}'); print('Options available: ${response.options.length}'); if (response.info != null) { print('Amount: ${response.info!.amount.formatAmount()}'); print('Status: ${response.info!.status}'); print('Merchant: ${response.info!.merchant.name}'); } // Check which options require data collection (per-option) for (final option in response.options) { if (option.collectData != null) { print('Option ${option.id} requires info capture'); } } ``` ### Collect User Data (If Required) [#collect-user-data-if-required] After the user selects an option, check for `collectData` on it. If present, collect the data **before** fetching the required actions. ```dart if (selectedOption.collectData?.url != null) { // Use the "required" list from selectedOption.collectData.schema to determine which fields to prefill final prefillData = { 'fullName': 'John Doe', 'dob': '1990-01-15', 'pobAddress': '123 Main St, New York, NY 10001', }; // Encode prefill as base64url final prefillBase64 = base64Url.encode(utf8.encode(jsonEncode(prefillData))).replaceAll('=', ''); final uri = Uri.parse(selectedOption.collectData!.url); final webViewUrl = uri.replace( queryParameters: { ...uri.queryParameters, 'prefill': prefillBase64, // Optional appearance params (see "Form URL parameters"): 'theme': 'dark', // "light" | "dark" // themeVariables is a base64url string exported from the Pay Dashboard: // 'themeVariables': themeVariables, }, ).toString(); // Show WebView — see Data Collection Implementation section below showDataCollectionWebView(webViewUrl); } ``` ### Get Required Actions [#get-required-actions] Get the required wallet actions (e.g., transactions to sign) for a selected payment option: ```dart final actionsRequest = GetRequiredPaymentActionsRequest( optionId: response.options.first.id, // Or whatever other option chosen by the user paymentId: response.paymentId, ); final actions = await payClient.getRequiredPaymentActions( request: actionsRequest, ); // Process each action (e.g., sign transactions) for (final action in actions) { final walletRpc = action.walletRpc; print('Chain ID: ${walletRpc.chainId}'); print('Method: ${walletRpc.method}'); print('Params: ${walletRpc.params}'); // Dispatch based on walletRpc.method — see Sign Actions below } ``` ### Sign Actions [#sign-actions] Sign each action using your wallet's signing implementation, dispatching on the RPC method: ```dart // Sign each action based on its RPC method final data = []; for (final action in actions) { final rpc = action.walletRpc; switch (rpc.method) { case 'eth_signTypedData_v4': data.add(await signTypedData(rpc.chainId, rpc.params)); break; case 'eth_sendTransaction': data.add(await sendTransaction(rpc.chainId, rpc.params)); break; case 'personal_sign': data.add(await personalSign(rpc.chainId, rpc.params)); break; default: throw UnimplementedError('Unsupported RPC method: ${rpc.method}'); } } ``` Payment options may include multiple actions with different RPC methods. For example, a Permit2 payment where the user lacks sufficient allowance returns two actions: an `eth_sendTransaction` to approve the token allowance, followed by an `eth_signTypedData_v4` to sign the Permit2 transfer. Your wallet must check `action.walletRpc.method` and dispatch to the appropriate handler. For full implementation guidance, see [USDT support](/payments/wallets/token-chain-support/usdt-support). Keep `data` in the same order as the actions array. ### Confirm Payment [#confirm-payment] Confirm the payment with the wallet RPC results (`data`) collected in the previous step. Each element of `data` is either a plain `String` (a signature or transaction hash) or, for chains like Tron, a `Map` JSON object; the SDK forwards each element verbatim. See [Tron support](/payments/wallets/token-chain-support/tron-support) for the Tron payload. ```dart final confirmRequest = ConfirmPaymentRequest( paymentId: response.paymentId, optionId: response.options.first.id, data: data, // Wallet RPC results from the Sign Actions step maxPollMs: 60000, // Optional: max polling time in milliseconds ); final confirmResponse = await payClient.confirmPayment(request: confirmRequest); print('Payment Status: ${confirmResponse.status}'); print('Is Final status: ${confirmResponse.isFinal}'); if (!confirmResponse.isFinal && confirmResponse.pollInMs != null) { // Poll again after the specified interval await Future.delayed(Duration(milliseconds: confirmResponse.pollInMs!)); // Re-confirm or check status } ``` The `signatures` parameter is deprecated in favor of `data` and will be removed in a future major version. Existing integrations that pass `signatures` keep working; the SDK uses it as a fallback when `data` is null. When using the WebView data-collection approach, you do **not** pass `collectedData` to `confirmPayment`. The WebView submits the collected data directly to the backend during the earlier Collect User Data step. ## Data Collection Implementation [#data-collection-implementation] When `selectedOption.collectData.url` is present, display the URL in a WebView using the `webview_flutter` package (v4.10.0+). Add it to your `pubspec.yaml`: ```yaml dependencies: webview_flutter: ^4.10.0 url_launcher: ^6.1.0 ``` ```dart import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:webview_flutter/webview_flutter.dart'; import 'package:url_launcher/url_launcher.dart'; class PayDataCollectionWebView extends StatefulWidget { final String url; final VoidCallback onComplete; final ValueChanged onError; const PayDataCollectionWebView({ super.key, required this.url, required this.onComplete, required this.onError, }); @override State createState() => _PayDataCollectionWebViewState(); } class _PayDataCollectionWebViewState extends State { late final WebViewController _controller; bool _isLoading = true; @override void initState() { super.initState(); _controller = WebViewController() ..setJavaScriptMode(JavaScriptMode.unrestricted) ..setNavigationDelegate(NavigationDelegate( onPageFinished: (_) => setState(() => _isLoading = false), onNavigationRequest: (request) { if (!request.url.contains('pay.walletconnect.com')) { launchUrl(Uri.parse(request.url), mode: LaunchMode.externalApplication); return NavigationDecision.prevent; } return NavigationDecision.navigate; }, )) ..addJavaScriptChannel( 'ReactNativeWebView', onMessageReceived: (message) { try { final data = jsonDecode(message.message) as Map; switch (data['type']) { case 'IC_COMPLETE': widget.onComplete(); break; case 'IC_ERROR': widget.onError(data['error'] ?? 'Unknown error'); break; } } catch (_) { // Ignore non-JSON messages } }, ) ..loadRequest(Uri.parse(widget.url)); // Inject JS bridge for compatibility _controller.runJavaScript(''' window.ReactNativeWebView = { postMessage: function(data) { ReactNativeWebView.postMessage(data); } }; '''); } @override Widget build(BuildContext context) { return Stack( children: [ WebViewWidget(controller: _controller), if (_isLoading) const Center(child: CircularProgressIndicator()), ], ); } } String buildFormUrl( String baseUrl, { Map prefillData = const {}, String? theme, // "light" or "dark" String? themeVariables, // base64url string exported from the Pay Dashboard }) { final uri = Uri.parse(baseUrl); final params = {...uri.queryParameters}; if (prefillData.isNotEmpty) { params['prefill'] = base64Url.encode(utf8.encode(jsonEncode(prefillData))).replaceAll('=', ''); } if (theme != null) params['theme'] = theme; if (themeVariables != null) params['themeVariables'] = themeVariables; return uri.replace(queryParameters: params).toString(); } ``` ## Complete Example [#complete-example] Here's a complete implementation example: ```dart import 'package:walletconnect_pay/walletconnect_pay.dart'; class PaymentService { late final WalletConnectPay _payClient; Future initialize() async { _payClient = WalletConnectPay( appId: 'YOUR_WCP_ID', ); await _payClient.init(); } Future processPayment( String paymentLink, List accounts, ) async { // Step 1: Get payment options final optionsResponse = await _payClient.getPaymentOptions( request: GetPaymentOptionsRequest( paymentLink: paymentLink, accounts: accounts, includePaymentInfo: true, ), ); if (optionsResponse.options.isEmpty) { throw Exception('No payment options available'); } // Step 2: Select payment option (simplified - use first option) final selectedOption = optionsResponse.options.first; // Step 3: Collect data via WebView if required. // This must happen BEFORE fetching the required payment actions — // the backend rejects the actions request with 400 "IC data required" // for options needing Information Capture if data wasn't collected first. // The WebView submits the data directly to the backend, so it is NOT // passed to confirmPayment later. if (selectedOption.collectData?.url != null) { // Show WebView and wait for IC_COMPLETE await showDataCollectionWebView(selectedOption.collectData!.url); } // Step 4: Get required payment actions final actions = await _payClient.getRequiredPaymentActions( request: GetRequiredPaymentActionsRequest( optionId: selectedOption.id, paymentId: optionsResponse.paymentId, ), ); // Step 5: Sign all actions final data = []; for (final action in actions) { final signature = await signAction(action.walletRpc); data.add(signature); } // Step 6: Confirm payment final confirmResponse = await _payClient.confirmPayment( request: ConfirmPaymentRequest( paymentId: optionsResponse.paymentId, optionId: selectedOption.id, data: data, maxPollMs: 60000, ), ); // Step 7: Poll until final status (if needed) var response = confirmResponse; while (!response.isFinal && response.pollInMs != null) { await Future.delayed(Duration(milliseconds: response.pollInMs!)); response = await _payClient.confirmPayment( request: ConfirmPaymentRequest( paymentId: optionsResponse.paymentId, optionId: selectedOption.id, data: data, maxPollMs: 60000, ), ); } return response; } Future signAction(WalletRpcAction walletRpc) async { switch (walletRpc.method) { case 'eth_signTypedData_v4': return await signTypedData(walletRpc.chainId, walletRpc.params); case 'eth_sendTransaction': return await sendTransaction(walletRpc.chainId, walletRpc.params); case 'personal_sign': return await personalSign(walletRpc.chainId, walletRpc.params); default: throw UnimplementedError('Unsupported RPC method: ${walletRpc.method}'); } } } ``` ## API Reference [#api-reference] **WalletConnectPay** The main class for interacting with the WalletConnect Pay SDK. **Constructor** ```dart WalletConnectPay({ String? apiKey, String? appId, String? clientId, String? baseUrl, }) ``` **Methods** | Method | Description | |--------|-------------| | `Future init()` | Initializes the SDK. Returns `true` on success or throw `PayInitializeError` on error | | `Future getPaymentOptions({required GetPaymentOptionsRequest request})` | Retrieves available payment options | | `Future> getRequiredPaymentActions({required GetRequiredPaymentActionsRequest request})` | Gets the required wallet actions for a selected option (to be called if the selected option does not have actions included) | | `Future confirmPayment({required ConfirmPaymentRequest request})` | Confirms a payment | ## Data Models [#data-models] **GetPaymentOptionsRequest** ```dart GetPaymentOptionsRequest({ required String paymentLink, required List accounts, @Default(false) bool includePaymentInfo, }) ``` **PaymentOptionsResponse** ```dart PaymentOptionsResponse({ required String paymentId, PaymentInfo? info, required List options, CollectDataAction? collectData, PaymentResultInfo? resultInfo, // Transaction result details (present when payment already completed) }) ``` **PaymentResultInfo** ```dart class PaymentResultInfo { final String txId; // Transaction ID final PayAmount optionAmount; // Token amount details } ``` **PaymentInfo** ```dart PaymentInfo({ required PaymentStatus status, required PayAmount amount, required int expiresAt, required MerchantInfo merchant, BuyerInfo? buyer, }) ``` **PaymentOption** ```dart PaymentOption({ required String id, required String account, required PayAmount amount, @JsonKey(name: 'etaS') required int etaSeconds, required List actions, CollectDataAction? collectData, // Per-option data collection (null if not required) }) ``` **ConfirmPaymentRequest** ```dart ConfirmPaymentRequest({ required String paymentId, required String optionId, List? data, // Wallet RPC results in action order: Strings or Map JSON objects @Default([]) List signatures, // Deprecated alias for `data`, still accepted as fallback when data is null List? collectedData, int? maxPollMs, }) ``` **ConfirmPaymentResponse** ```dart ConfirmPaymentResponse({ required PaymentStatus status, required bool isFinal, int? pollInMs, }) ``` **PaymentStatus** ```dart enum PaymentStatus { requires_action, processing, succeeded, failed, expired, } ``` **Action & WalletRpcAction** ```dart class Action { final WalletRpcAction walletRpc; } class WalletRpcAction { final String chainId; // CAIP-2 chain ID (e.g., "eip155:8453") final String method; // RPC method (e.g., "eth_signTypedData_v4", "eth_sendTransaction") final String params; // JSON-encoded parameters } ``` **CollectDataAction** ```dart class CollectDataAction { final String url; // WebView URL for data collection final String? schema; // JSON schema describing required fields } ``` ## Error Handling [#error-handling] The SDK throws specific exception types for different error scenarios. All errors extend the abstract `PayError` class, which itself extends `PlatformException`: ```dart abstract class PayError extends PlatformException { PayError({ required super.code, required super.message, required super.details, required super.stacktrace, }); } ``` | Exception | Description | |-----------|-------------| | `PayInitializeError` | Initialization failures | | `GetPaymentOptionsError` | Errors when fetching payment options | | `GetRequiredActionsError` | Errors when getting required actions | | `ConfirmPaymentError` | Errors when confirming payment | All errors include: - `code`: Error code - `message`: Error message - `details`: Additional error details - `stacktrace`: Stack trace **Example Error Handling** ```dart try { await payClient.init(); } on PayInitializeError catch (e) { print('Initialization failed: ${e.code} - ${e.message}'); } try { final response = await payClient.getPaymentOptions(request: request); } on GetPaymentOptionsError catch (e) { print('Error code: ${e.code}'); print('Error message: ${e.message}'); } on PayError catch (e) { // Catch any Pay-related error print('Pay error: ${e.message}'); } catch (e) { print('Unexpected error: $e'); } ``` ## Best Practices [#best-practices] 1. **Initialize once**: Call `init()` only once, typically during app startup 2. **Account Format**: Always use CAIP-10 format for accounts: `eip155:{chainId}:{address}` 3. **Multiple Chains**: Provide accounts for all supported chains to maximize payment options 4. **Result Order**: Keep `data` in the same order as the actions array 5. **Error Handling**: Always handle errors gracefully and show appropriate user feedback 6. **Loading States**: Show loading indicators during API calls and signing operations 7. **Expiration**: Check `paymentInfo.expiresAt` and warn users if time is running low 8. **User Data**: Only collect data when `collectData` is present in the response and you don't already have the required user data. If you already have the required data, you can submit this without collecting from the user. You must make sure the user accepts WalletConnect Terms and Conditions and Privacy Policy before submitting user information to WalletConnect. 9. **WebView Data Collection**: When `selectedOption.collectData.url` is present, display the URL in a WebView using `webview_flutter` rather than building native forms. The WebView handles form rendering, validation, and T&C acceptance. # WalletConnect Pay SDK - Kotlin (/payments/wallets/standalone/kotlin) The WalletConnect Pay SDK allows wallet users to pay merchants using their crypto assets. The SDK handles payment option discovery, permit signing coordination, and payment confirmation while leveraging your wallet's existing signing infrastructure. ## Sample Wallet [#sample-wallet] For a complete working example, check out our sample wallet implementation: } href="https://github.com/reown-com/reown-kotlin/tree/develop/sample/wallet"> A reference Android wallet app demonstrating WalletConnect Pay integration. ## Requirements [#requirements] - **Min SDK**: 23 (Android 6.0) - **Target SDK**: 36 - **JVM Target**: 11 - **WalletConnect Pay SDK**: 1.3.0+ (`com.walletconnect:pay`, ships yttrium-wcpay 0.10.60). Required for the `data` parameter in `confirmPayment`. ## Installation [#installation] Add the WalletConnect Pay SDK to your project's `build.gradle.kts` file: ```kotlin dependencies { implementation("com.walletconnect:pay:1.3.0") } ``` The version shown above may not be the latest. Check the [GitHub releases](https://github.com/reown-com/reown-kotlin/releases) for the most recent version. **JNA Dependency Configuration** If you encounter JNA-related errors (e.g., `UnsatisfiedLinkError` or class loading issues), explicitly configure the JNA dependency: ```kotlin implementation("com.walletconnect:pay:1.3.0") { exclude(group = "net.java.dev.jna", module = "jna") } implementation("net.java.dev.jna:jna:5.17.0@aar") ``` ## Initialization [#initialization] Initialize the SDK in your `Application` class or before any payment operations: ```kotlin import com.walletconnect.pay.Pay import com.walletconnect.pay.WalletConnectPay WalletConnectPay.initialize( Pay.SdkConfig( apiKey = "your-api-key", // Your WalletConnect Pay API key (optional) appId = "your-wcp-id", // Your WCP ID (optional) packageName = "com.your.app" // Your app's package name ) ) ``` **Configuration Parameters** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `apiKey` | `String` | No* | Your WalletConnect Pay API key | | `appId` | `String` | No* | Your WCP ID | | `packageName` | `String` | Yes | Your application's package name | *Either `apiKey` or `appId` is required for authentication. Don't have a project ID? Create one at the [WalletConnect Dashboard](https://dashboard.walletconnect.com) by signing up and creating a new project. The SDK will throw `IllegalStateException` if already initialized. Call `initialize()` only once. ## Supported Networks & Tokens [#supported-networks--tokens] WalletConnect Pay currently supports the following tokens and networks: | Token | Network | Chain ID | CAIP-2 Format | |-------|---------|----------|---------------| | USDC | Arbitrum | 42161 | `eip155:42161` | | USDC | Base | 8453 | `eip155:8453` | | USDC | Polygon | 137 | `eip155:137` | | USDC | Ethereum | 1 | `eip155:1` | | USDC | Optimism | 10 | `eip155:10` | | USDC | Monad | 143 | `eip155:143` | | USDC | Celo | 42220 | `eip155:42220` | | USDC | BSC | 56 | `eip155:56` | | EURC | Ethereum | 1 | `eip155:1` | | EURC | Base | 8453 | `eip155:8453` | | USDT0 | Arbitrum | 42161 | `eip155:42161` | | PYUSD | Ethereum | 1 | `eip155:1` | | PYUSD | Arbitrum | 42161 | `eip155:42161` | | USDG | Ethereum | 1 | `eip155:1` | | USDT | Ethereum | 1 | `eip155:1` | | USDT | Polygon | 137 | `eip155:137` | | USDT | BSC | 56 | `eip155:56` | All account addresses must be provided in CAIP-10 format: `eip155::
` Include accounts for all supported networks to maximize payment options for your users. ## Payment Flow [#payment-flow] The payment flow consists of five main steps: **Get Options -> Collect Data (if required) -> Get Actions -> Sign Actions -> Confirm Payment** ```mermaid sequenceDiagram participant User participant Wallet participant PaySDK as Pay SDK participant Backend as WalletConnect Pay participant WebView User->>Wallet: Scan QR / Open payment link Wallet->>PaySDK: getPaymentOptions(link, accounts) PaySDK->>Backend: Fetch payment options Backend-->>PaySDK: Payment options + merchant info PaySDK-->>Wallet: PaymentOptionsResponse Wallet->>User: Display payment options User->>Wallet: Select payment option alt Selected option requires data collection Wallet->>WebView: Load selectedOption.collectData.url WebView->>User: Display data collection form User->>WebView: Fill form & accept T&C WebView-->>Wallet: IC_COMPLETE message end Wallet->>PaySDK: getRequiredPaymentActions(paymentId, optionId) PaySDK->>Backend: Get signing actions Backend-->>PaySDK: Required wallet RPC actions PaySDK-->>Wallet: List of actions to sign Wallet->>User: Request signature(s) User->>Wallet: Approve & sign Wallet->>PaySDK: confirmPayment(data) PaySDK->>Backend: Submit payment Backend-->>PaySDK: Payment status PaySDK-->>Wallet: ConfirmPaymentResponse Wallet->>User: Show result ``` ### Initialize the SDK [#initialize-the-sdk] ```kotlin import com.walletconnect.pay.Pay import com.walletconnect.pay.WalletConnectPay // In your Application class or before payment operations WalletConnectPay.initialize( Pay.SdkConfig( appId = "your-wcp-id", // Your WCP ID packageName = "com.your.app" ) ) // Check if initialized if (WalletConnectPay.isInitialized) { // SDK ready for use } ``` ### Get Payment Options [#get-payment-options] When a user scans a payment QR code or opens a payment link, fetch available payment options: ```kotlin val result = WalletConnectPay.getPaymentOptions( paymentLink = "https://pay.walletconnect.com/pay_xxx", accounts = listOf( "eip155:1:0xYourAddress", // Ethereum "eip155:8453:0xYourAddress", // Base "eip155:10:0xYourAddress" // Optimism ) ) result.onSuccess { response -> // Payment metadata val paymentId = response.paymentId val paymentInfo = response.info // Merchant info, amount, expiry // Available payment options val options = response.options options.forEach { option -> println("Option: ${option.id}") println("Amount: ${option.amount.value} ${option.amount.unit}") println("Account: ${option.account}") println("Estimated transactions: ${option.estimatedTxs}") println("Requires IC: ${option.collectData != null}") } }.onFailure { error -> handleError(error) } ``` ### Collect User Data (If Required) [#collect-user-data-if-required] After the user selects an option, check for `collectData` on it. If present, collect the data **before** fetching the required actions. ```kotlin // Check per-option data collection requirement after user selects an option selectedOption.collectData?.let { collectAction -> val url = collectAction.url if (url != null) { // Build prefill URL with known user data // Use the "required" list from collectAction.schema to determine which fields to prefill val prefillJson = JSONObject().apply { put("fullName", "John Doe") put("dob", "1990-01-15") put("pobAddress", "123 Main St, New York, NY 10001") }.toString() // Encode prefill as base64url (URL-safe, no padding) val prefillBase64 = Base64.encodeToString( prefillJson.toByteArray(), Base64.NO_WRAP or Base64.URL_SAFE or Base64.NO_PADDING ) val webViewUrl = Uri.parse(url).buildUpon() .appendQueryParameter("prefill", prefillBase64) // Optional appearance params (see "Form URL parameters"): .appendQueryParameter("theme", "dark") // "light" | "dark" // themeVariables is a base64url string exported from the Pay Dashboard: // .appendQueryParameter("themeVariables", themeVariables) .build().toString() // Show WebView for this specific option — see Data Collection Implementation section below showWebView(webViewUrl) } } ``` ### Get Required Actions [#get-required-actions] After the user selects a payment option (and any required data collection has completed), get the wallet RPC actions needed to complete the payment: ```kotlin val actionsResult = WalletConnectPay.getRequiredPaymentActions( paymentId = paymentId, optionId = selectedOption.id ) actionsResult.onSuccess { actions -> actions.forEach { action -> when (action) { is Pay.RequiredAction.WalletRpc -> { val rpcAction = action.action // rpcAction.chainId - e.g., "eip155:8453" // rpcAction.method - e.g., "eth_signTypedData_v4" or "personal_sign" // rpcAction.params - JSON string with signing parameters } } } }.onFailure { error -> handleError(error) } ``` ### Sign Actions [#sign-actions] Sign each action using your wallet's signing implementation: ```kotlin val data = actions.map { action -> when (action) { is Pay.RequiredAction.WalletRpc -> { val rpc = action.action when (rpc.method) { "eth_signTypedData_v4" -> wallet.signTypedData(rpc.chainId, rpc.params) "personal_sign" -> wallet.personalSign(rpc.chainId, rpc.params) "eth_sendTransaction" -> wallet.sendTransaction(rpc.chainId, rpc.params) else -> throw UnsupportedOperationException("Unsupported method: ${rpc.method}") } } } } ``` Payment options may include multiple actions with different RPC methods. For example, a Permit2 payment where the user lacks sufficient allowance returns two actions: an `eth_sendTransaction` to approve the token allowance, followed by an `eth_signTypedData_v4` to sign the Permit2 transfer. Your wallet must check `rpc.method` (or `action.action.method`) and dispatch to the appropriate handler. For full implementation guidance, see [USDT support](/payments/wallets/token-chain-support/usdt-support). Keep `data` in the same order as the actions array. ### Confirm Payment [#confirm-payment] Submit the wallet RPC results (`data`) and finalize the payment. Each element of `data` is either a plain string (a signature or transaction hash) or, for chains like Tron, a JSON object encoded as a string; WalletConnect Pay forwards each element verbatim to the gateway. See [Tron support](/payments/wallets/token-chain-support/tron-support) for the Tron payload. ```kotlin val confirmResult = WalletConnectPay.confirmPayment( paymentId = paymentId, optionId = selectedOption.id, data = data ) confirmResult.onSuccess { response -> when (response.status) { Pay.PaymentStatus.SUCCEEDED -> { // Payment completed successfully } Pay.PaymentStatus.PROCESSING -> { // Payment is being processed // The SDK automatically polls until final status } Pay.PaymentStatus.FAILED -> { // Payment failed } Pay.PaymentStatus.EXPIRED -> { // Payment expired } Pay.PaymentStatus.REQUIRES_ACTION -> { // Additional action required } Pay.PaymentStatus.CANCELLED -> { // Payment cancelled by user } } }.onFailure { error -> handleError(error) } ``` The `signatures` parameter is deprecated in favor of `data` and will be removed in a future major version. Existing integrations that pass `signatures` keep working; the SDK uses it as a fallback when `data` is omitted. ## Data Collection Implementation [#data-collection-implementation] When `selectedOption.collectData.url` is present, display the URL in a WebView. The WebView handles form rendering, validation, and T&C acceptance. ```kotlin import android.webkit.JavascriptInterface import android.webkit.WebView import android.webkit.WebViewClient import android.webkit.WebResourceRequest import android.content.Intent import android.net.Uri import android.util.Base64 import androidx.compose.runtime.Composable import androidx.compose.ui.viewinterop.AndroidView import org.json.JSONObject @Composable fun PayDataCollectionWebView( url: String, onComplete: () -> Unit, onError: (String) -> Unit ) { AndroidView(factory = { context -> WebView(context).apply { settings.javaScriptEnabled = true settings.domStorageEnabled = true settings.allowFileAccess = false addJavascriptInterface( object { @JavascriptInterface fun onDataCollectionComplete(json: String) { val message = JSONObject(json) when (message.optString("type")) { "IC_COMPLETE" -> onComplete() "IC_ERROR" -> onError( message.optString("error", "Unknown error") ) } } }, "AndroidWallet" ) webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading( view: WebView?, request: WebResourceRequest? ): Boolean { val requestUrl = request?.url?.toString() ?: return false // Open external links (T&C, Privacy Policy) in system browser if (!requestUrl.contains("pay.walletconnect.com")) { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(requestUrl))) return true } return false } } loadUrl(url) } }) } fun buildFormUrl( baseUrl: String, prefillData: Map = emptyMap(), theme: String? = null, // "light" or "dark" themeVariables: String? = null // base64url string exported from the Pay Dashboard ): String { val builder = Uri.parse(baseUrl).buildUpon() if (prefillData.isNotEmpty()) { val prefill = Base64.encodeToString( JSONObject(prefillData).toString().toByteArray(), Base64.NO_WRAP or Base64.URL_SAFE or Base64.NO_PADDING ) builder.appendQueryParameter("prefill", prefill) } theme?.let { builder.appendQueryParameter("theme", it) } themeVariables?.let { builder.appendQueryParameter("themeVariables", it) } return builder.build().toString() } ``` ## Complete Example [#complete-example] Here's a complete implementation example using a ViewModel: ```kotlin import com.walletconnect.pay.Pay import com.walletconnect.pay.WalletConnectPay import kotlinx.coroutines.launch class PaymentViewModel : ViewModel() { fun initializeSdk() { WalletConnectPay.initialize( Pay.SdkConfig( appId = "your-wcp-id", // Your WCP ID packageName = "com.your.app" ) ) } fun processPayment(paymentLink: String, walletAddress: String) { viewModelScope.launch { // Step 1: Get payment options val optionsResult = WalletConnectPay.getPaymentOptions( paymentLink = paymentLink, accounts = listOf( "eip155:1:$walletAddress", "eip155:8453:$walletAddress", "eip155:10:$walletAddress" ) ) optionsResult.onSuccess { response -> val paymentId = response.paymentId val selectedOption = response.options.first() // Step 2: Collect data if required for selected option (via WebView). // IC must happen BEFORE fetching the required actions — the WebView // submits the data directly to the backend. selectedOption.collectData?.url?.let { webViewUrl -> // Show WebView and wait for IC_COMPLETE showDataCollectionWebView(webViewUrl) return@launch // Resume after WebView completes } // Step 3: Get required actions val actionsResult = WalletConnectPay.getRequiredPaymentActions( paymentId = paymentId, optionId = selectedOption.id ) actionsResult.onSuccess { actions -> // Step 4: Sign actions val data = signActions(actions) // Step 5: Confirm payment val confirmResult = WalletConnectPay.confirmPayment( paymentId = paymentId, optionId = selectedOption.id, data = data ) confirmResult.onSuccess { confirmation -> handlePaymentStatus(confirmation.status) }.onFailure { error -> handleError(error) } }.onFailure { error -> handleError(error) } }.onFailure { error -> handleError(error) } } } private suspend fun signActions(actions: List): List { return actions.map { action -> when (action) { is Pay.RequiredAction.WalletRpc -> { // Implement signing logic using your wallet signWithWallet(action.action) } } } } private fun handlePaymentStatus(status: Pay.PaymentStatus) { when (status) { Pay.PaymentStatus.SUCCEEDED -> showSuccess() Pay.PaymentStatus.PROCESSING -> showProcessing() Pay.PaymentStatus.FAILED -> showFailure() Pay.PaymentStatus.EXPIRED -> showExpired() Pay.PaymentStatus.REQUIRES_ACTION -> { /* Handle additional actions */ } Pay.PaymentStatus.CANCELLED -> showCancelled() } } } ``` ## API Reference [#api-reference] **WalletConnectPay** Main entry point for the Pay SDK (singleton object). **Properties** | Property | Type | Description | |----------|------|-------------| | `isInitialized` | `Boolean` | Whether the SDK has been initialized | **Methods** | Method | Description | |--------|-------------| | `initialize(config: Pay.SdkConfig)` | Initialize the SDK | | `getPaymentOptions(paymentLink, accounts)` | Get available payment options | | `getRequiredPaymentActions(paymentId, optionId)` | Get actions requiring signatures | | `confirmPayment(paymentId, optionId, data = ...)` | Confirm and finalize payment. `data: List` holds the wallet RPC results in action order (plain strings or JSON-encoded objects) | | `confirmPayment(paymentId, optionId, signatures = ...)` | Deprecated alias for `data`; still accepted | ## Data Models [#data-models] **Pay.PaymentOptionsResponse** ```kotlin data class PaymentOptionsResponse( val info: PaymentInfo?, // Payment metadata val options: List, // Available payment options val paymentId: String, // Unique payment identifier val collectDataAction: CollectDataAction?, // Data collection requirements val resultInfo: PaymentResultInfo? // Transaction result details (present when payment already completed) ) data class PaymentResultInfo( val txId: String, // Transaction ID val optionAmount: Amount // Token amount details ) ``` **Pay.PaymentInfo** ```kotlin data class PaymentInfo( val status: PaymentStatus, val amount: Amount, val expiresAt: Long, // Unix timestamp val merchant: MerchantInfo ) data class MerchantInfo( val name: String, val iconUrl: String? ) ``` **Pay.PaymentOption** ```kotlin data class PaymentOption( val id: String, val amount: Amount, val account: String, // CAIP-10 account that can pay val estimatedTxs: Int?, // Estimated number of transactions val collectData: CollectDataAction? // Per-option data collection (null if not required) ) ``` **Pay.Amount** ```kotlin data class Amount( val value: String, val unit: String, val display: AmountDisplay? ) data class AmountDisplay( val assetSymbol: String, val assetName: String, val decimals: Int, val iconUrl: String?, val networkName: String?, val networkIconUrl: String? ) ``` **Pay.WalletRpcAction** ```kotlin data class WalletRpcAction( val chainId: String, // CAIP-2 chain ID (e.g., "eip155:8453") val method: String, // RPC method (e.g., "eth_signTypedData_v4", "eth_sendTransaction") val params: String // JSON-encoded parameters ) ``` **Pay.RequiredAction** ```kotlin sealed class RequiredAction { data class WalletRpc(val action: WalletRpcAction) : RequiredAction() } ``` **Pay.CollectDataAction** ```kotlin data class CollectDataAction( val url: String, // WebView URL for data collection val schema: String? // JSON schema describing required fields ) ``` **Pay.ConfirmPaymentResponse** ```kotlin data class ConfirmPaymentResponse( val status: PaymentStatus, val isFinal: Boolean, val pollInMs: Long?, val info: PaymentResultInfo? // Transaction result details (present on success) ) ``` **Pay.PaymentStatus** | Status | Description | |--------|-------------| | `REQUIRES_ACTION` | Additional action needed | | `PROCESSING` | Payment in progress | | `SUCCEEDED` | Payment completed | | `FAILED` | Payment failed | | `EXPIRED` | Payment expired | | `CANCELLED` | Payment cancelled by user | ## Error Handling [#error-handling] The SDK provides typed errors for different failure scenarios: **GetPaymentOptionsError** | Error | Description | |-------|-------------| | `InvalidPaymentLink` | Invalid payment link format | | `PaymentExpired` | Payment has expired | | `PaymentNotFound` | Payment ID doesn't exist | | `InvalidRequest` | Invalid request parameters | | `InvalidAccount` | Invalid account format | | `ComplianceFailed` | Compliance check failed | | `Http` | Network error | | `InternalError` | Server error | **GetPaymentRequestError** | Error | Description | |-------|-------------| | `OptionNotFound` | Selected option doesn't exist | | `PaymentNotFound` | Payment ID doesn't exist | | `InvalidAccount` | Invalid account format | | `Http` | Network error | **ConfirmPaymentError** | Error | Description | |-------|-------------| | `PaymentNotFound` | Payment ID doesn't exist | | `PaymentExpired` | Payment has expired | | `InvalidOption` | Invalid option ID | | `InvalidSignature` | Signature verification failed | | `RouteExpired` | Payment route expired | | `Http` | Network error | **Example Error Handling** ```kotlin val result = WalletConnectPay.getPaymentOptions(paymentLink, accounts) result.onFailure { error -> when (error) { is Pay.GetPaymentOptionsError.InvalidPaymentLink -> { showError("Invalid payment link") } is Pay.GetPaymentOptionsError.PaymentExpired -> { showError("Payment has expired") } is Pay.GetPaymentOptionsError.PaymentNotFound -> { showError("Payment not found") } is Pay.GetPaymentOptionsError.InvalidAccount -> { showError("Invalid account address") } is Pay.GetPaymentOptionsError.ComplianceFailed -> { showError("Compliance check failed") } is Pay.GetPaymentOptionsError.Http -> { showError("Network error: ${error.message}") } else -> { showError("An error occurred: ${error.message}") } } } ``` ## Best Practices [#best-practices] 1. **Initialize once**: Call `initialize()` only once, typically in `Application.onCreate()` 2. **Account Format**: Always use CAIP-10 format for accounts: `eip155:{chainId}:{address}` 3. **Multiple Chains**: Provide accounts for all supported chains to maximize payment options 4. **Result Order**: Keep `data` in the same order as the actions array 5. **Error Handling**: Always handle errors gracefully and show appropriate user feedback 6. **Thread Safety**: Events are delivered on IO dispatcher; update UI on main thread 7. **WebView Data Collection**: When `selectedOption.collectData?.url` is present, display the URL in a WebView rather than building native forms. The WebView handles form rendering, validation, and T&C acceptance. 8. **Per-Option Data Collection**: When displaying payment options, check each option's `collectData` field. Show a visual indicator (e.g., "Info required" badge) on options that require data collection. Only open the WebView when the user selects an option with `collectData` present — use the option's `collectData.url` which is already scoped to that option's account. # WalletConnect Pay SDK - React Native (/payments/wallets/standalone/react-native) The WalletConnect Pay SDK allows wallet users to pay merchants using their crypto assets. The SDK handles payment option discovery, permit signing coordination, and payment confirmation while leveraging your wallet's existing signing infrastructure. ## Sample Wallet [#sample-wallet] For a complete working example, check out our sample wallet implementation: } href="https://github.com/reown-com/react-native-examples/tree/main/wallets/rn_cli_wallet"> A reference React Native wallet app demonstrating WalletConnect Pay integration. ## Requirements [#requirements] - React Native 0.70+ - `@walletconnect/pay` 1.1.0 or later - `@walletconnect/react-native-compat` 2.25.0 or later, installed and linked (ships the native Yttrium module: yttrium-wcpay 0.10.60 on Android, YttriumWrapper 0.10.59 on iOS) ## Installation [#installation] Install the WalletConnect Pay SDK using npm or yarn: ```bash npm install @walletconnect/pay ``` ```bash yarn add @walletconnect/pay ``` **React Native Setup** This SDK requires the WalletConnect React Native native module. Make sure you have `@walletconnect/react-native-compat` 2.25.0 or later installed and linked in your React Native project: ```bash npm install @walletconnect/react-native-compat ``` ## Architecture [#architecture] The SDK uses a provider abstraction that allows different implementations: - **NativeProvider**: Uses React Native uniffi module (current) - **WasmProvider**: Uses WebAssembly module (coming soon for web browsers) The SDK auto-detects the best available provider for your environment. ## Initialization [#initialization] Initialize the WalletConnect Pay client with your credentials: ```typescript import { WalletConnectPay } from "@walletconnect/pay"; const client = new WalletConnectPay({ appId: "your-wcp-id", // OR use apiKey instead: // apiKey: "your-api-key", }); ``` **Configuration Parameters** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `appId` | `string` | No* | WCP ID for authentication | | `apiKey` | `string` | No* | API key for authentication | | `clientId` | `string` | No | Client ID for tracking | | `baseUrl` | `string` | No | Custom API base URL | | `logger` | `Logger` | No | Custom logger instance or level | Either `appId` or `apiKey` must be provided for authentication. Don't have a project ID? Create one at the [WalletConnect Dashboard](https://dashboard.walletconnect.com) by signing up and creating a new project. ## Supported Networks & Tokens [#supported-networks--tokens] WalletConnect Pay currently supports the following tokens and networks: | Token | Network | Chain ID | CAIP-10 Format | |-------|---------|----------|----------------| | USDC | Arbitrum | 42161 | `eip155:42161:{address}` | | USDC | Base | 8453 | `eip155:8453:{address}` | | USDC | Polygon | 137 | `eip155:137:{address}` | | USDC | Ethereum | 1 | `eip155:1:{address}` | | USDC | Optimism | 10 | `eip155:10:{address}` | | USDC | Monad | 143 | `eip155:143:{address}` | | USDC | Celo | 42220 | `eip155:42220:{address}` | | USDC | BSC | 56 | `eip155:56:{address}` | | EURC | Ethereum | 1 | `eip155:1:{address}` | | EURC | Base | 8453 | `eip155:8453:{address}` | | USDT0 | Arbitrum | 42161 | `eip155:42161:{address}` | | PYUSD | Ethereum | 1 | `eip155:1:{address}` | | PYUSD | Arbitrum | 42161 | `eip155:42161:{address}` | | USDG | Ethereum | 1 | `eip155:1:{address}` | | USDT | Ethereum | 1 | `eip155:1:{address}` | | USDT | Polygon | 137 | `eip155:137:{address}` | | USDT | BSC | 56 | `eip155:56:{address}` | Include accounts for all supported networks to maximize payment options for your users. ## Payment Flow [#payment-flow] The payment flow consists of five main steps: **Get Options -> Collect Data (if required) -> Get Actions -> Sign Actions -> Confirm Payment** ```mermaid sequenceDiagram participant User participant Wallet participant PaySDK as Pay SDK participant Backend as WalletConnect Pay participant WebView User->>Wallet: Scan QR / Open payment link Wallet->>PaySDK: getPaymentOptions(link, accounts) PaySDK->>Backend: Fetch payment options Backend-->>PaySDK: Payment options + merchant info PaySDK-->>Wallet: PaymentOptionsResponse Wallet->>User: Display payment options User->>Wallet: Select payment option alt Selected option requires data collection Wallet->>WebView: Load selectedOption.collectData.url WebView->>User: Display data collection form User->>WebView: Fill form & accept T&C WebView-->>Wallet: IC_COMPLETE message end Wallet->>PaySDK: getRequiredPaymentActions(paymentId, optionId) PaySDK->>Backend: Get signing actions Backend-->>PaySDK: Required wallet RPC actions PaySDK-->>Wallet: List of actions to sign Wallet->>User: Request signature(s) User->>Wallet: Approve & sign Wallet->>PaySDK: confirmPayment(data) PaySDK->>Backend: Submit payment Backend-->>PaySDK: Payment status PaySDK-->>Wallet: ConfirmPaymentResponse Wallet->>User: Show result ``` ### Get Payment Options [#get-payment-options] When a user scans a payment QR code or opens a payment link, fetch available payment options: ```typescript const options = await client.getPaymentOptions({ paymentLink: "https://pay.walletconnect.com/pay_123", accounts: [ `eip155:1:${walletAddress}`, // Ethereum Mainnet `eip155:8453:${walletAddress}`, // Base ], includePaymentInfo: true, }); console.log("Payment ID:", options.paymentId); console.log("Options:", options.options); // Display merchant info if (options.info) { console.log("Merchant:", options.info.merchant.name); console.log("Amount:", options.info.amount.display.assetSymbol, options.info.amount.value); } // Check which options require data collection for (const option of options.options) { if (option.collectData) { console.log(`Option ${option.id} requires info capture`); } } ``` ### Collect User Data (If Required) [#collect-user-data-if-required] After the user selects an option, check for `collectData` on it. If present, collect the data **before** fetching the required actions. ```typescript // Check per-option data collection requirement after user selects an option if (selectedOption.collectData?.url) { // Use the "required" list from selectedOption.collectData.schema to determine which fields to prefill const prefillData = { fullName: "John Doe", dob: "1990-01-15", pobAddress: "123 Main St, New York, NY 10001", }; // Encode prefill as base64url (URL-safe, no padding) const prefill = btoa(JSON.stringify(prefillData)) .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); // Optional appearance params (see "Form URL parameters"): // theme=light|dark — base color mode // themeVariables= — exported from the WalletConnect Pay Dashboard const themeVariables = ""; const query = `prefill=${prefill}&theme=dark&themeVariables=${themeVariables}`; const separator = selectedOption.collectData.url.includes("?") ? "&" : "?"; const webViewUrl = `${selectedOption.collectData.url}${separator}${query}`; // Show WebView for this specific option — see Data Collection Implementation section below showDataCollectionWebView(webViewUrl); } ``` ### Get Required Actions [#get-required-actions] After the user selects a payment option, get the wallet RPC actions required to complete the payment: ```typescript const actions = await client.getRequiredPaymentActions({ paymentId: options.paymentId, optionId: options.options[0].id, }); // Each action contains wallet RPC data to sign for (const action of actions) { console.log("Chain:", action.walletRpc.chainId); console.log("Method:", action.walletRpc.method); console.log("Params:", action.walletRpc.params); } ``` ### Sign Actions [#sign-actions] Sign each action with your wallet's signing implementation: ```typescript // Sign each action based on its RPC method const data = await Promise.all( actions.map(async (action) => { const { chainId, method, params } = action.walletRpc; const parsedParams = JSON.parse(params); switch (method) { case "eth_signTypedData_v4": return await wallet.signTypedData(chainId, parsedParams); case "eth_sendTransaction": return await wallet.sendTransaction(chainId, parsedParams[0]); case "personal_sign": return await wallet.personalSign(chainId, parsedParams); default: throw new Error(`Unsupported RPC method: ${method}`); } }) ); ``` Payment options may include multiple actions with different RPC methods. For example, a Permit2 payment where the user lacks sufficient allowance returns two actions: an `eth_sendTransaction` to approve the token allowance, followed by an `eth_signTypedData_v4` to sign the Permit2 transfer. Your wallet must check `action.walletRpc.method` and dispatch to the appropriate handler. For full implementation guidance, see [USDT support](/payments/wallets/token-chain-support/usdt-support). Keep `data` in the same order as the actions array. ### Confirm Payment [#confirm-payment] Submit the wallet RPC results (`data`) and collected data to complete the payment. Each element of `data` is either a plain string (a signature or transaction hash) or, for chains like Tron, a JSON object; the SDK forwards each element verbatim. See [Tron support](/payments/wallets/token-chain-support/tron-support) for the Tron payload. ```typescript const result = await client.confirmPayment({ paymentId: options.paymentId, optionId: options.options[0].id, data, collectedData, // Include if collectData was present }); if (result.status === "succeeded") { console.log("Payment successful!"); } else if (result.status === "processing") { console.log("Payment is processing..."); } else if (result.status === "failed") { console.log("Payment failed"); } ``` The `signatures` parameter is deprecated in favor of `data` and will be removed in a future major version. Existing integrations that pass `signatures` keep working; the SDK uses it as a fallback when `data` is omitted. ## Data Collection Implementation [#data-collection-implementation] When `selectedOption.collectData.url` is present, display the URL in a WebView using `react-native-webview`. Install the dependency: ```bash npm install react-native-webview@13.16.0 ``` ```tsx import React, { useCallback } from "react"; import { WebView, WebViewMessageEvent } from "react-native-webview"; import { Linking, View, ActivityIndicator } from "react-native"; interface PayDataCollectionWebViewProps { url: string; onComplete: () => void; onError: (error: string) => void; } function PayDataCollectionWebView({ url, onComplete, onError, }: PayDataCollectionWebViewProps) { const handleMessage = useCallback( (event: WebViewMessageEvent) => { try { const data = JSON.parse(event.nativeEvent.data); switch (data.type) { case "IC_COMPLETE": onComplete(); break; case "IC_ERROR": onError(data.error || "Unknown error"); break; } } catch { // Ignore non-JSON messages } }, [onComplete, onError] ); const handleNavigationRequest = useCallback( (request: { url: string }) => { // Open external links (T&C, Privacy Policy) in system browser if (!request.url.includes("pay.walletconnect.com")) { Linking.openURL(request.url); return false; } return true; }, [] ); return ( ( )} /> ); } function buildFormUrl( baseUrl: string, options: { prefill?: Record; theme?: "light" | "dark"; themeVariables?: string; // base64url string exported from the Pay Dashboard } = {} ): string { const params: string[] = []; if (options.prefill && Object.keys(options.prefill).length > 0) { // base64url: URL-safe, no padding const prefill = btoa(JSON.stringify(options.prefill)) .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); params.push(`prefill=${prefill}`); } if (options.theme) params.push(`theme=${options.theme}`); if (options.themeVariables) params.push(`themeVariables=${options.themeVariables}`); if (params.length === 0) return baseUrl; const separator = baseUrl.includes("?") ? "&" : "?"; return `${baseUrl}${separator}${params.join("&")}`; } ``` ## Complete Example [#complete-example] Here's a complete implementation example: ```typescript import { WalletConnectPay, CollectDataFieldResult } from "@walletconnect/pay"; class PaymentManager { private client: WalletConnectPay; constructor() { this.client = new WalletConnectPay({ appId: "your-wcp-id", }); } async processPayment(paymentLink: string, walletAddress: string) { try { // Step 1: Get payment options const options = await this.client.getPaymentOptions({ paymentLink, accounts: [ `eip155:1:${walletAddress}`, `eip155:137:${walletAddress}`, `eip155:8453:${walletAddress}`, ], includePaymentInfo: true, }); if (options.options.length === 0) { throw new Error("No payment options available"); } // Step 2: Let user select an option (simplified - use first option) const selectedOption = options.options[0]; // Step 3: Collect data via WebView if required for selected option — // must happen BEFORE fetching the required actions, otherwise the // backend rejects the request if (selectedOption.collectData?.url) { // Show WebView and wait for IC_COMPLETE await this.showDataCollectionWebView(selectedOption.collectData.url); } // Step 4: Get required actions const actions = await this.client.getRequiredPaymentActions({ paymentId: options.paymentId, optionId: selectedOption.id, }); // Step 5: Sign all actions const data = await Promise.all( actions.map((action) => this.signAction(action, walletAddress) ) ); // Step 6: Confirm payment const result = await this.client.confirmPayment({ paymentId: options.paymentId, optionId: selectedOption.id, data, }); return result; } catch (error) { console.error("Payment failed:", error); throw error; } } private async signAction(action: Action, walletAddress: string): Promise { const { chainId, method, params } = action.walletRpc; const parsedParams = JSON.parse(params); switch (method) { case "eth_signTypedData_v4": return await wallet.signTypedData(chainId, parsedParams); case "eth_sendTransaction": return await wallet.sendTransaction(chainId, parsedParams[0]); case "personal_sign": return await wallet.personalSign(chainId, parsedParams); default: throw new Error(`Unsupported RPC method: ${method}`); } } } ``` ## Provider Utilities [#provider-utilities] The SDK provides utilities for checking provider availability: ```typescript import { isProviderAvailable, detectProviderType, isNativeProviderAvailable, setNativeModule, } from "@walletconnect/pay"; // Check if any provider is available if (isProviderAvailable()) { // SDK can be used } // Detect which provider type is available const providerType = detectProviderType(); // 'native' | 'wasm' | null // Check specifically for native provider if (isNativeProviderAvailable()) { // React Native native module is available } // Manually inject native module (if auto-discovery fails) import { NativeModules } from "react-native"; setNativeModule(NativeModules.RNWalletConnectPay); ``` ## API Reference [#api-reference] **WalletConnectPay** Main client for payment operations. **Constructor** ```typescript new WalletConnectPay(options: WalletConnectPayOptions) ``` **Methods** | Method | Description | |--------|-------------| | `getPaymentOptions(params)` | Fetch available payment options | | `getRequiredPaymentActions(params)` | Get signing actions for a payment option | | `confirmPayment(params)` | Confirm and execute the payment | | `static isAvailable()` | Check if a provider is available | **Data Types** **PaymentStatus** ```typescript type PaymentStatus = | "requires_action" | "processing" | "succeeded" | "failed" | "expired"; ``` **PayProviderType** ```typescript type PayProviderType = "native" | "wasm"; ``` **CollectDataFieldType** ```typescript type CollectDataFieldType = "text" | "date"; ``` **Method Parameters** ```typescript interface GetPaymentOptionsParams { /** Payment link or ID */ paymentLink: string; /** List of CAIP-10 accounts */ accounts: string[]; /** Whether to include payment info in response */ includePaymentInfo?: boolean; } interface GetRequiredPaymentActionsParams { /** Payment ID */ paymentId: string; /** Option ID */ optionId: string; } interface ConfirmPaymentParams { /** Payment ID */ paymentId: string; /** Option ID */ optionId: string; /** Wallet RPC results in action order: plain strings or JSON objects (e.g. Tron) */ data: (string | object)[]; /** @deprecated Alias for `data`, still accepted */ signatures?: string[]; } ``` The SDK types `data` as `(string | Record | unknown[])[]`. A value typed with a TypeScript `interface` does not satisfy `Record`; declare it as a `type` alias or spread it into an object literal. **Response Types** ```typescript interface PaymentOptionsResponse { /** Payment ID extracted from the payment link */ paymentId: string; /** Payment information (if includePaymentInfo was true) */ info?: PaymentInfo; /** Available payment options */ options: PaymentOption[]; /** Data collection requirements (if any) */ collectData?: CollectDataAction; /** Transaction result details (present when payment already completed) */ resultInfo?: PaymentResultInfo; } interface PaymentResultInfo { /** Transaction ID */ txId: string; /** Token amount details */ optionAmount: PayAmount; } interface ConfirmPaymentResponse { /** Payment status */ status: PaymentStatus; /** True if the payment is in a final state */ isFinal: boolean; /** Time to poll for payment status, in milliseconds */ pollInMs?: number; } ``` **PaymentOption** ```typescript interface PaymentOption { /** ID of the option */ id: string; /** The option's token and amount */ amount: PayAmount; /** Estimated time to complete the option, in seconds */ etaS: number; /** Actions required to complete the option */ actions: Action[]; /** Per-option data collection requirements */ collectData?: CollectDataAction; } ``` **Action** ```typescript interface Action { walletRpc: WalletRpcAction; } interface WalletRpcAction { /** Chain ID in CAIP-2 format (e.g., "eip155:8453") */ chainId: string; /** RPC method name (e.g., "eth_signTypedData_v4", "eth_sendTransaction") */ method: string; /** JSON-encoded params array */ params: string; } ``` **Amount Types** ```typescript interface PayAmount { /** Currency unit, prefixed with either "iso4217/" or "caip19/" */ unit: string; /** Amount value, in the currency unit's minor units */ value: string; /** Display information for the amount */ display: AmountDisplay; } interface AmountDisplay { /** Ticker/symbol of the asset */ assetSymbol: string; /** Full name of the asset */ assetName: string; /** Number of minor decimals of the asset */ decimals: number; /** URL of the icon of the asset (if token) */ iconUrl?: string; /** Name of the network of the asset (if token) */ networkName?: string; } ``` **Payment Info Types** ```typescript interface PaymentInfo { /** Payment status */ status: PaymentStatus; /** Amount to be paid */ amount: PayAmount; /** Payment expiration timestamp, in seconds since epoch */ expiresAt: number; /** Merchant information */ merchant: MerchantInfo; /** Buyer information (present if payment has been submitted) */ buyer?: BuyerInfo; } interface MerchantInfo { /** Merchant name */ name: string; /** Merchant icon URL */ iconUrl?: string; } interface BuyerInfo { /** Account CAIP-10 */ accountCaip10: string; /** Account provider name */ accountProviderName: string; /** Account provider icon URL */ accountProviderIcon?: string; } ``` **Collect Data Types** ```typescript interface CollectDataAction { /** URL for data collection (displayed in WebView) */ url: string; /** JSON schema describing required fields */ schema?: string; } ``` ## Error Handling [#error-handling] The SDK throws typed errors for different failure scenarios: ```typescript import { PayError, PaymentOptionsError, PaymentActionsError, ConfirmPaymentError, NativeModuleNotFoundError } from "@walletconnect/pay"; try { const options = await client.getPaymentOptions({ paymentLink: link, accounts, }); } catch (error) { if (error instanceof PaymentOptionsError) { console.error("Failed to get options:", error.originalMessage); } else if (error instanceof PayError) { console.error("Pay error:", error.code, error.message); } } ``` **Error Types** | Error Class | Description | |-------------|-------------| | `PayError` | Base error class for all Pay SDK errors | | `PaymentOptionsError` | Error when fetching payment options | | `PaymentActionsError` | Error when fetching required payment actions | | `ConfirmPaymentError` | Error when confirming payment | | `NativeModuleNotFoundError` | Error when native module is not available | **Error Codes** The `PayError` class includes a `code` property with one of the following values: ```typescript type PayErrorCode = | "JSON_PARSE" | "JSON_SERIALIZE" | "PAYMENT_OPTIONS" | "PAYMENT_REQUEST" | "CONFIRM_PAYMENT" | "NATIVE_MODULE_NOT_FOUND" | "INITIALIZATION_ERROR" | "UNKNOWN"; ``` ## Best Practices [#best-practices] 1. **Check Provider Availability**: Always check if a provider is available before using the SDK 2. **Account Format**: Always use CAIP-10 format for accounts: `eip155:{chainId}:{address}` 3. **Multiple Chains**: Provide accounts for all supported chains to maximize payment options 4. **Result Order**: Keep `data` in the same order as the actions array 5. **Error Handling**: Always handle errors gracefully and show appropriate user feedback 6. **Loading States**: Show loading indicators during API calls and signing operations 7. **Expiration**: Check `paymentInfo.expiresAt` and warn users if time is running low 8. **User Data**: Only collect data when `collectData` is present on the selected payment option and you don't already have the required user data. If you already have the required data, you can submit this without collecting from the user. You must make sure the user accepts WalletConnect Terms and Conditions and Privacy Policy before submitting user information to WalletConnect. 9. **WebView Data Collection**: When `selectedOption.collectData?.url` is present, display the URL in a WebView using `react-native-webview` rather than building native forms. The WebView handles form rendering, validation, and T&C acceptance. 10. **Per-Option Data Collection**: When displaying payment options, check each option's `collectData` field. Show a visual indicator (e.g., "Info required" badge) on options that require data collection. Only open the WebView when the user selects an option with `collectData` present — use the option's `collectData.url` which is already scoped to that option's account. # WalletConnect Pay SDK - Swift (/payments/wallets/standalone/swift) The WalletConnect Pay SDK allows wallet users to pay merchants using their crypto assets. The SDK handles payment option discovery, permit signing coordination, and payment confirmation while leveraging your wallet's existing signing infrastructure. ## Sample Wallet [#sample-wallet] For a complete working example, check out our sample wallet implementation: } href="https://github.com/reown-com/reown-swift/tree/develop/Example/WalletApp"> A reference iOS wallet app demonstrating WalletConnect Pay integration. ## Requirements [#requirements] - iOS 13.0+ - Swift 5.7+ - Xcode 14.0+ - WalletConnectPay 2.4.0 or later (ships YttriumWrapper 0.10.59). Required for the `data` parameter in `confirmPayment`. ## Installation [#installation] **Swift Package Manager** Add WalletConnectPay to your `Package.swift`: ```swift dependencies: [ .package(url: "https://github.com/reown-com/reown-swift", from: "2.4.0") ] ``` Then add `WalletConnectPay` to your target dependencies: ```swift .target( name: "YourApp", dependencies: ["WalletConnectPay"] ) ``` The version shown above may not be the latest. Check the [GitHub releases](https://github.com/reown-com/reown-swift/releases) for the most recent version. ## Initialization [#initialization] Configure the Pay client during app initialization, typically in your `AppDelegate` or `SceneDelegate`: ```swift import WalletConnectPay func application(_ application: UIApplication, didFinishLaunchingWithOptions...) { // Option 1: With appId (recommended for wallets) WalletConnectPay.configure( appId: "your-wcp-id", logging: true ) // Option 2: With API key WalletConnectPay.configure( apiKey: "your-pay-api-key" ) } ``` **Configuration Parameters** | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `apiKey` | `String?` | No* | `nil` | Your WalletConnect Pay API key | | `appId` | `String?` | No* | `nil` | Your WCP ID | | `baseUrl` | `String` | No | Production URL | Custom API URL | | `logging` | `Bool` | No | `false` | Enable debug logging | At least one of `apiKey` or `appId` must be provided. Don't have a project ID? Create one at the [WalletConnect Dashboard](https://dashboard.walletconnect.com) by signing up and creating a new project. ## Supported Networks & Tokens [#supported-networks--tokens] WalletConnect Pay currently supports the following tokens and networks: | Token | Network | Chain ID | CAIP-10 Format | |-------|---------|----------|----------------| | USDC | Arbitrum | 42161 | `eip155:42161:{address}` | | USDC | Base | 8453 | `eip155:8453:{address}` | | USDC | Polygon | 137 | `eip155:137:{address}` | | USDC | Ethereum | 1 | `eip155:1:{address}` | | USDC | Optimism | 10 | `eip155:10:{address}` | | USDC | Monad | 143 | `eip155:143:{address}` | | USDC | Celo | 42220 | `eip155:42220:{address}` | | USDC | BSC | 56 | `eip155:56:{address}` | | EURC | Ethereum | 1 | `eip155:1:{address}` | | EURC | Base | 8453 | `eip155:8453:{address}` | | USDT0 | Arbitrum | 42161 | `eip155:42161:{address}` | | PYUSD | Ethereum | 1 | `eip155:1:{address}` | | PYUSD | Arbitrum | 42161 | `eip155:42161:{address}` | | USDG | Ethereum | 1 | `eip155:1:{address}` | | USDT | Ethereum | 1 | `eip155:1:{address}` | | USDT | Polygon | 137 | `eip155:137:{address}` | | USDT | BSC | 56 | `eip155:56:{address}` | Include accounts for all supported networks to maximize payment options for your users. ## Payment Link Detection [#payment-link-detection] The `isPaymentLink` utility method detects WalletConnect Pay links by checking for: - `pay.` hosts (e.g., pay.walletconnect.com) - `pay=` parameter in WalletConnect URIs - `pay_` prefix in bare payment IDs ```swift func isPaymentLink(_ string: String) -> Bool { let lower = string.lowercased() return lower.contains("pay.") || lower.contains("pay=") || lower.contains("pay_") } ``` Call it wherever your wallet receives a link — from a deep link or a scanned QR code: ```swift // Deep link opened from outside your app (SceneDelegate or AppDelegate) func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { guard let url = URLContexts.first?.url else { return } if isPaymentLink(url.absoluteString) { startPaymentFlow(paymentLink: url.absoluteString) } } // QR code payload func handleScannedQR(_ content: String) { if isPaymentLink(content) { startPaymentFlow(paymentLink: content) } } ``` ## Payment Flow [#payment-flow] The payment flow consists of five main steps: **Get Options -> Collect Data (if required) -> Get Actions -> Sign Actions -> Confirm Payment** ```mermaid sequenceDiagram participant User participant Wallet participant PaySDK as Pay SDK participant Backend as WalletConnect Pay participant WebView User->>Wallet: Scan QR / Open payment link Wallet->>PaySDK: getPaymentOptions(link, accounts) PaySDK->>Backend: Fetch payment options Backend-->>PaySDK: Payment options + merchant info PaySDK-->>Wallet: PaymentOptionsResponse Wallet->>User: Display payment options User->>Wallet: Select payment option alt Selected option requires data collection Wallet->>WebView: Load selectedOption.collectData.url WebView->>User: Display data collection form User->>WebView: Fill form & accept T&C WebView-->>Wallet: IC_COMPLETE message end Wallet->>PaySDK: getRequiredPaymentActions(paymentId, optionId) PaySDK->>Backend: Get signing actions Backend-->>PaySDK: Required wallet RPC actions PaySDK-->>Wallet: List of actions to sign Wallet->>User: Request signature(s) User->>Wallet: Approve & sign Wallet->>PaySDK: confirmPayment(data) PaySDK->>Backend: Submit payment Backend-->>PaySDK: Payment status PaySDK-->>Wallet: ConfirmPaymentResponse Wallet->>User: Show result ``` ### Get Payment Options [#get-payment-options] When a user scans a payment QR code or opens a payment link, fetch available payment options: ```swift let paymentLink = "https://pay.walletconnect.com/?pid=pay_abc123..." // Provide all user's EVM accounts in CAIP-10 format let accounts = [ "eip155:1:\(walletAddress)", // Ethereum Mainnet "eip155:137:\(walletAddress)", // Polygon "eip155:8453:\(walletAddress)", // Base "eip155:42161:\(walletAddress)" // Arbitrum ] do { let response = try await WalletConnectPay.instance.getPaymentOptions( paymentLink: paymentLink, accounts: accounts ) // Display merchant info if let info = response.info { print("Merchant: \(info.merchant.name)") print("Amount: \(info.amount.display.assetSymbol) \(info.amount.value)") } // Show available payment options to user for option in response.options { print("Pay with \(option.amount.display.assetSymbol) on \(option.amount.display.networkName ?? "Unknown")") } // Check which options require data collection for option in response.options { if option.collectData != nil { print("Option \(option.id) requires info capture") } } } catch { print("Failed to get payment options: \(error)") } ``` ### Collect User Data (If Required) [#collect-user-data-if-required] After the user selects an option, check for `collectData` on it. If present, collect the data **before** fetching the required actions. ```swift // Check per-option data collection requirement after user selects an option if let collectData = selectedOption.collectData, let url = collectData.url { // Build prefill URL with known user data // Use the "required" list from collectData.schema to determine which fields to prefill let prefillData: [String: String] = [ "fullName": "John Doe", "dob": "1990-01-15", "pobAddress": "123 Main St, New York, NY 10001" ] let jsonData = try JSONSerialization.data(withJSONObject: prefillData) // Encode prefill as base64url (URL-safe, no padding) let prefillBase64 = jsonData.base64EncodedString() .replacingOccurrences(of: "+", with: "-") .replacingOccurrences(of: "/", with: "_") .replacingOccurrences(of: "=", with: "") var components = URLComponents(string: url)! var queryItems = components.queryItems ?? [] queryItems.append(URLQueryItem(name: "prefill", value: prefillBase64)) // Optional appearance params (see "Form URL parameters"): queryItems.append(URLQueryItem(name: "theme", value: "dark")) // "light" | "dark" // themeVariables is a base64url string exported from the WalletConnect Pay Dashboard: // queryItems.append(URLQueryItem(name: "themeVariables", value: themeVariables)) components.queryItems = queryItems let webViewUrl = components.string! // Show WebView for this specific option — see Data Collection Implementation section below showWebView(url: webViewUrl) } ``` ### Get Required Actions [#get-required-actions] After the user selects a payment option, get the signing actions: ```swift let actions = try await WalletConnectPay.instance.getRequiredPaymentActions( paymentId: response.paymentId, optionId: selectedOption.id ) ``` ### Sign Actions [#sign-actions] Each action contains a `walletRpc` describing the RPC call to execute. Your wallet must check the `method` field and dispatch accordingly — for example, a payment option may require an `eth_sendTransaction` to approve a token allowance followed by an `eth_signTypedData_v4` to sign Permit2 typed data. ```swift var data: [String] = [] for action in actions { let rpc = action.walletRpc // rpc.chainId - The chain to execute on (e.g., "eip155:8453") // rpc.method - The RPC method (e.g., "eth_signTypedData_v4", "eth_sendTransaction") // rpc.params - JSON string with method-specific parameters let result: String switch rpc.method { case "eth_signTypedData_v4": let paramsData = rpc.params.data(using: .utf8)! let params = try JSONSerialization.jsonObject(with: paramsData) as! [Any] let typedDataJson = params[1] as! String result = try await yourWallet.signTypedData( typedData: typedDataJson, address: walletAddress, chainId: rpc.chainId ) case "eth_sendTransaction": result = try await yourWallet.sendTransaction( params: rpc.params, chainId: rpc.chainId ) case "personal_sign": result = try await yourWallet.personalSign( params: rpc.params, chainId: rpc.chainId ) default: throw PaymentError.unsupportedMethod(rpc.method) } data.append(result) } ``` Payment options may include multiple actions with different RPC methods. For example, a Permit2 payment where the user lacks sufficient allowance returns two actions: an `eth_sendTransaction` to approve the token allowance, followed by an `eth_signTypedData_v4` to sign the Permit2 transfer. Your wallet must check `action.walletRpc.method` and dispatch to the appropriate handler. For full implementation guidance, see [USDT support](/payments/wallets/token-chain-support/usdt-support). Keep `data` in the same order as the actions array. ### Confirm Payment [#confirm-payment] Submit the wallet RPC results (`data`) and finalize the payment. Each element of `data` is either a plain string (a signature or transaction hash) or, for chains like Tron, a JSON-encoded object; WalletConnect Pay forwards each element verbatim to the gateway. See [Tron support](/payments/wallets/token-chain-support/tron-support) for the Tron payload. When using the WebView approach for data collection, the WebView submits the captured data directly to the backend, so you do **not** pass `collectedData` to `confirmPayment`. ```swift let result = try await WalletConnectPay.instance.confirmPayment( paymentId: response.paymentId, optionId: selectedOption.id, data: data, maxPollMs: 60000 // Wait up to 60 seconds for confirmation ) switch result.status { case .succeeded: print("Payment successful!") case .processing: print("Payment is being processed...") case .failed: print("Payment failed") case .expired: print("Payment expired") case .requiresAction: print("Additional action required") case .cancelled: print("Payment cancelled") } ``` The `signatures:` overload of `confirmPayment` is deprecated in favor of `data:` and will be removed in a future major version. Existing integrations that pass `signatures:` keep working; the overload forwards its value to `data`. ## Data Collection Implementation [#data-collection-implementation] When `selectedOption.collectData.url` is present, display the URL in a `WKWebView`. The WebView handles form rendering, validation, and T&C acceptance. ```swift import WebKit import SwiftUI struct PayDataCollectionWebView: UIViewRepresentable { let url: URL let onComplete: () -> Void let onError: (String) -> Void func makeCoordinator() -> Coordinator { Coordinator(onComplete: onComplete, onError: onError) } func makeUIView(context: Context) -> WKWebView { let config = WKWebViewConfiguration() config.userContentController.add( context.coordinator, name: "payDataCollectionComplete" ) let webView = WKWebView(frame: .zero, configuration: config) webView.navigationDelegate = context.coordinator webView.load(URLRequest(url: url)) return webView } func updateUIView(_ uiView: WKWebView, context: Context) {} class Coordinator: NSObject, WKScriptMessageHandler, WKNavigationDelegate { let onComplete: () -> Void let onError: (String) -> Void init(onComplete: @escaping () -> Void, onError: @escaping (String) -> Void) { self.onComplete = onComplete self.onError = onError } func userContentController( _ userContentController: WKUserContentController, didReceive message: WKScriptMessage ) { guard let body = message.body as? String, let data = body.data(using: .utf8), let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let type = json["type"] as? String else { return } DispatchQueue.main.async { switch type { case "IC_COMPLETE": self.onComplete() case "IC_ERROR": let error = json["error"] as? String ?? "Unknown error" self.onError(error) default: break } } } func webView( _ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void ) { guard let url = navigationAction.request.url else { decisionHandler(.allow) return } // Open external links (T&C, Privacy Policy) in Safari if let host = url.host, !host.contains("pay.walletconnect.com") { UIApplication.shared.open(url) decisionHandler(.cancel) return } decisionHandler(.allow) } } } func buildFormUrl( baseUrl: String, prefillData: [String: String] = [:], theme: String? = nil, // "light" or "dark" themeVariables: String? = nil // base64url string exported from the Pay Dashboard ) -> String { guard var components = URLComponents(string: baseUrl) else { return baseUrl } var queryItems = components.queryItems ?? [] if !prefillData.isEmpty, let jsonData = try? JSONSerialization.data(withJSONObject: prefillData) { // base64url: URL-safe, no padding let prefill = jsonData.base64EncodedString() .replacingOccurrences(of: "+", with: "-") .replacingOccurrences(of: "/", with: "_") .replacingOccurrences(of: "=", with: "") queryItems.append(URLQueryItem(name: "prefill", value: prefill)) } if let theme = theme { queryItems.append(URLQueryItem(name: "theme", value: theme)) } if let themeVariables = themeVariables { queryItems.append(URLQueryItem(name: "themeVariables", value: themeVariables)) } components.queryItems = queryItems return components.string ?? baseUrl } ``` ## Complete Example [#complete-example] Here's a complete implementation example: ```swift import WalletConnectPay class PaymentManager { func processPayment( paymentLink: String, walletAddress: String, signer: YourSignerProtocol ) async throws { // 1. Get payment options let accounts = [ "eip155:1:\(walletAddress)", "eip155:137:\(walletAddress)", "eip155:8453:\(walletAddress)" ] let optionsResponse = try await WalletConnectPay.instance.getPaymentOptions( paymentLink: paymentLink, accounts: accounts ) guard !optionsResponse.options.isEmpty else { throw PaymentError.noOptionsAvailable } // 2. Let user select an option (simplified - use first option) let selectedOption = optionsResponse.options[0] // 3. Collect data via WebView if required (before fetching actions) if let collectData = selectedOption.collectData, let url = collectData.url { // Show WebView and wait for IC_COMPLETE message try await showDataCollectionWebView(url: url) } // 4. Get required actions let actions = try await WalletConnectPay.instance.getRequiredPaymentActions( paymentId: optionsResponse.paymentId, optionId: selectedOption.id ) // 5. Sign all actions var data: [String] = [] for action in actions { let signature = try await signAction( action: action, walletAddress: walletAddress, signer: signer ) data.append(signature) } // 6. Confirm payment let result = try await WalletConnectPay.instance.confirmPayment( paymentId: optionsResponse.paymentId, optionId: selectedOption.id, data: data ) switch result.status { case .succeeded: break // Success case .cancelled: throw PaymentError.paymentCancelled default: throw PaymentError.paymentFailed(result.status) } } private func signAction( action: Action, walletAddress: String, signer: YourSignerProtocol ) async throws -> String { let rpc = action.walletRpc switch rpc.method { case "eth_signTypedData_v4": guard let paramsData = rpc.params.data(using: .utf8), let params = try JSONSerialization.jsonObject(with: paramsData) as? [Any], params.count >= 2, let typedDataJson = params[1] as? String else { throw PaymentError.invalidParams } return try await signer.signTypedData( data: typedDataJson, address: walletAddress ) case "eth_sendTransaction": return try await signer.sendTransaction( params: rpc.params, chainId: rpc.chainId ) case "personal_sign": return try await signer.personalSign( params: rpc.params, address: walletAddress ) default: throw PaymentError.unsupportedMethod(rpc.method) } } } ``` ## API Reference [#api-reference] **WalletConnectPay** Static configuration class for the Pay SDK. | Method | Description | |--------|-------------| | `configure(apiKey:appId:baseUrl:logging:)` | Initialize the SDK with your credentials | | `instance` | Access the shared `PayClient` instance | **PayClient** Main client for payment operations. | Method | Description | |--------|-------------| | `getPaymentOptions(paymentLink:accounts:includePaymentInfo:)` | Fetch available payment options | | `getRequiredPaymentActions(paymentId:optionId:)` | Get signing actions for a payment option | | `confirmPayment(paymentId:optionId:data:collectedData:maxPollMs:)` | Confirm and execute the payment. `data: [String]` holds the wallet RPC results in action order (plain strings or JSON-encoded objects) | | `confirmPayment(paymentId:optionId:signatures:collectedData:maxPollMs:)` | Deprecated alias for the `data:` overload; still compiles and forwards to `data` | **Data Types** **PaymentOptionsResponse** ```swift struct PaymentOptionsResponse { let paymentId: String // Unique payment identifier let info: PaymentInfo? // Merchant and amount details let options: [PaymentOption] // Available payment methods let collectData: CollectDataAction? // Required user data fields (travel rule) let resultInfo: PaymentResultInfo? // Transaction result details (present when payment already completed) } struct PaymentResultInfo { let txId: String // Transaction ID let optionAmount: PayAmount // Token amount details } ``` **PaymentInfo** ```swift struct PaymentInfo { let status: PaymentStatus // Current payment status let amount: PayAmount // Requested payment amount let expiresAt: Int64 // Expiration timestamp let merchant: MerchantInfo // Merchant details let buyer: BuyerInfo? // Buyer info if available } ``` **PaymentOption** ```swift struct PaymentOption { let id: String // Option identifier let amount: PayAmount // Amount in this asset let etaS: Int64 // Estimated time to complete (seconds) let actions: [Action] // Required signing actions let collectData: CollectDataAction? // Per-option data collection (nil if not required) } ``` **PayAmount** ```swift struct PayAmount { let unit: String // Asset unit (e.g., "USDC") let value: String // Raw value in smallest unit let display: AmountDisplay // Human-readable display info } struct AmountDisplay { let assetSymbol: String // Token symbol (e.g., "USDC") let assetName: String // Token name (e.g., "USD Coin") let decimals: Int64 // Token decimals let iconUrl: String? // Token icon URL let networkName: String? // Network name (e.g., "Base") } ``` **Action & WalletRpcAction** ```swift struct Action { let walletRpc: WalletRpcAction // RPC call to sign } struct WalletRpcAction { let chainId: String // Chain ID (e.g., "eip155:8453") let method: String // RPC method (e.g., "eth_signTypedData_v4", "eth_sendTransaction") let params: String // JSON-encoded parameters } ``` **CollectDataAction & CollectDataField** ```swift struct CollectDataAction { let url: String // WebView URL for data collection let schema: String? // JSON schema describing required fields } ``` **ConfirmPaymentResultResponse** ```swift struct ConfirmPaymentResultResponse { let status: PaymentStatus // Final payment status let isFinal: Bool // Whether status is final let pollInMs: Int64? // Suggested poll interval let info: PaymentResultInfo? // Transaction result details (present on success) } enum PaymentStatus { case requiresAction // Additional action needed case processing // Payment in progress case succeeded // Payment completed case failed // Payment failed case expired // Payment expired case cancelled // Payment cancelled by user } ``` ## Error Handling [#error-handling] The SDK throws specific error types for different failure scenarios: **GetPaymentOptionsError** | Error | Description | |-------|-------------| | `.paymentNotFound` | Payment ID doesn't exist | | `.paymentExpired` | Payment has expired | | `.invalidRequest` | Invalid request parameters | | `.invalidAccount` | Invalid account format | | `.complianceFailed` | Compliance check failed | | `.http` | Network error | | `.internalError` | Server error | **GetPaymentRequestError** | Error | Description | |-------|-------------| | `.optionNotFound` | Selected option doesn't exist | | `.paymentNotFound` | Payment ID doesn't exist | | `.invalidAccount` | Invalid account format | | `.http` | Network error | **ConfirmPaymentError** | Error | Description | |-------|-------------| | `.paymentNotFound` | Payment ID doesn't exist | | `.paymentExpired` | Payment has expired | | `.invalidOption` | Invalid option ID | | `.invalidSignature` | Signature verification failed | | `.routeExpired` | Payment route expired | | `.http` | Network error | ## Best Practices [#best-practices] 1. **Account Format**: Always use CAIP-10 format for accounts: `eip155:{chainId}:{address}` 2. **Multiple Chains**: Provide accounts for all supported chains to maximize payment options 3. **Result Order**: Keep `data` in the same order as the actions array 4. **Error Handling**: Always handle errors gracefully and show appropriate user feedback 5. **Loading States**: Show loading indicators during API calls and signing operations 6. **Expiration**: Check `paymentInfo.expiresAt` and warn users if time is running low 7. **User Data**: Only collect data when `collectData` is present on the selected payment option and you don't already have the required user data. If you already have the required data, you can submit this without collecting from the user. You must make sure the user accepts WalletConnect Terms and Conditions and Privacy Policy before submitting user information to WalletConnect. 8. **WebView Data Collection**: When `selectedOption.collectData?.url` is present, display the URL in a WKWebView rather than building native forms. The WebView handles form rendering, validation, and T&C acceptance. 9. **Per-Option Data Collection**: When displaying payment options, check each option's `collectData` field. Show a visual indicator (e.g., "Info required" badge) on options that require data collection. Only open the WebView when the user selects an option with `collectData` present — use the option's `collectData.url` which is already scoped to that option's account. # WalletConnect Pay SDK - Web/Node.js (/payments/wallets/standalone/web) The WalletConnect Pay SDK allows wallet users to pay merchants using their crypto assets. The SDK handles payment option discovery, permit signing coordination, and payment confirmation while leveraging your wallet's existing signing infrastructure. ## Sample Wallet [#sample-wallet] For a complete working example, check out our sample wallet implementation: } href="https://github.com/reown-com/web-examples/tree/main/advanced/wallets/react-wallet-v2"> A reference web wallet app demonstrating WalletConnect Pay integration. ## Requirements [#requirements] - Node.js 16+ - `@walletconnect/pay` 1.1.0 or later (ships the WASM Yttrium module 0.10.59) ## Installation [#installation] Install the WalletConnect Pay SDK using npm or yarn: ```bash npm install @walletconnect/pay ``` ```bash yarn add @walletconnect/pay ``` ## Architecture [#architecture] The SDK uses a provider abstraction that allows different implementations: - **WasmProvider**: Uses WebAssembly module for web browsers - **NativeProvider**: Uses platform-specific uniffi module (for React Native environments) The SDK auto-detects the best available provider for your environment. ## Initialization [#initialization] Initialize the WalletConnect Pay client with your credentials: ```typescript import { WalletConnectPay } from "@walletconnect/pay"; const client = new WalletConnectPay({ appId: "your-wcp-id", // OR use apiKey instead: // apiKey: "your-api-key", }); ``` **Configuration Parameters** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `appId` | `string` | No* | WCP ID for authentication | | `apiKey` | `string` | No* | API key for authentication | | `clientId` | `string` | No | Client ID for tracking | | `baseUrl` | `string` | No | Custom API base URL | | `logger` | `Logger` | No | Custom logger instance or level | Either `appId` or `apiKey` must be provided for authentication. Don't have a project ID? Create one at the [WalletConnect Dashboard](https://dashboard.walletconnect.com) by signing up and creating a new project. ## Supported Networks & Tokens [#supported-networks--tokens] WalletConnect Pay currently supports the following tokens and networks: | Token | Network | Chain ID | CAIP-10 Format | |-------|---------|----------|----------------| | USDC | Arbitrum | 42161 | `eip155:42161:{address}` | | USDC | Base | 8453 | `eip155:8453:{address}` | | USDC | Polygon | 137 | `eip155:137:{address}` | | USDC | Ethereum | 1 | `eip155:1:{address}` | | USDC | Optimism | 10 | `eip155:10:{address}` | | USDC | Monad | 143 | `eip155:143:{address}` | | USDC | Celo | 42220 | `eip155:42220:{address}` | | USDC | BSC | 56 | `eip155:56:{address}` | | EURC | Ethereum | 1 | `eip155:1:{address}` | | EURC | Base | 8453 | `eip155:8453:{address}` | | USDT0 | Arbitrum | 42161 | `eip155:42161:{address}` | | PYUSD | Ethereum | 1 | `eip155:1:{address}` | | PYUSD | Arbitrum | 42161 | `eip155:42161:{address}` | | USDG | Ethereum | 1 | `eip155:1:{address}` | | USDT | Ethereum | 1 | `eip155:1:{address}` | | USDT | Polygon | 137 | `eip155:137:{address}` | | USDT | BSC | 56 | `eip155:56:{address}` | Include accounts for all supported networks to maximize payment options for your users. ## Payment Flow [#payment-flow] The payment flow consists of five main steps: **Get Options -> Collect Data (if required) -> Get Actions -> Sign Actions -> Confirm Payment** ```mermaid sequenceDiagram participant User participant Wallet participant PaySDK as Pay SDK participant Backend as WalletConnect Pay participant Iframe User->>Wallet: Scan QR / Open payment link Wallet->>PaySDK: getPaymentOptions(link, accounts) PaySDK->>Backend: Fetch payment options Backend-->>PaySDK: Payment options + merchant info PaySDK-->>Wallet: PaymentOptionsResponse Wallet->>User: Display payment options User->>Wallet: Select payment option alt Selected option requires data collection Wallet->>Iframe: Load selectedOption.collectData.url in iframe Iframe->>User: Display data collection form User->>Iframe: Fill form & accept T&C Iframe-->>Wallet: IC_COMPLETE message via postMessage end Wallet->>PaySDK: getRequiredPaymentActions(paymentId, optionId) PaySDK->>Backend: Get signing actions Backend-->>PaySDK: Required wallet RPC actions PaySDK-->>Wallet: List of actions to sign Wallet->>User: Request signature(s) User->>Wallet: Approve & sign Wallet->>PaySDK: confirmPayment(data) PaySDK->>Backend: Submit payment Backend-->>PaySDK: Payment status PaySDK-->>Wallet: ConfirmPaymentResponse Wallet->>User: Show result ``` ### Get Payment Options [#get-payment-options] When a user scans a payment QR code or opens a payment link, fetch available payment options: ```typescript const options = await client.getPaymentOptions({ paymentLink: "https://pay.walletconnect.com/pay_123", accounts: [ `eip155:1:${walletAddress}`, // Ethereum Mainnet `eip155:8453:${walletAddress}`, // Base ], includePaymentInfo: true, }); console.log("Payment ID:", options.paymentId); console.log("Options:", options.options); // Display merchant info if (options.info) { console.log("Merchant:", options.info.merchant.name); console.log("Amount:", options.info.amount.display.assetSymbol, options.info.amount.value); } // Check which options require data collection for (const option of options.options) { if (option.collectData) { console.log(`Option ${option.id} requires info capture`); } } ``` ### Collect User Data (If Required) [#collect-user-data-if-required] After the user selects an option, check for `collectData` on it. If present, collect the data **before** fetching the required actions. ```typescript // Check per-option data collection requirement after user selects an option if (selectedOption.collectData?.url) { // Use the "required" list from selectedOption.collectData.schema to determine which fields to prefill const prefillData = { fullName: "John Doe", dob: "1990-01-15", pobAddress: "123 Main St, New York, NY 10001", }; // Encode prefill as base64url (URL-safe, no padding) const prefill = btoa(JSON.stringify(prefillData)) .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); // Optional appearance params (see "Form URL parameters"): // theme=light|dark — base color mode // themeVariables= — exported from the WalletConnect Pay Dashboard const themeVariables = ""; const query = `prefill=${prefill}&theme=dark&themeVariables=${themeVariables}`; const separator = selectedOption.collectData.url.includes("?") ? "&" : "?"; const iframeUrl = `${selectedOption.collectData.url}${separator}${query}`; // Show data collection in an iframe or popup — see Data Collection Implementation section below showDataCollectionView(iframeUrl); } ``` ### Iframe Message Types [#iframe-message-types] The iframe communicates with your wallet through `postMessage` events. The message payload is a JSON string with the following structure: | Message Type | Payload | Description | |-------------|---------|-------------| | `IC_COMPLETE` | `{ "type": "IC_COMPLETE", "success": true }` | User completed the form successfully. Proceed to payment confirmation. | | `IC_ERROR` | `{ "type": "IC_ERROR", "error": "..." }` | An error occurred. Display the error message and allow the user to retry. | ### Get Required Actions [#get-required-actions] After the user selects a payment option, get the wallet RPC actions required to complete the payment: ```typescript const actions = await client.getRequiredPaymentActions({ paymentId: options.paymentId, optionId: options.options[0].id, }); // Each action contains wallet RPC data to sign for (const action of actions) { console.log("Chain:", action.walletRpc.chainId); console.log("Method:", action.walletRpc.method); console.log("Params:", action.walletRpc.params); } ``` ### Sign Actions [#sign-actions] Sign each action with your wallet's signing implementation: ```typescript // Sign each action based on its RPC method const data = await Promise.all( actions.map(async (action) => { const { chainId, method, params } = action.walletRpc; const parsedParams = JSON.parse(params); switch (method) { case "eth_signTypedData_v4": return await wallet.signTypedData(chainId, parsedParams); case "eth_sendTransaction": return await wallet.sendTransaction(chainId, parsedParams[0]); case "personal_sign": return await wallet.personalSign(chainId, parsedParams); default: throw new Error(`Unsupported RPC method: ${method}`); } }) ); ``` Payment options may include multiple actions with different RPC methods. For example, a Permit2 payment where the user lacks sufficient allowance returns two actions: an `eth_sendTransaction` to approve the token allowance, followed by an `eth_signTypedData_v4` to sign the Permit2 transfer. Your wallet must check `action.walletRpc.method` and dispatch to the appropriate handler. For full implementation guidance, see [USDT support](/payments/wallets/token-chain-support/usdt-support). Keep `data` in the same order as the actions array. ### Confirm Payment [#confirm-payment] Submit the wallet RPC results (`data`) and collected data to complete the payment. Each element of `data` is either a plain string (a signature or transaction hash) or, for chains like Tron, a JSON object; the SDK forwards each element verbatim. See [Tron support](/payments/wallets/token-chain-support/tron-support) for the Tron payload. ```typescript const result = await client.confirmPayment({ paymentId: options.paymentId, optionId: options.options[0].id, data, collectedData, // Include if collectData was present }); if (result.status === "succeeded") { console.log("Payment successful!"); } else if (result.status === "processing") { console.log("Payment is processing..."); } else if (result.status === "failed") { console.log("Payment failed"); } ``` The `signatures` parameter is deprecated in favor of `data` and will be removed in a future major version. Existing integrations that pass `signatures` keep working; the SDK uses it as a fallback when `data` is omitted. ## Data Collection Implementation [#data-collection-implementation] When `selectedOption.collectData.url` is present, display the URL in an iframe or modal. Listen for `postMessage` events to handle completion: ```typescript function showDataCollectionView(url: string): Promise { // Create a modal/overlay container const overlay = document.createElement("div"); overlay.style.cssText = "position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);display:flex;align-items:center;justify-content:center;z-index:9999;"; const iframe = document.createElement("iframe"); iframe.src = url; iframe.style.cssText = "width:450px;height:650px;border:none;border-radius:12px;"; overlay.appendChild(iframe); document.body.appendChild(overlay); return new Promise((resolve, reject) => { function handleMessage(event: MessageEvent) { try { const data = typeof event.data === "string" ? JSON.parse(event.data) : event.data; if (data.type === "IC_COMPLETE") { cleanup(); resolve(); } else if (data.type === "IC_ERROR") { cleanup(); reject(new Error(data.error || "Unknown error")); } } catch { // Ignore non-JSON messages } } function cleanup() { window.removeEventListener("message", handleMessage); document.body.removeChild(overlay); } window.addEventListener("message", handleMessage); }); } function buildFormUrl( baseUrl: string, options: { prefill?: Record; theme?: "light" | "dark"; themeVariables?: string; // base64url string exported from the Pay Dashboard } = {} ): string { const params: string[] = []; if (options.prefill && Object.keys(options.prefill).length > 0) { // base64url: URL-safe, no padding const prefill = btoa(JSON.stringify(options.prefill)) .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); params.push(`prefill=${prefill}`); } if (options.theme) params.push(`theme=${options.theme}`); if (options.themeVariables) params.push(`themeVariables=${options.themeVariables}`); if (params.length === 0) return baseUrl; const separator = baseUrl.includes("?") ? "&" : "?"; return `${baseUrl}${separator}${params.join("&")}`; } ``` ## Complete Example [#complete-example] Here's a complete implementation example: ```typescript import { WalletConnectPay, CollectDataFieldResult } from "@walletconnect/pay"; class PaymentManager { private client: WalletConnectPay; constructor() { this.client = new WalletConnectPay({ appId: "your-wcp-id", }); } async processPayment(paymentLink: string, walletAddress: string) { try { // Step 1: Get payment options const options = await this.client.getPaymentOptions({ paymentLink, accounts: [ `eip155:1:${walletAddress}`, `eip155:137:${walletAddress}`, `eip155:8453:${walletAddress}`, ], includePaymentInfo: true, }); if (options.options.length === 0) { throw new Error("No payment options available"); } // Step 2: Let user select an option (simplified - use first option) const selectedOption = options.options[0]; // Step 3: Collect data via iframe if required for selected option. // This must happen BEFORE fetching required actions, otherwise the // backend rejects the fetch for options that require info capture. if (selectedOption.collectData?.url) { // Show iframe and wait for IC_COMPLETE await this.showDataCollectionView(selectedOption.collectData.url); } // Step 4: Get required actions const actions = await this.client.getRequiredPaymentActions({ paymentId: options.paymentId, optionId: selectedOption.id, }); // Step 5: Sign all actions const data = await Promise.all( actions.map((action) => this.signAction(action, walletAddress) ) ); // Step 6: Confirm payment const result = await this.client.confirmPayment({ paymentId: options.paymentId, optionId: selectedOption.id, data, }); return result; } catch (error) { console.error("Payment failed:", error); throw error; } } private async signAction(action: Action, walletAddress: string): Promise { const { chainId, method, params } = action.walletRpc; const parsedParams = JSON.parse(params); switch (method) { case "eth_signTypedData_v4": return await wallet.signTypedData(chainId, parsedParams); case "eth_sendTransaction": return await wallet.sendTransaction(chainId, parsedParams[0]); case "personal_sign": return await wallet.personalSign(chainId, parsedParams); default: throw new Error(`Unsupported RPC method: ${method}`); } } } ``` ## Provider Utilities [#provider-utilities] The SDK provides utilities for checking provider availability: ```typescript import { isProviderAvailable, detectProviderType, } from "@walletconnect/pay"; // Check if any provider is available if (isProviderAvailable()) { // SDK can be used } // Detect which provider type is available const providerType = detectProviderType(); // 'native' | 'wasm' | null ``` ## API Reference [#api-reference] **WalletConnectPay** Main client for payment operations. **Constructor** ```typescript new WalletConnectPay(options: WalletConnectPayOptions) ``` **Methods** | Method | Description | |--------|-------------| | `getPaymentOptions(params)` | Fetch available payment options | | `getRequiredPaymentActions(params)` | Get signing actions for a payment option | | `confirmPayment(params)` | Confirm and execute the payment | | `static isAvailable()` | Check if a provider is available | **Data Types** **PaymentStatus** ```typescript type PaymentStatus = | "requires_action" | "processing" | "succeeded" | "failed" | "expired"; ``` **PayProviderType** ```typescript type PayProviderType = "native" | "wasm"; ``` **CollectDataFieldType** ```typescript type CollectDataFieldType = "text" | "date"; ``` **Method Parameters** ```typescript interface GetPaymentOptionsParams { /** Payment link or ID */ paymentLink: string; /** List of CAIP-10 accounts */ accounts: string[]; /** Whether to include payment info in response */ includePaymentInfo?: boolean; } interface GetRequiredPaymentActionsParams { /** Payment ID */ paymentId: string; /** Option ID */ optionId: string; } interface ConfirmPaymentParams { /** Payment ID */ paymentId: string; /** Option ID */ optionId: string; /** Wallet RPC results in action order: plain strings or JSON objects (e.g. Tron) */ data: (string | object)[]; /** @deprecated Alias for `data`, still accepted */ signatures?: string[]; } ``` The SDK types `data` as `(string | Record | unknown[])[]`. A value typed with a TypeScript `interface` does not satisfy `Record`; declare it as a `type` alias or spread it into an object literal. **Response Types** ```typescript interface PaymentOptionsResponse { /** Payment ID extracted from the payment link */ paymentId: string; /** Payment information (if includePaymentInfo was true) */ info?: PaymentInfo; /** Available payment options */ options: PaymentOption[]; /** Data collection requirements (if any) */ collectData?: CollectDataAction; /** Transaction result details (present when payment already completed) */ resultInfo?: PaymentResultInfo; } interface PaymentResultInfo { /** Transaction ID */ txId: string; /** Token amount details */ optionAmount: PayAmount; } interface ConfirmPaymentResponse { /** Payment status */ status: PaymentStatus; /** True if the payment is in a final state */ isFinal: boolean; /** Time to poll for payment status, in milliseconds */ pollInMs?: number; } ``` **PaymentOption** ```typescript interface PaymentOption { /** ID of the option */ id: string; /** The option's token and amount */ amount: PayAmount; /** Estimated time to complete the option, in seconds */ etaS: number; /** Actions required to complete the option */ actions: Action[]; /** Per-option data collection requirements */ collectData?: CollectDataAction; } ``` **Action** ```typescript interface Action { walletRpc: WalletRpcAction; } interface WalletRpcAction { /** Chain ID in CAIP-2 format (e.g., "eip155:8453") */ chainId: string; /** RPC method name (e.g., "eth_signTypedData_v4", "eth_sendTransaction") */ method: string; /** JSON-encoded params array */ params: string; } ``` **Amount Types** ```typescript interface PayAmount { /** Currency unit, prefixed with either "iso4217/" or "caip19/" */ unit: string; /** Amount value, in the currency unit's minor units */ value: string; /** Display information for the amount */ display: AmountDisplay; } interface AmountDisplay { /** Ticker/symbol of the asset */ assetSymbol: string; /** Full name of the asset */ assetName: string; /** Number of minor decimals of the asset */ decimals: number; /** URL of the icon of the asset (if token) */ iconUrl?: string; /** Name of the network of the asset (if token) */ networkName?: string; } ``` **Payment Info Types** ```typescript interface PaymentInfo { /** Payment status */ status: PaymentStatus; /** Amount to be paid */ amount: PayAmount; /** Payment expiration timestamp, in seconds since epoch */ expiresAt: number; /** Merchant information */ merchant: MerchantInfo; /** Buyer information (present if payment has been submitted) */ buyer?: BuyerInfo; } interface MerchantInfo { /** Merchant name */ name: string; /** Merchant icon URL */ iconUrl?: string; } interface BuyerInfo { /** Account CAIP-10 */ accountCaip10: string; /** Account provider name */ accountProviderName: string; /** Account provider icon URL */ accountProviderIcon?: string; } ``` **Collect Data Types** ```typescript interface CollectDataAction { /** URL for data collection (displayed in iframe) */ url: string; /** JSON schema describing required fields */ schema?: string; } ``` ## Error Handling [#error-handling] The SDK throws typed errors for different failure scenarios: ```typescript import { PayError, PaymentOptionsError, PaymentActionsError, ConfirmPaymentError, } from "@walletconnect/pay"; try { const options = await client.getPaymentOptions({ paymentLink: link, accounts, }); } catch (error) { if (error instanceof PaymentOptionsError) { console.error("Failed to get options:", error.originalMessage); } else if (error instanceof PayError) { console.error("Pay error:", error.code, error.message); } } ``` **Error Types** | Error Class | Description | |-------------|-------------| | `PayError` | Base error class for all Pay SDK errors | | `PaymentOptionsError` | Error when fetching payment options | | `PaymentActionsError` | Error when fetching required payment actions | | `ConfirmPaymentError` | Error when confirming payment | **Error Codes** The `PayError` class includes a `code` property with one of the following values: ```typescript type PayErrorCode = | "JSON_PARSE" | "JSON_SERIALIZE" | "PAYMENT_OPTIONS" | "PAYMENT_REQUEST" | "CONFIRM_PAYMENT" | "INITIALIZATION_ERROR" | "UNKNOWN"; ``` ## Best Practices [#best-practices] 1. **Check Provider Availability**: Always check if a provider is available before using the SDK 2. **Account Format**: Always use CAIP-10 format for accounts: `eip155:{chainId}:{address}` 3. **Multiple Chains**: Provide accounts for all supported chains to maximize payment options 4. **Result Order**: Keep `data` in the same order as the actions array 5. **Error Handling**: Always handle errors gracefully and show appropriate user feedback 6. **Loading States**: Show loading indicators during API calls and signing operations 7. **Expiration**: Check `paymentInfo.expiresAt` and warn users if time is running low 8. **User Data**: Only collect data when `collectData` is present on the selected payment option and you don't already have the required user data. If you already have the required data, you can submit this without collecting from the user. You must make sure the user accepts WalletConnect Terms and Conditions and Privacy Policy before submitting user information to WalletConnect. 9. **Data Collection**: When `selectedOption.collectData?.url` is present, display the URL in an iframe or modal rather than building custom forms. The hosted form handles rendering, validation, and T&C acceptance. 10. **Per-Option Data Collection**: When displaying payment options, check each option's `collectData` field. Show a visual indicator (e.g., "Info required" badge) on options that require data collection. Only open the iframe when the user selects an option with `collectData` present — use the option's `collectData.url` which is already scoped to that option's account. # Tap to Pay - Wallet Integration Guide (/payments/wallets/tap-to-pay) Tap to Pay is an experimental feature. If you're interested in implementing and testing it in your wallet, reach out to our team before getting started. This guide covers how to integrate Tap to Pay into a third-party wallet app on Android and iOS. ## Android [#android] ### How It Works [#how-it-works] When a user taps their phone on a POS terminal, the terminal emits an NDEF tag with a single URI record pointing to `https://pay.walletconnect.com`. Android dispatches this in one of three ways: - **One wallet installed with a verified App Link** — Android opens the wallet's `NfcPaymentActivity` directly. - **Multiple wallets installed** — Android shows the "Open with..." chooser; user selects a wallet. - **No wallet installed** — Android opens the URL in the browser, which shows a wallet chooser page with App Store / Play Store links. When the wallet app is already in the foreground, foreground dispatch takes priority over manifest filters and delivers the intent directly. #### Flow: Tap from Home Screen (Phone Unlocked, No App in Foreground) [#flow-tap-from-home-screen-phone-unlocked-no-app-in-foreground] ```mermaid sequenceDiagram participant POS as POS Terminal participant NFC as Android NFC Stack participant OS as Android OS participant W as Wallet App participant B as Browser POS->>NFC: NDEF tag emulated (single URI record) NFC->>OS: NDEF_DISCOVERED intent
(matches URI: https://pay.walletconnect.com) alt 1 wallet with verified App Link OS->>W: App Link opens NfcPaymentActivity W->>W: Extract payment URL from intent data W->>W: Start payment flow else Multiple wallets installed OS->>OS: Show Activity Chooser
("Open with...") OS->>W: User selects wallet W->>W: Extract payment URL from intent data W->>W: Start payment flow else No wallet installed OS->>B: Open https://pay.walletconnect.com/?pid=pay_xxx B->>B: Wallet chooser web page
(App Store / Play Store links) end ``` #### Flow: Tap from Wallet App (Foreground) [#flow-tap-from-wallet-app-foreground] ```mermaid sequenceDiagram participant POS as POS Terminal participant NFC as Android NFC participant W as Wallet App (Foreground) Note over W: App is open, NFC foreground dispatch active POS->>NFC: NDEF tag emulated (URI record) NFC->>W: NDEF_DISCOVERED dispatched
to foreground Activity W->>W: Parse URI record W->>W: Extract payment URL W->>W: Start payment flow immediately ``` ### Integration Steps [#integration-steps] #### Register with WalletConnect for App Links [#register-with-walletconnect-for-app-links] Android App Links require `pay.walletconnect.com` to list your app in its `/.well-known/assetlinks.json` file. Without this, `autoVerify` intent filters won't pass verification. Provide the following to WalletConnect: - Package name - SHA-256 certificate fingerprint(s) #### Manifest Setup [#manifest-setup] Add NFC permissions: ```xml title="AndroidManifest.xml" ``` Register a translucent activity with three intent filters — each covers a different Android dispatch path for the same NFC tap: ```xml title="AndroidManifest.xml" ``` Create `res/xml/nfc_tech_filter.xml`: ```xml title="nfc_tech_filter.xml" android.nfc.tech.IsoDep android.nfc.tech.Ndef android.nfc.tech.Ndef android.nfc.tech.NfcA android.nfc.tech.NfcB ``` #### Implement the NFC Interceptor Activity [#implement-the-nfc-interceptor-activity] The activity handles multiple intent paths to extract the payment URL: ```kotlin title="NfcPaymentActivity.kt" class NfcPaymentActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val paymentUrl = extractPaymentUrl(intent) if (paymentUrl != null) openPaymentFlow(paymentUrl) finish() } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) val paymentUrl = extractPaymentUrl(intent) ?: return openPaymentFlow(paymentUrl) finish() } private fun openPaymentFlow(paymentUrl: String) { startActivity( Intent(this, YourMainWalletActivity::class.java).apply { action = ACTION_NFC_PAYMENT putExtra(EXTRA_PAYMENT_URL, paymentUrl) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP) } ) } private fun extractPaymentUrl(intent: Intent?): String? { if (intent == null) return null return when (intent.action) { // App Links — URL is in intent.data Intent.ACTION_VIEW -> intent.data?.let { unwrapPaymentUrl(it.toString()) } // NDEF tag — URL is in NDEF extras NfcAdapter.ACTION_NDEF_DISCOVERED -> extractFromNdefExtras(intent) // TECH fallback — read NDEF from Tag object NfcAdapter.ACTION_TECH_DISCOVERED -> extractFromTag(intent) ?: extractFromNdefExtras(intent) else -> null } } } ``` #### Add Foreground Dispatch (wallet already open) [#add-foreground-dispatch-wallet-already-open] When the wallet activity is in the foreground, manifest intent filters may not fire. Use foreground dispatch to claim NFC priority: ```kotlin title="NfcPaymentReader.kt" class NfcPaymentReader( private val activity: Activity, private val onPaymentUrl: (String) -> Unit, ) { private val nfcAdapter = NfcAdapter.getDefaultAdapter(activity) private val pendingIntent by lazy { PendingIntent.getActivity( activity, 0, Intent(activity, activity.javaClass) .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_MUTABLE ) } fun enable() { nfcAdapter?.enableForegroundDispatch( activity, pendingIntent, arrayOf(IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED)), arrayOf( arrayOf(Ndef::class.java.name), arrayOf(IsoDep::class.java.name) ) ) } fun disable() { nfcAdapter?.disableForegroundDispatch(activity) } /** Call from Activity.onNewIntent(). Returns true if handled. */ fun handleIntent(intent: Intent): Boolean { // Same NDEF/Tag extraction logic as NfcPaymentActivity. // If a pay.walletconnect.com URL is found, call onPaymentUrl(url) and return true. // Otherwise return false. } } ``` Wire it into your main activity: ```kotlin title="MainActivity.kt" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) nfcReader = NfcPaymentReader(this) { url -> processPayment(url) } } override fun onResume() { super.onResume(); nfcReader.enable() } override fun onPause() { super.onPause(); nfcReader.disable() } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) if (nfcReader.handleIntent(intent)) return // ...other intent handling } ``` #### Process Payment via WalletKit Pay [#process-payment-via-walletkit-pay] ```kotlin title="PaymentFlow.kt" // 1. Fetch payment options val accounts = listOf("eip155:1:0xABC...", "eip155:137:0xABC...") val options = WalletKit.Pay.getPaymentOptions(paymentUrl, accounts).getOrThrow() // 2. Display options to user; user selects one // 3. Get required signing actions val actions = WalletKit.Pay.getRequiredPaymentActions(paymentId, optionId).getOrThrow() // 4. Sign each action val data = actions .filterIsInstance() .map { rpc -> yourSigner.sign(rpc.action.method, rpc.action.params) } // 5. Confirm payment WalletKit.Pay.confirmPayment( Wallet.Params.ConfirmPayment( paymentId = paymentId, optionId = optionId, data = data, collectedData = collectedData ) ) ``` ## iOS [#ios] ### How It Works [#how-it-works-1] When a user taps their phone on a POS terminal, iOS reads the NDEF tag automatically (Background Tag Reading, iOS 13+) and resolves the URL as a Universal Link. Depending on what's installed: - **One wallet registered in AASA** — iOS shows a notification banner "Open in [Wallet]"; user taps to open. - **Multiple wallets in AASA** — AASA is evaluated top-to-bottom; first installed match wins (no disambiguation UI). On iOS 26, a system wallet chooser modal is shown instead. - **No wallet installed** — iOS opens the URL in Safari, which shows a wallet chooser page with App Store links. When the wallet app is in the foreground, the app can trigger a manual NFC scan via `NFCNDEFReaderSession`, which takes priority over Background Tag Reading. #### Flow: Tap from Home Screen (Phone Unlocked, No App in Foreground) [#flow-tap-from-home-screen-phone-unlocked-no-app-in-foreground-1] ```mermaid sequenceDiagram participant POS as POS Terminal participant NFC as iOS Background Tag Reading participant OS as iOS participant W as Wallet App participant S as Safari POS->>NFC: NDEF tag detected (screen on) NFC->>OS: Parse NDEF records
Find URI record with Universal Link alt 1 wallet registered in AASA OS->>OS: Show notification banner:
"Open in [Wallet]" OS->>W: User taps notification W->>W: SceneDelegate receives Universal Link W->>W: Start payment flow (autoPayMode) else Multiple wallets in AASA OS->>OS: AASA evaluated top-to-bottom OS->>W: First installed match wins
(no disambiguation UI) W->>W: SceneDelegate receives Universal Link W->>W: Start payment flow (autoPayMode) else Multiple wallets in AASA (iOS 26) OS->>OS: Show system wallet chooser modal OS->>W: User picks a wallet W->>W: SceneDelegate receives Universal Link W->>W: Start payment flow (autoPayMode) else No wallet installed OS->>S: Open payment URL in Safari S->>S: Wallet chooser web page
(App Store links) end ``` #### Flow: Tap from Wallet App (Foreground) [#flow-tap-from-wallet-app-foreground-1] ```mermaid sequenceDiagram participant POS as POS Terminal participant W as Wallet App (Foreground) participant NFC as NFCNDEFReaderSession participant Pay as Payment Flow W->>W: Press NFC scanner button W->>NFC: onAppear() -> NFCPaymentReader.scan() NFC->>NFC: Show "Ready to Pay" NFC sheet Note over NFC: Active reader session takes
priority over Background Tag Reading POS->>NFC: NDEF tag detected NFC->>NFC: invalidateAfterFirstRead: true NFC->>W: didDetectNDEFs callback W->>W: Extract URI from NDEF record NFC->>NFC: Auto-close NFC sheet W->>Pay: Present PayModule (full screen) Pay->>Pay: Payment confirmation + signing Note over Pay: Payment completes Pay->>W: Dismiss PayModule W->>W: Return to Balances screen W->>NFC: onAppear() restarts NFC session NFC->>NFC: Show "Ready to Pay" again ``` ### Integration Steps [#integration-steps-1] #### Register with WalletConnect for Universal Links [#register-with-walletconnect-for-universal-links] Universal Links require `pay.walletconnect.com` to host an Apple App Site Association (AASA) file listing your app. WalletConnect will add your app to `pay.walletconnect.com/.well-known/apple-app-site-association`. Provide: - Apple Team ID - Bundle ID #### Entitlements [#entitlements] Add two entitlements in your `.entitlements` file. **Associated Domains** (for Universal Links / Background Tag Reading): ```xml title="Entitlements.plist" com.apple.developer.associated-domains applinks:pay.walletconnect.com ``` **NFC Tag Reading** (for manual CoreNFC scans): ```xml title="Entitlements.plist" com.apple.developer.nfc.readersession.formats TAG ``` Also enable these capabilities in **Xcode → Target → Signing & Capabilities**: - Associated Domains - Near Field Communication Tag Reading #### Info.plist [#infoplist] Add the NFC usage description (required by Apple for CoreNFC): ```xml title="Info.plist" NFCReaderUsageDescription This app reads NFC tags to receive payment links from POS terminals. ``` #### Implement the NFC Reader (manual scan path) [#implement-the-nfc-reader-manual-scan-path] This handles the case where the user taps an NFC button inside the app to initiate a read: ```swift title="NFCPaymentReader.swift" import CoreNFC final class NFCPaymentReader: NSObject { static let shared = NFCPaymentReader() static var isAvailable: Bool { NFCNDEFReaderSession.readingAvailable } private var session: NFCNDEFReaderSession? private var completion: ((Result) -> Void)? func scan(completion: @escaping (Result) -> Void) { guard NFCNDEFReaderSession.readingAvailable else { completion(.failure(NFCPaymentError.notAvailable)) return } self.completion = completion session = NFCNDEFReaderSession( delegate: self, queue: .main, invalidateAfterFirstRead: true // auto-dismiss after first tag ) session?.alertMessage = "Ready to Pay" session?.begin() } } extension NFCPaymentReader: NFCNDEFReaderSessionDelegate { func readerSessionDidBecomeActive(_ session: NFCNDEFReaderSession) {} func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) { for message in messages { for record in message.records { if let url = record.wellKnownTypeURIPayload() { session.alertMessage = "Payment link received!" session.invalidate() completion?(.success(url.absoluteString)) completion = nil return } } } session.invalidate(errorMessage: "No payment link found on this NFC tag.") completion?(.failure(NFCPaymentError.noPaymentLink)) completion = nil } func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) { if let nfcError = error as? NFCReaderError, nfcError.code == .readerSessionInvalidationErrorFirstNDEFTagRead || nfcError.code == .readerSessionInvalidationErrorUserCanceled { if nfcError.code == .readerSessionInvalidationErrorUserCanceled { completion?(.failure(NFCPaymentError.cancelled)) completion = nil } return } completion?(.failure(error)) completion = nil } } enum NFCPaymentError: LocalizedError { case notAvailable case noPaymentLink case cancelled var errorDescription: String? { switch self { case .notAvailable: return "NFC is not available on this device." case .noPaymentLink: return "No payment link found on the NFC tag." case .cancelled: return "NFC scan cancelled." } } } ``` Key points: - `invalidateAfterFirstRead: true` — iOS dismisses the NFC sheet after one tag is read. - `wellKnownTypeURIPayload()` — extracts the URI from a standard NDEF URI record (what the POS emits). - `.readerSessionInvalidationErrorFirstNDEFTagRead` — normal completion, not an error. #### Handle Background Tag Reading (Universal Links) [#handle-background-tag-reading-universal-links] This is the zero-interaction path. The user holds their phone near the POS terminal — even from the lock screen or home screen — and iOS reads the NDEF tag automatically, resolves the URL as a Universal Link, and opens your app. The URL arrives via `NSUserActivity` in your `SceneDelegate`: ```swift title="SceneDelegate.swift" func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { guard let url = userActivity.webpageURL else { return } let urlString = url.absoluteString if WalletKit.isPaymentLink(urlString) { showPaymentFlow(paymentLink: urlString) return } // ...handle other Universal Links } ``` For **cold start** (app was not running), Universal Links arrive in `connectionOptions.userActivities`: ```swift title="SceneDelegate.swift" func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // ...window setup... // Check for payment Universal Link on cold start if let url = connectionOptions.userActivities .first(where: { $0.activityType == NSUserActivityTypeBrowsingWeb })? .webpageURL, WalletKit.isPaymentLink(url.absoluteString) { // Delay slightly to let the UI finish loading DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { self.showPaymentFlow(paymentLink: url.absoluteString) } } } ``` #### Wire the NFC Button in Your UI [#wire-the-nfc-button-in-your-ui] Show an NFC scan button only on devices that support it: ```swift title="NFCScanView.swift" // SwiftUI if NFCPaymentReader.isAvailable { Button(action: { startNfcScan() }) { Image(systemName: "wave.3.right") } } func startNfcScan() { NFCPaymentReader.shared.scan { result in switch result { case .success(let urlString): if WalletKit.isPaymentLink(urlString) { showPaymentFlow(paymentLink: urlString) } case .failure(let error): if case NFCPaymentError.cancelled = error { return } showError(error) } } } ``` #### Process Payment via WalletKit Pay [#process-payment-via-walletkit-pay-1] ```swift title="PaymentFlow.swift" // 1. Fetch payment options let accounts = ["eip155:1:0xABC...", "eip155:137:0xABC..."] let options = try await WalletKit.instance.Pay.getPaymentOptions( paymentLink: paymentUrl, accounts: accounts ) // 2. Show options UI — user selects one // 3. Get required signing actions let actions = try await WalletKit.instance.Pay.getRequiredPaymentActions( paymentId: options.paymentId, optionId: selectedOption.id ) // 4. Sign each action (typically eth_signTypedData_v4) let data = try actions.map { action in try yourSigner.sign(method: action.method, params: action.params) } // 5. Confirm payment let result = try await WalletKit.instance.Pay.confirmPayment( paymentId: options.paymentId, optionId: selectedOption.id, data: data ) ``` ## Testing [#testing] You can test your implementation using our Demo POS App. An Android device is required — reach out to our team to request access. # Token & Chain Support (/payments/wallets/token-chain-support) This section covers implementation details for supporting specific tokens and blockchains in your WalletConnect Pay wallet integration. ## Available Guides [#available-guides] } href="/payments/wallets/token-chain-support/usdt-support"> Learn how to implement the two-action Permit2 flow required for USDT and other ERC-20 tokens without native typed-data authorization. } href="/payments/wallets/token-chain-support/solana-support"> Implement Solana payment capabilities including native SOL transactions and mixed-chain payment options. } href="/payments/wallets/token-chain-support/tron-support"> Accept USDT on Tron: advertise the Tron account, verify and sign the gateway-built transaction, and return the signed result as an object. } href="/payments/wallets/token-chain-support/stellar-support"> Accept USDC on Stellar: advertise the Stellar account, sign the gateway-built envelope with `stellar_signXDR`, and let WalletConnect Pay sponsor the network fee. # Solana Support (/payments/wallets/token-chain-support/solana-support) WalletConnect Pay supports Solana payments, enabling users to pay with native SOL and SPL tokens. This guide covers how to extend your wallet's WalletConnect Pay integration to support Solana payments end-to-end. This guide applies whether you integrate with the **Wallet Pay SDK** or directly with the **Gateway API** ([API-first](/payments/wallets/api-first)). The signing requirements are identical — Solana actions arrive as `walletRpc` actions, and the signed transaction is returned in the results array. The code samples below use SDK method names; if you are integrating API-first, the equivalents are: | SDK | Gateway API | |-----|-------------| | `getPaymentOptions({ accounts })` | `POST /v1/gateway/payment/{id}/options` with `accounts[]` | | `option.actions` / `getRequiredPaymentActions` | the option's `actions[]`, resolved via `POST /v1/gateway/payment/{id}/fetch` when an action is type `build` | | `confirmPayment(data)` | `POST /v1/gateway/payment/{id}/confirm` with `results[]` | Everything else in this guide — advertising Solana accounts, routing by namespace, the `solana_signTransaction` payload, and returning the signed transaction blob — is the same in both integrations. ## Solana payment flow [#solana-payment-flow] A Solana payment follows the same three-call flow as any other WalletConnect Pay payment. The only Solana-specific parts are the signing method (`solana_signTransaction`) and that your wallet **signs but never broadcasts** — the WalletConnect Pay backend submits the signed transaction to the network. ```mermaid sequenceDiagram participant User participant Wallet participant Gateway as WalletConnect Pay (Gateway API / SDK) participant Chain as Solana RPC / Chain User->>Wallet: Scan QR / Open payment link Wallet->>Gateway: Get payment options (incl. solana:… accounts) Gateway-->>Wallet: options[] (some with solana_signTransaction actions) Wallet->>User: Display payment options User->>Wallet: Select Solana option alt Option includes a build action Wallet->>Gateway: Fetch action (optionId, data) Gateway-->>Wallet: walletRpc actions (solana_signTransaction) end Wallet->>User: Request signature User-->>Wallet: Approve Wallet->>Wallet: Sign transaction (solana_signTransaction) Note over Wallet: Return signed tx blob (base64)
Do NOT broadcast Wallet->>Gateway: Confirm payment (results: [signed tx blob]) Gateway->>Chain: Broadcast signed transaction Chain-->>Gateway: Confirmation Gateway-->>Wallet: status + isFinal Wallet->>User: Show result / status ``` The `data[]` (or `results[]` API-first) you submit on confirm must match the option's `actions[]` in **order and length** — including any EVM actions that precede a Solana action in a mixed-chain option. The former `signatures` parameter is deprecated but still accepted. ## Key capabilities [#key-capabilities] Implementing Solana support enables three primary features: 1. **Native SOL transactions** — Users can initiate Solana payments through Pay links when merchants support the network 2. **Mixed-chain options** — Single payment links can present both EVM and Solana choices simultaneously 3. **Namespace-based routing** — Individual actions route to appropriate signers based on CAIP-2 namespace identifiers ## Implementation requirements [#implementation-requirements] Follow these requirements to correctly implement Solana payment support in your wallet. ### Advertise Solana accounts [#advertise-solana-accounts] Include Solana accounts when calling `getPaymentOptions` using the CAIP-10 format: ``` solana:: ``` For example, a Solana mainnet account would be formatted as: ``` solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp:7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU ``` ```typescript const evmAccounts = evmChains.map( (chain) => `eip155:${chain.id}:${evmAddress}` ); const solanaAccounts = solanaChains.map( (chain) => `solana:${chain.reference}:${solanaPublicKey.toBase58()}` ); const options = await pay.getPaymentOptions({ paymentId, accounts: [...evmAccounts, ...solanaAccounts], }); ``` ```kotlin val evmAccounts = evmChains.map { chain -> "eip155:${chain.id}:${evmAddress}" } val solanaAccounts = solanaChains.map { chain -> "solana:${chain.reference}:${solanaPublicKey}" } val options = pay.getPaymentOptions( paymentId = paymentId, accounts = evmAccounts + solanaAccounts ) ``` ```swift let evmAccounts = evmChains.map { chain in "eip155:\(chain.id):\(evmAddress)" } let solanaAccounts = solanaChains.map { chain in "solana:\(chain.reference):\(solanaPublicKey)" } let options = try await pay.getPaymentOptions( paymentId: paymentId, accounts: evmAccounts + solanaAccounts ) ``` Only advertise Solana accounts if your wallet has Solana keys available. Wallets without Solana support should not include Solana accounts in the request. ### Route actions by namespace [#route-actions-by-namespace] Determine the signing wallet for each action using the namespace from the chain ID. Extract the namespace from `actions[i].walletRpc.chainId` rather than assuming a single wallet type for all actions. ```typescript function getNamespace(chainId: string): string { return chainId.split(':')[0]; } for (const action of actions) { const namespace = getNamespace(action.walletRpc.chainId); switch (namespace) { case 'eip155': // Route to EVM wallet await handleEvmAction(action); break; case 'solana': // Route to Solana wallet await handleSolanaAction(action); break; default: throw new Error(`Unsupported namespace: ${namespace}`); } } ``` ```kotlin fun getNamespace(chainId: String): String = chainId.split(':')[0] for (action in actions) { val namespace = getNamespace(action.walletRpc.chainId) when (namespace) { "eip155" -> handleEvmAction(action) "solana" -> handleSolanaAction(action) else -> error("Unsupported namespace: $namespace") } } ``` ```swift func getNamespace(_ chainId: String) -> String { chainId.split(separator: ":").first.map(String.init) ?? "" } for action in actions { let namespace = getNamespace(action.walletRpc.chainId) switch namespace { case "eip155": try await handleEvmAction(action) case "solana": try await handleSolanaAction(action) default: throw PaymentError.unsupportedNamespace(namespace) } } ``` ### Implement Solana signing [#implement-solana-signing] For Solana actions, implement the `solana_signTransaction` method. Sign the transaction and append the **signed transaction blob, base64-encoded** to the `data` array. ```typescript async function handleSolanaAction(action: Action): Promise { const { method, params } = action.walletRpc; if (method !== 'solana_signTransaction') { throw new Error(`Unsupported Solana method: ${method}`); } // Params are array-wrapped: [{ transaction }] const [{ transaction }] = JSON.parse(params); // Decode the base64 transaction const txBuffer = Buffer.from(transaction, 'base64'); const tx = Transaction.from(txBuffer); // Sign the transaction tx.sign(solanaKeypair); // Return the signed transaction as base64 return tx.serialize().toString('base64'); } ``` ```kotlin suspend fun handleSolanaAction(action: Action): String { val method = action.walletRpc.method require(method == "solana_signTransaction") { "Unsupported Solana method: $method" } // Params are array-wrapped: [{ transaction }] val params = JSONArray(action.walletRpc.params) val txData = params.getJSONObject(0).getString("transaction") // Decode and sign the transaction val txBytes = Base64.decode(txData, Base64.DEFAULT) val signedTx = solanaWallet.signTransaction(txBytes) // Return the signed transaction as base64 return Base64.encodeToString(signedTx, Base64.NO_WRAP) } ``` ```swift func handleSolanaAction(_ action: Action) async throws -> String { let method = action.walletRpc.method guard method == "solana_signTransaction" else { throw PaymentError.unsupportedMethod(method) } // Params are array-wrapped: [{ transaction }] let params = try JSONDecoder().decode( [[String: String]].self, from: action.walletRpc.params.data(using: .utf8)! ) let txData = params[0]["transaction"]! // Decode and sign the transaction let txBytes = Data(base64Encoded: txData)! let signedTx = try solanaWallet.signTransaction(txBytes) // Return the signed transaction as base64 return signedTx.base64EncodedString() } ``` **Return the signed transaction, not the signature.** Solana signer libraries may return both a detached bs58 signature and the signed transaction blob. WalletConnect Pay expects the complete base64-encoded signed transaction, not the detached signature. ### Do not send transactions [#do-not-send-transactions] Do not implement `solana_signAndSendTransaction` for Pay flows. The WalletConnect Pay backend handles broadcasting the signed transaction. Your wallet should only sign and return the signed transaction blob. ### Handle array-wrapped params [#handle-array-wrapped-params] The Pay backend provides params in an array-wrapped structure: `[{ transaction }]`. Make sure to unwrap this structure when parsing the transaction data. ```typescript // Correct: unwrap the array const [{ transaction }] = JSON.parse(params); // Incorrect: accessing params directly const { transaction } = JSON.parse(params); // This will fail ``` ### Validate signers at runtime [#validate-signers-at-runtime] Guard action handlers against missing signers at execution time. If your wallet doesn't have a Solana signer available when a Solana action is encountered, raise an error rather than silently skipping the action. ```typescript if (namespace === 'solana' && !solanaWallet) { throw new Error('Solana wallet not available'); } ``` ### Reject unknown methods [#reject-unknown-methods] Reject unknown wallet-RPC methods instead of silently omitting them from result arrays. The `data` array must match the actions array in order and length. ```typescript default: throw new Error(`Unknown method: ${method}`); // Never silently skip or return undefined ``` ## Complete action handler [#complete-action-handler] Here's a complete example showing how to handle both EVM and Solana actions in a single payment flow: ```typescript async function approvePayment(actions: Action[]): Promise { const data: string[] = []; for (const action of actions) { const { chainId, method, params } = action.walletRpc; const namespace = chainId.split(':')[0]; let signature: string; switch (namespace) { case 'eip155': signature = await handleEvmAction(method, chainId, params); break; case 'solana': signature = await handleSolanaAction(method, params); break; default: throw new Error(`Unsupported namespace: ${namespace}`); } data.push(signature); } return data; } async function handleEvmAction( method: string, chainId: string, params: string ): Promise { const parsed = JSON.parse(params); switch (method) { case 'eth_sendTransaction': { const tx = await evmWallet.sendTransaction(chainId, parsed[0]); await tx.wait(); return tx.hash; } case 'eth_signTypedData_v4': return await evmWallet.signTypedData(chainId, parsed); default: throw new Error(`Unsupported EVM method: ${method}`); } } async function handleSolanaAction( method: string, params: string ): Promise { if (method !== 'solana_signTransaction') { throw new Error(`Unsupported Solana method: ${method}`); } const [{ transaction }] = JSON.parse(params); const txBuffer = Buffer.from(transaction, 'base64'); const tx = Transaction.from(txBuffer); tx.sign(solanaKeypair); return tx.serialize().toString('base64'); } ``` ## Validate your integration [#validate-your-integration] Before shipping your Solana support implementation, verify these scenarios work correctly: ### SOL-only payment [#sol-only-payment] Test a payment link that only offers Solana options. Verify that: - The Solana option is presented to the user - The transaction is signed correctly - The base64-encoded signed transaction is submitted - The payment completes successfully ### Mixed EVM and Solana payment [#mixed-evm-and-solana-payment] Test a payment link that offers both EVM and Solana options. Verify that: - Both option types are presented - Users can select either network - The correct signer is used for the selected option - Payment completes regardless of which option is chosen ### EVM flow regression [#evm-flow-regression] After adding Solana support, verify that existing EVM flows still work: - USDC payments with EIP-3009 - USDT payments with Permit2 - Native token payments ### Missing Solana wallet [#missing-solana-wallet] Test behavior when Solana keys are not available: - Solana options should not be advertised to users - No errors should occur during option fetching - EVM options should work normally ## Sample implementation [#sample-implementation] The React Native reference wallet demonstrates Solana support implementation: } href="https://github.com/reown-com/react-native-examples/tree/main/wallets/rn_cli_wallet"> `wallets/rn_cli_wallet` — see `PaymentStore.approvePayment` for namespace dispatch logic and `usePairing.handlePaymentLink` for account concatenation. # Stellar Support (/payments/wallets/token-chain-support/stellar-support) WalletConnect Pay supports Stellar payments with USDC. Stellar is a **sign-only, fee-sponsored** chain: WalletConnect Pay builds the payment transaction, your wallet signs it with [`stellar_signXDR`](/wallets/chains/stellar#stellar-signxdr), and WalletConnect Pay wraps the signed transaction in a [fee-bump transaction](https://developers.stellar.org/docs/learn/encyclopedia/transactions-specialized/fee-bump-transactions) and broadcasts it. The buyer never pays the XLM network fee, and your wallet never submits the transaction. This guide applies whether you integrate with the **Wallet Pay SDK** or directly with the **Gateway API** ([API-first](/payments/wallets/api-first)). The signing requirements are identical — Stellar actions arrive as `walletRpc` actions, and the signed envelope is returned in the results array. The code samples below use SDK method names; if you are integrating API-first, the equivalents are: | SDK | Gateway API | |-----|-------------| | `getPaymentOptions({ accounts })` | `POST /v1/gateway/payment/{id}/options` with `accounts[]` | | `option.actions` / `getRequiredPaymentActions` | the option's `actions[]`, resolved via `POST /v1/gateway/payment/{id}/fetch` when an action is type `build` | | `confirmPayment(data)` | `POST /v1/gateway/payment/{id}/confirm` with `results[]` | Everything else in this guide — advertising Stellar accounts, routing by namespace, the `stellar_signXDR` payload, and returning the signed envelope — is the same in both integrations. ## Stellar payment flow [#stellar-payment-flow] A Stellar payment follows the same three-call flow as any other WalletConnect Pay payment. The Stellar-specific parts are the signing method (`stellar_signXDR`), the checks your wallet performs before signing, and the fee bump WalletConnect Pay adds on confirm. ```mermaid sequenceDiagram participant User participant Wallet participant Gateway as WalletConnect Pay (Gateway API / SDK) participant Chain as Stellar User->>Wallet: Scan QR / Open payment link Wallet->>Gateway: Get payment options (incl. stellar:pubnet:G… account) Note over Gateway: Stellar option offered only if the account
exists and holds enough USDC (trustline) Gateway-->>Wallet: options[] (Stellar option with a build action) Wallet->>User: Display payment options User->>Wallet: Select USDC on Stellar Wallet->>Gateway: Fetch action (optionId, data) Gateway-->>Wallet: stellar_signXDR { xdr, chain, account } Wallet->>Wallet: Decode envelope with the pubnet passphrase
Verify source == account, show payment details Wallet->>User: Request signature User-->>Wallet: Approve Wallet->>Wallet: Sign the inner transaction (Ed25519) Note over Wallet: Return the signed envelope (base64 XDR)
Do NOT rebuild or submit Wallet->>Gateway: Confirm payment (data: [signedXDR]) Gateway->>Gateway: Validate, wrap in fee bump (WalletConnect Pay pays the fee) Gateway->>Chain: Broadcast fee-bump transaction Chain-->>Gateway: Inclusion Gateway-->>Wallet: status: succeeded / failed Wallet->>User: Show result ``` The `data[]` you submit on confirm must match the option's `actions[]` in **order and length**. A Stellar option has a single action, so `data` contains exactly one signed envelope. ## Key differences from other chains [#key-differences-from-other-chains] 1. **Fee-sponsored** — WalletConnect Pay wraps the buyer-signed transaction in a fee bump and pays the XLM fee. The buyer only needs USDC; there is no fee or gas balance check. 2. **Sign only, never submit** — use `stellar_signXDR`, not `stellar_signAndSubmitXDR`. Submitting the inner transaction yourself would make the buyer pay the fee and consume the sequence number WalletConnect Pay is waiting for, which fails the payment. 3. **The envelope is opaque** — WalletConnect Pay pins the transaction to the buyer's next sequence number, a single USDC payment operation, no memo, and a time bound that ends when the quote expires. Confirm validates all of these, so re-building, adding operations, changing the fee, or adjusting the time bounds gets the payment rejected. 4. **Plain string result** — the confirm result is the signed `TransactionEnvelope` as a base64 string, just like a Solana signed transaction. No object result is involved. 5. **Mainnet only** — WalletConnect Pay settles Stellar on pubnet (`stellar:pubnet`). ## Supported assets [#supported-assets] | Token | CAIP-19 | |-------|---------| | USDC | `stellar:pubnet/asset:USDC-GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN` | USDC is a Stellar issued asset, so the buyer's account must have a trustline to the Circle issuer above. An account without the trustline reads as a zero balance, and the gateway does not offer the Stellar option. ## Implementation requirements [#implementation-requirements] ### Advertise Stellar accounts [#advertise-stellar-accounts] Include the wallet's Stellar **pubnet** account when calling `getPaymentOptions`, using the CAIP-10 format with the `G…` StrKey account ID: ``` stellar:pubnet: ``` For example: ``` stellar:pubnet:GCZ73GTH6LBGTT2K6UB76JR3JQIKMMIPCTI3ZGKN5SJVLJ65GPYSCIBQ ``` ```typescript title="accounts.ts" const evmAccounts = evmChains.map( (chain) => `eip155:${chain.id}:${evmAddress}` ); const stellarAccounts = stellarAddress ? [`stellar:pubnet:${stellarAddress}`] : []; const options = await pay.getPaymentOptions({ paymentLink, accounts: [...evmAccounts, ...stellarAccounts], }); ``` Only advertise the `G…` account ID. Muxed (`M…`) accounts and raw public keys are not valid Stellar accounts for WalletConnect Pay. The gateway checks that the account exists on-chain and holds enough USDC, and omits the Stellar option otherwise — this is expected, not an integration error. ### Route actions by namespace [#route-actions-by-namespace] Extract the namespace from `actions[i].walletRpc.chainId` and route `stellar` actions to the Stellar signer: ```typescript title="routeActions.ts" const data: string[] = []; for (const action of actions) { const namespace = action.walletRpc.chainId.split(':')[0]; switch (namespace) { case 'eip155': data.push(await handleEvmAction(action)); break; case 'solana': data.push(await handleSolanaAction(action)); break; case 'stellar': data.push(handleStellarAction(action)); // signed envelope, see below break; default: throw new Error(`Unsupported namespace: ${namespace}`); } } ``` ### The `stellar_signXDR` action [#the-stellar_signxdr-action] After the user selects the Stellar option, the build action resolves to a `walletRpc` action. Its `params` is a JSON string containing a single-element array: ```json { "chainId": "stellar:pubnet", "method": "stellar_signXDR", "params": "[{\"xdr\":\"AAAAAgAAAACz/ZNn8sJpz0r1A/8mO0wQVjEPFNG8mU3sk1Wk7TPxIQAAAGQAGYGzAAAACgAAAAEAAAAA...\",\"chain\":\"stellar:pubnet\",\"account\":\"stellar:pubnet:GCZ73GTH6LBGTT2K6UB76JR3JQIKMMIPCTI3ZGKN5SJVLJ65GPYSCIBQ\"}]" } ``` | Field | Description | |-------|-------------| | `xdr` | The unsigned `TransactionEnvelope` (V1), base64-encoded XDR. Contains one USDC payment operation from the buyer to the payment's receiving account. | | `chain` | The CAIP-2 chain, always `stellar:pubnet`. | | `account` | The buyer's CAIP-10 account. It is the transaction's source account and the account that must sign. | The payload follows the [Stellar RPC reference](/wallets/chains/stellar#stellar-signxdr). If your wallet already implements `stellar_signXDR` for WalletConnect sessions, reuse that signer. ### Verify and sign the envelope [#verify-and-sign-the-envelope] Before signing, your wallet must: 1. **Bind the network passphrase from `chainId`** — derive it from the action's CAIP-2 chain (`stellar:pubnet` → `Public Global Stellar Network ; September 2015`). Never trust a network reference from the request body. 2. **Check the source account** — the transaction's source must equal the `account` parameter, and your wallet must custody that account. 3. **Show the payment** — decode the operation and display the USDC amount and destination in the signing UI. 4. **Sign without modifying** — add the buyer's signature and return the full envelope. Do not change the fee, sequence number, time bounds, memo, or operations. ```typescript title="stellarSigner.ts" import { Keypair, Networks, TransactionBuilder } from '@stellar/stellar-sdk'; const NETWORK_PASSPHRASES: Record = { 'stellar:pubnet': Networks.PUBLIC, }; function handleStellarAction(action: Action): string { const { chainId, method, params } = action.walletRpc; if (method !== 'stellar_signXDR') { throw new Error(`Unsupported Stellar method: ${method}`); } // Bound from the action's chain, never from the request body const networkPassphrase = NETWORK_PASSPHRASES[chainId]; if (!networkPassphrase) { throw new Error(`Unsupported Stellar chain: ${chainId}`); } const [{ xdr, account }] = JSON.parse(params); const signerAddress = account.split(':')[2]; const transaction = TransactionBuilder.fromXDR(xdr, networkPassphrase); if ('innerTransaction' in transaction || transaction.source !== signerAddress) { throw new Error('Stellar transaction source does not match the buyer account'); } const keypair: Keypair = getStellarKeypair(signerAddress); // your key management transaction.sign(keypair); // Plain base64 string — WalletConnect Pay adds the fee bump and broadcasts return transaction.toXDR(); } ``` ### Return the signed envelope on confirm [#return-the-signed-envelope-on-confirm] Pass the signed envelope in `data`, in the same position as its action. It is a plain base64 string, so it fits the same `data` array as EVM signatures and Solana transactions: ```typescript title="approvePayment.ts" const result = await pay.confirmPayment({ paymentId, optionId, data, // e.g. ["AAAAAgAAAACz/ZNn8sJpz0r1A/8mO0wQVjEPFNG8mU3sk1Wk7TPxIQAAAGQ...AAAAAEFNB7s="] }); ``` The gateway also accepts `{ "signedXDR": "" }` — the `stellar_signXDR` response shape — as the result. Returning the bare string is the simplest option and works with every SDK version. On confirm, WalletConnect Pay validates the envelope against the quote, wraps it in a fee bump paid by WalletConnect Pay, and broadcasts it. `confirmPayment` resolves with `succeeded` or `failed`, exactly as on other chains. ## Error handling [#error-handling] | Situation | Cause | What to do | |-----------|-------|------------| | Stellar option not offered | Account does not exist, has no USDC trustline, or the USDC balance is too low | Expected — show the remaining options | | Payment fails after confirm | The buyer's account submitted another transaction between fetch and confirm, so the envelope's sequence number is no longer valid | Sign and confirm right after fetch, and do not submit other transactions from the account while a payment is pending | | Confirm rejected with an expired quote | The user took longer than the quote validity to approve | Fetch payment options again | | Confirm rejected with a validation error | The envelope was modified (fee, time bounds, operations, memo) or is not valid base64 XDR | Sign the envelope exactly as received | ## Validate your integration [#validate-your-integration] ### Funded Stellar account [#funded-stellar-account] Import a pubnet account with a USDC trustline and a USDC balance. Open a payment link whose merchant accepts USDC on Stellar and verify that: - The Stellar option is presented - The wallet decodes the envelope with the pubnet passphrase and checks the source account before signing - The confirm request carries the signed envelope as a base64 string in `data` - `confirmPayment` resolves with `succeeded` and the fee-bump transaction appears in a Stellar explorer, with the fee paid by an account other than the buyer ### Account without a trustline [#account-without-a-trustline] Advertise a Stellar account that has no USDC trustline and verify that the Stellar option is omitted while other options are still shown. ### Regression on other chains [#regression-on-other-chains] Confirm that EVM and Solana payments still work — their results stay in the same `data` array. ## Sample implementation [#sample-implementation] } href="https://github.com/reown-com/web-examples/tree/main/advanced/wallets/react-wallet-v2"> `advanced/wallets/react-wallet-v2` — see `StellarLib.signXDR` for signing, the `stellar_signXDR` branch in `PaymentStore.approvePayment`, and `pages/walletconnect.tsx` for advertising the Stellar pubnet account. ## Additional resources [#additional-resources] - [Stellar RPC reference](/wallets/chains/stellar) — method signatures, account format, and signing semantics for WalletConnect sessions. - [Fee-bump transactions](https://developers.stellar.org/docs/learn/encyclopedia/transactions-specialized/fee-bump-transactions) — how the sponsored fee works. - [Stellar XDR reference](https://developers.stellar.org/docs/encyclopedia/xdr). # Tron Support (/payments/wallets/token-chain-support/tron-support) WalletConnect Pay supports Tron payments with USDT (TRC-20). Tron is a **sign-only relay** chain: WalletConnect Pay builds the transaction, commits to its `txID`, and broadcasts the signed bytes itself. Your wallet only verifies what it was given and signs it — it never rebuilds, re-serializes, or submits the transaction. This guide applies whether you integrate with the **Wallet Pay SDK** or directly with the **Gateway API** ([API-first](/payments/wallets/api-first)). The signing requirements are identical — Tron actions arrive as `walletRpc` actions, and the signed result is returned in the results array. The code samples below use SDK method names; if you are integrating API-first, the equivalents are: | SDK | Gateway API | |-----|-------------| | `getPaymentOptions({ accounts })` | `POST /v1/gateway/payment/{id}/options` with `accounts[]` | | `option.actions` / `getRequiredPaymentActions` | the option's `actions[]`, resolved via `POST /v1/gateway/payment/{id}/fetch` when an action is type `build` | | `confirmPayment(data)` | `POST /v1/gateway/payment/{id}/confirm` with `results[]` | Everything else in this guide — advertising Tron accounts, routing by namespace, the `tron_signTransaction` payload, and returning the `{ raw_data_hex, signature }` object — is the same in both integrations. ## Requirements [#requirements] Object results in `data` require these minimum SDK versions: | Platform | Package | Minimum version | |----------|---------|-----------------| | Kotlin | `com.reown:walletkit` / `com.walletconnect:pay` | 1.9.0 / 1.3.0 | | Swift | reown-swift (`WalletConnectPay` / `ReownWalletKit`) | 2.4.0 | | Flutter | `reown_walletkit` / `walletconnect_pay` | 1.5.1 / 1.1.0 | | React Native | `@reown/walletkit` / `@walletconnect/pay` / `@walletconnect/react-native-compat` | 1.6.0 / 1.1.0 / 2.25.0 | | Web | `@reown/walletkit` / `@walletconnect/pay` | 1.6.0 / 1.1.0 | Earlier versions type the confirm results as strings only and cannot carry the Tron result object. ## Tron payment flow [#tron-payment-flow] A Tron payment follows the same three-call flow as any other WalletConnect Pay payment. The Tron-specific parts are the signing method (`tron_signTransaction`), the verification your wallet performs before signing, the **object** it returns, and the asynchronous settlement. ```mermaid sequenceDiagram participant User participant Wallet participant Gateway as WalletConnect Pay (Gateway API / SDK) participant Chain as Tron User->>Wallet: Scan QR / Open payment link Wallet->>Gateway: Get payment options (incl. tron:… account) Note over Gateway: Tron option offered only if the account
holds USDT and enough TRX for energy Gateway-->>Wallet: options[] (some with tron_signTransaction actions) Wallet->>User: Display payment options User->>Wallet: Select USDT on Tron Wallet->>Gateway: Fetch action (optionId, data) Gateway-->>Wallet: tron_signTransaction { txID, raw_data_hex, raw_data } Wallet->>Wallet: Verify txID == sha256(raw_data_hex)
Verify owner == quoted buyer Wallet->>User: Request signature User-->>Wallet: Approve Wallet->>Wallet: Sign the digest (r ‖ s ‖ v) Note over Wallet: Return { raw_data_hex, signature: ["<130 hex>"] }
Do NOT rebuild or broadcast Wallet->>Gateway: Confirm payment (data: [{ raw_data_hex, signature }]) Gateway->>Chain: Broadcast signed transaction Note over Wallet,Gateway: SDK polls the payment status
until it is final (keep your loader) Chain-->>Gateway: Inclusion Gateway-->>Wallet: status: succeeded / failed Wallet->>User: Show result ``` The `data[]` you submit on confirm must match the option's `actions[]` in **order and length**. The Tron result is a single JSON object — do not wrap it in an extra array and do not stringify it into a plain signature string. ## Key differences from other chains [#key-differences-from-other-chains] 1. **Sign-only relay** — `raw_data_hex` is opaque. Refreshing the expiration, re-deriving the TAPOS reference block, adjusting `fee_limit`, or re-encoding `raw_data` all change the hash and get the payment rejected with `tx_id_mismatch`. 2. **Object result** — the confirm result is `{ raw_data_hex, signature }`, not a bare signature string. This is why `confirmPayment` takes `data` rather than `signatures`. 3. **The buyer pays energy** — there is no fee payer and no fee bump on Tron. WalletConnect Pay offers a Tron option only to accounts holding USDT **and** enough TRX for energy (currently 14 TRX). An unfunded account is not offered Tron at all. 4. **Mainnet only** — WalletConnect Pay settles Tron on mainnet (`tron:0x2b6653dc`). 5. **Settlement takes a few seconds** — the gateway broadcasts the transaction and waits for inclusion. `confirmPayment` keeps polling and resolves with `succeeded` or `failed`, exactly as on other chains; nothing extra to handle. ## Implementation requirements [#implementation-requirements] ### Advertise Tron accounts [#advertise-tron-accounts] Include the wallet's Tron **mainnet** account when calling `getPaymentOptions`, using the CAIP-10 format: ``` tron:0x2b6653dc: ``` For example: ``` tron:0x2b6653dc:TNCwFenyM9VExurrWMPrjq1Jd6qUTmSuL3 ``` ```typescript title="accounts.ts" const evmAccounts = evmChains.map( (chain) => `eip155:${chain.id}:${evmAddress}` ); const tronAccounts = tronAddress ? [`tron:0x2b6653dc:${tronAddress}`] : []; const options = await pay.getPaymentOptions({ paymentLink, accounts: [...evmAccounts, ...tronAccounts], }); ``` ```kotlin title="Accounts.kt" val evmAccounts = evmChains.map { chain -> "eip155:${chain.id}:$evmAddress" } val tronAccounts = tronAddress?.let { listOf("tron:0x2b6653dc:$it") } ?: emptyList() val options = WalletKit.Pay.getPaymentOptions( Wallet.Params.PaymentOptions( paymentLink = paymentLink, accounts = evmAccounts + tronAccounts ) ) ``` ```swift title="Accounts.swift" let evmAccounts = evmChains.map { chain in "eip155:\(chain.id):\(evmAddress)" } let tronAccounts = tronAddress.map { ["tron:0x2b6653dc:\($0)"] } ?? [] let options = try await WalletKit.instance.Pay.getPaymentOptions( paymentLink: paymentLink, accounts: evmAccounts + tronAccounts ) ``` ```dart title="accounts.dart" final evmAccounts = evmChains.map((chain) => 'eip155:${chain.id}:$evmAddress'); final tronAccounts = tronAddress != null ? ['tron:0x2b6653dc:$tronAddress'] : []; final options = await walletKit.getPaymentOptions( request: GetPaymentOptionsRequest( paymentLink: paymentLink, accounts: [...evmAccounts, ...tronAccounts], ), ); ``` Only advertise a Tron account if your wallet holds Tron keys. The gateway checks the account's USDT and TRX balances and omits the Tron option when either is insufficient — this is expected, not an integration error. ### Route actions by namespace [#route-actions-by-namespace] Extract the namespace from `actions[i].walletRpc.chainId` and route `tron` actions to the Tron signer: ```typescript title="routeActions.ts" for (const action of actions) { const namespace = action.walletRpc.chainId.split(':')[0]; switch (namespace) { case 'eip155': data.push(await handleEvmAction(action)); break; case 'solana': data.push(await handleSolanaAction(action)); break; case 'tron': data.push(handleTronAction(action)); // returns an object, see below break; default: throw new Error(`Unsupported namespace: ${namespace}`); } } ``` ```kotlin title="RouteActions.kt" for (action in actions.filterIsInstance()) { val namespace = action.action.chainId.split(':')[0] data += when (namespace) { "eip155" -> handleEvmAction(action) "solana" -> handleSolanaAction(action) "tron" -> handleTronAction(action) // JSON-encoded object, see below else -> error("Unsupported namespace: $namespace") } } ``` ```swift title="RouteActions.swift" for action in actions { let namespace = action.walletRpc.chainId.split(separator: ":").first.map(String.init) ?? "" switch namespace { case "eip155": data.append(try await handleEvmAction(action)) case "solana": data.append(try await handleSolanaAction(action)) case "tron": data.append(try handleTronAction(action)) // JSON-encoded object, see below default: throw PaymentError.unsupportedNamespace(namespace) } } ``` ```dart title="route_actions.dart" for (final action in actions) { final namespace = action.walletRpc.chainId.split(':').first; switch (namespace) { case 'eip155': data.add(await handleEvmAction(action)); break; case 'solana': data.add(await handleSolanaAction(action)); break; case 'tron': data.add(handleTronAction(action)); // returns a Map, see below break; default: throw UnimplementedError('Unsupported namespace: $namespace'); } } ``` ### Parse the `tron_signTransaction` action [#parse-the-tron_signtransaction-action] The action's `params` is a JSON string. It may be array-wrapped, and the transaction may be nested once more under `transaction` — accept both shapes, exactly as the WalletConnect Sign `tron_signTransaction` request handler does: ```json title="params.json" [ { "transaction": { "txID": "d2a9…", "raw_data_hex": "0a02…", "raw_data": { "contract": [{ "parameter": { "value": { "owner_address": "41…" } } }] }, "visible": false } } ] ``` ```typescript title="parseTronAction.ts" const parsed = JSON.parse(action.walletRpc.params); const request = Array.isArray(parsed) ? parsed[0] : parsed; // `transaction` is either the transaction itself or `{ transaction }` const transaction = request?.transaction?.transaction ?? request?.transaction; if (!transaction?.raw_data_hex || !transaction?.txID) { throw new Error('Missing transaction in Tron payment action params'); } ``` ### Verify before signing [#verify-before-signing] Verify the payload before asking the user to approve, so a bad payload surfaces as a readable wallet-side error instead of an opaque gateway rejection at confirm: 1. **`txID` must equal `sha256(raw_data_hex)`** — anything else means the bytes were altered and the gateway would reject the payment with `tx_id_mismatch`. 2. **The transaction owner must be the quoted buyer** — `raw_data.contract[0].parameter.value.owner_address` must match the account the option was quoted against, or the gateway rejects with `owner_mismatch`. ### Sign the digest verbatim [#sign-the-digest-verbatim] Sign `sha256(raw_data_hex)` with the account's secp256k1 key and return the 65-byte recoverable signature (`r ‖ s ‖ v`) as 130 hex characters. Do **not** pass the transaction through a helper that re-serializes `raw_data` from JSON (such as TronWeb's `trx.sign`) — it can change the bytes and therefore the hash. ```typescript title="handleTronAction.ts" import { TronWeb, utils } from 'tronweb'; interface TronUnsignedTransaction { txID: string; raw_data_hex: string; raw_data?: Record; } // A type alias (not an interface) so it is assignable to the Pay SDK's // `data` element type without a cast. type TronSignedTransaction = { raw_data_hex: string; signature: string[] }; function signTronPayment( tx: TronUnsignedTransaction, privateKeyHex: string, walletAddress: string ): TronSignedTransaction { // 1. txID must be sha256(raw_data_hex) const digest = utils.crypto.SHA256(utils.code.hexStr2byteArray(tx.raw_data_hex)); const computedTxID = utils.bytes.byteArray2hexStr(digest).toLowerCase(); if (computedTxID !== tx.txID.replace(/^0x/, '').toLowerCase()) { throw new Error(`Tron txID mismatch: expected ${computedTxID}, got ${tx.txID}`); } // 2. The transaction must spend from the quoted buyer const owner = tx.raw_data?.contract?.[0]?.parameter?.value?.owner_address; if (owner && TronWeb.address.toHex(owner) !== TronWeb.address.toHex(walletAddress)) { throw new Error('Tron transaction owner does not match the wallet account'); } // 3. Sign the digest — 65-byte recoverable signature as 130 hex chars const signature = utils.crypto.ECKeySign( digest, utils.code.hexStr2byteArray(privateKeyHex.replace(/^0x/, '')) ); return { raw_data_hex: tx.raw_data_hex, signature: [signature] }; } ``` ```kotlin title="HandleTronAction.kt" // 1. txID must be sha256(raw_data_hex) val digest = MessageDigest.getInstance("SHA-256").digest(rawDataHex.hexToByteArray()) require(digest.toHexString() == txId.removePrefix("0x").lowercase()) { "Tron txID mismatch" } // 2. The transaction must spend from the quoted buyer val owner = rawData?.optJSONArray("contract")?.optJSONObject(0) ?.optJSONObject("parameter")?.optJSONObject("value")?.optString("owner_address") require(owner == null || tronWallet.ownsAddress(owner)) { "Tron transaction owner mismatch" } // 3. Sign the digest — a 65-byte recoverable secp256k1 signature (r ‖ s ‖ v) as 130 hex chars. // Use your wallet's Tron signer (Yttrium utils ship a Tron transaction signer as well). val signatureHex = tronWallet.signDigest(digest) // The Pay SDK takes `data` elements as strings; a JSON-encoded object is // sent to the gateway as an object. val tronResult = JSONObject().apply { put("raw_data_hex", rawDataHex) put("signature", JSONArray().put(signatureHex)) }.toString() ``` ```swift title="HandleTronAction.swift" // 1. txID must be sha256(raw_data_hex) let digest = SHA256.hash(data: Data(hex: rawDataHex)) guard digest.hexString == txId.removingPrefix("0x").lowercased() else { throw PaymentError.tronTxIdMismatch } // 2. The transaction must spend from the quoted buyer if let owner = rawData?.contract?.first?.parameter?.value?.ownerAddress, !tronWallet.owns(address: owner) { throw PaymentError.tronOwnerMismatch } // 3. Sign the digest — a 65-byte recoverable secp256k1 signature (r ‖ s ‖ v) as 130 hex chars. let signatureHex = try tronWallet.signDigest(digest) // The Pay SDK takes `data` elements as strings; a JSON-encoded object is // sent to the gateway as an object. let tronResult = try JSONSerialization.data( withJSONObject: ["raw_data_hex": rawDataHex, "signature": [signatureHex]] ) data.append(String(decoding: tronResult, as: UTF8.self)) ``` ```dart title="handle_tron_action.dart" import 'package:blockchain_utils/blockchain_utils.dart'; import 'package:on_chain/on_chain.dart'; Map signTronPayment( Map tx, String privateKeyHex, String walletAddress, ) { final rawDataHex = tx['raw_data_hex'] as String; final rawDataBytes = BytesUtils.fromHexString(rawDataHex); // 1. txID must be sha256(raw_data_hex) final computedTxId = BytesUtils.toHexString(QuickCrypto.sha256Hash(rawDataBytes)); final txId = (tx['txID'] as String).replaceFirst(RegExp(r'^0x'), '').toLowerCase(); if (computedTxId != txId) { throw StateError('Tron txID mismatch: expected $computedTxId, got $txId'); } // 2. The transaction must spend from the quoted buyer final contract = (tx['raw_data']?['contract'] as List?)?.firstOrNull as Map?; final owner = contract?['parameter']?['value']?['owner_address'] as String?; if (owner != null && TronAddress(owner) != TronAddress(walletAddress)) { throw StateError('Tron transaction owner does not match the wallet account'); } // 3. Sign the digest — TronPrivateKey.sign hashes the raw bytes with sha256 and // returns the 65-byte recoverable signature (r ‖ s ‖ v). Do not rebuild the // transaction with Transaction.fromJson(...).rawData.toBuffer() — that // re-serializes raw_data and can change the hash. final signature = TronPrivateKey(privateKeyHex).sign(rawDataBytes); // `data` elements are Objects on Flutter — return the Map itself. return { 'raw_data_hex': rawDataHex, 'signature': [BytesUtils.toHexString(signature)], // 130 hex chars }; } ``` **Return the object, not a bare signature.** The gateway needs both `raw_data_hex` and `signature` to broadcast. On React Native, Web and Flutter pass the object directly; on Kotlin and Swift pass it JSON-encoded as a string — the SDK detects JSON objects in `data` and forwards them as objects. ### Do not broadcast [#do-not-broadcast] Do not implement `tron_sendTransaction` for Pay flows and do not call `sendRawTransaction`. WalletConnect Pay broadcasts the signed transaction; a wallet that also broadcasts causes a duplicate submission. ## Complete action handler [#complete-action-handler] ```typescript title="approvePayment.ts" import type { ConfirmPaymentParams } from '@walletconnect/pay'; async function approvePayment(actions: Action[]): Promise> { // Plain strings for EVM/Solana results, a JSON object for Tron — in action order const data: NonNullable = []; for (const action of actions) { const { chainId, method, params } = action.walletRpc; const namespace = chainId.split(':')[0]; switch (namespace) { case 'eip155': data.push(await handleEvmAction(method, chainId, params)); break; case 'solana': data.push(await handleSolanaAction(method, params)); break; case 'tron': { if (method !== 'tron_signTransaction') { throw new Error(`Unsupported Tron method: ${method}`); } const parsed = JSON.parse(params); const request = Array.isArray(parsed) ? parsed[0] : parsed; const transaction = request?.transaction?.transaction ?? request?.transaction; data.push(signTronPayment(transaction, tronPrivateKey, tronAddress)); break; } default: throw new Error(`Unsupported namespace: ${namespace}`); } } return data; } const result = await pay.confirmPayment({ paymentId, optionId, data }); ``` ```kotlin title="ApprovePayment.kt" // Plain strings for EVM/Solana results, a JSON-encoded object for Tron — in action order val data = mutableListOf() for (action in actions.filterIsInstance()) { val rpc = action.action val namespace = rpc.chainId.split(':')[0] data += when (namespace) { "eip155" -> handleEvmAction(rpc.method, rpc.chainId, rpc.params) "solana" -> handleSolanaAction(rpc.method, rpc.params) "tron" -> { require(rpc.method == "tron_signTransaction") { "Unsupported Tron method: ${rpc.method}" } val parsed = JSONTokener(rpc.params).nextValue() val request = if (parsed is JSONArray) parsed.getJSONObject(0) else parsed as JSONObject val transaction = request.getJSONObject("transaction") .let { it.optJSONObject("transaction") ?: it } // Verify txID and owner, sign the digest, JSON-encode { raw_data_hex, signature } (see above) signTronPayment(transaction, tronWallet) } else -> error("Unsupported namespace: $namespace") } } val result = WalletKit.Pay.confirmPayment( Wallet.Params.ConfirmPayment(paymentId = paymentId, optionId = optionId, data = data) ) ``` ```swift title="ApprovePayment.swift" // Plain strings for EVM/Solana results, a JSON-encoded object for Tron — in action order var data: [String] = [] for action in actions { let rpc = action.walletRpc let namespace = rpc.chainId.split(separator: ":").first.map(String.init) ?? "" switch namespace { case "eip155": data.append(try await handleEvmAction(rpc)) case "solana": data.append(try await handleSolanaAction(rpc)) case "tron": guard rpc.method == "tron_signTransaction" else { throw PaymentError.unsupportedMethod(rpc.method) } let parsed = try JSONSerialization.jsonObject(with: Data(rpc.params.utf8)) let request = ((parsed as? [Any])?.first ?? parsed) as? [String: Any] let wrapper = request?["transaction"] as? [String: Any] guard let transaction = (wrapper?["transaction"] as? [String: Any]) ?? wrapper else { throw PaymentError.malformedTronAction } // Verify txID and owner, sign the digest, JSON-encode { raw_data_hex, signature } (see above) data.append(try signTronPayment(transaction, wallet: tronWallet)) default: throw PaymentError.unsupportedNamespace(namespace) } } let result = try await WalletKit.instance.Pay.confirmPayment( paymentId: paymentId, optionId: optionId, data: data ) ``` ```dart title="approve_payment.dart" // Plain Strings for EVM/Solana results, a Map for Tron — in action order final data = []; for (final action in actions) { final rpc = action.walletRpc; final namespace = rpc.chainId.split(':').first; switch (namespace) { case 'eip155': data.add(await handleEvmAction(rpc.method, rpc.chainId, rpc.params)); break; case 'solana': data.add(await handleSolanaAction(rpc.method, rpc.params)); break; case 'tron': if (rpc.method != 'tron_signTransaction') { throw UnimplementedError('Unsupported Tron method: ${rpc.method}'); } final parsed = jsonDecode(rpc.params); final request = (parsed is List ? parsed.first : parsed) as Map; final wrapper = request['transaction'] as Map; final transaction = (wrapper['transaction'] as Map?) ?? wrapper; data.add(signTronPayment(transaction, tronPrivateKeyHex, tronAddress)); break; default: throw UnimplementedError('Unsupported namespace: $namespace'); } } final result = await walletKit.confirmPayment( request: ConfirmPaymentRequest(paymentId: paymentId, optionId: optionId, data: data), ); ``` ## Validate your integration [#validate-your-integration] ### Funded Tron account [#funded-tron-account] Import a mainnet account holding USDT and at least 14 TRX. Open a payment link whose merchant accepts USDT on Tron and verify that: - The Tron option is presented - The wallet verifies `txID` and the owner, then signs - The confirm request carries `{ raw_data_hex, signature }` as an object in `data` - `confirmPayment` resolves with `succeeded` and the transaction appears in a Tron explorer ### Tampered payload [#tampered-payload] Alter one byte of `raw_data_hex` in a test harness and verify the wallet fails with a `txID` mismatch **before** signing, rather than at confirm. ### Regression on other chains [#regression-on-other-chains] Confirm that EVM and Solana payments still work — their results stay plain strings in the same `data` array. ## Sample implementations [#sample-implementations] } href="https://github.com/reown-com/react-native-examples/tree/main/wallets/rn_cli_wallet"> `wallets/rn_cli_wallet` — see `TronLib.signPaymentTransaction` for the verification and signing, `PaymentStore.approvePayment` for the `tron` route, and `usePairing` for advertising the Tron mainnet account. } href="https://github.com/reown-com/web-examples/tree/main/advanced/wallets/react-wallet-v2"> `advanced/wallets/react-wallet-v2` — see `TronLib.signPaymentTransaction` and the `tron_signTransaction` branch in `PaymentStore`. # USDT Support (/payments/wallets/token-chain-support/usdt-support) The simple WalletConnect Pay flow signs an EIP-3009 `transferWithAuthorization` typed-data payload — the gasless transfer used by USDC and similar stablecoins. USDT does not implement EIP-3009, so WalletConnect Pay routes it through the [Permit2](https://github.com/Uniswap/permit2) contract instead. The first time a user pays a given token on a given chain, the wallet must approve Permit2 on-chain. Subsequent payments on the same token only require the typed-data signature. ## The two-action flow [#the-two-action-flow] When an option needs a Permit2 approval, `getRequiredPaymentActions` returns **two** actions — in the order they must execute: 1. `eth_sendTransaction` — ERC-20 `approve(Permit2, amount)` on the token contract 2. `eth_signTypedData_v4` — Permit2 typed-data payload authorizing the transfer ```mermaid sequenceDiagram participant User participant Wallet participant PaySDK as Pay SDK participant Chain User->>Wallet: Tap Pay Wallet->>PaySDK: getRequiredPaymentActions PaySDK-->>Wallet: [approveTx, permit2TypedData] Wallet->>Chain: eth_sendTransaction (approve -> Permit2) Chain-->>Wallet: txHash Wallet->>Chain: wait for receipt Chain-->>Wallet: receipt Wallet->>User: Sign Permit2 typed data User-->>Wallet: signature Wallet->>PaySDK: confirmPayment(data: [txHash, signature]) PaySDK-->>Wallet: status ``` `data[]` passed to `confirmPayment` must match `actions[]` in **order and length** — the approve tx hash first, then the Permit2 signature. Both results are plain strings; `data` also accepts JSON objects for chains such as [Tron](/payments/wallets/token-chain-support/tron-support). The former `signatures` parameter is deprecated but still accepted. ## Detecting an approval-required option [#detecting-an-approval-required-option] Inspect the action list for an `eth_sendTransaction` entry. In standalone SDK flows, this means `option.actions`; in WalletKit flows, this means the actions returned by `getRequiredPaymentActions`. If one is present, the option is a Permit2 flow and your wallet should prepare for an on-chain step. ```kotlin // WalletKit: inspect the actions returned by getRequiredPaymentActions fun requiresApproval(requiredActions: List?): Boolean = requiredActions ?.filterIsInstance() ?.any { it.action.method == "eth_sendTransaction" } ?: false ``` ```swift func requiresApproval(_ actions: [Action]?) -> Bool { actions?.contains { $0.walletRpc.method == "eth_sendTransaction" } ?? false } ``` ```typescript function requiresApproval(actions: readonly Action[] | null): boolean { return !!actions?.some(a => a.walletRpc?.method === "eth_sendTransaction"); } ``` ```dart bool requiresApproval(List? actions) => actions?.any((a) => a.walletRpc.method == 'eth_sendTransaction') ?? false; ``` ## Showing the approval gas estimate [#showing-the-approval-gas-estimate] The approve tx costs native gas (e.g. POL on Polygon, ETH on mainnet) — separate from the token amount the user is paying. Estimate it and show the user the expected fee before they confirm so they aren't surprised by a wallet prompt for a one-time on-chain cost. This can live wherever your wallet collects user intent — a review screen, a confirmation sheet, or inline on the option row. ```kotlin suspend fun estimateApprovalFee( chainId: String, txParams: JSONObject, ): BigInteger? = runCatching { val gasLimit = rpcEstimateGas(chainId, txParams) val maxFeePerGas = fetchFeeData(chainId).maxFeePerGas gasLimit.multiply(maxFeePerGas) }.getOrNull() ``` ```swift func estimateApprovalFee( chainId: String, txParams: [String: Any] ) async -> BigUInt? { do { let gasLimit = try await rpc.estimateGas(chainId: chainId, tx: txParams) let maxFeePerGas = try await rpc.maxFeePerGas(chainId: chainId) return gasLimit * maxFeePerGas } catch { return nil } } ``` ```typescript async function estimateApprovalFee( provider: providers.JsonRpcProvider, tx: providers.TransactionRequest, ): Promise { try { const [gasLimit, feeData] = await Promise.all([ provider.estimateGas(tx), provider.getFeeData(), ]); return feeData.maxFeePerGas ? gasLimit.mul(feeData.maxFeePerGas) : null; } catch { return null; } } ``` ```dart Future estimateApprovalFee(Map txParams) async { try { final gasLimit = await ethClient.estimateGas(/* tx params */); final fees = await ethClient.getFeeData(); return gasLimit * fees.maxFeePerGas.getInWei; } catch (_) { return null; } } ``` If estimation fails (RPC error, missing fields, etc.), don't block the flow. Fall back to a generic message such as "Network fee set by wallet" — the wallet's signing prompt will still surface the actual cost when the user confirms. ## Executing the actions in order [#executing-the-actions-in-order] Because the Permit2 typed data signs against the token allowance the approve tx grants, the **approve must be mined before you sign**. 1. Submit `eth_sendTransaction` (action 1) and wait for the receipt. 2. Parse the typed data from `eth_signTypedData_v4` (action 2) and sign it. 3. Push both results into `data[]` in the order the actions were returned. 4. Call `confirmPayment(data)`. ```kotlin val data = mutableListOf() for (action in actions.filterIsInstance()) { data += when (action.action.method) { "eth_sendTransaction" -> { val txHash = wallet.sendTransaction(action.action.chainId, action.action.params) wallet.awaitReceipt(action.action.chainId, txHash) txHash } "eth_signTypedData_v4" -> wallet.signTypedData(action.action.chainId, action.action.params) else -> error("Unsupported method: ${action.action.method}") } } ``` ```swift var data: [String] = [] for action in actions { let rpc = action.walletRpc let result: String switch rpc.method { case "eth_sendTransaction": let txHash = try await wallet.sendTransaction(chainId: rpc.chainId, params: rpc.params) try await wallet.awaitReceipt(chainId: rpc.chainId, txHash: txHash) result = txHash case "eth_signTypedData_v4": result = try await wallet.signTypedData(chainId: rpc.chainId, params: rpc.params) default: throw PaymentError.unsupportedMethod(rpc.method) } data.append(result) } ``` ```typescript const data: string[] = []; for (const action of actions) { const { chainId, method, params } = action.walletRpc; const parsed = JSON.parse(params); switch (method) { case "eth_sendTransaction": { const tx = await wallet.sendTransaction(chainId, parsed[0]); await tx.wait(); data.push(tx.hash); break; } case "eth_signTypedData_v4": data.push(await wallet.signTypedData(chainId, parsed)); break; default: throw new Error(`Unsupported method: ${method}`); } } ``` ```dart final data = []; for (final action in actions) { final rpc = action.walletRpc; switch (rpc.method) { case 'eth_sendTransaction': // sendPayTransaction broadcasts and waits for the receipt final params = (jsonDecode(rpc.params) as List).first as Map; data.add(await service.sendPayTransaction( Map.from(params), )); break; case 'eth_signTypedData_v4': data.add(service.ethSignTypedDataV4(rpc.params)); break; default: throw UnimplementedError('Unsupported method: ${rpc.method}'); } } ``` **EIP-712 library quirks.** EIP-712 signing libraries disagree on whether `types.EIP712Domain` must be present in the payload. The Permit2 typed data returned by WalletConnect Pay omits it. - Libraries that **require** `EIP712Domain` (e.g. `eth_sig_util_plus` on Flutter, some Android libraries): synthesize an `EIP712Domain` entry in `types` from the fields actually present in `domain` before signing. - Libraries that **reject** `EIP712Domain` (e.g. ethers v5 `_signTypedData`): strip it from `types` before signing. - Yttrium's `signTypedData` is currently hardcoded to ERC-3009 (`from`/`to`/`value`/`validAfter`/`validBefore`/`nonce`) and rejects Permit2. Wallets using Yttrium need a generic EIP-712 hasher — see [`EIP712TypedData.swift`](https://github.com/reown-com/reown-swift/blob/develop/Example/Shared/Signer/EIP712TypedData.swift) for a reference implementation. If your signing library throws on a Permit2 typed-data payload, normalize the payload before retrying. ## Loader UX [#loader-ux] The two-action flow has two distinct user-visible steps that can each take several seconds: 1. The approve tx is broadcast and you wait for the receipt. 2. The user is prompted to sign the Permit2 typed data. Show different loader copy for each step so the user understands what is happening — especially during the on-chain wait, which is much slower than a typed-data signature on its own. Pick whatever wording fits your wallet's voice. ## Recommended UX [#recommended-ux] Follow these patterns to provide the best user experience when implementing USDT and Permit2-based payments: ### Pre-load fee estimates [#pre-load-fee-estimates] Preload per-option fee estimates before user selection. This allows users to make informed decisions by comparing realistic gas costs across different payment options. ### Display one-time setup messaging [#display-one-time-setup-messaging] When approval actions are present (first-time Permit2 setup), clearly communicate to users that this is a one-time on-chain approval. Subsequent payments with the same token will only require a signature. ### Separate gas cost display [#separate-gas-cost-display] Explain native-token gas costs separately from the token amounts being paid. Users should understand that: - The token amount goes to the merchant - The gas fee (in the chain's native token) goes to network validators ### Remember user preferences [#remember-user-preferences] Retain and auto-select the last-paid token when it's available in future payments. This reduces friction for repeat users who prefer specific payment methods. ### Guard against stale data [#guard-against-stale-data] Implement safeguards against stale data from rapid option switching and expired payment sessions. Always validate that payment data is current before executing actions. ## Validate your integration [#validate-your-integration] Before shipping your USDT support implementation, verify these scenarios work correctly: ### First-time ERC-20 with Permit2 [#first-time-erc-20-with-permit2] Test a payment with a token requiring Permit2 approval for the first time. The flow should: - Present the approval transaction first - Wait for on-chain confirmation - Then prompt for the Permit2 signature - Complete successfully with both results in `data[]` ### Repeat ERC-20 payment [#repeat-erc-20-payment] After completing the first-time flow, make another payment with the same token. This should: - Skip the approval transaction entirely - Only require a single Permit2 signature - Complete faster than the first-time flow ### Native token payment [#native-token-payment] Test a payment using the chain's native token (e.g., ETH on Base). Verify that: - The transaction hash is correctly included in `data[]` - The payment completes successfully ### Rapid option switching [#rapid-option-switching] Quickly switch between payment options and verify: - No stale data leaks between options - Fee estimates update correctly for each option - The correct actions execute for the final selected option ### Expired payment handling [#expired-payment-handling] Test behavior when a payment session expires: - Before any results are submitted - The wallet should handle expiration gracefully - Users should receive clear feedback about the expiration ## Sample wallets [#sample-wallets] The four reference wallets below all implement this two-action flow and are good starting points to copy from. } href="https://github.com/reown-com/react-native-examples/tree/main/wallets/rn_cli_wallet"> `wallets/rn_cli_wallet` — see `PaymentUtil.ts`, `PaymentTransactionUtil.ts`, `PaymentStore.ts`. } href="https://github.com/reown-com/reown-kotlin/tree/develop/sample/wallet"> `sample/wallet` — see `PaymentUtil.kt`, `PaymentTransactionUtil.kt`, `PaymentViewModel.kt`. } href="https://github.com/reown-com/reown-swift/tree/develop/Example/WalletApp"> `Example/WalletApp` — see `PaymentUtil.swift`, `PayTransactionService.swift`, `PayPresenter.swift`, `EIP712TypedData.swift`. } href="https://github.com/reown-com/reown_flutter/tree/develop/packages/reown_walletkit/example"> `packages/reown_walletkit/example` — see `evm_service.dart`, `wcp_payment_details.dart`, `wcp_confirming_payment.dart`. # AI Integration Prompt - Flutter (/payments/wallets/walletkit/ai-prompts/flutter) This guide enables Flutter wallet developers to integrate WalletConnect Pay for processing crypto payment links through `reown_walletkit`. The integration allows wallet applications to accept and process payment requests from merchants using the WalletConnect Pay protocol. ## Important Approach [#important-approach] **Study and adapt, don't blindly copy.** Before implementing, examine how your existing wallet app handles: - Deep links and QR code scanning - Modal/bottom sheet presentation - State management patterns - Signing implementations for different methods Maintain consistent architecture and naming conventions with your existing codebase. --- ## Prerequisites [#prerequisites] Before starting, ensure your wallet app has: 1. **WalletKit SDK integrated** (`reown_walletkit: ^1.5.1` package or newer, which bundles `walletconnect_pay` 1.1.0) 2. **EVM signing capability** supporting: - `eth_signTypedData_v4` (EIP-712 typed data signing) - `personal_sign` (message signing) 3. **Async/await patterns** for handling asynchronous operations 4. **UI modal/bottom sheet system** for presenting payment flows 5. **Understanding of CAIP-10 account format**: `{namespace}:{chainId}:{address}` (e.g., `eip155:1:0x1234...`) --- ## Core Concepts [#core-concepts] ### Payment Flow Overview [#payment-flow-overview] ``` Payment Link → Detect → Get Options → [WebView Data Collection] → Get Actions → Sign Actions → Confirm Payment → Result ``` 1. **Payment Link Detection**: Identify incoming payment links from QR codes, deep links, or text input 2. **Get Payment Options**: Retrieve available payment methods with merchant information 3. **WebView Data Collection** (optional): Display WebView form for KYC/compliance data if required by the payment. The WebView submits data directly to the backend, so this must happen BEFORE fetching actions. 4. **Get Actions**: Fetch the required signing actions via `getRequiredPaymentActions` (only needed when the selected option's `actions` are empty) 5. **Sign Actions**: Execute wallet signing operations (typically `eth_signTypedData_v4`) 6. **Confirm Payment**: Submit the wallet RPC results (`data`) to complete the transaction 7. **Handle Result**: Display success/failure and handle polling if needed ### Key Data Models [#key-data-models] | Model | Purpose | |-------|---------| | `GetPaymentOptionsRequest` | Request to fetch available payment options | | `PaymentOptionsResponse` | Contains payment ID, options, merchant info, and data collection requirements | | `PaymentOption` | Individual payment option with amount, account, and actions | | `Action` / `WalletRpcAction` | Signing request with chain ID, method, and parameters | | `CollectDataAction` | Optional data collection with WebView URL | | `ConfirmPaymentRequest` | Request to confirm payment with the wallet RPC results (`data`) | | `ConfirmPaymentResponse` | Payment status and polling information | | `PaymentStatus` | Enum: `requires_action`, `processing`, `succeeded`, `failed`, `expired` | --- ## Step-by-Step Integration [#step-by-step-integration] ### Step 1: Dependency Setup [#step-1-dependency-setup] The `walletconnect_pay` package is already a dependency of `reown_walletkit` and is re-exported. No additional dependencies are needed. ```yaml # pubspec.yaml dependencies: reown_walletkit: ^1.5.1 # Check for latest version ``` All Pay-related types are exported from `reown_walletkit`: ```dart import 'package:reown_walletkit/reown_walletkit.dart'; // This includes: WalletConnectPay, PaymentOptionsResponse, PaymentOption, // Action, WalletRpcAction, ConfirmPaymentRequest, PaymentStatus, etc. ``` ### Step 2: WalletKit Initialization [#step-2-walletkit-initialization] Pay is automatically initialized when you call `walletKit.init()`. No separate Pay configuration is required. ```dart // Create WalletKit instance final walletKit = ReownWalletKit( core: ReownCore( projectId: 'YOUR_PROJECT_ID', logLevel: LogLevel.info, ), metadata: PairingMetadata( name: 'Your Wallet Name', description: 'Your wallet description', url: 'https://yourwallet.app', icons: ['https://yourwallet.app/icon.png'], redirect: Redirect( native: 'yourwallet://', universal: 'https://yourwallet.app', ), ), ); // Initialize - this also initializes Pay await walletKit.init(); // Pay is now available via walletKit.pay or through delegated methods ``` ### Step 3: Payment Link Detection [#step-3-payment-link-detection] Use `walletKit.isPaymentLink()` to detect payment links. This check must occur at ALL URI entry points in your app. ```dart /// Check if a URI is a payment link bool isPaymentLink(String uri) { return walletKit.isPaymentLink(uri); } ``` **CRITICAL**: Add payment link detection to: - QR code scanner results - Deep link handlers (cold start and warm start) - Paste/text input handlers - Universal link handlers **Important**: Payment links are HTTPS URLs. Ensure the `isPaymentLink()` check happens BEFORE any generic HTTPS URL handling to prevent opening payment links in a browser. ```dart // Example: In your pairing/URI handler Future handleUri(String uri) async { if (walletKit.isPaymentLink(uri)) { // Handle as payment // See fetchPaymentOptions on Step 4 } else { // Handle as standard WalletConnect pairing await walletKit.pair(uri: Uri.parse(uri)); } } ``` ### Step 4: Get Payment Options [#step-4-get-payment-options] Retrieve available payment options using the wallet's accounts in CAIP-10 format. ```dart /// Get payment options for a payment link Future fetchPaymentOptions(String paymentLink) async { // Get wallet accounts in CAIP-10 format // Format: eip155:{chainId}:{address} final accounts = await getWalletAccounts(); // Example: ['eip155:1:0x123...', 'eip155:137:0x123...', 'eip155:42161:0x123...'] final request = GetPaymentOptionsRequest( paymentLink: paymentLink, accounts: accounts, includePaymentInfo: true, // Include merchant and payment details ); try { final response = await walletKit.getPaymentOptions(request: request); return response; } on GetPaymentOptionsError catch (e) { // Handle specific error codes // e.code: 'PaymentExpired', 'PaymentNotFound', 'InvalidAccount', etc. throw e; } } /// Helper: Get wallet accounts in CAIP-10 format Future> getWalletAccounts() async { final List accounts = []; // For each supported chain, add the account // Adjust this based on your wallet's key management for (final chainId in supportedChainIds) { final address = await getAddressForChain(chainId); accounts.add('$chainId:$address'); } return accounts; } ``` **Response Structure:** ```dart class PaymentOptionsResponse { final String paymentId; // Unique ID for this payment session final PaymentInfo? info; // Merchant and payment details final List options; // Available payment methods final CollectDataAction? collectData; // Optional data collection with WebView URL final PaymentResultInfo? resultInfo; // Transaction result details (present when payment already completed) } class PaymentResultInfo { final String txId; // Transaction ID final PayAmount optionAmount; // Token amount details } class CollectDataAction { final String url; // WebView URL for data collection final String? schema; // JSON schema describing required fields } class PaymentInfo { final PaymentStatus status; final PayAmount amount; // Payment amount with display info final int expiresAt; // Unix timestamp final MerchantInfo merchant; // Merchant name and icon final BuyerInfo? buyer; } class PaymentOption { final String id; // Option ID for subsequent requests final String account; // CAIP-10 account to pay from final PayAmount amount; // Amount in this option's token final int etaSeconds; // Estimated completion time final List actions; // Signing actions (may be empty initially) final CollectDataAction? collectData; // Per-option data collection (null if not required) } ``` ### Step 5: Handle Data Collection via WebView [#step-5-handle-data-collection-via-webview] If the selected option's `collectData` is not null and has a `url`, display the URL in a WebView for data collection. The hosted form handles rendering, validation, and T&C acceptance. The form URL accepts optional query parameters — append them to `selectedOption.collectData.url` before loading, preserving existing query parameters: - `prefill` — base64url-encoded JSON of known user fields. Keys must match the `required` fields from `collectData.schema` (e.g. `fullName`, `dob`, `pobAddress`). - `theme` — `light` or `dark`, to match your wallet's color mode. - `themeVariables` — a base64url string exported from the [WalletConnect Pay Dashboard](https://dashboard.walletconnect.com) that overrides design tokens (font, font size, some colors, button/input border radius). Append it verbatim. ```dart String buildFormUrl( String baseUrl, { Map prefillData = const {}, String? theme, // "light" or "dark" String? themeVariables, // base64url string exported from the Pay Dashboard }) { final uri = Uri.parse(baseUrl); final params = {...uri.queryParameters}; if (prefillData.isNotEmpty) { params['prefill'] = base64Url.encode(utf8.encode(jsonEncode(prefillData))).replaceAll('=', ''); } if (theme != null) params['theme'] = theme; if (themeVariables != null) params['themeVariables'] = themeVariables; return uri.replace(queryParameters: params).toString(); } ``` ```dart import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:webview_flutter/webview_flutter.dart'; import 'package:url_launcher/url_launcher.dart'; /// Show WebView for data collection Future showDataCollectionWebView( BuildContext context, String url, ) async { final completer = Completer(); Navigator.push(context, MaterialPageRoute( builder: (_) => PayDataCollectionWebView( url: url, onComplete: () { Navigator.pop(context); completer.complete(true); }, onError: (error) { Navigator.pop(context); completer.complete(false); showError('Data collection failed: $error'); }, ), )); return completer.future; } class PayDataCollectionWebView extends StatefulWidget { final String url; final VoidCallback onComplete; final ValueChanged onError; const PayDataCollectionWebView({ super.key, required this.url, required this.onComplete, required this.onError, }); @override State createState() => _PayDataCollectionWebViewState(); } class _PayDataCollectionWebViewState extends State { late final WebViewController _controller; bool _isLoading = true; @override void initState() { super.initState(); _controller = WebViewController() ..setJavaScriptMode(JavaScriptMode.unrestricted) ..setNavigationDelegate(NavigationDelegate( onPageFinished: (_) => setState(() => _isLoading = false), onNavigationRequest: (request) { if (!request.url.contains('pay.walletconnect.com')) { launchUrl(Uri.parse(request.url), mode: LaunchMode.externalApplication); return NavigationDecision.prevent; } return NavigationDecision.navigate; }, )) ..addJavaScriptChannel( 'ReactNativeWebView', onMessageReceived: (message) { try { final data = jsonDecode(message.message) as Map; switch (data['type']) { case 'IC_COMPLETE': widget.onComplete(); break; case 'IC_ERROR': widget.onError(data['error'] ?? 'Unknown error'); break; } } catch (_) {} }, ) ..loadRequest(Uri.parse(widget.url)); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Information Collection')), body: Stack( children: [ WebViewWidget(controller: _controller), if (_isLoading) const Center(child: CircularProgressIndicator()), ], ), ); } } ``` > **Important:** When using the WebView approach, do **not** pass `collectedData` to `confirmPayment()`. The WebView submits data directly to the backend. Add `webview_flutter` and `url_launcher` to your dependencies: ```yaml dependencies: webview_flutter: ^4.10.0 url_launcher: ^6.1.0 ``` ### Step 6: Get Required Payment Actions [#step-6-get-required-payment-actions] If the selected payment option has empty `actions`, fetch them explicitly. ```dart /// Get signing actions for a payment option Future> fetchRequiredActions( String paymentId, String optionId, ) async { final request = GetRequiredPaymentActionsRequest( paymentId: paymentId, optionId: optionId, ); try { return await walletKit.getRequiredPaymentActions(request: request); } on GetRequiredActionsError catch (e) { throw e; } } ``` **Action Structure:** ```dart class Action { final WalletRpcAction walletRpc; } class WalletRpcAction { final String chainId; // CAIP-2 chain ID (e.g., 'eip155:1') final String method; // JSON-RPC method (e.g., 'eth_signTypedData_v4') final String params; // JSON string of parameters } ``` ### Step 7: Sign Payment Actions [#step-7-sign-payment-actions] **CRITICAL**: The `params` field contains a JSON string. Handle it appropriately for your signing library. ```dart /// Sign all actions and return the wallet RPC results, in action order Future> signActions(List actions) async { final List data = []; for (final action in actions) { final signature = await signAction(action); data.add(signature); } return data; } /// Sign a single action Future signAction(Action action) async { final walletRpc = action.walletRpc; final chainId = walletRpc.chainId; final method = walletRpc.method; final params = walletRpc.params; switch (method) { case 'eth_signTypedData_v4': return await signTypedDataV4(chainId, params); case 'personal_sign': return await personalSign(chainId, params); default: throw UnimplementedError('Unsupported signing method: $method'); } } ``` #### EIP-712 Typed Data Signing (`eth_signTypedData_v4`) [#eip-712-typed-data-signing-eth_signtypeddata_v4] ```dart import 'dart:convert'; import 'package:eth_sig_util_plus/eth_sig_util_plus.dart' as eth_sig_util; /// Sign typed data (EIP-712) String signTypedDataV4(String chainId, String params) { // Parse the params - it's a JSON array: [address, typedData] final decodedParams = jsonDecode(params) as List; final typedData = decodedParams.last; // The typed data object or string // Get the typed data as a JSON string final String jsonData; if (typedData is String) { jsonData = typedData; } else { jsonData = jsonEncode(typedData); } // Normalize hex values (some values may have odd-length hex strings) final normalizedData = _normalizeHexValues(jsonData); // Get the private key for the chain final privateKey = getPrivateKeyForChain(chainId); // Sign using eth_sig_util final signature = eth_sig_util.EthSigUtil.signTypedData( privateKey: privateKey, jsonData: normalizedData, version: eth_sig_util.TypedDataVersion.V4, ); return signature; } /// Normalize hex values to have even length String _normalizeHexValues(String jsonString) { // Pad odd-length hex values (e.g., "0x186a0" -> "0x0186a0") return jsonString.replaceAllMapped( RegExp(r'"0x([0-9a-fA-F]+)"'), (match) { final hex = match.group(1)!; return hex.length % 2 == 0 ? match.group(0)! : '"0x0$hex"'; }, ); } ``` #### Personal Sign [#personal-sign] ```dart import 'dart:convert'; import 'dart:typed_data'; import 'package:eth_sig_util_plus/eth_sig_util_plus.dart' as eth_sig_util; import 'package:eth_sig_util_plus/util/utils.dart' as eth_sig_util_util; /// Sign a personal message String personalSign(String chainId, String params) { // Parse the params - it's a JSON array: [message, address] final decodedParams = jsonDecode(params) as List; final message = decodedParams.first as String; // Get the private key final privateKey = getPrivateKeyForChain(chainId); final credentials = EthPrivateKey.fromHex(privateKey); // Sign the message final Uint8List messageBytes; if (message.startsWith('0x')) { messageBytes = eth_sig_util_util.hexToBytes(message.substring(2)); } else { messageBytes = utf8.encode(message); } final signature = credentials.signPersonalMessageToUint8List(messageBytes); return eth_sig_util_util.bytesToHex(signature, include0x: true); } ``` ### Step 8: Confirm Payment [#step-8-confirm-payment] Submit the wallet RPC results (`data`) to complete the payment. Each element of `data` is either a plain `String` (a signature or transaction hash) or, for chains like Tron, a `Map` JSON object; the SDK forwards each element verbatim. See [Tron support](/payments/wallets/token-chain-support/tron-support) for the Tron payload. ```dart /// Confirm the payment with the wallet RPC results Future confirmPayment({ required String paymentId, required String optionId, required List data, }) async { final request = ConfirmPaymentRequest( paymentId: paymentId, optionId: optionId, data: data, maxPollMs: 60000, // Poll for up to 60 seconds ); try { final response = await walletKit.confirmPayment(request: request); return response; } on ConfirmPaymentError catch (e) { // Handle specific errors // e.code: 'InvalidSignature', 'PaymentExpired', 'RouteExpired', etc. throw e; } } ``` **CRITICAL**: The `data` list must match the actions array order exactly. Misalignment causes payment failures. The `signatures` parameter is deprecated in favor of `data` and will be removed in a future major version. Existing integrations that pass `signatures` keep working; the SDK uses it as a fallback when `data` is null. ### Step 9: Handle Payment Result [#step-9-handle-payment-result] ```dart /// Handle the payment response Future handlePaymentResult(ConfirmPaymentResponse response) async { switch (response.status) { case PaymentStatus.succeeded: // Payment completed successfully showSuccessScreen(); break; case PaymentStatus.processing: // Payment is being processed if (!response.isFinal && response.pollInMs != null) { // Continue polling await Future.delayed(Duration(milliseconds: response.pollInMs!)); // Call confirmPayment again to check status } break; case PaymentStatus.failed: showErrorScreen('Payment failed'); break; case PaymentStatus.expired: showErrorScreen('Payment expired'); break; case PaymentStatus.requires_action: // Should not reach here after signing showErrorScreen('Additional action required'); break; } } ``` --- ## Complete Payment Flow Example [#complete-payment-flow-example] ```dart /// Complete payment processing flow Future processPayment(String paymentLink) async { try { // Step 1: Get payment options final accounts = await getWalletAccounts(); final options = await walletKit.getPaymentOptions( request: GetPaymentOptionsRequest( paymentLink: paymentLink, accounts: accounts, includePaymentInfo: true, ), ); if (options.options.isEmpty) { throw Exception('No payment options available'); } // Step 2: Show payment UI and let user select option final selectedOption = await showPaymentOptionsModal(options); if (selectedOption == null) return; // User cancelled // Step 3: Collect data via WebView if required for selected option if (selectedOption.collectData?.url != null) { final success = await showDataCollectionWebView( context, selectedOption.collectData!.url, ); if (!success) return; // User cancelled or error } // Step 4: Get actions if not included in option List actions = selectedOption.actions; if (actions.isEmpty) { actions = await walletKit.getRequiredPaymentActions( request: GetRequiredPaymentActionsRequest( paymentId: options.paymentId, optionId: selectedOption.id, ), ); } // Step 5: Sign all actions final data = await signActions(actions); // Step 6: Confirm payment final result = await walletKit.confirmPayment( request: ConfirmPaymentRequest( paymentId: options.paymentId, optionId: selectedOption.id, data: data, maxPollMs: 60000, ), ); // Step 7: Handle result await handlePaymentResult(result); } on GetPaymentOptionsError catch (e) { showError('Failed to get payment options: ${e.message}'); } on GetRequiredActionsError catch (e) { showError('Failed to get signing actions: ${e.message}'); } on ConfirmPaymentError catch (e) { showError('Failed to confirm payment: ${e.message}'); } catch (e) { showError('Payment error: $e'); } } ``` --- ## UI Implementation Guidelines [#ui-implementation-guidelines] ### Recommended Screens/Modals [#recommended-screensmodals] 1. **Loading State**: Show while fetching payment options 2. **Payment Details**: Display merchant info, amount, and payment options 3. **Data Collection** (conditional): Collect required fields 4. **Processing State**: Show while confirming payment 5. **Result Screen**: Success or failure with details ### Example Modal Structure [#example-modal-structure] ```dart /// Payment details modal class PaymentDetailsModal extends StatefulWidget { final PaymentOptionsResponse options; const PaymentDetailsModal({required this.options}); @override State createState() => _PaymentDetailsModalState(); } class _PaymentDetailsModalState extends State { late PaymentOption _selectedOption; @override void initState() { super.initState(); _selectedOption = widget.options.options.first; } @override Widget build(BuildContext context) { final info = widget.options.info; return Container( child: Column( children: [ // Merchant header if (info != null) ...[ MerchantHeader(merchant: info.merchant), AmountDisplay(amount: info.amount), ], // Payment options selector PaymentOptionSelector( options: widget.options.options, selected: _selectedOption, onSelected: (option) => setState(() => _selectedOption = option), ), // Pay button ElevatedButton( onPressed: () => Navigator.pop(context, _selectedOption), child: Text('Pay ${formatAmount(info?.amount)}'), ), ], ), ); } } ``` --- ## Utility Functions [#utility-functions] ### Format Payment Amount [#format-payment-amount] ```dart /// Format a PayAmount for display String formatPayAmount(PayAmount payAmount) { // Handle fiat currency (ISO 4217) if (payAmount.unit.startsWith('iso4217')) { return _formatFiatAmount(payAmount); } // Handle crypto amount using the extension return payAmount.formatAmount(); } String _formatFiatAmount(PayAmount payAmount) { final unitOrCode = payAmount.unit; final code = unitOrCode.contains('/') ? unitOrCode.split('/').last.toUpperCase() : unitOrCode.toUpperCase(); const Map symbols = { 'USD': r'$', 'EUR': '€', 'GBP': '£', 'JPY': '¥', 'CAD': r'$', 'AUD': r'$', 'CHF': 'CHF', 'CNY': '¥', // Add more as needed }; final symbol = symbols[code] ?? code; return '$symbol${payAmount.formatAmount(withSymbol: false).trim()}'; } ``` ### Format Expiration Time [#format-expiration-time] ```dart /// Format expiration time String formatExpiration(int expiresAt) { final expiry = DateTime.fromMillisecondsSinceEpoch(expiresAt * 1000); final remaining = expiry.difference(DateTime.now()); if (remaining.isNegative) return 'Expired'; if (remaining.inMinutes < 1) return '${remaining.inSeconds}s'; if (remaining.inHours < 1) return '${remaining.inMinutes}m'; return '${remaining.inHours}h ${remaining.inMinutes % 60}m'; } ``` ### Date Formatting for Data Collection [#date-formatting-for-data-collection] ```dart extension DateTimeFormatting on DateTime { /// Format date as YYYY-MM-DD for data collection String get formatted { return '$year-${month.toString().padLeft(2, '0')}-${day.toString().padLeft(2, '0')}'; } } ``` --- ## Error Handling [#error-handling] ### Error Types [#error-types] | Error Class | When Thrown | |-------------|-------------| | `GetPaymentOptionsError` | Failed to fetch payment options | | `GetRequiredActionsError` | Failed to fetch signing actions | | `ConfirmPaymentError` | Failed to confirm payment | | `PayInitializeError` | Failed to initialize Pay SDK | ### Common Error Codes [#common-error-codes] **GetPaymentOptions:** - `PaymentExpired` - Payment link has expired - `PaymentNotFound` - Invalid payment link - `InvalidAccount` - Provided account format is invalid - `ComplianceFailed` - Compliance check failed **ConfirmPayment:** - `InvalidSignature` - Signature verification failed - `PaymentExpired` - Payment expired during process - `RouteExpired` - Selected payment route expired - `UnsupportedMethod` - Signing method not supported ### Error Handling Pattern [#error-handling-pattern] ```dart try { final response = await walletKit.getPaymentOptions(request: request); // Handle success } on GetPaymentOptionsError catch (e) { switch (e.code) { case 'PaymentExpired': showError('This payment link has expired'); break; case 'PaymentNotFound': showError('Invalid payment link'); break; case 'InvalidAccount': showError('Please check your wallet configuration'); break; default: showError('Error: ${e.message}'); } } catch (e) { showError('Unexpected error: $e'); } ``` --- ## Common Pitfalls [#common-pitfalls] ### 1. Account Format [#1-account-format] **Wrong**: `0x1234...` **Correct**: `eip155:1:0x1234...` (CAIP-10 format) ### 2. Result Order [#2-result-order] **CRITICAL**: `data` must be in the same order as actions. ```dart // CORRECT final data = []; for (final action in actions) { data.add(await signAction(action)); } // WRONG - parallel execution may change order final data = await Future.wait( actions.map((a) => signAction(a)), ); ``` ### 3. JSON Params Handling [#3-json-params-handling] The `walletRpc.params` is a JSON string. Parse appropriately: ```dart // For eth_signTypedData_v4 final decodedParams = jsonDecode(params) as List; final typedData = decodedParams.last; // May be String or Map ``` ### 4. Hex Value Normalization [#4-hex-value-normalization] Some hex values may have odd length. Normalize before signing: ```dart // "0x186a0" -> "0x0186a0" ``` ### 5. Deep Link Handling Order [#5-deep-link-handling-order] Check for payment links BEFORE generic URL handling: ```dart if (walletKit.isPaymentLink(uri)) { await processPayment(uri); // Handle as payment } else if (uri.startsWith('wc:')) { await walletKit.pair(uri: Uri.parse(uri)); // WalletConnect pairing } else if (uri.startsWith('https://')) { // Generic HTTPS - this should come LAST } ``` ### 6. Empty Actions [#6-empty-actions] Payment options may have empty `actions` array initially. Always check and fetch if needed: ```dart List actions = option.actions; if (actions.isEmpty) { actions = await walletKit.getRequiredPaymentActions(...); } ``` --- ## Testing [#testing] ### Test Payment Links [#test-payment-links] Create test payment links from the WalletConnect Pay dashboard using a test-mode API key: ``` https://pay.walletconnect.com/?pid= ``` ### Debug Logging [#debug-logging] Enable logging during development: ```dart final walletKit = ReownWalletKit( core: ReownCore( projectId: 'YOUR_PROJECT_ID', logLevel: LogLevel.all, // Enable all logs ), // ... ); ``` --- ## Summary [#summary] ### Quick Reference - API Methods [#quick-reference---api-methods] ```dart // Check if URI is a payment link walletKit.isPaymentLink(uri) // Get payment options walletKit.getPaymentOptions(request: GetPaymentOptionsRequest(...)) // Get signing actions walletKit.getRequiredPaymentActions(request: GetRequiredPaymentActionsRequest(...)) // Confirm payment walletKit.confirmPayment(request: ConfirmPaymentRequest(...)) // Direct access to Pay instance walletKit.pay ``` ### Integration Checklist [#integration-checklist] - [ ] WalletKit initialized with `await walletKit.init()` - [ ] Payment link detection added to all URI entry points - [ ] `isPaymentLink()` check occurs BEFORE generic URL handling - [ ] Accounts formatted in CAIP-10 format - [ ] `eth_signTypedData_v4` signing implemented - [ ] Hex value normalization for typed data signing - [ ] `data` order matches action order - [ ] WebView data collection for compliance (using webview_flutter) - [ ] Error handling for all error types - [ ] Loading states during API calls - [ ] Success/failure result screens - [ ] Polling handled for non-final responses --- ## Reference Implementation [#reference-implementation] See the complete working implementation in the WalletKit example app: - `packages/reown_walletkit/example/lib/dependencies/walletkit_service.dart` - `packages/reown_walletkit/example/lib/walletconnect_pay/` (UI modals) - `packages/reown_walletkit/example/lib/dependencies/chain_services/evm_service.dart` (signing) ## Resources [#resources] - [Reown Documentation](https://docs.reown.com) - [WalletKit Flutter Docs](https://docs.reown.com/walletkit/flutter/installation) - [pub.dev Package](https://pub.dev/packages/reown_walletkit) # AI Integration Prompt - Kotlin (/payments/wallets/walletkit/ai-prompts/kotlin) This guide enables Android wallet developers to integrate WalletConnect Pay into applications that already have WalletKit configured.By following this guide, your wallet will be able to process crypto payment links, allowing users to pay merchants directly from your app. ## Before You Begin [#before-you-begin] ### Study First, Then Implement [#study-first-then-implement] This document is a reference guide, not boilerplate code to copy-paste. Before implementing: 1. **Study your existing codebase** - Understand how URI handling, signing, and navigation work in your app 2. **Follow established patterns** - Match your app's architecture, naming conventions, and code style 3. **Adapt, don't copy** - The code examples show what to do, not necessarily how your specific app should do it ### Prerequisites [#prerequisites] - WalletKit SDK 1.9.0+ integrated and initialized (`com.reown:walletkit`; bundles `com.walletconnect:pay` 1.3.0+, required for the `data` parameter in `confirmPayment`) - Ethereum signing capability (EIP-712 typed data, personal_sign) - Kotlin Coroutines for async operations - Understanding of your app's navigation and state management ### Dependencies [#dependencies] ```kotlin // In your build.gradle.kts dependencies { implementation("com.reown:walletkit:$walletKitVersion") // For EIP-712 signing (if not already included) implementation("org.web3j:core:4.9.8") } ``` ## Architecture Overview [#architecture-overview] ### How WalletConnect Pay Works [#how-walletconnect-pay-works] WalletConnect Pay enables crypto payments through payment links. The flow works as follows: ``` Payment Link → Get Options → Select Option → [WebView Data Collection]* → Get Actions → Sign Actions → Confirm Payment ↓ ↓ ↓ ↓ ↓ ↓ ↓ Detection API call User picks Per-option IC (if needed) Fetch actions Wallet signs Backend confirms ``` ### WalletKit Integration [#walletkit-integration] WalletKit automatically initializes WalletConnectPay during `WalletKit.initialize()`. The Pay functionality is exposed through the `WalletKit.Pay` object: ```kotlin object WalletKit { object Pay { suspend fun getPaymentOptions(paymentLink: String, accounts: List): Result suspend fun getRequiredPaymentActions(params: Params.RequiredPaymentActions): Result> suspend fun confirmPayment(params: Params.ConfirmPayment): Result fun isPaymentLink(uri: String): Boolean } } ``` ## Step 1: Payment Link Detection [#step-1-payment-link-detection] ### Using the Official Detection Function [#using-the-official-detection-function] WalletKit provides `isPaymentLink()` to identify payment URIs. Always use this function rather than custom URL parsing to ensure compatibility as the protocol evolves. ```kotlin import com.reown.walletkit.client.WalletKit fun handleUri(uri: String) { when { WalletKit.Pay.isPaymentLink(uri) -> { // Handle as payment link navigateToPaymentFlow(uri) } // Handle other URI types (WalletConnect pairing, deep links, etc.) else -> handleOtherUri(uri) } } ``` ### Add Detection to All Entry Points [#add-detection-to-all-entry-points] Payment link detection must be added wherever your app processes URIs: 1. **QR Code Scanner** ```kotlin fun onQrCodeScanned(scannedUri: String) { if (WalletKit.Pay.isPaymentLink(scannedUri)) { navigateToPaymentFlow(scannedUri) } else { // Handle as WalletConnect pairing or other URI handleWalletConnectUri(scannedUri) } } ``` 2. **Text Input / Paste** ```kotlin fun onUriPasted(pastedUri: String) { if (WalletKit.Pay.isPaymentLink(pastedUri)) { navigateToPaymentFlow(pastedUri) } else { handleGenericUri(pastedUri) } } ``` 3. **Deep Link Handler** ```kotlin // In your Activity or deep link handler override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) intent?.data?.toString()?.let { uri -> if (WalletKit.Pay.isPaymentLink(uri)) { navigateToPaymentFlow(uri) } else { handleDeepLink(uri) } } } ``` > **Important:** The `isPaymentLink()` check must precede any generic HTTPS handlers to prevent payment links from accidentally opening in a browser. ## Step 2: Implement the Payment Flow [#step-2-implement-the-payment-flow] ### Data Models [#data-models] WalletKit exposes payment models under `Wallet.Model`: ```kotlin // Payment status enumeration enum class PaymentStatus { REQUIRES_ACTION, // Additional action needed PROCESSING, // Payment being processed SUCCEEDED, // Payment completed FAILED, // Payment failed EXPIRED // Payment link expired } // Payment information from merchant data class PaymentInfo( val status: PaymentStatus, val amount: PaymentAmount, val expiresAt: Long, val merchant: MerchantInfo ) // Payment option (token/chain combination) data class PaymentOption( val id: String, val amount: PaymentAmount, val account: String, val estimatedTxs: Int?, val collectData: CollectDataAction? // Per-option data collection (null if not required) ) // Data collection action (for KYC/compliance via WebView) data class CollectDataAction( val url: String, // WebView URL for data collection val schema: String? // JSON schema describing required fields ) // Transaction result details (present when payment already completed) data class PaymentResultInfo( val txId: String, // Transaction ID val optionAmount: PaymentAmount // Token amount details ) // Signing action required from wallet data class WalletRpcAction( val chainId: String, val method: String, // "eth_signTypedData_v4" or "personal_sign" val params: String // JSON array as string ) ``` ### Payment Flow Implementation [#payment-flow-implementation] #### 2.1 Get Payment Options [#21-get-payment-options] ```kotlin import com.reown.walletkit.client.WalletKit import com.reown.walletkit.client.Wallet suspend fun getPaymentOptions( paymentLink: String, walletAddress: String ): Result { // Format account as CAIP-10: "eip155:{chainId}:{address}" // Include all chains your wallet supports val accounts = listOf( "eip155:1:$walletAddress", // Ethereum Mainnet "eip155:137:$walletAddress", // Polygon "eip155:42161:$walletAddress", // Arbitrum "eip155:10:$walletAddress", // Optimism "eip155:8453:$walletAddress" // Base ) return WalletKit.Pay.getPaymentOptions( paymentLink = paymentLink, accounts = accounts ) } ``` #### 2.2 Handle Data Collection via WebView (if required) [#22-handle-data-collection-via-webview-if-required] Some payments require user information (KYC/AML compliance). Data collection requirements are specified per payment option via `collectData`. Show all options first, then handle data collection after the user selects an option: ```kotlin fun processPaymentOptionsResponse(response: Wallet.Model.PaymentOptionsResponse) { if (response.options.isEmpty()) { showError("No payment options available") return } // Show all options — each option's collectData indicates if IC is needed showPaymentOptions(response.options, response.info) } ``` When `selectedOption.collectData?.url` is present, display the URL in a WebView before proceeding with signing. The hosted form handles rendering, validation, and Terms & Conditions acceptance. The WebView communicates completion via JavaScript bridge messages (`IC_COMPLETE` / `IC_ERROR`). The form URL accepts optional query parameters (append them with `buildFormUrl` before loading): - `prefill` — base64url-encoded JSON of known user fields. Keys must match the `required` fields from `collectData.schema` (e.g. `fullName`, `dob`, `pobAddress`). - `theme` — `light` or `dark`, to match your wallet's color mode. - `themeVariables` — a base64url string exported from the [WalletConnect Pay Dashboard](https://dashboard.walletconnect.com) that overrides design tokens (font, font size, some colors, button/input border radius). Append it verbatim. > **Important:** When using the WebView approach, do **not** pass `collectedData` to `confirmPayment()`. The WebView submits data directly to the backend. #### WebView Implementation [#webview-implementation] ```kotlin import android.webkit.JavascriptInterface import android.webkit.WebView import android.webkit.WebViewClient import android.webkit.WebResourceRequest import android.content.Intent import android.net.Uri import android.util.Base64 import androidx.compose.runtime.Composable import androidx.compose.ui.viewinterop.AndroidView import org.json.JSONObject @Composable fun PayDataCollectionWebView( url: String, onComplete: () -> Unit, onError: (String) -> Unit ) { AndroidView(factory = { context -> WebView(context).apply { settings.javaScriptEnabled = true settings.domStorageEnabled = true settings.allowFileAccess = false addJavascriptInterface( object { @JavascriptInterface fun onDataCollectionComplete(json: String) { val message = JSONObject(json) when (message.optString("type")) { "IC_COMPLETE" -> onComplete() "IC_ERROR" -> onError( message.optString("error", "Unknown error") ) } } }, "AndroidWallet" ) webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading( view: WebView?, request: WebResourceRequest? ): Boolean { val requestUrl = request?.url?.toString() ?: return false if (!requestUrl.contains("pay.walletconnect.com")) { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(requestUrl))) return true } return false } } loadUrl(url) } }) } fun buildFormUrl( baseUrl: String, prefillData: Map = emptyMap(), theme: String? = null, // "light" or "dark" themeVariables: String? = null // base64url string exported from the Pay Dashboard ): String { val builder = Uri.parse(baseUrl).buildUpon() if (prefillData.isNotEmpty()) { val prefill = Base64.encodeToString( JSONObject(prefillData).toString().toByteArray(), Base64.NO_WRAP or Base64.URL_SAFE or Base64.NO_PADDING ) builder.appendQueryParameter("prefill", prefill) } theme?.let { builder.appendQueryParameter("theme", it) } themeVariables?.let { builder.appendQueryParameter("themeVariables", it) } return builder.build().toString() } ``` #### 2.3 Get Required Payment Actions [#23-get-required-payment-actions] After user selects a payment option, get the signing actions: ```kotlin suspend fun getRequiredActions( paymentId: String, optionId: String ): Result> { return WalletKit.Pay.getRequiredPaymentActions( Wallet.Params.RequiredPaymentActions( paymentId = paymentId, optionId = optionId ) ) } ``` #### 2.4 Sign the Actions [#24-sign-the-actions] Sign each `WalletRpcAction` with the wallet's private key: ```kotlin import org.json.JSONArray import org.web3j.crypto.ECKeyPair import org.web3j.crypto.Sign import org.web3j.crypto.StructuredDataEncoder fun signWalletRpcAction( action: Wallet.Model.WalletRpcAction, privateKey: ByteArray, walletAddress: String ): String { return when (action.method) { "eth_signTypedData_v4" -> signTypedDataV4(action.params, privateKey, walletAddress) "personal_sign" -> personalSign(action.params, privateKey) else -> throw UnsupportedOperationException("Unsupported method: ${action.method}") } } /** * Sign EIP-712 typed data. * The params are a JSON array: [address, typedDataJson] */ fun signTypedDataV4( params: String, privateKey: ByteArray, walletAddress: String ): String { val paramsArray = JSONArray(params) val requestedAddress = paramsArray.getString(0) val typedData = paramsArray.getString(1) // Verify address matches require(requestedAddress.equals(walletAddress, ignoreCase = true)) { "Requested address does not match wallet address" } // Hash the typed data using StructuredDataEncoder val encoder = StructuredDataEncoder(typedData) val hash = encoder.hashStructuredData() // Sign the hash val keyPair = ECKeyPair.create(privateKey) val signatureData = Sign.signMessage(hash, keyPair, false) // Encode signature as hex string val r = signatureData.r.toHexString() val s = signatureData.s.toHexString() val v = (signatureData.v[0].toInt() and 0xff).toString(16).padStart(2, '0') return "0x$r$s$v".lowercase() } /** * Sign a personal message. * The params are a JSON array: [messageHex, address] */ fun personalSign( params: String, privateKey: ByteArray ): String { val paramsArray = JSONArray(params) val messageHex = paramsArray.getString(0) // Remove "0x" prefix and decode hex to bytes val messageBytes = messageHex.removePrefix("0x").hexToByteArray() // Prefix with Ethereum signed message header val prefix = "\u0019Ethereum Signed Message:\n${messageBytes.size}" val prefixedMessage = prefix.toByteArray() + messageBytes // Hash and sign val hash = org.web3j.crypto.Hash.sha3(prefixedMessage) val keyPair = ECKeyPair.create(privateKey) val signatureData = Sign.signMessage(hash, keyPair, false) val r = signatureData.r.toHexString() val s = signatureData.s.toHexString() val v = (signatureData.v[0].toInt() and 0xff).toString(16).padStart(2, '0') return "0x$r$s$v".lowercase() } // Extension function for hex conversion fun ByteArray.toHexString(): String = joinToString("") { "%02x".format(it) } fun String.hexToByteArray(): ByteArray = chunked(2).map { it.toInt(16).toByte() }.toByteArray() ``` > **Critical:** Pass raw JSON strings directly to signing APIs. Do not parse and reconstruct the JSON data, as this can cause transformation issues leading to signature verification failures. #### 2.5 Confirm Payment [#25-confirm-payment] Submit the wallet RPC results (`data`) to confirm the payment (data collection, if any, was already submitted by the WebView). Each element of `data` is either a plain string (a signature or transaction hash) or, for chains like Tron, a JSON object encoded as a string; WalletConnect Pay forwards each element verbatim to the gateway. See [Tron support](/payments/wallets/token-chain-support/tron-support) for the Tron payload. ```kotlin suspend fun confirmPayment( paymentId: String, optionId: String, data: List ): Result { return WalletKit.Pay.confirmPayment( Wallet.Params.ConfirmPayment( paymentId = paymentId, optionId = optionId, data = data ) ) } // Handle the response fun handleConfirmationResult(response: Wallet.Model.ConfirmPaymentResponse) { when (response.status) { Wallet.Model.PaymentStatus.SUCCEEDED -> { showSuccessScreen("Payment completed successfully!") } Wallet.Model.PaymentStatus.PROCESSING -> { // Payment is being processed asynchronously showSuccessScreen("Payment is being processed...") // Optionally poll for updates using response.pollInMs } Wallet.Model.PaymentStatus.FAILED -> { showErrorScreen("Payment failed. Please try again.") } Wallet.Model.PaymentStatus.EXPIRED -> { showErrorScreen("Payment link has expired.") } Wallet.Model.PaymentStatus.REQUIRES_ACTION -> { // Additional action needed (rare case) showErrorScreen("Additional action required.") } } } ``` `Wallet.Params.ConfirmPayment` fields: ```kotlin data class ConfirmPayment( val paymentId: String, val optionId: String, @Deprecated("Use data instead") val signatures: List = emptyList(), // Deprecated alias for data, still accepted val collectedData: List? = null, val data: List? = null // Wallet RPC results in action order: plain strings or JSON-encoded objects (e.g. Tron); falls back to signatures when null ) ``` The `signatures` field is deprecated in favor of `data` and will be removed in a future major version. Existing integrations that pass `signatures` keep working; the SDK uses it as a fallback when `data` is omitted. ## Step 3: State Management [#step-3-state-management] ### Recommended State Machine [#recommended-state-machine] Implement a state machine to manage the payment flow: ```kotlin sealed class PaymentUiState { data object Loading : PaymentUiState() data class Options( val paymentInfo: Wallet.Model.PaymentInfo?, val options: List ) : PaymentUiState() data class WebViewDataCollection( val url: String ) : PaymentUiState() data class Processing( val message: String, val paymentInfo: Wallet.Model.PaymentInfo? = null ) : PaymentUiState() data class Success( val message: String, val paymentInfo: Wallet.Model.PaymentInfo? = null ) : PaymentUiState() data class Error(val message: String) : PaymentUiState() } ``` ### ViewModel Implementation [#viewmodel-implementation] ```kotlin import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch class PaymentViewModel( private val walletRepository: WalletRepository ) : ViewModel() { private val _uiState = MutableStateFlow(PaymentUiState.Loading) val uiState: StateFlow = _uiState.asStateFlow() private var currentPaymentId: String? = null private var selectedOptionId: String? = null private var pendingActions: List = emptyList() private var storedPaymentInfo: Wallet.Model.PaymentInfo? = null private var storedOptions: List = emptyList() fun loadPaymentOptions(paymentLink: String) { viewModelScope.launch { _uiState.value = PaymentUiState.Loading val accounts = walletRepository.getAccounts() // CAIP-10 format WalletKit.Pay.getPaymentOptions(paymentLink, accounts) .onSuccess { response -> currentPaymentId = response.paymentId storedPaymentInfo = response.info storedOptions = response.options if (response.options.isEmpty()) { _uiState.value = PaymentUiState.Error("No payment options available") } else { _uiState.value = PaymentUiState.Options( paymentInfo = response.info, options = response.options ) } } .onFailure { error -> _uiState.value = PaymentUiState.Error(error.message ?: "Failed to load payment options") } } } fun selectPaymentOption(optionId: String) { val paymentId = currentPaymentId ?: return selectedOptionId = optionId // Check if the selected option requires data collection val selectedOption = storedOptions.find { it.id == optionId } selectedOption?.collectData?.url?.let { url -> // Show WebView for data collection before proceeding _uiState.value = PaymentUiState.WebViewDataCollection(url = url) return } // No data collection needed — proceed directly to signing proceedWithPaymentExecution(paymentId, optionId) } private fun proceedWithPaymentExecution(paymentId: String, optionId: String) { viewModelScope.launch { _uiState.value = PaymentUiState.Processing("Preparing payment...") WalletKit.Pay.getRequiredPaymentActions( Wallet.Params.RequiredPaymentActions(paymentId, optionId) ) .onSuccess { actions -> pendingActions = actions.filterIsInstance() executePayment() } .onFailure { error -> _uiState.value = PaymentUiState.Error(error.message ?: "Failed to get payment actions") } } } private suspend fun executePayment() { val paymentId = currentPaymentId ?: return val optionId = selectedOptionId ?: return _uiState.value = PaymentUiState.Processing( message = "Confirming payment...", paymentInfo = storedPaymentInfo ) try { // Sign all pending actions val data = pendingActions.map { action -> walletRepository.signWalletRpcAction(action.action) } // Confirm payment (no collectedData - WebView handles submission) WalletKit.Pay.confirmPayment( Wallet.Params.ConfirmPayment( paymentId = paymentId, optionId = optionId, data = data ) ) .onSuccess { response -> when (response.status) { Wallet.Model.PaymentStatus.SUCCEEDED, Wallet.Model.PaymentStatus.PROCESSING -> { _uiState.value = PaymentUiState.Success( message = if (response.status == Wallet.Model.PaymentStatus.SUCCEEDED) "Payment completed!" else "Payment processing...", paymentInfo = storedPaymentInfo ) } else -> { _uiState.value = PaymentUiState.Error("Payment ${response.status.name.lowercase()}") } } } .onFailure { error -> _uiState.value = PaymentUiState.Error(error.message ?: "Payment confirmation failed") } } catch (e: Exception) { _uiState.value = PaymentUiState.Error(e.message ?: "An error occurred") } } fun onWebViewComplete() { // WebView data collection completed, proceed with payment execution for selected option val paymentId = currentPaymentId ?: return val optionId = selectedOptionId ?: return proceedWithPaymentExecution(paymentId, optionId) } fun onWebViewError(error: String) { _uiState.value = PaymentUiState.Error(error) } fun cancel() { currentPaymentId = null selectedOptionId = null pendingActions = emptyList() _uiState.value = PaymentUiState.Loading } } ``` ## Step 4: UI Components [#step-4-ui-components] ### Required Screens [#required-screens] 1. **Loading Screen** - Show while fetching payment options 2. **Options Screen** - List of payment options (tokens/chains). Show an "Info required" badge on options that have `collectData != null` 3. **Data Collection Screen** - WebView for KYC/compliance data (shown after selecting an option that requires IC) 4. **Processing Screen** - Show while signing and confirming 5. **Success Screen** - Payment completed successfully 6. **Error Screen** - Handle failures gracefully ### Jetpack Compose Example [#jetpack-compose-example] ```kotlin @Composable fun PaymentScreen( viewModel: PaymentViewModel = viewModel(), onDismiss: () -> Unit ) { val uiState by viewModel.uiState.collectAsState() when (val state = uiState) { is PaymentUiState.Loading -> LoadingContent() is PaymentUiState.Options -> OptionsContent( paymentInfo = state.paymentInfo, options = state.options, onSelectOption = { option -> viewModel.selectPaymentOption(option.id) }, onCancel = { viewModel.cancel(); onDismiss() } ) is PaymentUiState.WebViewDataCollection -> PayDataCollectionWebView( url = state.url, onComplete = { viewModel.onWebViewComplete() }, onError = { error -> viewModel.onWebViewError(error) } ) is PaymentUiState.Processing -> ProcessingContent( message = state.message, paymentInfo = state.paymentInfo ) is PaymentUiState.Success -> SuccessContent( message = state.message, paymentInfo = state.paymentInfo, onDone = { viewModel.cancel(); onDismiss() } ) is PaymentUiState.Error -> ErrorContent( message = state.message, onRetry = { /* implement retry logic */ }, onDismiss = { viewModel.cancel(); onDismiss() } ) } } ``` ## Utility Functions [#utility-functions] ### Format Payment Amount [#format-payment-amount] ```kotlin fun formatPaymentAmount(amount: Wallet.Model.PaymentAmount): String { val value = amount.value.toBigDecimalOrNull() ?: return "${amount.value} ${amount.unit}" val decimals = amount.display?.decimals ?: 18 val divisor = BigDecimal.TEN.pow(decimals) val formattedValue = value.divide(divisor, decimals, RoundingMode.HALF_UP) .stripTrailingZeros() .toPlainString() val symbol = amount.display?.assetSymbol ?: amount.unit return "$formattedValue $symbol" } ``` ### Format Expiry Time [#format-expiry-time] ```kotlin fun formatExpiryTime(expiresAtMillis: Long): String { val now = System.currentTimeMillis() val remainingMillis = expiresAtMillis - now if (remainingMillis <= 0) return "Expired" val minutes = TimeUnit.MILLISECONDS.toMinutes(remainingMillis) val seconds = TimeUnit.MILLISECONDS.toSeconds(remainingMillis) % 60 return when { minutes > 60 -> "${minutes / 60}h ${minutes % 60}m remaining" minutes > 0 -> "${minutes}m ${seconds}s remaining" else -> "${seconds}s remaining" } } ``` ### Validate Date Input [#validate-date-input] ```kotlin fun validateDateInput(input: String): Boolean { // Expected format: YYYY-MM-DD val regex = Regex("""^\d{4}-\d{2}-\d{2}$""") if (!regex.matches(input)) return false return try { LocalDate.parse(input) true } catch (e: Exception) { false } } ``` ## Error Handling [#error-handling] ### Common Errors [#common-errors] WalletKit exposes typed errors for payment operations: ```kotlin sealed class PaymentError : Exception() { data class InvalidPaymentLink(override val message: String) : PaymentError() data class PaymentExpired(override val message: String) : PaymentError() data class PaymentNotFound(override val message: String) : PaymentError() data class InvalidRequest(override val message: String) : PaymentError() data class ComplianceFailed(override val message: String) : PaymentError() data class NetworkError(override val message: String) : PaymentError() data class InternalError(override val message: String) : PaymentError() } ``` ### Error Handling Strategy [#error-handling-strategy] ```kotlin fun handlePaymentError(error: Throwable): String { return when (error) { is PaymentError.InvalidPaymentLink -> "Invalid payment link format" is PaymentError.PaymentExpired -> "This payment link has expired" is PaymentError.PaymentNotFound -> "Payment not found" is PaymentError.ComplianceFailed -> "Unable to process payment due to compliance requirements" is PaymentError.NetworkError -> "Network error. Please check your connection" else -> error.message ?: "An unexpected error occurred" } } ``` ## Troubleshooting [#troubleshooting] ### Payment Options Empty [#payment-options-empty] **Symptom:** `getPaymentOptions` returns an empty options list. **Causes:** - Wallet address not supported by merchant - Chain not supported for this payment - Payment link already used or expired **Solution:** - Verify CAIP-10 account format: `eip155:{chainId}:{address}` - Include all chains your wallet supports - Check if payment link is still valid ### Signature Verification Failed [#signature-verification-failed] **Symptom:** `confirmPayment` fails with signature verification error. **Causes:** - Incorrect EIP-712 signing implementation - JSON transformation altering the typed data - Wrong address used for signing **Solution:** - Use `StructuredDataEncoder` for EIP-712 hashing - Pass raw JSON strings to signing without parsing/reconstruction - Verify the signing address matches the requested address in params ### Wrong Chain [#wrong-chain] **Symptom:** Transaction fails or signing produces unexpected results. **Causes:** - Not using the chainId from `WalletRpcAction` - Signing with wrong network context **Solution:** - Always use `action.chainId` to determine which network to sign for - Ensure your wallet's signing context matches the action's chain ### Payment Status Polling [#payment-status-polling] For `PROCESSING` status, implement polling: ```kotlin suspend fun pollPaymentStatus( paymentId: String, optionId: String, pollIntervalMs: Long ) { delay(pollIntervalMs) // Re-call getPaymentOptions or implement a status check endpoint // Continue polling until status is final (SUCCEEDED, FAILED, EXPIRED) } ``` ## Complete Flow Example [#complete-flow-example] ```kotlin class PaymentFlowExample( private val walletRepository: WalletRepository ) { suspend fun processPayment(paymentLink: String): Result = runCatching { // 1. Get accounts in CAIP-10 format val accounts = walletRepository.getAccountsAsCaip10() // 2. Get payment options val optionsResponse = WalletKit.Pay.getPaymentOptions(paymentLink, accounts) .getOrThrow() val paymentId = optionsResponse.paymentId // 3. Let user select payment option val selectedOption = showOptionsAndGetSelection(optionsResponse.options) // 4. Handle data collection via WebView if required for selected option selectedOption.collectData?.url?.let { url -> showDataCollectionWebView(url) // Wait for IC_COMPLETE before proceeding } // 5. Get required signing actions val actions = WalletKit.Pay.getRequiredPaymentActions( Wallet.Params.RequiredPaymentActions(paymentId, selectedOption.id) ).getOrThrow() // 6. Sign all actions val data = actions .filterIsInstance() .map { walletRepository.signWalletRpcAction(it.action) } // 7. Confirm payment val confirmResponse = WalletKit.Pay.confirmPayment( Wallet.Params.ConfirmPayment( paymentId = paymentId, optionId = selectedOption.id, data = data ) ).getOrThrow() // 8. Handle result when (confirmResponse.status) { Wallet.Model.PaymentStatus.SUCCEEDED -> { /* Success! */ } Wallet.Model.PaymentStatus.PROCESSING -> { // Optionally poll for final status confirmResponse.pollInMs?.let { delay(it) } } else -> throw Exception("Payment ${confirmResponse.status}") } } } ``` ## Reference Implementation [#reference-implementation] For a complete working example, see the sample wallet implementation: - `sample/wallet/src/main/kotlin/com/reown/sample/wallet/ui/routes/dialog_routes/payment/PaymentViewModel.kt` - `sample/wallet/src/main/kotlin/com/reown/sample/wallet/ui/routes/dialog_routes/payment/PaymentRoute.kt` ## Additional Resources [#additional-resources] - [WalletKit Documentation](https://docs.reown.com/walletkit/kotlin/overview) - [WalletConnect Pay Overview](https://docs.reown.com/pay/overview) - [EIP-712 Specification](https://eips.ethereum.org/EIPS/eip-712) - [CAIP-10 Account ID Specification](https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-10.md) # AI Integration Prompt - React Native (/payments/wallets/walletkit/ai-prompts/react-native) This guide provides all details needed to integrate WalletConnect Pay into a React Native wallet that **already has WalletKit integrated**. Pay is accessed through `walletKit.pay`. --- ## Agent Guidance: Adapt, Don't Copy [#agent-guidance-adapt-dont-copy] **This plan is a reference, not a script.** Each wallet has its own architecture, conventions, and patterns. Follow these principles: ### 1. Match the Target Wallet's Patterns [#1-match-the-target-wallets-patterns] - **Study the existing codebase first.** Look at how similar features are implemented (e.g., how session requests are handled, how modals work, how state is managed). - **Follow existing conventions** for file naming, folder structure, imports, and code style. - **Use the wallet's existing UI components** rather than creating new ones from scratch. - **Adapt the examples in this plan** to fit the wallet's architecture, not the other way around. ### 2. When in Doubt, Ask [#2-when-in-doubt-ask] If you're uncertain about: - Which pattern to follow when multiple exist in the codebase - Whether to create new infrastructure or extend existing - How a specific wallet feature works - The correct location for new files **Stop and ask the user** rather than guessing. ### 3. Test Incrementally [#3-test-incrementally] Don't implement everything at once. Verify each step: 1. `walletKit.pay` is accessible 2. Payment links are detected via `isPaymentLink` 3. Modal/screen opens 4. Payment options load 5. Signing works 6. Payment confirms ### 4. Validate After Every Step (CRITICAL) [#4-validate-after-every-step-critical] **After completing each step in the implementation:** 1. **Go back and review** - Re-read the plan to ensure all requirements for that step were implemented correctly 2. **Check for linting errors** - Run the linter on all modified/created files and fix any errors before proceeding 3. **Verify the code compiles** - Ensure there are no TypeScript or build errors 4. **Test the functionality** - If possible, verify the step works as expected before moving on This prevents accumulating errors that become harder to debug later. --- ## Prerequisites [#prerequisites] The wallet must already have: - `@reown/walletkit` 1.6.0 or later integrated and working (bundles `@walletconnect/pay` 1.1.0) - `@walletconnect/react-native-compat` 2.25.0 or later installed (ships the native Yttrium module: yttrium-wcpay 0.10.60 on Android, YttriumWrapper 0.10.59 on iOS) - WalletKit initialization in place ### Required Package Versions [#required-package-versions] ```json { "@reown/walletkit": "1.6.0", "@walletconnect/react-native-compat": "2.25.0" } ``` These are the minimum versions that include Pay support via `walletKit.pay` with the `data` parameter on `confirmPayment`. --- ## Architecture Overview [#architecture-overview] ``` ┌─────────────────────────────────────────────────────────────┐ │ walletKit │ │ │ │ walletKit.pair() walletKit.pay │ │ walletKit.approveSession() │ │ │ walletKit.respondSessionRequest() │ │ │ ▼ │ │ ┌───────────────────┐ │ │ │ Pay Client API │ │ │ │ getPaymentOptions │ │ │ │ getRequiredActions│ │ │ │ confirmPayment │ │ │ └───────────────────┘ │ └─────────────────────────────────────────────────────────────┘ ``` Pay is automatically available on any WalletKit instance - no additional configuration required. --- ## Step 1: Import isPaymentLink from WalletKit [#step-1-import-ispaymentlink-from-walletkit] WalletKit automatically provides pay functionality via `walletKit.pay`. No additional configuration is needed. Just add the `isPaymentLink` import to detect payment links: ```typescript import { WalletKit, isPaymentLink } from '@reown/walletkit'; export { isPaymentLink }; // Your existing WalletKit initialization - no changes needed const walletKit = await WalletKit.init({ core, metadata: getMetadata(), }); // Pay is automatically available // walletKit.pay.getPaymentOptions(...) ``` --- ## Step 2: Add Payment Link Detection [#step-2-add-payment-link-detection] ### Payment Link Detection [#payment-link-detection] **IMPORTANT**: Always use `isPaymentLink` from WalletKit to detect payment links. Do NOT implement custom URL parsing or regex matching. Current known formats (for reference only - may change): ``` # Direct payment link https://pay.walletconnect.com/?pid=xxx # WC URI with pay parameter wc:xxx?pay=https://pay.walletconnect.com/?pid=xxx ``` The `isPaymentLink` function handles all current and future formats internally, ensuring your integration remains compatible as the protocol evolves. ### Use isPaymentLink from WalletKit [#use-ispaymentlink-from-walletkit] ```typescript import { isPaymentLink } from '@reown/walletkit'; // In your URI handler const handleUri = async (uri: string) => { if (isPaymentLink(uri)) { // Handle as payment handlePaymentLink(uri); return; } // Regular WalletConnect pairing await walletKit.pair({ uri }); }; ``` ### CRITICAL: Check ALL URI Entry Points [#critical-check-all-uri-entry-points] Payment link detection must be added to ALL places where URIs are processed: 1. **QR Scanner** - barcode scanning callback 2. **URI Paste/Input Field** - text input with "Connect" button 3. **Deep Link Handler** - `Linking.addEventListener` for app URLs 4. **Clipboard Paste** - if the app supports paste-to-connect Search for all calls to `walletKit.pair()` and ensure each checks `isPaymentLink(uri)` first. **IMPORTANT**: Payment links are HTTPS URLs (e.g., `https://pay.walletconnect.com/?pid=xxx`). Ensure the `isPaymentLink()` check happens BEFORE any generic HTTP/HTTPS URL handling that might open a browser. --- ## Step 3: Implement Payment Flow [#step-3-implement-payment-flow] ### 3.1 Handle Payment Link [#31-handle-payment-link] ```typescript const handlePaymentLink = async (paymentLink: string) => { const payClient = walletKit?.pay; if (!payClient) { showError('Pay SDK not initialized'); return; } // Show loading state openPaymentModal({ loading: true }); try { // Build accounts array in CAIP-10 format const accounts = supportedChainIds.map( chainId => `eip155:${chainId}:${walletAddress}` ); const paymentOptions = await payClient.getPaymentOptions({ paymentLink, accounts, includePaymentInfo: true, }); // Show payment modal with options openPaymentModal({ paymentOptions }); } catch (error) { openPaymentModal({ error: error.message }); } }; ``` ### 3.2 Collect User Data via WebView (Information Capture) [#32-collect-user-data-via-webview-information-capture] **IMPORTANT - ORDERING**: After the user selects an option, check whether that option requires Information Capture. If `selectedOption.collectData?.url` is present, you MUST collect the data via the WebView **before** calling `getRequiredPaymentActions`. The WebView submits the captured data directly to the backend, and `getRequiredPaymentActions` (which triggers `POST /payment/{id}/fetch`) now requires any IC to already be submitted. Do not fetch actions or sign until the WebView signals completion. If the selected option has no `collectData?.url`, skip this step and go straight to fetching the required actions. ```typescript // Called when the user selects a payment option. // Runs the WebView IC step (if needed) BEFORE fetching the required actions. const onOptionSelected = async (option: PaymentOption) => { setSelectedOption(option); if (option.collectData?.url) { // Step into the WebView; fetchPaymentActions runs in its onComplete. setWebViewUrl(option.collectData.url); setStep('webviewDataCollection'); return; } // No Information Capture needed - fetch actions directly. await fetchPaymentActions(option); }; // Called by the WebView's onComplete callback once IC is submitted to the backend. const onDataCollectionComplete = async () => { if (selectedOption) { await fetchPaymentActions(selectedOption); } }; ``` See [section 3.6](#3-6-webview-data-collection) for the `PayDataCollectionWebView` component implementation. ### 3.3 Get Required Actions for Selected Option [#33-get-required-actions-for-selected-option] Only call this AFTER the WebView Information Capture step has completed (when the selected option requires it). ```typescript const fetchPaymentActions = async (option: PaymentOption) => { const payClient = walletKit?.pay; if (!payClient || !paymentData) return; // Triggers POST /payment/{id}/fetch on the backend. // Any required Information Capture must already be submitted via the WebView. const actions = await payClient.getRequiredPaymentActions({ paymentId: paymentData.paymentId, optionId: option.id, }); setPaymentActions(actions); setStep('confirming'); return actions; }; ``` ### 3.4 Sign and Confirm Payment [#34-sign-and-confirm-payment] **IMPORTANT**: Always try passing the raw JSON string first. This is the safest approach. Collect each wallet RPC result into `data`, in the same order as the actions. Each element is a plain string (a signature or transaction hash) or, for chains like Tron, a JSON object that the SDK forwards verbatim — see [Tron support](/payments/wallets/token-chain-support/tron-support) for the Tron payload. ```typescript const confirmPayment = async () => { const payClient = walletKit?.pay; const data: (string | object)[] = []; for (const action of paymentActions) { if (!action.walletRpc) continue; const { method, params } = action.walletRpc; const parsedParams = JSON.parse(params); if ( method === 'eth_signTypedData_v4' || method === 'eth_signTypedData_v3' || method === 'eth_signTypedData' ) { const fromAddress = parsedParams[0]; const typedDataString = parsedParams[1]; // Already a JSON string // RECOMMENDED: Pass the raw JSON string directly const signature = await wallet.signTypedMessage( { from: fromAddress, data: typedDataString }, SignTypedDataVersion.V4 ); data.push(signature); } else if (method === 'eth_sendTransaction') { const txHash = await wallet.sendTransaction(parsedParams[0]); data.push(txHash); } else if (method === 'personal_sign') { const sig = await wallet.personalSign(parsedParams); data.push(sig); } } // Confirm the payment (no collectedData - WebView handles submission) const result = await payClient.confirmPayment({ paymentId: paymentData.paymentId, optionId: selectedOption.id, data, }); return result; }; ``` The `signatures` parameter is deprecated in favor of `data` and will be removed in a future major version. Existing integrations that pass `signatures` keep working; the SDK uses it as a fallback when `data` is omitted. ### 3.5 Signing API Variations [#35-signing-api-variations] Different wallet libraries have different signing APIs. The key insight is that `parsedParams[1]` is already a complete, correctly-formatted JSON string. **Try the simplest approach first.** #### Approach 1: Pass Raw JSON String (RECOMMENDED - Try This First) [#approach-1-pass-raw-json-string-recommended---try-this-first] **This is the recommended approach.** Many wallet signing APIs accept the typed data as a JSON string directly: ```typescript const fromAddress = parsedParams[0]; const typedDataString = parsedParams[1]; // Already a JSON string // Pass directly without parsing - let the wallet handle it const signature = await wallet.signTypedMessage( { from: fromAddress, data: typedDataString }, SignTypedDataVersion.V4 ); ``` **Always try this first.** If your wallet's signing API accepts a string, this avoids potential data transformation issues that can cause signature verification failures. #### Approach 2: Parse for APIs Requiring Objects (Fallback Only) [#approach-2-parse-for-apis-requiring-objects-fallback-only] **Only use this if Approach 1 fails.** If your wallet API requires parsed objects (like ethers.js `_signTypedData`): ```typescript const typedData = JSON.parse(parsedParams[1]); const { domain, types, message } = typedData; delete types.EIP712Domain; const signature = await wallet._signTypedData(domain, types, message); ``` #### Common Pitfalls When Parsing [#common-pitfalls-when-parsing] If you must parse the typed data, be aware of these issues: 1. **chainId as hex string**: The domain may contain `chainId: "0x2105"` (hex string) instead of `chainId: 8453` (number). Some signing implementations require the number: ```typescript if (typeof domain.chainId === 'string') { domain.chainId = parseInt(domain.chainId, 16); } ``` 2. **Don't guess primaryType**: If your API needs `primaryType`, extract it from the original data—don't use `Object.keys(types)[0]` which returns the alphabetically first key (often wrong): ```typescript // WRONG - may return wrong type const primaryType = Object.keys(types)[0]; // CORRECT - use the actual primaryType from the data const { primaryType } = typedData; ``` 3. **String vs Object format**: Test whether your signing API expects: - `data: "{...}"` (JSON string) - `data: {...}` (parsed object) The wrong format may sign successfully but produce an invalid signature. --- ## Step 4: Payment Modal/Screen UI [#step-4-payment-modalscreen-ui] ### State Machine [#state-machine] The WebView data-collection step (Information Capture) runs AFTER the user selects an option but BEFORE fetching the required actions. `getRequiredPaymentActions` triggers the backend `POST /payment/{id}/fetch`, which now expects any required IC to already be submitted by the WebView. ``` LOADING → ERROR (if failed) → CONFIRM (show options) → WEBVIEW (if selected option needs IC) → GET ACTIONS (getRequiredPaymentActions) → CONFIRMING (sign + confirmPayment) → SUCCESS → CONFIRM (show options) → GET ACTIONS (getRequiredPaymentActions) → CONFIRMING (sign + confirmPayment) → SUCCESS ``` ### State Definition [#state-definition] ```typescript type Step = 'loading' | 'confirm' | 'webviewDataCollection' | 'confirming' | 'result'; interface PaymentModalState { step: Step; resultStatus: 'success' | 'error'; resultMessage: string; selectedOption: PaymentOption | null; paymentActions: Action[] | null; isLoadingActions: boolean; actionsError: string | null; webViewUrl: string | null; } ``` ### Required UI Components [#required-ui-components] 1. **Loading View** - Spinner with message 2. **Confirm View** - Payment options list (with "Info required" badge on options with `collectData`), selected option details, approve button 3. **WebView Data Collection View** - WebView form (if `selectedOption.collectData?.url` exists) 4. **Confirming View** - Spinner while signing and confirming 5. **Result View** - Success or error message with close button ### Display Elements [#display-elements] - Merchant name and icon from `paymentOptions.info.merchant` - Payment amount from `option.amount.display` - Network name and asset symbol - ETA in seconds --- ## Step 5: Utility Functions [#step-5-utility-functions] ### Format Amount [#format-amount] ```typescript function formatAmount(value: string, decimals: number, minDecimals = 0): string { const num = BigInt(value); const divisor = BigInt(10 ** decimals); const integerPart = num / divisor; const fractionalPart = num % divisor; if (fractionalPart === BigInt(0)) { return minDecimals > 0 ? `${integerPart}.${'0'.repeat(minDecimals)}` : integerPart.toString(); } const fractionalStr = fractionalPart.toString().padStart(decimals, '0'); let trimmedFractional = fractionalStr.replace(/0+$/, ''); if (trimmedFractional.length < minDecimals) { trimmedFractional = trimmedFractional.padEnd(minDecimals, '0'); } return `${integerPart}.${trimmedFractional}`; } ``` ### Format Date Input (for collectData) [#format-date-input-for-collectdata] ```typescript function formatDateInput(value: string): string { const cleaned = value.replace(/[^0-9]/g, ''); if (cleaned.length <= 4) return cleaned; if (cleaned.length <= 6) return `${cleaned.slice(0, 4)}-${cleaned.slice(4)}`; return `${cleaned.slice(0, 4)}-${cleaned.slice(4, 6)}-${cleaned.slice(6, 8)}`; } ``` ### Validate Date [#validate-date] ```typescript function isValidDateOfBirth(dateStr: string): boolean { if (!/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) return false; const [year, month, day] = dateStr.split('-').map(Number); const date = new Date(year, month - 1, day); const now = new Date(); return ( date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day && date < now && year >= 1900 ); } ``` --- ## Core API Reference [#core-api-reference] ### Pay Client Methods (via walletKit.pay) [#pay-client-methods-via-walletkitpay] ```typescript // Get payment options await walletKit.pay.getPaymentOptions({ paymentLink: string, // Full pay.walletconnect.com URL accounts: string[], // CAIP-10 format: 'eip155:chainId:address' includePaymentInfo: true, // Always include for merchant info }); // Get required actions await walletKit.pay.getRequiredPaymentActions({ paymentId: string, // From PaymentOptionsResponse optionId: string, // From selected PaymentOption }); // Confirm payment await walletKit.pay.confirmPayment({ paymentId: string, optionId: string, data: (string | object)[], // Wallet RPC results in action order: strings or JSON objects (e.g. Tron) // signatures: string[] // Deprecated alias for `data`, still accepted }); ``` The SDK types `data` as `(string | Record | unknown[])[]`. A value typed with a TypeScript `interface` does not satisfy `Record`; declare it as a `type` alias or spread it into an object literal. ### Account Format (CAIP-10) [#account-format-caip-10] ``` eip155:{chainId}:{address} // Example: eip155:8453:0x1234... ``` ### Key Types [#key-types] ```typescript interface PaymentOptionsResponse { paymentId: string; options: PaymentOption[]; collectData?: CollectDataAction; info?: PaymentInfo; resultInfo?: PaymentResultInfo; // present when payment already completed } interface PaymentResultInfo { txId: string; optionAmount: PayAmount; } interface PaymentOption { id: string; amount: PayAmount; etaS: number; actions: Action[]; collectData?: CollectDataAction; // Per-option data collection } interface PayAmount { unit: string; value: string; display: { assetSymbol: string; assetName: string; decimals: number; iconUrl?: string; networkName?: string; }; } interface CollectDataAction { url: string; // WebView URL for data collection schema?: string; // JSON schema describing required fields } interface Action { walletRpc?: { chainId: string; method: string; params: string; // JSON string - must parse before use }; } ``` --- ## Architecture Adaptation Examples [#architecture-adaptation-examples] ### Modal System Variations [#modal-system-variations] **React Native Modal (overlay):** ```typescript // Use existing modal manager if available ModalStore.open('PaymentOptionsModal', { paymentOptions }); ``` **React Navigation (screen):** ```typescript navigation.navigate('PaymentOptions', { paymentOptions }); ``` **Expo Router:** ```typescript router.push({ pathname: '/payment-options', params: { paymentLink } }); ``` **Bottom Sheet:** ```typescript bottomSheetRef.current?.present(); setPaymentData(paymentOptions); ``` ### Wallet Library Variations [#wallet-library-variations] **MetaMask KeyringController (recommended for MetaMask-based wallets):** ```typescript import { SignTypedDataVersion } from '@metamask/keyring-controller'; // Pass raw JSON string - this is the recommended approach const signature = await keyringController.signTypedMessage( { from: fromAddress, data: typedDataString }, SignTypedDataVersion.V4 ); ``` **ethers.js v5:** ```typescript const signature = await wallet._signTypedData(domain, types, message); ``` **viem:** ```typescript const primaryType = Object.keys(types).find(k => k !== 'EIP712Domain'); const signature = await wallet.signTypedData({ domain, types, primaryType, message }); ``` **web3.js:** ```typescript const signature = await web3.eth.signTypedData(address, typedData); ``` ### 3.6 WebView Data Collection [#36-webview-data-collection] When `selectedOption.collectData?.url` is present, display the URL in a WebView. This happens immediately after the user selects an option and **before** `getRequiredPaymentActions` is called (see [section 3.2](#3-2-collect-user-data-via-webview-information-capture)). The URL comes from the selected option's `collectData.url`, which is already scoped to that option's account. The hosted form handles rendering, validation, and T&C acceptance. Wire `onComplete` to your `onDataCollectionComplete` handler (which then calls `fetchPaymentActions`), so action fetching only happens once the WebView has submitted the Information Capture data to the backend. The form URL accepts optional query parameters — append them to `selectedOption.collectData.url` before loading, preserving existing query parameters: - `prefill` — base64url-encoded JSON of known user fields. Keys must match the `required` fields from `collectData.schema` (e.g. `fullName`, `dob`, `pobAddress`). - `theme` — `light` or `dark`, to match your wallet's color mode. - `themeVariables` — a base64url string exported from the [WalletConnect Pay Dashboard](https://dashboard.walletconnect.com) that overrides design tokens (font, font size, some colors, button/input border radius). Append it verbatim. ```typescript function buildFormUrl(baseUrl, options = {}) { const params = []; if (options.prefill && Object.keys(options.prefill).length > 0) { // base64url: URL-safe, no padding const prefill = btoa(JSON.stringify(options.prefill)) .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); params.push(`prefill=${prefill}`); } if (options.theme) params.push(`theme=${options.theme}`); if (options.themeVariables) params.push(`themeVariables=${options.themeVariables}`); if (params.length === 0) return baseUrl; const separator = baseUrl.includes("?") ? "&" : "?"; return `${baseUrl}${separator}${params.join("&")}`; } ``` Install `react-native-webview`: ```bash npm install react-native-webview@13.16.0 ``` ```tsx import React, { useCallback } from "react"; import { WebView, WebViewMessageEvent } from "react-native-webview"; import { Linking, View, ActivityIndicator } from "react-native"; interface PayDataCollectionWebViewProps { url: string; onComplete: () => void; onError: (error: string) => void; } function PayDataCollectionWebView({ url, onComplete, onError, }: PayDataCollectionWebViewProps) { const handleMessage = useCallback( (event: WebViewMessageEvent) => { try { const data = JSON.parse(event.nativeEvent.data); switch (data.type) { case "IC_COMPLETE": onComplete(); break; case "IC_ERROR": onError(data.error || "Unknown error"); break; } } catch { // Ignore non-JSON messages } }, [onComplete, onError] ); const handleNavigationRequest = useCallback((request: { url: string }) => { if (!request.url.includes("pay.walletconnect.com")) { Linking.openURL(request.url); return false; } return true; }, []); return ( ( )} /> ); } ``` > **Important:** When using the WebView approach, do **not** pass `collectedData` to `confirmPayment()`. The WebView submits data directly to the backend. --- ## Expo Considerations [#expo-considerations] ### Development Build Required [#development-build-required] The Pay SDK uses native modules. Expo Go will NOT work. ```bash npx expo prebuild npx expo run:ios # or run:android ``` --- ## Troubleshooting [#troubleshooting] ### walletKit.pay is undefined [#walletkitpay-is-undefined] **Cause**: Native module not available. **Solutions**: 1. Verify `@walletconnect/react-native-compat` is installed 2. iOS: Run `cd ios && pod install --repo-update` 3. Android: Sync gradle and rebuild 4. For Expo: Ensure using development build, not Expo Go ### Payment Options Empty [#payment-options-empty] **Check**: 1. Accounts array format is correct: `['eip155:chainId:address']` 2. Payment link URL is valid with `pid` parameter 3. Wallet has supported chains configured ### Signing Fails [#signing-fails] **Check**: 1. Are you passing the raw JSON string? Try that first 2. If parsing: `EIP712Domain` is removed from types before signing 3. Params are parsed correctly (double-encoded JSON) 4. Wallet address matches account used in `getPaymentOptions` ### "Recovered address does not match from address" [#recovered-address-does-not-match-from-address] **Cause**: The signature was created with different data than the verifier expects. **Debug steps**: 1. **Try passing raw string first**: Use `parsedParams[1]` directly without parsing/reconstructing 2. **Check chainId format**: Domain may have hex string (`"0x2105"`) instead of number (`8453`) 3. **Check primaryType**: Ensure it's extracted from data, not guessed via `Object.keys(types)[0]` 4. **Check data format**: Does your signing API expect a JSON string or parsed object? **Quick fix**: Start with the simplest approach (pass raw `parsedParams[1]` string directly), only parse if your API specifically requires it. ### "Missing or invalid. pair() uri#relay-protocol" Error [#missing-or-invalid-pair-urirelay-protocol-error] **Cause**: Payment link was passed to `walletKit.pair()` instead of being handled as payment. **Solution**: Ensure `isPaymentLink(uri)` check happens BEFORE calling `pair()`. ### Payment Link Opens Browser Instead of Pay Modal [#payment-link-opens-browser-instead-of-pay-modal] **Cause**: Payment links are HTTPS URLs, and your URI handling may have a generic HTTP/HTTPS handler that opens a browser before checking for payment links. **Solution**: Move the `isPaymentLink(uri)` check BEFORE any HTTP/HTTPS URL handling in your QR scanner, deep link handler, and paste handler. --- ## File Checklist [#file-checklist] When implementation is complete, verify: **Modified Files:** - [ ] WalletKit exports (re-export `isPaymentLink`) - [ ] QR scanner handler (detect payment links BEFORE http/https handling) - [ ] URI paste handler (detect payment links BEFORE http/https handling) - [ ] Deep link handler (detect payment links) - [ ] Modal/navigation system (register payment modal/screen) **New Files:** - [ ] Payment modal/screen component - [ ] Payment sub-components (IntroView, ConfirmView, etc.) - [ ] Payment utility functions - [ ] Payment state reducer (if using reducer pattern) - [ ] WebView data collection component (using react-native-webview) **Native Build:** - [ ] iOS: `pod install` completed - [ ] Android: Gradle sync completed **Validation (after each step):** - [ ] No linting errors in modified files - [ ] No TypeScript errors - [ ] Code compiles successfully - [ ] Functionality works as expected --- ## Common Pitfalls [#common-pitfalls] ### 1. Double-Encoded JSON in Action Params [#1-double-encoded-json-in-action-params] ```typescript // WRONG const typedData = JSON.parse(action.walletRpc.params)[1]; // CORRECT - parse twice const parsedParams = JSON.parse(action.walletRpc.params); const typedDataString = parsedParams[1]; // This is still a JSON string ``` ### 2. Parsing When You Don't Need To [#2-parsing-when-you-dont-need-to] ```typescript // RISKY - parsing and reconstructing can introduce issues const typedData = JSON.parse(parsedParams[1]); const { domain, types, message, primaryType } = typedData; delete types.EIP712Domain; const signature = await sign({ data: { domain, types, message, primaryType }, from }); // SAFER - pass the original string if your API supports it const signature = await sign({ data: parsedParams[1], from: parsedParams[0] }); ``` **Always try the raw string approach first.** Only parse and transform if your wallet's signing API specifically requires it. ### 3. viem Requires primaryType [#3-viem-requires-primarytype] ```typescript // ethers.js - no primaryType needed await wallet._signTypedData(domain, types, message); // viem - MUST include primaryType const primaryType = Object.keys(types).find(k => k !== 'EIP712Domain'); await wallet.signTypedData({ domain, types, primaryType, message }); ``` ### 4. walletRpc May Be Undefined [#4-walletrpc-may-be-undefined] ```typescript for (const action of actions) { if (!action.walletRpc) continue; // Skip actions without walletRpc // ... process } ``` ### 5. QR Scanner Fires Multiple Times [#5-qr-scanner-fires-multiple-times] ```typescript const hasScanned = useRef(false); const onCodeScanned = (result) => { if (hasScanned.current) return; hasScanned.current = true; // Process... }; ``` ### 6. Payment Link Handled as Browser URL [#6-payment-link-handled-as-browser-url] ```typescript // WRONG ORDER - payment link opens browser if (isHttpUrl(uri)) { openBrowser(uri); } else if (isPaymentLink(uri)) { // Never reached for https://pay.walletconnect.com links! openPaymentModal(uri); } // CORRECT ORDER - check payment link first if (isPaymentLink(uri)) { openPaymentModal(uri); } else if (isHttpUrl(uri)) { openBrowser(uri); } ``` --- ## Testing [#testing] ### Test Payment Links [#test-payment-links] Create test payment links from the WalletConnect Pay dashboard using a test-mode API key: ``` https://pay.walletconnect.com/?pid= ``` ### Supported Chains [#supported-chains] Currently Base (chainId: 8453) is the primary test chain: ```typescript const accounts = [`eip155:8453:${walletAddress}`]; ``` # AI Integration Prompt - Swift (/payments/wallets/walletkit/ai-prompts/swift) Integration guide for iOS/Swift wallets that already have WalletKit integrated. --- ## Agent Guidance (For AI Assistants) [#agent-guidance-for-ai-assistants] ### Adaptation Principles [#adaptation-principles] 1. **WalletKit Required** - This guide assumes WalletKit is already configured. Pay is accessed via `WalletKit.instance.Pay.*`. 2. **Configuration Order Matters**: ```swift Networking.configure(projectId:) // FIRST WalletKit.configure(...) // SECOND - Pay auto-configured ``` 3. **CAIP-10 Format Required** - All accounts must be in `eip155:{chainId}:{address}` format. 4. **Result Order Critical** - The `data` array passed to `confirmPayment` must match the actions array order exactly. 5. **Travel Rule Conditional** - Only collect user data when `selectedOption.collectData` is non-nil. IC is per-option, not global. ### Code Adaptation Guidelines [#code-adaptation-guidelines] When adapting for a specific wallet: 1. **Replace Signing Logic** - Use the wallet's native EIP-712 signing implementation. 2. **Adapt UI Flow** - Match the wallet's existing design patterns and navigation. 3. **Account Discovery** - Use the wallet's account management to build CAIP-10 accounts. 4. **Error Handling** - Add wallet-specific error handling and user feedback. ### Common Patterns [#common-patterns] ```swift // Pattern: Check for payment link in QR scanner func handleScannedQR(_ content: String) { if WalletKit.isPaymentLink(content) { startPaymentFlow(paymentLink: content) } else if content.hasPrefix("wc:") { startPairingFlow(uri: content) } } // Pattern: Multi-chain accounts func getCAIP10Accounts(address: String) -> [String] { return [ "eip155:1:\(address)", // Ethereum "eip155:137:\(address)", // Polygon "eip155:8453:\(address)", // Base "eip155:42161:\(address)" // Arbitrum ] } ``` --- ## Prerequisites [#prerequisites] - iOS 13.0+ - Swift 5.7+ - WalletKit (reown-swift 2.4.0 or later) already integrated (ships YttriumWrapper 0.10.59; required for the `data` parameter in `confirmPayment`) - WalletConnect Cloud `PROJECT_ID` ([Get one](https://cloud.walletconnect.com)) ```swift // Package.swift dependencies: [ .package(url: "https://github.com/reown-com/reown-swift", from: "2.4.0") ] ``` --- ## Architecture Overview [#architecture-overview] ``` ┌─────────────────────────────────────────────────────────────────────────────┐ │ PAYMENT FLOW │ └─────────────────────────────────────────────────────────────────────────────┘ ┌──────────┐ ┌──────────┐ │ User │ │ Merchant │ │ Wallet │ │ POS │ └────┬─────┘ └────┬─────┘ │ │ │ 1. Scan QR / Open Deep Link │ │◀──────────────────────────────────────────────────────────────┤ │ │ │ 2. getPaymentOptions(paymentLink, accounts) │ │──────────────────────▶┌─────────────┐ │ │ │ Pay API │ │ │◀──────────────────────└─────────────┘ │ │ PaymentOptionsResponse │ │ │ │ 3. User selects payment option │ │ │ │ 4. Collect user data via WebView (if required) │ │ │ │ 5. getRequiredPaymentActions(paymentId, optionId) │ │──────────────────────▶┌─────────────┐ │ │◀──────────────────────│ Pay API │ │ │ Actions[] (walletRpc — method varies) │ │ └─────────────┘ │ │ │ │ 6. Sign typed data (wallet's EIP-712 signer) │ │ │ │ 7. confirmPayment(data) │ │──────────────────────▶┌─────────────┐ ┌────────────┐ │ │ │ Pay API │────▶│ Blockchain │ │ │◀──────────────────────└─────────────┘ └────────────┘ │ │ ConfirmPaymentResultResponse (status: succeeded) │ │ │ ▼ ▼ ┌──────────┐ ┌──────────┐ │ Payment │ │ Payment │ │ Complete │ │ Received │ └──────────┘ └──────────┘ ``` ### State Machine [#state-machine] ``` [Options] ──▶ [WebView Data Collection]* ──▶ [Confirmation] ──▶ [Confirming] ──▶ [Success] │ ▼ [Error] * WebView step - skip if selectedOption.collectData is nil ``` --- ## Step 1: Configure WalletKit [#step-1-configure-walletkit] **IMPORTANT**: Pay is auto-configured when you configure WalletKit. No separate Pay configuration needed. ```swift import ReownWalletKit func configureWalletKit() { // 1. Configure Networking with your project ID Networking.configure( groupIdentifier: "group.com.yourcompany.wallet", projectId: "YOUR_PROJECT_ID", socketFactory: DefaultSocketFactory() ) // 2. Configure WalletKit - Pay is automatically configured let metadata = AppMetadata( name: "Your Wallet", description: "A crypto wallet", url: "https://yourwallet.com", icons: ["https://yourwallet.com/icon.png"], redirect: try! AppMetadata.Redirect( native: "yourwallet://", universal: "https://yourwallet.com/wc", linkMode: true ) ) WalletKit.configure( metadata: metadata, crypto: DefaultCryptoProvider(), environment: .production, payLogging: true // Enable for debugging ) } ``` --- ## Step 2: Handle Deep Links [#step-2-handle-deep-links] ### Info.plist Configuration [#infoplist-configuration] ```xml CFBundleURLTypes CFBundleTypeRole Editor CFBundleURLSchemes yourwallet ``` ### SceneDelegate Implementation [#scenedelegate-implementation] ```swift import UIKit import ReownWalletKit final class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? // MARK: - Cold Start func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // ... window setup ... // Check for payment deep link on cold start if let urlContext = connectionOptions.urlContexts.first { if let paymentLink = extractPaymentLink(from: urlContext.url) { // Delay to ensure UI is ready DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in self?.handlePaymentLink(paymentLink) } } } } // MARK: - Warm Start func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { guard let url = URLContexts.first?.url else { return } if let paymentLink = extractPaymentLink(from: url) { handlePaymentLink(paymentLink) // For POS scan format, return early - no pairing needed if url.host == "walletconnectpay" { return } } // Continue with regular WalletConnect pairing if needed... } // MARK: - Payment Link Extraction /// Supports two formats: /// 1. WC URI format: yourwallet://?uri=wc:abc...&pay=pay_xyz /// 2. POS scan format: yourwallet://walletconnectpay?paymentId=pay_xyz private func extractPaymentLink(from url: URL) -> String? { guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false), let queryItems = components.queryItems else { return nil } // Format 1: WC URI with embedded pay param if let uriValue = queryItems.first(where: { $0.name == "uri" })?.value, WalletKit.isPaymentLink(uriValue) { return uriValue } // Format 2: POS scan format if url.host == "walletconnectpay", let paymentId = queryItems.first(where: { $0.name == "paymentId" })?.value { return "yourwallet://walletconnectpay?paymentId=\(paymentId)" } return nil } private func handlePaymentLink(_ paymentLink: String) { // Get wallet address and build CAIP-10 accounts let address = getWalletAddress() let accounts = [ "eip155:1:\(address)", "eip155:137:\(address)", "eip155:8453:\(address)" ] // Present your payment UI presentPaymentFlow(paymentLink: paymentLink, accounts: accounts) } } ``` --- ## Step 3: Detect Payment Links [#step-3-detect-payment-links] Use `WalletKit.isPaymentLink()` to detect payment links from QR codes or deep links. ```swift // Static method - can be called BEFORE WalletKit.configure() if WalletKit.isPaymentLink(scannedString) { handlePaymentFlow(paymentLink: scannedString) } // Instance method - after configure() if WalletKit.instance.Pay.isPaymentLink(scannedString) { handlePaymentFlow(paymentLink: scannedString) } ``` **Detection Patterns:** - `pay.` hosts (e.g., `pay.walletconnect.com`) - `pay=` parameter in WalletConnect URIs - `pay_` prefix in bare payment IDs --- ## Step 4: Get Payment Options [#step-4-get-payment-options] ```swift func loadPaymentOptions(paymentLink: String, walletAddress: String) async throws -> PaymentOptionsResponse { // Build CAIP-10 accounts for supported chains let accounts = [ "eip155:1:\(walletAddress)", // Ethereum "eip155:137:\(walletAddress)", // Polygon "eip155:8453:\(walletAddress)", // Base "eip155:42161:\(walletAddress)" // Arbitrum ] let response = try await WalletKit.instance.Pay.getPaymentOptions( paymentLink: paymentLink, accounts: accounts, includePaymentInfo: true ) // Display merchant info if let info = response.info { print("Merchant: \(info.merchant.name)") print("Amount: \(info.amount.display.assetSymbol) \(info.amount.value)") } // Check which options require data collection for option in response.options { if option.collectData != nil { print("Option \(option.id) requires info capture") } } return response } ``` **CAIP-10 Format**: `eip155:{chainId}:{address}` --- ## Step 5: Complete Payment Flow [#step-5-complete-payment-flow] ```swift func confirmPayment( paymentId: String, selectedOption: PaymentOption, response: PaymentOptionsResponse ) async throws { // 1. Collect data via WebView if required for selected option if let collectData = selectedOption.collectData, let url = collectData.url { // Show WebView and wait for IC_COMPLETE message. // The WebView submits data directly to the backend. try await showDataCollectionWebView(url: url) } // 2. Get required signing actions let actions = try await WalletKit.instance.Pay.getRequiredPaymentActions( paymentId: paymentId, optionId: selectedOption.id ) // 3. Sign each action using YOUR wallet's signer var data: [String] = [] for action in actions { let rpc = action.walletRpc // rpc.chainId - e.g., "eip155:8453" // rpc.method - e.g., "eth_signTypedData_v4", "eth_sendTransaction" // rpc.params - JSON-encoded parameters guard let paramsData = rpc.params.data(using: .utf8), let params = try JSONSerialization.jsonObject(with: paramsData) as? [Any] else { throw PaymentError.invalidParams } switch rpc.method { case "eth_signTypedData_v4": guard params.count >= 2, let typedDataJson = params[1] as? String else { throw PaymentError.invalidParams } let signature = try await yourWallet.signTypedData(typedDataJson) data.append(signature) case "eth_sendTransaction": guard let txParams = params[0] as? [String: Any] else { throw PaymentError.invalidParams } let txHash = try await yourWallet.sendTransaction(txParams) data.append(txHash) case "personal_sign": guard params.count >= 2, let message = params[0] as? String else { throw PaymentError.invalidParams } let signature = try await yourWallet.personalSign(message) data.append(signature) default: throw PaymentError.unsupportedMethod(rpc.method) } } // 4. Confirm payment let result = try await WalletKit.instance.Pay.confirmPayment( paymentId: paymentId, optionId: selectedOption.id, data: data, maxPollMs: 60000 ) switch result.status { case .succeeded: print("Payment successful!") case .processing: print("Payment processing...") case .failed: print("Payment failed") case .expired: print("Payment expired") case .requiresAction: print("Additional action required") } } ``` **CRITICAL**: Keep `data` in the same order as the actions array. Each element of `data` is either a plain string (a signature or transaction hash) or, for chains like Tron, a JSON-encoded object; WalletConnect Pay forwards each element verbatim to the gateway. See [Tron support](/payments/wallets/token-chain-support/tron-support) for the Tron payload. The `signatures:` overload of `confirmPayment` is deprecated in favor of `data:` and will be removed in a future major version. Existing integrations that pass `signatures:` keep working; the overload forwards its value to `data`. --- ## WebView Data Collection [#webview-data-collection] When `selectedOption.collectData.url` is present, display the URL in a `WKWebView`. The hosted form handles rendering, validation, and T&C acceptance. The form URL accepts optional query parameters — append them to `selectedOption.collectData.url` before loading, preserving existing query parameters: - `prefill` — base64url-encoded JSON of known user fields. Keys must match the `required` fields from `collectData.schema` (e.g. `fullName`, `dob`, `pobAddress`). - `theme` — `light` or `dark`, to match your wallet's color mode. - `themeVariables` — a base64url string exported from the [WalletConnect Pay Dashboard](https://dashboard.walletconnect.com) that overrides design tokens (font, font size, some colors, button/input border radius). Append it verbatim. ```swift func buildFormUrl( baseUrl: String, prefillData: [String: String] = [:], theme: String? = nil, // "light" or "dark" themeVariables: String? = nil // base64url string exported from the Pay Dashboard ) -> String { guard var components = URLComponents(string: baseUrl) else { return baseUrl } var queryItems = components.queryItems ?? [] if !prefillData.isEmpty, let jsonData = try? JSONSerialization.data(withJSONObject: prefillData) { // base64url: URL-safe, no padding let prefill = jsonData.base64EncodedString() .replacingOccurrences(of: "+", with: "-") .replacingOccurrences(of: "/", with: "_") .replacingOccurrences(of: "=", with: "") queryItems.append(URLQueryItem(name: "prefill", value: prefill)) } if let theme = theme { queryItems.append(URLQueryItem(name: "theme", value: theme)) } if let themeVariables = themeVariables { queryItems.append(URLQueryItem(name: "themeVariables", value: themeVariables)) } components.queryItems = queryItems return components.string ?? baseUrl } ``` ```swift import WebKit import SwiftUI struct PayDataCollectionWebView: UIViewRepresentable { let url: URL let onComplete: () -> Void let onError: (String) -> Void func makeCoordinator() -> Coordinator { Coordinator(onComplete: onComplete, onError: onError) } func makeUIView(context: Context) -> WKWebView { let config = WKWebViewConfiguration() config.userContentController.add( context.coordinator, name: "payDataCollectionComplete" ) let webView = WKWebView(frame: .zero, configuration: config) webView.navigationDelegate = context.coordinator webView.load(URLRequest(url: url)) return webView } func updateUIView(_ uiView: WKWebView, context: Context) {} class Coordinator: NSObject, WKScriptMessageHandler, WKNavigationDelegate { let onComplete: () -> Void let onError: (String) -> Void init(onComplete: @escaping () -> Void, onError: @escaping (String) -> Void) { self.onComplete = onComplete self.onError = onError } func userContentController( _ userContentController: WKUserContentController, didReceive message: WKScriptMessage ) { guard let body = message.body as? String, let data = body.data(using: .utf8), let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let type = json["type"] as? String else { return } DispatchQueue.main.async { switch type { case "IC_COMPLETE": self.onComplete() case "IC_ERROR": let error = json["error"] as? String ?? "Unknown error" self.onError(error) default: break } } } func webView( _ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void ) { guard let url = navigationAction.request.url else { decisionHandler(.allow) return } if let host = url.host, !host.contains("pay.walletconnect.com") { UIApplication.shared.open(url) decisionHandler(.cancel) return } decisionHandler(.allow) } } } ``` > **Important:** When using the WebView approach, do **not** pass `collectedData` to `confirmPayment()`. The WebView submits data directly to the backend. --- ## Core API Reference [#core-api-reference] ### Methods [#methods] ```swift // Check if string is a payment link (static - works before configure) WalletKit.isPaymentLink(_ string: String) -> Bool // Get available payment options WalletKit.instance.Pay.getPaymentOptions( paymentLink: String, accounts: [String], // CAIP-10 format includePaymentInfo: Bool = true ) async throws -> PaymentOptionsResponse // Get signing actions for selected option WalletKit.instance.Pay.getRequiredPaymentActions( paymentId: String, optionId: String ) async throws -> [Action] // Confirm payment with the wallet RPC results (plain strings or JSON-encoded objects, in action order) WalletKit.instance.Pay.confirmPayment( paymentId: String, optionId: String, data: [String], collectedData: [CollectDataFieldResult]? = nil, maxPollMs: Int64? = nil ) async throws -> ConfirmPaymentResultResponse // Deprecated: `signatures:` is an alias for `data:`; still compiles and forwards to `data` WalletKit.instance.Pay.confirmPayment( paymentId: String, optionId: String, signatures: [String], collectedData: [CollectDataFieldResult]? = nil, maxPollMs: Int64? = nil ) async throws -> ConfirmPaymentResultResponse ``` ### Types [#types] ```swift struct PaymentOptionsResponse { let paymentId: String let info: PaymentInfo? let options: [PaymentOption] let collectData: CollectDataAction? // nil if no travel rule let resultInfo: PaymentResultInfo? // present when payment already completed } struct PaymentResultInfo { let txId: String let optionAmount: PayAmount } struct PaymentInfo { let status: PaymentStatus let amount: PayAmount let expiresAt: Int64 let merchant: MerchantInfo } struct PaymentOption { let id: String let amount: PayAmount let etaS: Int64 let collectData: CollectDataAction? // Per-option data collection (nil if not required) } struct PayAmount { let unit: String let value: String let display: AmountDisplay } struct AmountDisplay { let assetSymbol: String let assetName: String let decimals: Int64 let iconUrl: String? let networkName: String? } struct Action { let walletRpc: WalletRpcAction } struct WalletRpcAction { let chainId: String // "eip155:8453" let method: String // e.g., "eth_signTypedData_v4", "eth_sendTransaction" let params: String // JSON: ["address", "typedDataJson"] } struct CollectDataAction { let url: String // WebView URL for data collection let schema: String? // JSON schema describing required fields } struct ConfirmPaymentResultResponse { let status: PaymentStatus let isFinal: Bool } enum PaymentStatus { case requiresAction case processing case succeeded case failed case expired } ``` --- ## Troubleshooting [#troubleshooting] ### Configuration Issues [#configuration-issues] | Symptom | Cause | Solution | |---------|-------|----------| | "You must call configure() before accessing instance" | WalletKit not configured | Call `Networking.configure()` then `WalletKit.configure()` at app launch | | Pay methods not available | Wrong import | Use `import ReownWalletKit` | ### Deep Link Issues [#deep-link-issues] | Symptom | Cause | Solution | |---------|-------|----------| | App not opening from links | URL scheme missing | Add `CFBundleURLSchemes` to Info.plist | | Payment link not detected | Format not recognized | Use `WalletKit.isPaymentLink()` | | Cold start link ignored | UI not ready | Add delay before handling | ### Payment Failures [#payment-failures] | Error | Meaning | Solution | |-------|---------|----------| | `paymentExpired` | Link expired | Merchant generates new link | | `routeExpired` | Route expired | Retry `getPaymentOptions` | | `invalidSignature` | Signature mismatch | Check `data` order matches actions | | `optionNotFound` | Stale option | Refresh options and reselect | ### Signing Issues [#signing-issues] | Symptom | Cause | Solution | |---------|-------|----------| | Invalid signature error | Wrong method | Check `action.walletRpc.method` and dispatch to the correct handler for each method | | Params parsing fails | Unexpected format | Parse as `["address", "typedDataJson"]` | --- ## File Checklist [#file-checklist] | File | Purpose | |------|---------| | `Info.plist` | URL scheme configuration | | `SceneDelegate.swift` | Deep link handling | | `PaymentPresenter.swift` | Payment flow logic | | `PaymentView.swift` | Payment UI | --- ## Common Pitfalls [#common-pitfalls] 1. **Forgetting CAIP-10 format** - Accounts must be `eip155:{chainId}:{address}`, not just addresses. 2. **Wrong result order** - The `data` array must match the actions array order exactly. 3. **Skipping WebView data collection** - Always check `selectedOption.collectData?.url` after the user selects an option and show the WebView before calling `getRequiredPaymentActions`. 4. **Not handling cold start** - Deep links on app launch need delayed handling. 5. **Not dispatching on RPC method** — Always check `action.walletRpc.method` and use the appropriate handler. For example, `eth_signTypedData_v4` requires EIP-712 signing, while `eth_sendTransaction` requires sending a transaction on-chain. 6. **Missing chains** - Provide accounts for all chains you support to maximize payment options. --- ## Testing [#testing] 1. **Enable Logging**: ```swift WalletKit.configure(..., payLogging: true) ``` 2. **Test Both Deep Link Formats**: - WC URI: `yourwallet://?uri=wc:abc...&pay=pay_xyz` - POS: `yourwallet://walletconnectpay?paymentId=pay_xyz` 3. **Test Cold vs Warm Start**: - Cold: Kill app, open deep link - Warm: App in background, open deep link --- ## Support [#support] - [GitHub Issues](https://github.com/reown-com/reown-swift/issues) - [WalletConnect Docs](https://docs.walletconnect.com) # WalletConnect Pay via WalletKit - Flutter (/payments/wallets/walletkit/flutter) This documentation covers integrating WalletConnect Pay through ReownWalletKit. This approach provides a unified API where Pay is automatically initialized alongside WalletKit, simplifying the integration for wallet developers. ## Sample Wallet [#sample-wallet] For a complete working example, check out our sample wallet implementation: } href="https://github.com/reown-com/reown_flutter/tree/develop/packages/reown_walletkit/example"> A reference Flutter wallet app demonstrating WalletConnect Pay via WalletKit. **Using AI for Integration?** If you're using an AI IDE or assistant to help with integration, you can provide it with our comprehensive [AI integration prompt](/payments/wallets/walletkit/ai-prompts/flutter) for better context and guidance. ## Requirements [#requirements] - Flutter 3.0+ - iOS 13.0+ - Android API 23+ - ReownWalletKit (`reown_walletkit`) 1.5.1 or later (bundles `walletconnect_pay` 1.1.0) ## Installation [#installation] Add `reown_walletkit` to your `pubspec.yaml`: ```yaml dependencies: reown_walletkit: ^1.5.1 ``` Then run: ```bash flutter pub get ``` WalletConnectPay is automatically included as a dependency of ReownWalletKit. Check the [pub.dev page](https://pub.dev/packages/reown_walletkit) for the latest version. ## Initialization [#initialization] The `WalletConnectPay` client is automatically initialized during `ReownWalletKit.init()`. No additional setup is required. ```dart import 'package:reown_walletkit/reown_walletkit.dart'; final walletKit = await ReownWalletKit.createInstance( projectId: 'YOUR_PROJECT_ID', metadata: PairingMetadata( name: 'My Wallet', description: 'My Wallet App', url: 'https://mywallet.com', icons: ['https://mywallet.com/icon.png'], ), ); ``` Access the `WalletConnectPay` client directly via `walletKit.pay`: ```dart final payClient = walletKit.pay; ``` ## Payment Link Detection [#payment-link-detection] Detect if a URI is a payment link before processing: ```dart if (walletKit.isPaymentLink(uri)) { // Handle as payment. See [Get Payment Options] section } else { // Handle as regular WalletConnect pairing await walletKit.pair(uri: Uri.parse(uri)); } ``` ## Payment Flow [#payment-flow] The payment flow consists of six main steps: **Detect Payment Link -> Get Options -> Collect Data (if required) -> Get Actions -> Sign Actions -> Confirm Payment** ```mermaid sequenceDiagram participant User participant Wallet participant WebView participant WalletKit as WalletKit.Pay participant Backend as WalletConnect Pay User->>Wallet: Scan QR / Open payment link Wallet->>WalletKit: isPaymentLink(uri) WalletKit-->>Wallet: true Wallet->>WalletKit: getPaymentOptions(request) WalletKit->>Backend: Fetch payment options Backend-->>WalletKit: Payment options + merchant info WalletKit-->>Wallet: PaymentOptionsResponse Wallet->>User: Display payment options User->>Wallet: Select payment option alt Data collection required Wallet->>WebView: Load collectDataAction.url in WebView WebView->>User: Display data collection form User->>WebView: Fill form & accept T&C WebView-->>Wallet: IC_COMPLETE message end Wallet->>WalletKit: getRequiredPaymentActions(request) WalletKit->>Backend: Get signing actions Backend-->>WalletKit: Required wallet RPC actions WalletKit-->>Wallet: List of actions to sign Wallet->>User: Request signature(s) User->>Wallet: Approve & sign Wallet->>WalletKit: confirmPayment(request) WalletKit->>Backend: Submit payment Backend-->>WalletKit: Payment status WalletKit-->>Wallet: ConfirmPaymentResponse Wallet->>User: Show result ``` ### Get Payment Options [#get-payment-options] Retrieve available payment options for a payment link: ```dart final response = await walletKit.getPaymentOptions( request: GetPaymentOptionsRequest( paymentLink: 'https://pay.walletconnect.com/pay_123', accounts: ['eip155:1:0x...', 'eip155:137:0x...'], // Wallet's CAIP-10 accounts includePaymentInfo: true, ), ); print('Payment ID: ${response.paymentId}'); print('Options available: ${response.options.length}'); if (response.info != null) { print('Amount: ${response.info!.amount.formatAmount()}'); print('Merchant: ${response.info!.merchant.name}'); } // Check which options require data collection (per-option) for (final option in response.options) { if (option.collectData != null) { print('Option ${option.id} requires info capture'); } } ``` ### Collect User Data (If Required) [#collect-user-data-if-required] After the user selects an option, check for `collectData` on it. If present, collect the data **before** fetching the required actions. ```dart if (selectedOption.collectData?.url != null) { // Use the "required" list from selectedOption.collectData.schema to determine which fields to prefill final prefillData = { 'fullName': 'John Doe', 'dob': '1990-01-15', 'pobAddress': '123 Main St, New York, NY 10001', }; // Encode prefill as base64url (no padding, consistent with the other SDKs) final prefillBase64 = base64Url.encode(utf8.encode(jsonEncode(prefillData))).replaceAll('=', ''); final uri = Uri.parse(selectedOption.collectData!.url); final webViewUrl = uri.replace( queryParameters: { ...uri.queryParameters, 'prefill': prefillBase64, // Optional appearance params (see "Form URL parameters"): 'theme': 'dark', // "light" | "dark" // themeVariables is a base64url string exported from the Pay Dashboard: // 'themeVariables': themeVariables, }, ).toString(); // Show WebView and wait for IC_COMPLETE message showDataCollectionWebView(webViewUrl); } ``` ### Get Required Actions [#get-required-actions] Get the required wallet actions for a selected payment option: ```dart final actions = await walletKit.getRequiredPaymentActions( request: GetRequiredPaymentActionsRequest( optionId: 'option-id', paymentId: 'payment-id', ), ); // Process each action (e.g., sign transactions) for (final action in actions) { final walletRpc = action.walletRpc; print('Chain ID: ${walletRpc.chainId}'); print('Method: ${walletRpc.method}'); // Dispatch based on walletRpc.method — see Sign Actions below } ``` ### Sign Actions [#sign-actions] Sign each action using your wallet's signing implementation, dispatching on the RPC method: ```dart // Sign each action based on its RPC method final data = []; for (final action in actions) { final rpc = action.walletRpc; switch (rpc.method) { case 'eth_signTypedData_v4': data.add(await signTypedData(rpc.chainId, rpc.params)); break; case 'eth_sendTransaction': data.add(await sendTransaction(rpc.chainId, rpc.params)); break; case 'personal_sign': data.add(await personalSign(rpc.chainId, rpc.params)); break; default: throw UnimplementedError('Unsupported RPC method: ${rpc.method}'); } } ``` Payment options may include multiple actions with different RPC methods. For example, a Permit2 payment where the user lacks sufficient allowance returns two actions: an `eth_sendTransaction` to approve the token allowance, followed by an `eth_signTypedData_v4` to sign the Permit2 transfer. Your wallet must check `action.walletRpc.method` and dispatch to the appropriate handler. For full implementation guidance, see [USDT support](/payments/wallets/token-chain-support/usdt-support). Keep `data` in the same order as the actions array. ### Confirm Payment [#confirm-payment] Confirm the payment with the wallet RPC results (`data`) collected in the previous step. Each element of `data` is either a plain `String` (a signature or transaction hash) or, for chains like Tron, a `Map` JSON object; the SDK forwards each element verbatim. See [Tron support](/payments/wallets/token-chain-support/tron-support) for the Tron payload. ```dart final confirmResponse = await walletKit.confirmPayment( request: ConfirmPaymentRequest( paymentId: 'payment-id', optionId: 'option-id', data: data, // Wallet RPC results from the Sign Actions step maxPollMs: 60000, // Maximum polling time in milliseconds ), ); print('Payment Status: ${confirmResponse.status}'); print('Is Final: ${confirmResponse.isFinal}'); ``` The `signatures` parameter is deprecated in favor of `data` and will be removed in a future major version. Existing integrations that pass `signatures` keep working; the SDK uses it as a fallback when `data` is null. When using the WebView data-collection approach, you do **not** pass `collectedData` to `confirmPayment`. The WebView submits the collected data directly to the backend during the earlier Collect User Data step. ## Data Collection Implementation [#data-collection-implementation] When `selectedOption.collectData.url` is present, display the URL in a WebView using `webview_flutter` (v4.10.0+). Add dependencies: ```yaml dependencies: webview_flutter: ^4.10.0 url_launcher: ^6.1.0 ``` ```dart import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:webview_flutter/webview_flutter.dart'; import 'package:url_launcher/url_launcher.dart'; class PayDataCollectionWebView extends StatefulWidget { final String url; final VoidCallback onComplete; final ValueChanged onError; const PayDataCollectionWebView({ super.key, required this.url, required this.onComplete, required this.onError, }); @override State createState() => _PayDataCollectionWebViewState(); } class _PayDataCollectionWebViewState extends State { late final WebViewController _controller; bool _isLoading = true; @override void initState() { super.initState(); _controller = WebViewController() ..setJavaScriptMode(JavaScriptMode.unrestricted) ..setNavigationDelegate(NavigationDelegate( onPageFinished: (_) => setState(() => _isLoading = false), onNavigationRequest: (request) { if (!request.url.contains('pay.walletconnect.com')) { launchUrl(Uri.parse(request.url), mode: LaunchMode.externalApplication); return NavigationDecision.prevent; } return NavigationDecision.navigate; }, )) ..addJavaScriptChannel( 'ReactNativeWebView', onMessageReceived: (message) { try { final data = jsonDecode(message.message) as Map; switch (data['type']) { case 'IC_COMPLETE': widget.onComplete(); break; case 'IC_ERROR': widget.onError(data['error'] ?? 'Unknown error'); break; } } catch (_) {} }, ) ..loadRequest(Uri.parse(widget.url)); } @override Widget build(BuildContext context) { return Stack( children: [ WebViewWidget(controller: _controller), if (_isLoading) const Center(child: CircularProgressIndicator()), ], ); } } ``` ## Complete Example [#complete-example] Here's a complete example of processing a payment: ```dart import 'package:reown_walletkit/reown_walletkit.dart'; class PaymentService { final ReownWalletKit walletKit; PaymentService(this.walletKit); /// Process a payment from a payment link (e.g., after scanning QR code) Future processPayment(String paymentLink) async { try { // Step 1: Get payment options final accounts = await getWalletAccounts(); // Your wallet accounts final optionsResponse = await walletKit.getPaymentOptions( request: GetPaymentOptionsRequest( paymentLink: paymentLink, accounts: accounts, includePaymentInfo: true, ), ); if (optionsResponse.options.isEmpty) { throw Exception('No payment options available'); } // Step 2: Select payment option (or let user choose) PaymentOption selectedOption = optionsResponse.options.first; final paymentId = optionsResponse.paymentId; final optionId = selectedOption.id; // Step 3: Collect data via WebView if required for selected option. // This must happen BEFORE fetching the required payment actions — // the backend rejects the actions request with 400 "IC data required" // for options needing Information Capture if data wasn't collected first. // The WebView submits the data directly to the backend, so it is NOT // passed to confirmPayment later. if (selectedOption.collectData?.url != null) { await showDataCollectionWebView(selectedOption.collectData!.url); } // Step 4: Get required payment actions (if not already in the option) List actions = selectedOption.actions; if (actions.isEmpty) { actions = await walletKit.getRequiredPaymentActions( request: GetRequiredPaymentActionsRequest( optionId: optionId, paymentId: paymentId, ), ); } // Step 5: Execute wallet actions and collect the results final data = []; for (final action in actions) { // Dispatch based on action.walletRpc.method: // 'eth_signTypedData_v4' -> sign EIP-712 typed data // 'eth_sendTransaction' -> send transaction (e.g., token approval) // 'personal_sign' -> personal message signing data.add(await signAction(action.walletRpc)); } // Step 6: Confirm payment ConfirmPaymentResponse confirmResponse = await walletKit.confirmPayment( request: ConfirmPaymentRequest( paymentId: paymentId, optionId: optionId, data: data, maxPollMs: 60000, // Maximum polling time in milliseconds ), ); // Step 7: Poll until final status (if needed) while (!confirmResponse.isFinal && confirmResponse.pollInMs != null) { await Future.delayed(Duration(milliseconds: confirmResponse.pollInMs!)); confirmResponse = await walletKit.confirmPayment( request: ConfirmPaymentRequest( paymentId: paymentId, optionId: optionId, data: data, maxPollMs: 60000, ), ); } // Handle final payment status switch (confirmResponse.status) { case PaymentStatus.succeeded: print('Payment succeeded!'); break; case PaymentStatus.failed: throw Exception('Payment failed'); case PaymentStatus.expired: throw Exception('Payment expired'); case PaymentStatus.cancelled: throw Exception('Payment cancelled'); case PaymentStatus.requires_action: throw Exception('Payment requires additional action'); case PaymentStatus.processing: // Should not happen if isFinal is true break; } } catch (e) { print('Payment error: $e'); rethrow; } } Future> getWalletAccounts() async { // Return your wallet's CAIP-10 formatted accounts // Example: ['eip155:1:0x1234...', 'eip155:137:0x5678...'] return []; } } ``` ## API Reference [#api-reference] **ReownWalletKit Pay Methods** | Method | Description | |--------|-------------| | `isPaymentLink(String uri)` | Check if URI is a payment link | | `getPaymentOptions({required GetPaymentOptionsRequest request})` | Get available payment options | | `getRequiredPaymentActions({required GetRequiredPaymentActionsRequest request})` | Get actions requiring signatures | | `confirmPayment({required ConfirmPaymentRequest request})` | Confirm and finalize payment | | `pay` | Access the underlying WalletConnectPay instance | **Models** **GetPaymentOptionsRequest** ```dart GetPaymentOptionsRequest({ required String paymentLink, required List accounts, @Default(false) bool includePaymentInfo, }) ``` **PaymentOptionsResponse** ```dart PaymentOptionsResponse({ required String paymentId, PaymentInfo? info, required List options, CollectDataAction? collectData, PaymentResultInfo? resultInfo, // Transaction result details (present when payment already completed) }) ``` **PaymentResultInfo** ```dart class PaymentResultInfo { final String txId; // Transaction ID final PayAmount optionAmount; // Token amount details } ``` **PaymentInfo** ```dart PaymentInfo({ required PaymentStatus status, required PayAmount amount, required int expiresAt, required MerchantInfo merchant, BuyerInfo? buyer, }) ``` **PaymentOption** ```dart PaymentOption({ required String id, required String account, required PayAmount amount, @JsonKey(name: 'etaS') required int etaSeconds, required List actions, CollectDataAction? collectData, // Per-option data collection (null if not required) }) ``` **ConfirmPaymentRequest** ```dart ConfirmPaymentRequest({ required String paymentId, required String optionId, List? data, // Wallet RPC results in action order: Strings or Map JSON objects @Default([]) List signatures, // Deprecated alias for `data`, still accepted as fallback when data is null int? maxPollMs, }) ``` **ConfirmPaymentResponse** ```dart ConfirmPaymentResponse({ required PaymentStatus status, required bool isFinal, int? pollInMs, PaymentResultInfo? info, // Transaction result details (present on success) }) ``` **PaymentStatus** ```dart enum PaymentStatus { requires_action, processing, succeeded, failed, expired, cancelled, } ``` **CollectDataAction** ```dart class CollectDataAction { final String url; // WebView URL for data collection final String? schema; // JSON schema describing required fields } ``` ## Error Handling [#error-handling] The SDK throws specific exception types for different error scenarios. All errors extend the abstract `PayError` class, which itself extends `PlatformException`: ```dart abstract class PayError extends PlatformException { PayError({ required super.code, required super.message, required super.details, required super.stacktrace, }); } ``` | Exception | Description | |-----------|-------------| | `PayInitializeError` | Initialization failures | | `GetPaymentOptionsError` | Errors when fetching payment options | | `GetRequiredActionsError` | Errors when getting required actions | | `ConfirmPaymentError` | Errors when confirming payment | All errors include: - `code`: Error code - `message`: Error message - `details`: Additional error details - `stacktrace`: Stack trace **Example Error Handling** ```dart try { final response = await walletKit.getPaymentOptions(request: request); } on GetPaymentOptionsError catch (e) { print('Error code: ${e.code}'); print('Error message: ${e.message}'); } on PayError catch (e) { // Catch any Pay-related error print('Pay error: ${e.message}'); } catch (e) { print('Unexpected error: $e'); } ``` ## Best Practices [#best-practices] 1. **Use WalletKit Integration**: If your wallet already uses WalletKit, prefer this approach for automatic configuration 2. **Use `isPaymentLink()` for Detection**: Use the utility method instead of manual URL parsing for reliable payment link detection 3. **Account Format**: Always use CAIP-10 format for accounts: `eip155:{chainId}:{address}` 4. **Multiple Chains**: Provide accounts for all supported chains to maximize payment options 5. **Result Order**: Keep `data` in the same order as the actions array 6. **Error Handling**: Always handle errors gracefully and show appropriate user feedback 7. **Loading States**: Show loading indicators during API calls and signing operations 8. **Expiration**: Check `paymentInfo.expiresAt` and warn users if time is running low 9. **User Data**: Only collect data when `collectData` is present in the response and you don't already have the required user data. If you already have the required data, you can submit this without collecting from the user. You must make sure the user accepts WalletConnect Terms and Conditions and Privacy Policy before submitting user information to WalletConnect. 10. **WebView Data Collection**: When `selectedOption.collectData.url` is present, display the URL in a WebView using `webview_flutter` rather than building native forms. The WebView handles form rendering, validation, and T&C acceptance. # WalletConnect Pay via WalletKit - Kotlin (/payments/wallets/walletkit/kotlin) This documentation covers integrating WalletConnect Pay through WalletKit. This approach provides a unified API where Pay is automatically initialized alongside WalletKit, simplifying the integration for wallet developers. ## Sample Wallet [#sample-wallet] For a complete working example, check out our sample wallet implementation: } href="https://github.com/reown-com/reown-kotlin/tree/develop/sample/wallet"> A reference Android wallet app demonstrating WalletConnect Pay via WalletKit. **Using AI for Integration?** If you're using an AI IDE or assistant to help with integration, you can provide it with our comprehensive [AI integration prompt](/payments/wallets/walletkit/ai-prompts/kotlin) for better context and guidance. ## Requirements [#requirements] - **Min SDK**: 23 (Android 6.0) - **WalletKit**: 1.9.0+ (`com.reown:walletkit`) - **WalletConnect Pay**: 1.3.0+ (`com.walletconnect:pay`, bundled with WalletKit; ships yttrium-wcpay 0.10.60). Required for the `data` parameter in `confirmPayment`. ## Installation [#installation] First, add the required repositories to your project's `settings.gradle.kts` or root `build.gradle.kts`: ```kotlin allprojects { repositories { mavenCentral() maven { url = uri("https://jitpack.io") } } } ``` Then add WalletKit to your app's `build.gradle.kts` using the BOM (Bill of Materials): ```kotlin releaseImplementation(platform("com.reown:android-bom:$BOM_VERSION")) releaseImplementation("com.reown:android-core") releaseImplementation("com.reown:walletkit") ``` WalletConnectPay is automatically included as a dependency of WalletKit. Check the [GitHub releases](https://github.com/reown-com/reown-kotlin/releases) for the latest BOM version. ## Initialization [#initialization] WalletConnectPay is automatically initialized when you initialize WalletKit. No additional setup is required. ```kotlin import com.reown.android.Core import com.reown.android.CoreClient import com.reown.walletkit.client.WalletKit import com.reown.walletkit.client.Wallet // First, initialize CoreClient in your Application class val projectId = "" // Get Project ID at https://dashboard.walletconnect.com/ val appMetaData = Core.Model.AppMetaData( name = "Wallet Name", description = "Wallet Description", url = "Wallet URL", icons = listOf(/* list of icon url strings */), redirect = "kotlin-wallet-wc:/request" // Custom Redirect URI ) CoreClient.initialize( projectId = projectId, application = this, metaData = appMetaData, ) // Then initialize WalletKit val initParams = Wallet.Params.Init(core = CoreClient) WalletKit.initialize(initParams) { error -> // Error will be thrown if there's an issue during initialization } ``` The Pay SDK is initialized internally with: - `wcpId` from your WalletConnect Project ID - `packageName` from your application context For more details on WalletKit initialization, see the [WalletKit Usage documentation](/wallets/android/usage#initialization). ## Payment Link Detection [#payment-link-detection] Use `WalletKit.Pay.isPaymentLink()` to determine if a scanned URI is a payment link or a standard WalletConnect pairing URI: ```kotlin fun handleScannedUri(uri: String, accounts: List) { if (WalletKit.Pay.isPaymentLink(uri)) { // Handle as payment - call getPaymentOptions WalletKit.Pay.getPaymentOptions(uri, accounts) } else { // Handle as WalletConnect pairing WalletKit.pair(Wallet.Params.Pair(uri)) } } ``` ## Payment Flow [#payment-flow] The payment flow consists of six main steps: **Detect Payment Link -> Get Options -> Collect Data (if required) -> Get Actions -> Sign Actions -> Confirm Payment** ```mermaid sequenceDiagram participant User participant Wallet participant WalletKit as WalletKit.Pay participant Backend as WalletConnect Pay participant WebView User->>Wallet: Scan QR / Open payment link Wallet->>WalletKit: isPaymentLink(uri) WalletKit-->>Wallet: true Wallet->>WalletKit: getPaymentOptions(link, accounts) WalletKit->>Backend: Fetch payment options Backend-->>WalletKit: Payment options + merchant info WalletKit-->>Wallet: PaymentOptionsResponse Wallet->>User: Display payment options User->>Wallet: Select payment option alt Selected option requires data collection Wallet->>WebView: Load selectedOption.collectData.url WebView->>User: Display data collection form User->>WebView: Fill form & accept T&C WebView-->>Wallet: IC_COMPLETE message end Wallet->>WalletKit: getRequiredPaymentActions(params) WalletKit->>Backend: Get signing actions Backend-->>WalletKit: Required wallet RPC actions WalletKit-->>Wallet: List of actions to sign Wallet->>User: Request signature(s) User->>Wallet: Approve & sign Wallet->>WalletKit: confirmPayment(params) WalletKit->>Backend: Submit payment Backend-->>WalletKit: Payment status WalletKit-->>Wallet: ConfirmPaymentResponse Wallet->>User: Show result ``` ### Get Payment Options [#get-payment-options] Retrieve available payment options for a payment link: ```kotlin import com.reown.walletkit.client.WalletKit import com.reown.walletkit.client.Wallet viewModelScope.launch { val result = WalletKit.Pay.getPaymentOptions( paymentLink = "https://pay.walletconnect.com/pay_xxx", accounts = listOf( "eip155:1:0xYourAddress", // Ethereum "eip155:8453:0xYourAddress", // Base "eip155:10:0xYourAddress", // Optimism "eip155:137:0xYourAddress", // Polygon "eip155:42161:0xYourAddress" // Arbitrum ) ) result.onSuccess { response -> // Payment metadata val paymentId = response.paymentId val paymentInfo = response.info // Merchant info, amount, expiry // Available payment options val options = response.options options.forEach { option -> println("Option: ${option.id}") println("Amount: ${option.amount.value} ${option.amount.unit}") println("Account: ${option.account}") println("Requires IC: ${option.collectData != null}") } }.onFailure { error -> handleError(error) } } ``` ### Collect User Data (If Required) [#collect-user-data-if-required] After the user selects an option, check for `collectData` on it. If present, collect the data **before** fetching the required actions. ```kotlin // Check per-option data collection requirement after user selects an option selectedOption.collectData?.let { collectAction -> val url = collectAction.url if (url != null) { // Build prefill URL with known user data // Use the "required" list from collectAction.schema to determine which fields to prefill val prefillJson = JSONObject().apply { put("fullName", "John Doe") put("dob", "1990-01-15") put("pobAddress", "123 Main St, New York, NY 10001") }.toString() // Encode prefill as base64url (URL-safe, no padding) val prefillBase64 = Base64.encodeToString( prefillJson.toByteArray(), Base64.NO_WRAP or Base64.URL_SAFE or Base64.NO_PADDING ) val webViewUrl = Uri.parse(url).buildUpon() .appendQueryParameter("prefill", prefillBase64) // Optional appearance params (see "Form URL parameters"): .appendQueryParameter("theme", "dark") // "light" | "dark" // themeVariables is a base64url string exported from the Pay Dashboard: // .appendQueryParameter("themeVariables", themeVariables) .build().toString() // Show WebView for this specific option and wait for IC_COMPLETE message showWebView(webViewUrl) } } ``` ### Get Required Actions [#get-required-actions] Get the wallet RPC actions needed to complete the payment. Make sure any required data collection has already completed before calling this: ```kotlin val actionsResult = WalletKit.Pay.getRequiredPaymentActions( Wallet.Params.RequiredPaymentActions( paymentId = paymentId, optionId = selectedOption.id ) ) actionsResult.onSuccess { actions -> actions.forEach { action -> when (action) { is Wallet.Model.RequiredAction.WalletRpc -> { val rpcAction = action.action // rpcAction.chainId - e.g., "eip155:8453" // rpcAction.method - e.g., "eth_signTypedData_v4" or "personal_sign" // rpcAction.params - JSON string with signing parameters } } } }.onFailure { error -> handleError(error) } ``` ### Sign Actions [#sign-actions] Sign each required action using your wallet's signing implementation: ```kotlin val data = actions.map { action -> when (action) { is Wallet.Model.RequiredAction.WalletRpc -> { val rpc = action.action when (rpc.method) { "eth_signTypedData_v4" -> signTypedDataV4(rpc.params) "personal_sign" -> personalSign(rpc.params) "eth_sendTransaction" -> sendTransaction(rpc.params) else -> throw UnsupportedOperationException("Unsupported: ${rpc.method}") } } } } ``` #### Signing eth_signTypedData_v4 [#signing-eth_signtypeddata_v4] ```kotlin import org.json.JSONArray import org.web3j.crypto.ECKeyPair import org.web3j.crypto.Sign import org.web3j.crypto.StructuredDataEncoder fun signTypedDataV4(params: String): String { // params is a JSON array: [address, typedData] val paramsArray = JSONArray(params) val requestedAddress = paramsArray.getString(0) val typedData = paramsArray.getString(1) // Use StructuredDataEncoder for proper EIP-712 hashing val encoder = StructuredDataEncoder(typedData) val hash = encoder.hashStructuredData() val keyPair = ECKeyPair.create(privateKeyBytes) val signatureData = Sign.signMessage(hash, keyPair, false) val rHex = signatureData.r.bytesToHex() val sHex = signatureData.s.bytesToHex() val v = signatureData.v[0].toInt() and 0xff val vHex = v.toString(16).padStart(2, '0') return "0x$rHex$sHex$vHex".lowercase() } ``` Payment options may include multiple actions with different RPC methods. For example, a Permit2 payment where the user lacks sufficient allowance returns two actions: an `eth_sendTransaction` to approve the token allowance, followed by an `eth_signTypedData_v4` to sign the Permit2 transfer. Your wallet must check `action.action.method` (or `rpc.method` if you assign the action payload to a local variable) and dispatch to the appropriate handler. For full implementation guidance, see [USDT support](/payments/wallets/token-chain-support/usdt-support). Keep `data` in the same order as the actions array. ### Confirm Payment [#confirm-payment] Submit the wallet RPC results (`data`) and finalize the payment. Each element of `data` is either a plain string (a signature or transaction hash) or, for chains like Tron, a JSON object encoded as a string; WalletConnect Pay forwards each element verbatim to the gateway. See [Tron support](/payments/wallets/token-chain-support/tron-support) for the Tron payload. ```kotlin val confirmResult = WalletKit.Pay.confirmPayment( Wallet.Params.ConfirmPayment( paymentId = paymentId, optionId = selectedOption.id, data = data ) ) confirmResult.onSuccess { response -> when (response.status) { Wallet.Model.PaymentStatus.SUCCEEDED -> { // Payment completed successfully } Wallet.Model.PaymentStatus.PROCESSING -> { // Payment is being processed } Wallet.Model.PaymentStatus.FAILED -> { // Payment failed } Wallet.Model.PaymentStatus.EXPIRED -> { // Payment expired } Wallet.Model.PaymentStatus.REQUIRES_ACTION -> { // Additional action required } Wallet.Model.PaymentStatus.CANCELLED -> { // Payment cancelled by user } } }.onFailure { error -> handleError(error) } ``` The `signatures` parameter is deprecated in favor of `data` and will be removed in a future major version. Existing integrations that pass `signatures` keep working; the SDK uses it as a fallback when `data` is omitted. ## Data Collection Implementation [#data-collection-implementation] When `selectedOption.collectData.url` is present, display the URL in a WebView. The WebView handles form rendering, validation, and T&C acceptance. ```kotlin import android.webkit.JavascriptInterface import android.webkit.WebView import android.webkit.WebViewClient import android.webkit.WebResourceRequest import android.content.Intent import android.net.Uri import android.util.Base64 import androidx.compose.runtime.Composable import androidx.compose.ui.viewinterop.AndroidView import org.json.JSONObject @Composable fun PayDataCollectionWebView( url: String, onComplete: () -> Unit, onError: (String) -> Unit ) { AndroidView(factory = { context -> WebView(context).apply { settings.javaScriptEnabled = true settings.domStorageEnabled = true settings.allowFileAccess = false addJavascriptInterface( object { @JavascriptInterface fun onDataCollectionComplete(json: String) { val message = JSONObject(json) when (message.optString("type")) { "IC_COMPLETE" -> onComplete() "IC_ERROR" -> onError( message.optString("error", "Unknown error") ) } } }, "AndroidWallet" ) webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading( view: WebView?, request: WebResourceRequest? ): Boolean { val requestUrl = request?.url?.toString() ?: return false if (!requestUrl.contains("pay.walletconnect.com")) { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(requestUrl))) return true } return false } } loadUrl(url) } }) } ``` ## Complete Example [#complete-example] Here's a complete implementation example: ```kotlin import com.reown.walletkit.client.WalletKit import com.reown.walletkit.client.Wallet import kotlinx.coroutines.launch class PaymentViewModel : ViewModel() { fun handleScannedUri(uri: String) { if (WalletKit.Pay.isPaymentLink(uri)) { processPayment(uri) } else { // Handle as WalletConnect pairing WalletKit.pair(Wallet.Params.Pair(uri)) } } fun processPayment(paymentLink: String) { viewModelScope.launch { val walletAddress = "0xYourAddress" // Step 1: Get payment options val optionsResult = WalletKit.Pay.getPaymentOptions( paymentLink = paymentLink, accounts = listOf( "eip155:1:$walletAddress", "eip155:8453:$walletAddress", "eip155:10:$walletAddress" ) ) optionsResult.onSuccess { response -> val paymentId = response.paymentId val selectedOption = response.options.first() // Step 2: Collect data via WebView if required for selected option. // IC must happen BEFORE fetching the required actions — the WebView // submits the data directly to the backend. selectedOption.collectData?.url?.let { webViewUrl -> showDataCollectionWebView(webViewUrl) return@launch // Resume after WebView reports IC_COMPLETE } // Step 3: Get required actions val actionsResult = WalletKit.Pay.getRequiredPaymentActions( Wallet.Params.RequiredPaymentActions( paymentId = paymentId, optionId = selectedOption.id ) ) actionsResult.onSuccess { actions -> // Step 4: Sign actions val data = signActions(actions) // Step 5: Confirm payment val confirmResult = WalletKit.Pay.confirmPayment( Wallet.Params.ConfirmPayment( paymentId = paymentId, optionId = selectedOption.id, data = data ) ) confirmResult.onSuccess { confirmation -> handlePaymentStatus(confirmation.status) }.onFailure { error -> handleError(error) } }.onFailure { error -> handleError(error) } }.onFailure { error -> handleError(error) } } } private suspend fun signActions( actions: List ): List { return actions.map { action -> when (action) { is Wallet.Model.RequiredAction.WalletRpc -> { signWithWallet(action.action) } } } } private fun handlePaymentStatus(status: Wallet.Model.PaymentStatus) { when (status) { Wallet.Model.PaymentStatus.SUCCEEDED -> showSuccess() Wallet.Model.PaymentStatus.PROCESSING -> showProcessing() Wallet.Model.PaymentStatus.FAILED -> showFailure() Wallet.Model.PaymentStatus.EXPIRED -> showExpired() Wallet.Model.PaymentStatus.REQUIRES_ACTION -> { /* Handle */ } Wallet.Model.PaymentStatus.CANCELLED -> showCancelled() } } } ``` ## API Reference [#api-reference] **WalletKit.Pay** The payment operations object within WalletKit. **Methods** | Method | Description | |--------|-------------| | `isPaymentLink(uri: String): Boolean` | Check if URI is a payment link | | `getPaymentOptions(paymentLink, accounts)` | Get available payment options | | `getRequiredPaymentActions(params)` | Get actions requiring signatures | | `confirmPayment(params)` | Confirm and finalize payment | **Parameters** **Wallet.Params.RequiredPaymentActions** ```kotlin data class RequiredPaymentActions( val paymentId: String, val optionId: String ) ``` **Wallet.Params.ConfirmPayment** ```kotlin data class ConfirmPayment( val paymentId: String, val optionId: String, @Deprecated("Use data instead") val signatures: List = emptyList(), // Deprecated alias for data, still accepted val collectedData: List? = null, val data: List? = null // Wallet RPC results in action order: plain strings or JSON-encoded objects (e.g. Tron); falls back to signatures when null ) ``` ## Data Models [#data-models] **Wallet.Model.PaymentOptionsResponse** ```kotlin data class PaymentOptionsResponse( val paymentId: String, val info: PaymentInfo?, val options: List, val collectDataAction: CollectDataAction?, val resultInfo: PaymentResultInfo? // Transaction result details (present when payment already completed) ) data class PaymentResultInfo( val txId: String, // Transaction ID val optionAmount: PaymentAmount // Token amount details ) ``` **Wallet.Model.PaymentInfo** ```kotlin data class PaymentInfo( val status: PaymentStatus, val amount: PaymentAmount, val expiresAt: Long, val merchant: MerchantInfo ) data class MerchantInfo( val name: String, val iconUrl: String? ) ``` **Wallet.Model.PaymentOption** ```kotlin data class PaymentOption( val id: String, val amount: PaymentAmount, val account: String, val estimatedTxs: Int?, val collectData: CollectDataAction? // Per-option data collection (null if not required) ) ``` **Wallet.Model.PaymentAmount** ```kotlin data class PaymentAmount( val value: String, val unit: String, val display: PaymentAmountDisplay? ) data class PaymentAmountDisplay( val assetSymbol: String, val assetName: String, val decimals: Int, val iconUrl: String?, val networkName: String?, val networkIconUrl: String? ) ``` **Wallet.Model.WalletRpcAction** ```kotlin data class WalletRpcAction( val chainId: String, // CAIP-2 chain ID (e.g., "eip155:8453") val method: String, // RPC method (e.g., "eth_signTypedData_v4", "eth_sendTransaction") val params: String // JSON-encoded parameters ) ``` **Wallet.Model.CollectDataAction** ```kotlin data class CollectDataAction( val url: String, // WebView URL for data collection val schema: String? // JSON schema describing required fields ) ``` **Wallet.Model.ConfirmPaymentResponse** ```kotlin data class ConfirmPaymentResponse( val status: PaymentStatus, val isFinal: Boolean, val pollInMs: Long?, val info: PaymentResultInfo? // Transaction result details (present on success) ) ``` **Wallet.Model.PaymentStatus** | Status | Description | |--------|-------------| | `REQUIRES_ACTION` | Additional action needed | | `PROCESSING` | Payment in progress | | `SUCCEEDED` | Payment completed | | `FAILED` | Payment failed | | `EXPIRED` | Payment expired | | `CANCELLED` | Payment cancelled by user | ## Best Practices [#best-practices] 1. **Use WalletKit Integration**: If your wallet already uses WalletKit, prefer this approach for automatic configuration 2. **Use `isPaymentLink()` for Detection**: Use the utility method instead of manual URL parsing for reliable payment link detection 3. **Account Format**: Always use CAIP-10 format for accounts: `eip155:{chainId}:{address}` 4. **Multiple Chains**: Provide accounts for all supported chains to maximize payment options 5. **Result Order**: Keep `data` in the same order as the actions array 6. **Error Handling**: Always handle errors gracefully and show appropriate user feedback 7. **Loading States**: Show loading indicators during API calls and signing operations 8. **Expiration**: Check `paymentInfo.expiresAt` and warn users if time is running low 9. **User Data**: Only collect data when `collectData` is present on the selected payment option and you don't already have the required user data. If you already have the required data, you can submit this without collecting from the user. You must make sure the user accepts WalletConnect Terms and Conditions and Privacy Policy before submitting user information to WalletConnect. 10. **WebView Data Collection**: When `selectedOption.collectData?.url` is present, display the URL in a WebView rather than building native forms. The WebView handles form rendering, validation, and T&C acceptance. 11. **Per-Option Data Collection**: When displaying payment options, check each option's `collectData` field. Show a visual indicator (e.g., "Info required" badge) on options that require data collection. Only open the WebView when the user selects an option with `collectData` present — use the option's `collectData.url` which is already scoped to that option's account. # WalletConnect Pay via WalletKit - React Native (/payments/wallets/walletkit/react-native) This documentation covers integrating WalletConnect Pay through WalletKit for React Native wallets. This approach provides a unified API where Pay is built into WalletKit, simplifying the integration for wallet developers. ## Sample Wallet [#sample-wallet] For a complete working example, check out our sample wallet implementation: } href="https://github.com/reown-com/react-native-examples/tree/main/wallets/rn_cli_wallet"> A reference React Native wallet app demonstrating WalletConnect Pay via WalletKit. **Using AI for Integration?** If you're using an AI IDE or assistant to help with integration, you can provide it with our comprehensive [AI integration prompt](/payments/wallets/walletkit/ai-prompts/react-native) for better context and guidance. ## Requirements [#requirements] - Node.js 16+ - WalletKit (`@reown/walletkit`) 1.6.0 or later - `@walletconnect/pay` 1.1.0 or later (bundled with WalletKit) - `@walletconnect/react-native-compat` 2.25.0 or later (ships the native Yttrium module: yttrium-wcpay 0.10.60 on Android, YttriumWrapper 0.10.59 on iOS) ## Installation [#installation] Install WalletKit using npm or yarn: ```bash npm install @reown/walletkit @walletconnect/core ``` ```bash yarn add @reown/walletkit @walletconnect/core ``` WalletConnect Pay is automatically included as part of WalletKit. Check the [npm page](https://www.npmjs.com/package/@reown/walletkit) for the latest version. ## Initialization [#initialization] Initialize WalletKit as usual. Pay functionality is automatically available: ```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: [], }, payConfig: { appId: "", // or apiKey: "", } }); ``` ## Payment Link Detection [#payment-link-detection] Use `isPaymentLink` to determine if a scanned URI is a payment link or a standard WalletConnect pairing URI: ```javascript import { isPaymentLink } from "@reown/walletkit"; // Use when handling a scanned QR code or deep link if (isPaymentLink(uri)) { // Handle as payment (see below) await processPayment(uri); } else { // Handle as WalletConnect pairing await walletkit.pair({ uri }); } ``` ## Payment Flow [#payment-flow] The payment flow consists of six main steps: **Detect Payment Link -> Get Options -> Collect Data (if required) -> Get Actions -> Sign Actions -> Confirm Payment** ```mermaid sequenceDiagram participant User participant Wallet participant WalletKit as WalletKit.Pay participant Backend as WalletConnect Pay participant WebView User->>Wallet: Scan QR / Open payment link Wallet->>WalletKit: isPaymentLink(uri) WalletKit-->>Wallet: true Wallet->>WalletKit: pay.getPaymentOptions(params) WalletKit->>Backend: Fetch payment options Backend-->>WalletKit: Payment options + merchant info WalletKit-->>Wallet: PaymentOptionsResponse Wallet->>User: Display payment options User->>Wallet: Select payment option alt Data collection required Wallet->>WebView: Load collectDataAction.url in WebView WebView->>User: Display data collection form User->>WebView: Fill form & accept T&C WebView-->>Wallet: IC_COMPLETE message end Wallet->>WalletKit: pay.getRequiredPaymentActions(params) WalletKit->>Backend: Get signing actions Backend-->>WalletKit: Required wallet RPC actions WalletKit-->>Wallet: List of actions to sign Wallet->>User: Request signature(s) User->>Wallet: Approve & sign Wallet->>WalletKit: pay.confirmPayment(params) WalletKit->>Backend: Submit payment Backend-->>WalletKit: Payment status WalletKit-->>Wallet: ConfirmPaymentResponse Wallet->>User: Show result ``` ### Get Payment Options [#get-payment-options] Retrieve available payment options for a payment link: ```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) // Display merchant info if (options.info) { console.log("Merchant:", options.info.merchant.name); console.log("Amount:", options.info.amount.display.assetSymbol, options.info.amount.value); } // Check which options require data collection (per-option) for (const option of options.options) { if (option.collectData) { console.log(`Option ${option.id} requires info capture`); } } ``` ### Collect User Data (If Required) [#collect-user-data-if-required] After the user selects an option, check for `collectData` on it. If present, collect the data **before** fetching the required actions. ```javascript if (selectedOption.collectData?.url) { // Use the "required" list from selectedOption.collectData.schema to determine which fields to prefill const prefillData = { fullName: "John Doe", dob: "1990-01-15", pobAddress: "123 Main St, New York, NY 10001", }; // Encode prefill as base64url (URL-safe, no padding) const prefill = btoa(JSON.stringify(prefillData)) .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); // Optional appearance params (see "Form URL parameters"): // theme=light|dark — base color mode // themeVariables= — exported from the WalletConnect Pay Dashboard const themeVariables = ""; const query = `prefill=${prefill}&theme=dark&themeVariables=${themeVariables}`; const separator = selectedOption.collectData.url.includes("?") ? "&" : "?"; const webViewUrl = `${selectedOption.collectData.url}${separator}${query}`; // Show WebView and wait for IC_COMPLETE message showDataCollectionWebView(webViewUrl); } ``` ### Get Required Actions [#get-required-actions] Get the wallet RPC actions needed to complete the payment: ```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 } } for (const action of actions) { console.log("Chain:", action.walletRpc.chainId); console.log("Method:", action.walletRpc.method); console.log("Params:", action.walletRpc.params); } ``` ### Sign Actions [#sign-actions] Sign each required action using your wallet's signing implementation: ```javascript // Sign each action based on its RPC method const data = await Promise.all( actions.map(async (action) => { const { chainId, method, params } = action.walletRpc; const parsedParams = JSON.parse(params); switch (method) { case "eth_signTypedData_v4": return await wallet.signTypedData(chainId, parsedParams); case "eth_sendTransaction": return await wallet.sendTransaction(chainId, parsedParams[0]); case "personal_sign": return await wallet.personalSign(chainId, parsedParams); default: throw new Error(`Unsupported RPC method: ${method}`); } }) ); ``` Payment options may include multiple actions with different RPC methods. For example, a Permit2 payment where the user lacks sufficient allowance returns two actions: an `eth_sendTransaction` to approve the token allowance, followed by an `eth_signTypedData_v4` to sign the Permit2 transfer. Your wallet must check `action.walletRpc.method` and dispatch to the appropriate handler. For full implementation guidance, see [USDT support](/payments/wallets/token-chain-support/usdt-support). Keep `data` in the same order as the actions array. ### Confirm Payment [#confirm-payment] Submit the wallet RPC results (`data`) and collected data to complete the payment. Each element of `data` is either a plain string (a signature or transaction hash) or, for chains like Tron, a JSON object; the SDK forwards each element verbatim. See [Tron support](/payments/wallets/token-chain-support/tron-support) for the Tron payload. ```javascript const result = await walletkit.pay.confirmPayment({ paymentId: options.paymentId, optionId: options.options[0].id, data, collectedData, // Optional, if collectData was present }); // result.status - "succeeded" | "processing" | "failed" | "expired" // result.isFinal - whether the payment is complete // result.pollInMs - if not final, poll again after this delay if (result.status === "succeeded") { console.log("Payment successful!"); } else if (result.status === "processing") { console.log("Payment is processing..."); } else if (result.status === "failed") { console.log("Payment failed"); } ``` The `signatures` parameter is deprecated in favor of `data` and will be removed in a future major version. Existing integrations that pass `signatures` keep working; the SDK uses it as a fallback when `data` is omitted. ## Data Collection Implementation [#data-collection-implementation] When `selectedOption.collectData.url` is present, display the URL in a WebView using `react-native-webview`. Install the dependency: ```bash npm install react-native-webview@13.16.0 ``` ```jsx import React, { useCallback } from "react"; import { WebView } from "react-native-webview"; import { Linking, View, ActivityIndicator } from "react-native"; function PayDataCollectionWebView({ url, onComplete, onError }) { const handleMessage = useCallback( (event) => { try { const data = JSON.parse(event.nativeEvent.data); switch (data.type) { case "IC_COMPLETE": onComplete(); break; case "IC_ERROR": onError(data.error || "Unknown error"); break; } } catch { // Ignore non-JSON messages } }, [onComplete, onError] ); const handleNavigationRequest = useCallback((request) => { if (!request.url.includes("pay.walletconnect.com")) { Linking.openURL(request.url); return false; } return true; }, []); return ( ( )} /> ); } function buildFormUrl(baseUrl, options = {}) { const params = []; if (options.prefill && Object.keys(options.prefill).length > 0) { // base64url: URL-safe, no padding const prefill = btoa(JSON.stringify(options.prefill)) .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); params.push(`prefill=${prefill}`); } if (options.theme) params.push(`theme=${options.theme}`); if (options.themeVariables) params.push(`themeVariables=${options.themeVariables}`); if (params.length === 0) return baseUrl; const separator = baseUrl.includes("?") ? "&" : "?"; return `${baseUrl}${separator}${params.join("&")}`; } ``` ## Complete Example [#complete-example] Here's a complete implementation example: ```javascript import { Core } from "@walletconnect/core"; import { WalletKit, isPaymentLink } from "@reown/walletkit"; class PaymentManager { constructor() { this.walletkit = null; } async initialize(projectId) { const core = new Core({ projectId }); this.walletkit = await WalletKit.init({ core, metadata: { name: "My Wallet", description: "A crypto wallet", url: "https://mywallet.com", icons: ["https://mywallet.com/icon.png"], }, }); } async handleScannedUri(uri) { if (isPaymentLink(uri)) { await this.processPayment(uri); } else { await this.walletkit.pair({ uri }); } } async processPayment(paymentLink) { const walletAddress = "0xYourAddress"; try { // Step 1: Get payment options const options = await this.walletkit.pay.getPaymentOptions({ paymentLink, accounts: [ `eip155:1:${walletAddress}`, `eip155:8453:${walletAddress}`, `eip155:137:${walletAddress}`, ], includePaymentInfo: true, }); if (options.options.length === 0) { throw new Error("No payment options available"); } // Step 2: Let user select an option (simplified - use first option) const selectedOption = options.options[0]; // Step 3: Collect data via WebView if required — must happen BEFORE // fetching the required actions, otherwise the backend rejects the request if (selectedOption.collectData?.url) { await this.showDataCollectionWebView(selectedOption.collectData.url); } // Step 4: Get required actions const actions = await this.walletkit.pay.getRequiredPaymentActions({ paymentId: options.paymentId, optionId: selectedOption.id, }); // Step 5: Sign all actions const data = await Promise.all( actions.map((action) => this.signAction(action, walletAddress)) ); // Step 6: Confirm payment const result = await this.walletkit.pay.confirmPayment({ paymentId: options.paymentId, optionId: selectedOption.id, data, }); return result; } catch (error) { console.error("Payment failed:", error); throw error; } } async signAction(action, walletAddress) { const { chainId, method, params } = action.walletRpc; const parsedParams = JSON.parse(params); switch (method) { case "eth_signTypedData_v4": return await wallet.signTypedData(chainId, parsedParams); case "eth_sendTransaction": return await wallet.sendTransaction(chainId, parsedParams[0]); case "personal_sign": return await wallet.personalSign(chainId, parsedParams); default: throw new Error(`Unsupported RPC method: ${method}`); } } } ``` ## API Reference [#api-reference] **WalletKit Pay Methods** Pay methods are accessed via `walletkit.pay.*`. **Utility Functions** | Function | Description | |----------|-------------| | `isPaymentLink(uri: string): boolean` | Check if URI is a payment link (imported from `@reown/walletkit`) | **Instance Methods (walletkit.pay)** | Method | Description | |--------|-------------| | `getPaymentOptions(params)` | Fetch available payment options | | `getRequiredPaymentActions(params)` | Get signing actions for a payment option | | `confirmPayment(params)` | Confirm and execute the payment | **Parameters** **GetPaymentOptionsParams** ```typescript interface GetPaymentOptionsParams { paymentLink: string; // Payment link URL accounts: string[]; // CAIP-10 accounts includePaymentInfo?: boolean; // Include payment info in response } ``` **GetRequiredPaymentActionsParams** ```typescript interface GetRequiredPaymentActionsParams { paymentId: string; // Payment ID from getPaymentOptions optionId: string; // Selected option ID } ``` **ConfirmPaymentParams** ```typescript interface ConfirmPaymentParams { paymentId: string; // Payment ID optionId: string; // Selected option ID data: (string | object)[]; // Wallet RPC results in action order: strings or JSON objects (e.g. Tron) signatures?: string[]; // Deprecated alias for `data`, still accepted } ``` The SDK types `data` as `(string | Record | unknown[])[]`. A value typed with a TypeScript `interface` does not satisfy `Record`; declare it as a `type` alias or spread it into an object literal. **Response Types** **PaymentOptionsResponse** ```typescript interface PaymentOptionsResponse { paymentId: string; // Unique payment identifier info?: PaymentInfo; // Payment information options: PaymentOption[]; // Available payment options collectData?: CollectDataAction; // Data collection requirements resultInfo?: PaymentResultInfo; // Transaction result details (present when payment already completed) } interface PaymentResultInfo { txId: string; // Transaction ID optionAmount: PayAmount; // Token amount details } ``` **PaymentOption** ```typescript interface PaymentOption { id: string; // Option identifier amount: PayAmount; // Amount in this asset etaS: number; // Estimated time to complete (seconds) actions: Action[]; // Required signing actions collectData?: CollectDataAction; // Per-option data collection (undefined if not required) } ``` **Action** ```typescript interface Action { walletRpc: WalletRpcAction; } interface WalletRpcAction { chainId: string; // CAIP-2 chain ID (e.g., "eip155:8453") method: string; // RPC method (e.g., "eth_signTypedData_v4", "eth_sendTransaction") params: string; // JSON-encoded parameters } ``` **ConfirmPaymentResponse** ```typescript interface ConfirmPaymentResponse { status: PaymentStatus; // Payment status isFinal: boolean; // Whether status is final pollInMs?: number; // Suggested poll interval info?: PaymentResultInfo; // Transaction result details (present on success) } type PaymentStatus = | "requires_action" | "processing" | "succeeded" | "failed" | "expired" | "cancelled"; ``` **PaymentInfo** ```typescript interface PaymentInfo { status: PaymentStatus; // Current payment status amount: PayAmount; // Requested payment amount expiresAt: number; // Expiration timestamp (seconds since epoch) merchant: MerchantInfo; // Merchant details buyer?: BuyerInfo; // Buyer info if available } interface MerchantInfo { name: string; // Merchant display name iconUrl?: string; // Merchant logo URL } ``` **PayAmount** ```typescript interface PayAmount { unit: string; // Asset unit value: string; // Raw value in smallest unit display: AmountDisplay; // Human-readable display info } interface AmountDisplay { assetSymbol: string; // Token symbol (e.g., "USDC") assetName: string; // Token name (e.g., "USD Coin") decimals: number; // Token decimals iconUrl?: string; // Token icon URL networkName?: string; // Network name (e.g., "Base") } ``` **CollectDataAction** ```typescript interface CollectDataAction { /** WebView URL for data collection */ url: string; /** JSON schema describing required fields */ schema?: string; } ``` ## Error Handling [#error-handling] Handle errors gracefully in your payment flow: ```javascript try { const options = await walletkit.pay.getPaymentOptions({ paymentLink, accounts, }); } catch (error) { if (error.message.includes("payment not found")) { console.error("Payment not found"); } else if (error.message.includes("expired")) { console.error("Payment has expired"); } else { console.error("Payment error:", error); } } ``` ## Best Practices [#best-practices] 1. **Use WalletKit Integration**: If your wallet already uses WalletKit, prefer this approach for automatic configuration 2. **Use `isPaymentLink()` for Detection**: Use the utility function instead of manual URL parsing for reliable payment link detection 3. **Account Format**: Always use CAIP-10 format for accounts: `eip155:{chainId}:{address}` 4. **Multiple Chains**: Provide accounts for all supported chains to maximize payment options 5. **Result Order**: Keep `data` in the same order as the actions array 6. **Error Handling**: Always handle errors gracefully and show appropriate user feedback 7. **Loading States**: Show loading indicators during API calls and signing operations 8. **Expiration**: Check `paymentInfo.expiresAt` and warn users if time is running low 9. **User Data**: Only collect data when `collectData` is present in the response and you don't already have the required user data. If you already have the required data, you can submit this without collecting from the user. You must make sure the user accepts WalletConnect Terms and Conditions and Privacy Policy before submitting user information to WalletConnect. 10. **WebView Data Collection**: When `selectedOption.collectData.url` is present, display the URL in a WebView using `react-native-webview` rather than building native forms. The WebView handles form rendering, validation, and T&C acceptance. # WalletConnect Pay via WalletKit - Swift (/payments/wallets/walletkit/swift) This documentation covers integrating WalletConnect Pay through WalletKit. This approach provides a unified API where Pay is automatically configured when you configure WalletKit, simplifying the integration for wallet developers. ## Sample Wallet [#sample-wallet] For a complete working example, check out our sample wallet implementation: } href="https://github.com/reown-com/reown-swift/tree/develop/Example/WalletApp"> A reference iOS wallet app demonstrating WalletConnect Pay via WalletKit. **Using AI for Integration?** If you're using an AI IDE or assistant to help with integration, you can provide it with our comprehensive [AI integration prompt](/payments/wallets/walletkit/ai-prompts/swift) for better context and guidance. ## Requirements [#requirements] - iOS 13.0+ - Swift 5.7+ - Xcode 14.0+ - WalletKit (ReownWalletKit) 2.4.0 or later (ships YttriumWrapper 0.10.59). Required for the `data` parameter in `confirmPayment`. ## Installation [#installation] **Swift Package Manager** Add ReownWalletKit to your `Package.swift`: ```swift dependencies: [ .package(url: "https://github.com/reown-com/reown-swift", from: "2.4.0") ] ``` Then add `ReownWalletKit` to your target dependencies: ```swift .target( name: "YourApp", dependencies: ["ReownWalletKit"] ) ``` WalletConnectPay is automatically included as a dependency of WalletKit. Check the [GitHub releases](https://github.com/reown-com/reown-swift/releases) for the latest version. ## Initialization [#initialization] When using WalletKit, Pay is automatically configured using your project's `Networking.projectId`. No separate configuration is needed. ```swift import ReownWalletKit func application(_ application: UIApplication, didFinishLaunchingWithOptions...) { // Configure WalletKit - Pay is automatically configured WalletKit.configure( metadata: AppMetadata( name: "My Wallet", description: "A crypto wallet", url: "https://mywallet.com", icons: ["https://mywallet.com/icon.png"] ), crypto: DefaultCryptoProvider(), payLogging: true // Enable Pay debug logging ) } ``` ## Payment Link Detection [#payment-link-detection] Use the static `isPaymentLink` method to detect payment links before processing: ```swift // Static method - can be called before configure() if WalletKit.isPaymentLink(scannedString) { startPaymentFlow(paymentLink: scannedString) } // Or via the instance if WalletKit.instance.Pay.isPaymentLink(scannedString) { startPaymentFlow(paymentLink: scannedString) } ``` The `isPaymentLink` utility method detects WalletConnect Pay links by checking for: - `pay.` hosts (e.g., pay.walletconnect.com) - `pay=` parameter in WalletConnect URIs - `pay_` prefix in bare payment IDs Call it wherever your wallet receives a link — from a deep link or a scanned QR code: ```swift // Deep link opened from outside your app (SceneDelegate or AppDelegate) func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { guard let url = URLContexts.first?.url else { return } if WalletKit.isPaymentLink(url.absoluteString) { startPaymentFlow(paymentLink: url.absoluteString) } } // QR code payload func handleScannedQR(_ content: String) { if WalletKit.isPaymentLink(content) { startPaymentFlow(paymentLink: content) } } ``` ## Payment Flow [#payment-flow] The payment flow consists of six main steps: **Detect Payment Link -> Get Options -> Collect Data (if required) -> Get Actions -> Sign Actions -> Confirm Payment** ```mermaid sequenceDiagram participant User participant Wallet participant WalletKit as WalletKit.Pay participant Backend as WalletConnect Pay participant WebView User->>Wallet: Scan QR / Open payment link Wallet->>WalletKit: isPaymentLink(uri) WalletKit-->>Wallet: true Wallet->>WalletKit: getPaymentOptions(link, accounts) WalletKit->>Backend: Fetch payment options Backend-->>WalletKit: Payment options + merchant info WalletKit-->>Wallet: PaymentOptionsResponse Wallet->>User: Display payment options User->>Wallet: Select payment option alt Selected option requires data collection Wallet->>WebView: Load selectedOption.collectData.url WebView->>User: Display data collection form User->>WebView: Fill form & accept T&C WebView-->>Wallet: IC_COMPLETE message end Wallet->>WalletKit: getRequiredPaymentActions(paymentId, optionId) WalletKit->>Backend: Get signing actions Backend-->>WalletKit: Required wallet RPC actions WalletKit-->>Wallet: List of actions to sign Wallet->>User: Request signature(s) User->>Wallet: Approve & sign Wallet->>WalletKit: confirmPayment(params) WalletKit->>Backend: Submit payment Backend-->>WalletKit: Payment status WalletKit-->>Wallet: ConfirmPaymentResponse Wallet->>User: Show result ``` ### Get Payment Options [#get-payment-options] When a user scans a payment QR code or opens a payment link, fetch available payment options: ```swift // 1. Get payment options let options = try await WalletKit.instance.Pay.getPaymentOptions( paymentLink: paymentLink, accounts: ["eip155:1:\(address)", "eip155:137:\(address)"] ) // Display merchant info if let info = options.info { print("Merchant: \(info.merchant.name)") print("Amount: \(info.amount.display.assetSymbol) \(info.amount.value)") } // Show available payment options to user for option in options.options { print("Pay with \(option.amount.display.assetSymbol) on \(option.amount.display.networkName ?? "Unknown")") } // Check which options require data collection for option in options.options { if option.collectData != nil { print("Option \(option.id) requires info capture") } } ``` ### Collect User Data (If Required) [#collect-user-data-if-required] After the user selects an option, check for `collectData` on it. If present, collect the data **before** fetching the required actions. ```swift // Check per-option data collection requirement after user selects an option if let collectData = selectedOption.collectData, let url = collectData.url { // Use the "required" list from collectData.schema to determine which fields to prefill let prefillData: [String: String] = [ "fullName": "John Doe", "dob": "1990-01-15", "pobAddress": "123 Main St, New York, NY 10001" ] let jsonData = try JSONSerialization.data(withJSONObject: prefillData) // Encode prefill as base64url (URL-safe, no padding) let prefillBase64 = jsonData.base64EncodedString() .replacingOccurrences(of: "+", with: "-") .replacingOccurrences(of: "/", with: "_") .replacingOccurrences(of: "=", with: "") var components = URLComponents(string: url)! var queryItems = components.queryItems ?? [] queryItems.append(URLQueryItem(name: "prefill", value: prefillBase64)) // Optional appearance params (see "Form URL parameters"): queryItems.append(URLQueryItem(name: "theme", value: "dark")) // "light" | "dark" // themeVariables is a base64url string exported from the WalletConnect Pay Dashboard: // queryItems.append(URLQueryItem(name: "themeVariables", value: themeVariables)) components.queryItems = queryItems let webViewUrl = components.string! // Show WebView for this specific option and wait for IC_COMPLETE message showWebView(url: webViewUrl) } ``` ### Get Required Actions [#get-required-actions] After the user selects a payment option, get the signing actions: ```swift // 2. Get required actions for selected option let actions = try await WalletKit.instance.Pay.getRequiredPaymentActions( paymentId: options.paymentId, optionId: selectedOption.id ) ``` ### Sign Actions [#sign-actions] Each action contains a `walletRpc` describing the RPC call to execute. Your wallet must check the `method` field and dispatch accordingly — for example, a payment option may require an `eth_sendTransaction` to approve a token allowance followed by an `eth_signTypedData_v4` to sign Permit2 typed data: ```swift // 3. Sign each action based on its RPC method var data: [String] = [] for action in actions { let rpc = action.walletRpc let result: String switch rpc.method { case "eth_signTypedData_v4": result = try await signTypedData(rpc) case "eth_sendTransaction": result = try await sendTransaction(rpc) case "personal_sign": result = try await personalSign(rpc) default: throw PaymentError.unsupportedMethod(rpc.method) } data.append(result) } ``` Payment options may include multiple actions with different RPC methods. For example, a Permit2 payment where the user lacks sufficient allowance returns two actions: an `eth_sendTransaction` to approve the token allowance, followed by an `eth_signTypedData_v4` to sign the Permit2 transfer. Your wallet must check `action.walletRpc.method` and dispatch to the appropriate handler. For full implementation guidance, see [USDT support](/payments/wallets/token-chain-support/usdt-support). #### Signing Implementation [#signing-implementation] ```swift private func signAction( action: Action, walletAddress: String, signer: YourSignerProtocol ) async throws -> String { let rpc = action.walletRpc switch rpc.method { case "eth_signTypedData_v4": guard let paramsData = rpc.params.data(using: .utf8), let params = try JSONSerialization.jsonObject(with: paramsData) as? [Any], params.count >= 2, let typedDataJson = params[1] as? String else { throw PaymentError.invalidParams } return try await signer.signTypedData( data: typedDataJson, address: walletAddress ) case "eth_sendTransaction": return try await signer.sendTransaction( params: rpc.params, chainId: rpc.chainId ) case "personal_sign": return try await signer.personalSign( params: rpc.params, address: walletAddress ) default: throw PaymentError.unsupportedMethod(rpc.method) } } ``` Keep `data` in the same order as the actions array. ### Confirm Payment [#confirm-payment] Submit the wallet RPC results (`data`) and finalize the payment. Each element of `data` is either a plain string (a signature or transaction hash) or, for chains like Tron, a JSON-encoded object; WalletConnect Pay forwards each element verbatim to the gateway. See [Tron support](/payments/wallets/token-chain-support/tron-support) for the Tron payload. When using the WebView approach for data collection, the WebView submits the captured data directly to the backend, so you do **not** pass `collectedData` to `confirmPayment`. ```swift // 4. Confirm payment let result = try await WalletKit.instance.Pay.confirmPayment( paymentId: options.paymentId, optionId: selectedOption.id, data: data ) switch result.status { case .succeeded: print("Payment successful!") case .processing: print("Payment is being processed...") case .failed: print("Payment failed") case .expired: print("Payment expired") case .requiresAction: print("Additional action required") case .cancelled: print("Payment cancelled") } ``` The `signatures:` overload of `confirmPayment` is deprecated in favor of `data:` and will be removed in a future major version. Existing integrations that pass `signatures:` keep working; the overload forwards its value to `data`. ## Data Collection Implementation [#data-collection-implementation] When `selectedOption.collectData.url` is present, display the URL in a `WKWebView`. The WebView handles form rendering, validation, and T&C acceptance. ```swift import WebKit import SwiftUI struct PayDataCollectionWebView: UIViewRepresentable { let url: URL let onComplete: () -> Void let onError: (String) -> Void func makeCoordinator() -> Coordinator { Coordinator(onComplete: onComplete, onError: onError) } func makeUIView(context: Context) -> WKWebView { let config = WKWebViewConfiguration() config.userContentController.add( context.coordinator, name: "payDataCollectionComplete" ) let webView = WKWebView(frame: .zero, configuration: config) webView.navigationDelegate = context.coordinator webView.load(URLRequest(url: url)) return webView } func updateUIView(_ uiView: WKWebView, context: Context) {} class Coordinator: NSObject, WKScriptMessageHandler, WKNavigationDelegate { let onComplete: () -> Void let onError: (String) -> Void init(onComplete: @escaping () -> Void, onError: @escaping (String) -> Void) { self.onComplete = onComplete self.onError = onError } func userContentController( _ userContentController: WKUserContentController, didReceive message: WKScriptMessage ) { guard let body = message.body as? String, let data = body.data(using: .utf8), let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let type = json["type"] as? String else { return } DispatchQueue.main.async { switch type { case "IC_COMPLETE": self.onComplete() case "IC_ERROR": let error = json["error"] as? String ?? "Unknown error" self.onError(error) default: break } } } func webView( _ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void ) { guard let url = navigationAction.request.url else { decisionHandler(.allow) return } if let host = url.host, !host.contains("pay.walletconnect.com") { UIApplication.shared.open(url) decisionHandler(.cancel) return } decisionHandler(.allow) } } } ``` ## Complete Example [#complete-example] Here's a complete implementation using WalletKit: ```swift import ReownWalletKit class PaymentManager { func processPayment( paymentLink: String, walletAddress: String, signer: YourSignerProtocol ) async throws { // 1. Get payment options let accounts = [ "eip155:1:\(walletAddress)", "eip155:137:\(walletAddress)", "eip155:8453:\(walletAddress)" ] let optionsResponse = try await WalletKit.instance.Pay.getPaymentOptions( paymentLink: paymentLink, accounts: accounts ) guard !optionsResponse.options.isEmpty else { throw PaymentError.noOptionsAvailable } // 2. Let user select an option (simplified - use first option) let selectedOption = optionsResponse.options[0] // 3. Collect data via WebView if required (before fetching actions) if let collectData = selectedOption.collectData, let url = collectData.url { try await showDataCollectionWebView(url: url) } // 4. Get required actions let actions = try await WalletKit.instance.Pay.getRequiredPaymentActions( paymentId: optionsResponse.paymentId, optionId: selectedOption.id ) // 5. Sign all actions var data: [String] = [] for action in actions { let signature = try await signAction( action: action, walletAddress: walletAddress, signer: signer ) data.append(signature) } // 6. Confirm payment let result = try await WalletKit.instance.Pay.confirmPayment( paymentId: optionsResponse.paymentId, optionId: selectedOption.id, data: data ) switch result.status { case .succeeded: break // Success case .cancelled: throw PaymentError.paymentCancelled default: throw PaymentError.paymentFailed(result.status) } } private func signAction( action: Action, walletAddress: String, signer: YourSignerProtocol ) async throws -> String { let rpc = action.walletRpc switch rpc.method { case "eth_signTypedData_v4": guard let paramsData = rpc.params.data(using: .utf8), let params = try JSONSerialization.jsonObject(with: paramsData) as? [Any], params.count >= 2, let typedDataJson = params[1] as? String else { throw PaymentError.invalidParams } return try await signer.signTypedData( data: typedDataJson, address: walletAddress ) case "eth_sendTransaction": return try await signer.sendTransaction( params: rpc.params, chainId: rpc.chainId ) case "personal_sign": return try await signer.personalSign( params: rpc.params, address: walletAddress ) default: throw PaymentError.unsupportedMethod(rpc.method) } } } ``` ## API Reference [#api-reference] **WalletKit Integration** When using WalletKit, Pay methods are accessed via `WalletKit.instance.Pay.*`. **Static Methods** | Method | Description | |--------|-------------| | `WalletKit.isPaymentLink(_:)` | Check if a string is a payment link (can call before `configure()`) | **Instance Methods (WalletKit.instance.Pay)** | Method | Description | |--------|-------------| | `isPaymentLink(_:)` | Check if a string is a payment link | | `getPaymentOptions(paymentLink:accounts:includePaymentInfo:)` | Fetch available payment options | | `getRequiredPaymentActions(paymentId:optionId:)` | Get signing actions for a payment option | | `confirmPayment(paymentId:optionId:data:collectedData:maxPollMs:)` | Confirm and execute the payment. `data: [String]` holds the wallet RPC results in action order (plain strings or JSON-encoded objects) | | `confirmPayment(paymentId:optionId:signatures:collectedData:maxPollMs:)` | Deprecated alias for the `data:` overload; still compiles and forwards to `data` | **Data Types** **PaymentOptionsResponse** ```swift struct PaymentOptionsResponse { let paymentId: String // Unique payment identifier let info: PaymentInfo? // Merchant and amount details let options: [PaymentOption] // Available payment methods let collectData: CollectDataAction? // Required user data fields (travel rule) let resultInfo: PaymentResultInfo? // Transaction result details (present when payment already completed) } struct PaymentResultInfo { let txId: String // Transaction ID let optionAmount: PayAmount // Token amount details } ``` **PaymentInfo** ```swift struct PaymentInfo { let status: PaymentStatus // Current payment status let amount: PayAmount // Requested payment amount let expiresAt: Int64 // Expiration timestamp let merchant: MerchantInfo // Merchant details let buyer: BuyerInfo? // Buyer info if available } ``` **PaymentOption** ```swift struct PaymentOption { let id: String // Option identifier let amount: PayAmount // Amount in this asset let etaS: Int64 // Estimated time to complete (seconds) let actions: [Action] // Required signing actions let collectData: CollectDataAction? // Per-option data collection (nil if not required) } ``` **PayAmount** ```swift struct PayAmount { let unit: String // Asset unit (e.g., "USDC") let value: String // Raw value in smallest unit let display: AmountDisplay // Human-readable display info } struct AmountDisplay { let assetSymbol: String // Token symbol (e.g., "USDC") let assetName: String // Token name (e.g., "USD Coin") let decimals: Int64 // Token decimals let iconUrl: String? // Token icon URL let networkName: String? // Network name (e.g., "Base") } ``` **Action & WalletRpcAction** ```swift struct Action { let walletRpc: WalletRpcAction // RPC call to sign } struct WalletRpcAction { let chainId: String // Chain ID (e.g., "eip155:8453") let method: String // RPC method (e.g., "eth_signTypedData_v4", "eth_sendTransaction") let params: String // JSON-encoded parameters } ``` **CollectDataAction** ```swift struct CollectDataAction { let url: String // WebView URL for data collection let schema: String? // JSON schema describing required fields } ``` **ConfirmPaymentResultResponse** ```swift struct ConfirmPaymentResultResponse { let status: PaymentStatus // Final payment status let isFinal: Bool // Whether status is final let pollInMs: Int64? // Suggested poll interval let info: PaymentResultInfo? // Transaction result details (present on success) } ``` **PaymentStatus** ```swift enum PaymentStatus { case requiresAction // Additional action needed case processing // Payment in progress case succeeded // Payment completed case failed // Payment failed case expired // Payment expired case cancelled // Payment cancelled by user } ``` ## Error Handling [#error-handling] The SDK throws specific error types for different failure scenarios: **GetPaymentOptionsError** | Error | Description | |-------|-------------| | `.paymentNotFound` | Payment ID doesn't exist | | `.paymentExpired` | Payment has expired | | `.invalidRequest` | Invalid request parameters | | `.invalidAccount` | Invalid account format | | `.complianceFailed` | Compliance check failed | | `.http` | Network error | | `.internalError` | Server error | **GetPaymentRequestError** | Error | Description | |-------|-------------| | `.optionNotFound` | Selected option doesn't exist | | `.paymentNotFound` | Payment ID doesn't exist | | `.invalidAccount` | Invalid account format | | `.http` | Network error | **ConfirmPaymentError** | Error | Description | |-------|-------------| | `.paymentNotFound` | Payment ID doesn't exist | | `.paymentExpired` | Payment has expired | | `.invalidOption` | Invalid option ID | | `.invalidSignature` | Signature verification failed | | `.routeExpired` | Payment route expired | | `.http` | Network error | ## Best Practices [#best-practices] 1. **Use WalletKit Integration**: If your wallet already uses WalletKit, prefer the `WalletKit.instance.Pay.*` access pattern for automatic configuration 2. **Use `isPaymentLink()` for Detection**: Use the utility method instead of manual URL parsing for reliable payment link detection 3. **Account Format**: Always use CAIP-10 format for accounts: `eip155:{chainId}:{address}` 4. **Multiple Chains**: Provide accounts for all supported chains to maximize payment options 5. **Result Order**: Keep `data` in the same order as the actions array 6. **Error Handling**: Always handle errors gracefully and show appropriate user feedback 7. **Loading States**: Show loading indicators during API calls and signing operations 8. **Expiration**: Check `paymentInfo.expiresAt` and warn users if time is running low 9. **User Data**: Only collect data when `collectData` is present on the selected payment option and you don't already have the required user data. If you already have the required data, you can submit this without collecting from the user. You must make sure the user accepts WalletConnect Terms and Conditions and Privacy Policy before submitting user information to WalletConnect. 10. **WebView Data Collection**: When `selectedOption.collectData?.url` is present, display the URL in a WKWebView rather than building native forms. The WebView handles form rendering, validation, and T&C acceptance. 11. **Per-Option Data Collection**: When displaying payment options, check each option's `collectData` field. Show a visual indicator (e.g., "Info required" badge) on options that require data collection. Only open the WebView when the user selects an option with `collectData` present — use the option's `collectData.url` which is already scoped to that option's account. # WalletConnect Pay via WalletKit - Web/Node.js (/payments/wallets/walletkit/web) This documentation covers integrating WalletConnect Pay through WalletKit for Web/Node.js wallets. This approach provides a unified API where Pay is built into WalletKit, simplifying the integration for wallet developers. ## Sample Wallet [#sample-wallet] For a complete working example, check out our sample wallet implementation: } href="https://github.com/reown-com/web-examples/tree/main/advanced/wallets/react-wallet-v2"> A reference web wallet app demonstrating WalletConnect Pay via WalletKit. **Using AI for Integration?** If you're using an AI IDE or assistant to help with integration, you can provide it with our comprehensive [AI integration prompt](/payments/wallets/walletkit/ai-prompts/react-native) for better context and guidance. The React Native prompt applies to Web/Node.js as well since they share the same JavaScript SDK. ## Requirements [#requirements] - Node.js 16+ - WalletKit (`@reown/walletkit`) 1.6.0 or later - `@walletconnect/pay` 1.1.0 or later (bundled with WalletKit; ships the WASM Yttrium module 0.10.59) ## Installation [#installation] Install WalletKit using npm or yarn: ```bash npm install @reown/walletkit @walletconnect/core ``` ```bash yarn add @reown/walletkit @walletconnect/core ``` WalletConnect Pay is automatically included as part of WalletKit. Check the [npm page](https://www.npmjs.com/package/@reown/walletkit) for the latest version. ## Initialization [#initialization] Initialize WalletKit as usual. Pay functionality is automatically available: ```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: [], }, payConfig: { appId: "", // or apiKey: "", } }); ``` ## Payment Link Detection [#payment-link-detection] Use `isPaymentLink` to determine if a scanned URI is a payment link or a standard WalletConnect pairing URI: ```javascript import { isPaymentLink } from "@reown/walletkit"; // Use when handling a scanned QR code or deep link if (isPaymentLink(uri)) { // Handle as payment (see below) await processPayment(uri); } else { // Handle as WalletConnect pairing await walletkit.pair({ uri }); } ``` ## Payment Flow [#payment-flow] The payment flow consists of six main steps: **Detect Payment Link -> Get Options -> Collect Data (if required) -> Get Actions -> Sign Actions -> Confirm Payment** ```mermaid sequenceDiagram participant User participant Wallet participant WalletKit as WalletKit.Pay participant Backend as WalletConnect Pay participant Iframe User->>Wallet: Scan QR / Open payment link Wallet->>WalletKit: isPaymentLink(uri) WalletKit-->>Wallet: true Wallet->>WalletKit: pay.getPaymentOptions(params) WalletKit->>Backend: Fetch payment options Backend-->>WalletKit: Payment options + merchant info WalletKit-->>Wallet: PaymentOptionsResponse Wallet->>User: Display payment options User->>Wallet: Select payment option alt Data collection required Wallet->>Iframe: Load collectDataAction.url in iframe Iframe->>User: Display data collection form User->>Iframe: Fill form & accept T&C Iframe-->>Wallet: IC_COMPLETE message via postMessage end Wallet->>WalletKit: pay.getRequiredPaymentActions(params) WalletKit->>Backend: Get signing actions Backend-->>WalletKit: Required wallet RPC actions WalletKit-->>Wallet: List of actions to sign Wallet->>User: Request signature(s) User->>Wallet: Approve & sign Wallet->>WalletKit: pay.confirmPayment(params) WalletKit->>Backend: Submit payment Backend-->>WalletKit: Payment status WalletKit-->>Wallet: ConfirmPaymentResponse Wallet->>User: Show result ``` ### Get Payment Options [#get-payment-options] Retrieve available payment options for a payment link: ```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) // Display merchant info if (options.info) { console.log("Merchant:", options.info.merchant.name); console.log("Amount:", options.info.amount.display.assetSymbol, options.info.amount.value); } // Check which options require data collection (per-option) for (const option of options.options) { if (option.collectData) { console.log(`Option ${option.id} requires info capture`); } } ``` ### Collect User Data (If Required) [#collect-user-data-if-required] After the user selects an option, check for `collectData` on it. If present, collect the data **before** fetching the required actions. ```javascript if (selectedOption.collectData?.url) { // Use the "required" list from selectedOption.collectData.schema to determine which fields to prefill const prefillData = { fullName: "John Doe", dob: "1990-01-15", pobAddress: "123 Main St, New York, NY 10001", }; // Encode prefill as base64url (URL-safe, no padding) const prefill = btoa(JSON.stringify(prefillData)) .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); // Optional appearance params (see "Form URL parameters"): // theme=light|dark — base color mode // themeVariables= — exported from the WalletConnect Pay Dashboard const themeVariables = ""; const query = `prefill=${prefill}&theme=dark&themeVariables=${themeVariables}`; const separator = selectedOption.collectData.url.includes("?") ? "&" : "?"; const iframeUrl = `${selectedOption.collectData.url}${separator}${query}`; // Show data collection in an iframe or popup and wait for IC_COMPLETE message showDataCollectionView(iframeUrl); } ``` ### Iframe Message Types [#iframe-message-types] The iframe communicates with your wallet through `postMessage` events. The message payload is a JSON string with the following structure: | Message Type | Payload | Description | |-------------|---------|-------------| | `IC_COMPLETE` | `{ "type": "IC_COMPLETE", "success": true }` | User completed the form successfully. Proceed to payment confirmation. | | `IC_ERROR` | `{ "type": "IC_ERROR", "error": "..." }` | An error occurred. Display the error message and allow the user to retry. | ### Get Required Actions [#get-required-actions] Get the wallet RPC actions needed to complete the payment: ```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 } } for (const action of actions) { console.log("Chain:", action.walletRpc.chainId); console.log("Method:", action.walletRpc.method); console.log("Params:", action.walletRpc.params); } ``` ### Sign Actions [#sign-actions] Sign each required action using your wallet's signing implementation: ```javascript // Sign each action based on its RPC method const data = await Promise.all( actions.map(async (action) => { const { chainId, method, params } = action.walletRpc; const parsedParams = JSON.parse(params); switch (method) { case "eth_signTypedData_v4": return await wallet.signTypedData(chainId, parsedParams); case "eth_sendTransaction": return await wallet.sendTransaction(chainId, parsedParams[0]); case "personal_sign": return await wallet.personalSign(chainId, parsedParams); default: throw new Error(`Unsupported RPC method: ${method}`); } }) ); ``` Payment options may include multiple actions with different RPC methods. For example, a Permit2 payment where the user lacks sufficient allowance returns two actions: an `eth_sendTransaction` to approve the token allowance, followed by an `eth_signTypedData_v4` to sign the Permit2 transfer. Your wallet must check `action.walletRpc.method` and dispatch to the appropriate handler. For full implementation guidance, see [USDT support](/payments/wallets/token-chain-support/usdt-support). Keep `data` in the same order as the actions array. ### Confirm Payment [#confirm-payment] Submit the wallet RPC results (`data`) and collected data to complete the payment. Each element of `data` is either a plain string (a signature or transaction hash) or, for chains like Tron, a JSON object; the SDK forwards each element verbatim. See [Tron support](/payments/wallets/token-chain-support/tron-support) for the Tron payload. ```javascript const result = await walletkit.pay.confirmPayment({ paymentId: options.paymentId, optionId: options.options[0].id, data, collectedData, // Optional, if collectData was present }); // result.status - "succeeded" | "processing" | "failed" | "expired" // result.isFinal - whether the payment is complete // result.pollInMs - if not final, poll again after this delay if (result.status === "succeeded") { console.log("Payment successful!"); } else if (result.status === "processing") { console.log("Payment is processing..."); } else if (result.status === "failed") { console.log("Payment failed"); } ``` The `signatures` parameter is deprecated in favor of `data` and will be removed in a future major version. Existing integrations that pass `signatures` keep working; the SDK uses it as a fallback when `data` is omitted. ## Data Collection Implementation [#data-collection-implementation] When `selectedOption.collectData.url` is present, display the URL in an iframe or modal. Listen for `postMessage` events to handle completion: ```javascript function showDataCollectionView(url) { // Create a modal/overlay container const overlay = document.createElement("div"); overlay.style.cssText = "position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);display:flex;align-items:center;justify-content:center;z-index:9999;"; const iframe = document.createElement("iframe"); iframe.src = url; iframe.style.cssText = "width:450px;height:650px;border:none;border-radius:12px;"; overlay.appendChild(iframe); document.body.appendChild(overlay); return new Promise((resolve, reject) => { function handleMessage(event) { try { const data = typeof event.data === "string" ? JSON.parse(event.data) : event.data; if (data.type === "IC_COMPLETE") { cleanup(); resolve(); } else if (data.type === "IC_ERROR") { cleanup(); reject(new Error(data.error || "Unknown error")); } } catch { // Ignore non-JSON messages } } function cleanup() { window.removeEventListener("message", handleMessage); document.body.removeChild(overlay); } window.addEventListener("message", handleMessage); }); } function buildFormUrl(baseUrl, options = {}) { const params = []; if (options.prefill && Object.keys(options.prefill).length > 0) { // base64url: URL-safe, no padding const prefill = btoa(JSON.stringify(options.prefill)) .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); params.push(`prefill=${prefill}`); } if (options.theme) params.push(`theme=${options.theme}`); if (options.themeVariables) params.push(`themeVariables=${options.themeVariables}`); if (params.length === 0) return baseUrl; const separator = baseUrl.includes("?") ? "&" : "?"; return `${baseUrl}${separator}${params.join("&")}`; } ``` ## Complete Example [#complete-example] Here's a complete implementation example: ```javascript import { Core } from "@walletconnect/core"; import { WalletKit, isPaymentLink } from "@reown/walletkit"; class PaymentManager { constructor() { this.walletkit = null; } async initialize(projectId) { const core = new Core({ projectId }); this.walletkit = await WalletKit.init({ core, metadata: { name: "My Wallet", description: "A crypto wallet", url: "https://mywallet.com", icons: ["https://mywallet.com/icon.png"], }, }); } async handleScannedUri(uri) { if (isPaymentLink(uri)) { await this.processPayment(uri); } else { await this.walletkit.pair({ uri }); } } async processPayment(paymentLink) { const walletAddress = "0xYourAddress"; try { // Step 1: Get payment options const options = await this.walletkit.pay.getPaymentOptions({ paymentLink, accounts: [ `eip155:1:${walletAddress}`, `eip155:8453:${walletAddress}`, `eip155:137:${walletAddress}`, ], includePaymentInfo: true, }); if (options.options.length === 0) { throw new Error("No payment options available"); } // Step 2: Let user select an option (simplified - use first option) const selectedOption = options.options[0]; // Step 3: Collect data via iframe if required for selected option. // This must happen BEFORE fetching required actions, otherwise the // backend rejects the fetch for options that require info capture. if (selectedOption.collectData?.url) { await this.showDataCollectionView(selectedOption.collectData.url); } // Step 4: Get required actions const actions = await this.walletkit.pay.getRequiredPaymentActions({ paymentId: options.paymentId, optionId: selectedOption.id, }); // Step 5: Sign all actions const data = await Promise.all( actions.map((action) => this.signAction(action, walletAddress)) ); // Step 6: Confirm payment const result = await this.walletkit.pay.confirmPayment({ paymentId: options.paymentId, optionId: selectedOption.id, data, }); return result; } catch (error) { console.error("Payment failed:", error); throw error; } } async signAction(action, walletAddress) { const { chainId, method, params } = action.walletRpc; const parsedParams = JSON.parse(params); switch (method) { case "eth_signTypedData_v4": return await wallet.signTypedData(chainId, parsedParams); case "eth_sendTransaction": return await wallet.sendTransaction(chainId, parsedParams[0]); case "personal_sign": return await wallet.personalSign(chainId, parsedParams); default: throw new Error(`Unsupported RPC method: ${method}`); } } } ``` ## API Reference [#api-reference] **WalletKit Pay Methods** Pay methods are accessed via `walletkit.pay.*`. **Utility Functions** | Function | Description | |----------|-------------| | `isPaymentLink(uri: string): boolean` | Check if URI is a payment link (imported from `@reown/walletkit`) | **Instance Methods (walletkit.pay)** | Method | Description | |--------|-------------| | `getPaymentOptions(params)` | Fetch available payment options | | `getRequiredPaymentActions(params)` | Get signing actions for a payment option | | `confirmPayment(params)` | Confirm and execute the payment | **Parameters** **GetPaymentOptionsParams** ```typescript interface GetPaymentOptionsParams { paymentLink: string; // Payment link URL accounts: string[]; // CAIP-10 accounts includePaymentInfo?: boolean; // Include payment info in response } ``` **GetRequiredPaymentActionsParams** ```typescript interface GetRequiredPaymentActionsParams { paymentId: string; // Payment ID from getPaymentOptions optionId: string; // Selected option ID } ``` **ConfirmPaymentParams** ```typescript interface ConfirmPaymentParams { paymentId: string; // Payment ID optionId: string; // Selected option ID data: (string | object)[]; // Wallet RPC results in action order: strings or JSON objects (e.g. Tron) signatures?: string[]; // Deprecated alias for `data`, still accepted } ``` The SDK types `data` as `(string | Record | unknown[])[]`. A value typed with a TypeScript `interface` does not satisfy `Record`; declare it as a `type` alias or spread it into an object literal. **Response Types** **PaymentOptionsResponse** ```typescript interface PaymentOptionsResponse { paymentId: string; // Unique payment identifier info?: PaymentInfo; // Payment information options: PaymentOption[]; // Available payment options collectData?: CollectDataAction; // Data collection requirements resultInfo?: PaymentResultInfo; // Transaction result details (present when payment already completed) } interface PaymentResultInfo { txId: string; // Transaction ID optionAmount: PayAmount; // Token amount details } ``` **PaymentOption** ```typescript interface PaymentOption { id: string; // Option identifier amount: PayAmount; // Amount in this asset etaS: number; // Estimated time to complete (seconds) actions: Action[]; // Required signing actions collectData?: CollectDataAction; // Per-option data collection (undefined if not required) } ``` **Action** ```typescript interface Action { walletRpc: WalletRpcAction; } interface WalletRpcAction { chainId: string; // CAIP-2 chain ID (e.g., "eip155:8453") method: string; // RPC method (e.g., "eth_signTypedData_v4", "eth_sendTransaction") params: string; // JSON-encoded parameters } ``` **ConfirmPaymentResponse** ```typescript interface ConfirmPaymentResponse { status: PaymentStatus; // Payment status isFinal: boolean; // Whether status is final pollInMs?: number; // Suggested poll interval info?: PaymentResultInfo; // Transaction result details (present on success) } type PaymentStatus = | "requires_action" | "processing" | "succeeded" | "failed" | "expired" | "cancelled"; ``` **PaymentInfo** ```typescript interface PaymentInfo { status: PaymentStatus; // Current payment status amount: PayAmount; // Requested payment amount expiresAt: number; // Expiration timestamp (seconds since epoch) merchant: MerchantInfo; // Merchant details buyer?: BuyerInfo; // Buyer info if available } interface MerchantInfo { name: string; // Merchant display name iconUrl?: string; // Merchant logo URL } ``` **PayAmount** ```typescript interface PayAmount { unit: string; // Asset unit value: string; // Raw value in smallest unit display: AmountDisplay; // Human-readable display info } interface AmountDisplay { assetSymbol: string; // Token symbol (e.g., "USDC") assetName: string; // Token name (e.g., "USD Coin") decimals: number; // Token decimals iconUrl?: string; // Token icon URL networkName?: string; // Network name (e.g., "Base") } ``` **CollectDataAction** ```typescript interface CollectDataAction { /** URL for data collection (displayed in iframe) */ url: string; /** JSON schema describing required fields */ schema?: string; } ``` ## Error Handling [#error-handling] Handle errors gracefully in your payment flow: ```javascript try { const options = await walletkit.pay.getPaymentOptions({ paymentLink, accounts, }); } catch (error) { if (error.message.includes("payment not found")) { console.error("Payment not found"); } else if (error.message.includes("expired")) { console.error("Payment has expired"); } else { console.error("Payment error:", error); } } ``` ## Best Practices [#best-practices] 1. **Use WalletKit Integration**: If your wallet already uses WalletKit, prefer this approach for automatic configuration 2. **Use `isPaymentLink()` for Detection**: Use the utility function instead of manual URL parsing for reliable payment link detection 3. **Account Format**: Always use CAIP-10 format for accounts: `eip155:{chainId}:{address}` 4. **Multiple Chains**: Provide accounts for all supported chains to maximize payment options 5. **Result Order**: Keep `data` in the same order as the actions array 6. **Error Handling**: Always handle errors gracefully and show appropriate user feedback 7. **Loading States**: Show loading indicators during API calls and signing operations 8. **Expiration**: Check `paymentInfo.expiresAt` and warn users if time is running low 9. **User Data**: Only collect data when `collectData` is present in the response and you don't already have the required user data. If you already have the required data, you can submit this without collecting from the user. You must make sure the user accepts WalletConnect Terms and Conditions and Privacy Policy before submitting user information to WalletConnect. 10. **Data Collection**: When `selectedOption.collectData.url` is present, display the URL in an iframe or modal rather than building custom forms. The hosted form handles rendering, validation, and T&C acceptance. # Buyer Experience — WebView Integration (/payments/wallets/webview) Instead of redirecting users to an external browser, load the WalletConnect Pay checkout portal inside a native WebView. Supply two query parameters on the `gatewayUrl`, handle JavaScript bridge messages for the outcome, and intercept wallet deeplinks so the OS can route the user to their wallet app and back. The hosted UI handles wallet selection, payment option display, compliance data collection, and signing orchestration. Your app only needs to render a WebView, respond to the result, and verify it server-side. ## How It Works [#how-it-works] ```mermaid sequenceDiagram participant App as Your App participant Backend as Your Backend participant API as WalletConnect Pay API participant WV as WebView (checkout UI) participant Wallet as Wallet App App->>Backend: User initiates payment Backend->>API: POST /v1/merchant/payment API-->>Backend: { paymentId, gatewayUrl } Backend-->>App: gatewayUrl App->>App: Append returnUrl + preferUniversalLinks to gatewayUrl App->>WV: Load URL in WebView Note over WV: User selects payment option,
completes any data collection WV->>App: Navigation request — wallet deeplink (?uri=wc:…) App->>Wallet: Linking.openURL(walletDeeplink) Wallet-->>App: Returns via returnUrl deep link alt Payment succeeds WV-->>App: postMessage { type: "PAY_SUCCESS", message? } else Payment fails WV-->>App: postMessage { type: "PAY_FAILURE", error? } end App->>Backend: Verify payment status Backend->>API: GET /v1/payments/{paymentId}/status API-->>Backend: { status: "succeeded" } ``` ## Prerequisites [#prerequisites] - A `gatewayUrl` from the [Merchant API](/payments/ecommerce/integration) (`POST /v1/merchant/payment`) - Your app registered to handle its own deep link scheme (so wallets can return after signing) - JavaScript and DOM storage enabled in the WebView ## URL Construction [#url-construction] Start with the `gatewayUrl` the API returns and append the two WebView parameters. **Never construct the base URL manually.** ```typescript function buildPayUrl(gatewayUrl: string, appDeepLink: string): string { const url = new URL(gatewayUrl); // Required: the wallet returns here after signing url.searchParams.set('returnUrl', appDeepLink); // Required: open wallets via universal links instead of custom schemes url.searchParams.set('preferUniversalLinks', '1'); return url.toString(); } // Example const payUrl = buildPayUrl( 'https://pay.walletconnect.com/buy?pid=pay_01ABC', 'myapp://' // your app's registered deep link ); ``` | Parameter | Required | Description | |---|---|---| | `returnUrl` | **Yes** | Your app's native deep link (e.g. `myapp://`). The checkout passes this to wallets as the return destination so the OS routes the user back after signing. | | `preferUniversalLinks` | **Yes** | Set to `1`. Tells the checkout to open wallets via universal links (`https://`) rather than custom URL schemes when both are available — more reliable on iOS. | ## Bridge Messages [#bridge-messages] The checkout calls `window.ReactNativeWebView.postMessage(json)` with a JSON string payload. | `type` field | `success` field | Meaning | |---|---|---| | `PAY_SUCCESS` | `true` | Payment succeeded. Optionally contains `message` — a human-readable confirmation summary. | | `PAY_FAILURE` | `false` | Payment failed. Optionally contains `error` — a human-readable reason. | The checkout may send either the `type` field or the `success` boolean (or both). Treat `type === "PAY_SUCCESS"` **or** `success === true` as a success signal; `type === "PAY_FAILURE"` **or** `success === false` as failure. Always verify the final payment status server-side via `GET /v1/payments/{paymentId}/status` after receiving `PAY_SUCCESS`. Never rely solely on the bridge message to confirm a payment. ## Wallet Deeplink Interception [#wallet-deeplink-interception] The checkout opens the user's wallet by navigating to a URL that carries a `?uri=wc:…` query parameter. WebViews don't handle these natively, so **your app must intercept these navigations and forward them to the OS**. The checkout triggers this as a same-frame navigation, so intercepting navigation requests is all you need. Only forward URLs that carry a valid `wc:` URI — block any other non-`https:` navigation to prevent the page from driving the OS into arbitrary native schemes (`tel:`, `sms:`, `intent:`, etc.). ```typescript function isWalletDeeplink(url: string): boolean { try { const wcUri = new URL(url).searchParams.get('uri'); return !!wcUri && wcUri.startsWith('wc:'); } catch { return false; } } ``` ## Platform Examples [#platform-examples] Install the WebView package: ```bash npm install react-native-webview ``` ```tsx import React, {useCallback} from 'react'; import {Linking, StyleSheet} from 'react-native'; import {WebView, WebViewMessageEvent} from 'react-native-webview'; import type {ShouldStartLoadRequest} from 'react-native-webview/lib/WebViewTypes'; type PayMessage = { type?: 'PAY_SUCCESS' | 'PAY_FAILURE'; success?: boolean; error?: string; message?: string; }; function isWalletDeeplink(url: string): boolean { try { const wcUri = new URL(url).searchParams.get('uri'); return !!wcUri && wcUri.startsWith('wc:'); } catch { return false; } } function buildPayUrl(gatewayUrl: string, appDeepLink: string): string { const url = new URL(gatewayUrl); url.searchParams.set('returnUrl', appDeepLink); url.searchParams.set('preferUniversalLinks', '1'); return url.toString(); } interface PayWebViewProps { gatewayUrl: string; appDeepLink: string; onSuccess: (message?: string) => void; onFailure: (error?: string) => void; } export function PayWebView({gatewayUrl, appDeepLink, onSuccess, onFailure}: PayWebViewProps) { const url = buildPayUrl(gatewayUrl, appDeepLink); const onShouldStartLoadWithRequest = useCallback( (request: ShouldStartLoadRequest): boolean => { if (isWalletDeeplink(request.url)) { Linking.openURL(request.url).catch(console.warn); return false; } // Allow https (the checkout) and about:; block any other scheme so the // page can't drive the OS into arbitrary native schemes (tel:, sms:, …). try { const scheme = new URL(request.url).protocol; return scheme === 'https:' || scheme === 'about:'; } catch { return false; } }, [], ); const onMessage = useCallback( (event: WebViewMessageEvent) => { let msg: PayMessage; try { msg = JSON.parse(event.nativeEvent.data); } catch { return; } if (msg.type === 'PAY_SUCCESS' || msg.success === true) { onSuccess(msg.message); } else if (msg.type === 'PAY_FAILURE' || msg.success === false) { onFailure(msg.error); } }, [onSuccess, onFailure], ); return ( ); } const styles = StyleSheet.create({webview: {flex: 1}}); ``` ```kotlin import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.net.Uri import android.os.Handler import android.os.Looper import android.webkit.JavascriptInterface import android.webkit.WebResourceRequest import android.webkit.WebView import android.webkit.WebViewClient import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.viewinterop.AndroidView import org.json.JSONObject fun buildPayUrl(gatewayUrl: String, appDeepLink: String): String = Uri.parse(gatewayUrl).buildUpon() .appendQueryParameter("returnUrl", appDeepLink) .appendQueryParameter("preferUniversalLinks", "1") .build().toString() fun isWalletDeeplink(url: String): Boolean = try { Uri.parse(url).getQueryParameter("uri")?.startsWith("wc:") == true } catch (_: Exception) { false } // Shared by both shouldOverrideUrlLoading overloads. Returns true = handled (don't load // in the WebView), false = let the WebView load it. Forward wc: wallet deeplinks to the OS; // allow https (the checkout) and about: to load; block any other scheme (tel:, sms:, // intent:, …) so the page can't drive the OS into arbitrary native apps. private fun handleWalletDeeplink(context: Context, url: String?): Boolean { if (url == null) return false if (isWalletDeeplink(url)) { try { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) } catch (_: ActivityNotFoundException) { // No app can handle the wallet deeplink (wallet not installed). } return true } val scheme = Uri.parse(url).scheme?.lowercase() return scheme != "https" && scheme != "about" } @Composable fun PayWebView( gatewayUrl: String, appDeepLink: String, onSuccess: (message: String?) -> Unit, onFailure: (error: String?) -> Unit ) { // AndroidView's factory runs once, so the JS bridge closes over the callbacks captured // at that moment. Wrap them so the bridge always invokes the latest lambdas instead of // stale ones after recomposition. val currentOnSuccess by rememberUpdatedState(onSuccess) val currentOnFailure by rememberUpdatedState(onFailure) AndroidView( factory = { context -> WebView(context).apply { settings.javaScriptEnabled = true settings.domStorageEnabled = true settings.allowFileAccess = false addJavascriptInterface( object { @JavascriptInterface fun postMessage(json: String) { val msg = try { JSONObject(json) } catch (_: Exception) { return } val type = msg.optString("type") val hasSuccess = msg.has("success") val success = msg.optBoolean("success", false) // @JavascriptInterface methods run on a background thread — // hop to the main thread before touching UI/navigation state. Handler(Looper.getMainLooper()).post { when { type == "PAY_SUCCESS" || (hasSuccess && success) -> currentOnSuccess(msg.optString("message").ifEmpty { null }) type == "PAY_FAILURE" || (hasSuccess && !success) -> currentOnFailure(msg.optString("error").ifEmpty { null }) } } } }, "ReactNativeWebView" ) webViewClient = object : WebViewClient() { // API 24+ overload. override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean = handleWalletDeeplink(context, request?.url?.toString()) // Deprecated pre-API-24 overload — still the only one called on API 23, so // without it deeplink interception silently no-ops there and wc: links would // load inside the WebView instead of opening the wallet. @Suppress("DEPRECATION") override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean = handleWalletDeeplink(context, url) } loadUrl(buildPayUrl(gatewayUrl, appDeepLink)) } }, onRelease = { webView -> // Tear down the WebView when the screen leaves composition — otherwise it leaks and // its JavaScript, timers, and network requests keep running in the background. webView.stopLoading() webView.loadUrl("about:blank") webView.destroy() } ) } ``` ```swift import SwiftUI import WebKit struct PayWebView: UIViewRepresentable { let gatewayUrl: String let appDeepLink: String var onSuccess: (String?) -> Void var onFailure: (String?) -> Void func makeCoordinator() -> Coordinator { Coordinator(onSuccess: onSuccess, onFailure: onFailure) } func makeUIView(context: Context) -> WKWebView { let cc = WKUserContentController() // The checkout calls window.ReactNativeWebView.postMessage(...), which does NOT exist on a // native WKWebView — registering the handler only creates // window.webkit.messageHandlers.ReactNativeWebView.postMessage. Inject a shim at document // start that maps window.ReactNativeWebView.postMessage onto it. Without this shim the bridge // messages (PAY_SUCCESS / PAY_FAILURE) are silently dropped and the flow never completes. let shim = """ window.ReactNativeWebView = { postMessage: function (data) { window.webkit.messageHandlers.ReactNativeWebView.postMessage(data); } }; """ cc.addUserScript(WKUserScript(source: shim, injectionTime: .atDocumentStart, forMainFrameOnly: true)) cc.add(context.coordinator, name: "ReactNativeWebView") let config = WKWebViewConfiguration() config.userContentController = cc let wv = WKWebView(frame: .zero, configuration: config) wv.navigationDelegate = context.coordinator if let url = buildPayURL() { wv.load(URLRequest(url: url)) } return wv } func updateUIView(_ uiView: WKWebView, context: Context) {} private func buildPayURL() -> URL? { guard var c = URLComponents(string: gatewayUrl) else { return nil } c.queryItems = (c.queryItems ?? []) + [ URLQueryItem(name: "returnUrl", value: appDeepLink), URLQueryItem(name: "preferUniversalLinks", value: "1"), ] return c.url } class Coordinator: NSObject, WKScriptMessageHandler, WKNavigationDelegate { var onSuccess: (String?) -> Void var onFailure: (String?) -> Void init(onSuccess: @escaping (String?) -> Void, onFailure: @escaping (String?) -> Void) { self.onSuccess = onSuccess; self.onFailure = onFailure } func userContentController(_ uc: WKUserContentController, didReceive message: WKScriptMessage) { guard message.name == "ReactNativeWebView", let body = message.body as? String, let data = body.data(using: .utf8), let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return } let type = json["type"] as? String ?? "" let success = json["success"] as? Bool if type == "PAY_SUCCESS" || success == true { onSuccess(json["message"] as? String) } else if type == "PAY_FAILURE" || success == false { onFailure(json["error"] as? String) } } func webView(_ wv: WKWebView, decidePolicyFor action: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { if let url = action.request.url, isWalletDeeplink(url) { UIApplication.shared.open(url); decisionHandler(.cancel); return } // Allow https and the initial/programmatic loads; block any other scheme so the page // cannot drive the OS into arbitrary native schemes (tel:, sms:, intent:, …). let scheme = action.request.url?.scheme?.lowercased() if scheme == "https" || scheme == "about" || action.navigationType == .other { decisionHandler(.allow) } else { decisionHandler(.cancel) } } private func isWalletDeeplink(_ url: URL) -> Bool { URLComponents(url: url, resolvingAgainstBaseURL: false)? .queryItems?.first(where: { $0.name == "uri" })?.value?.hasPrefix("wc:") ?? false } } } ``` ```dart import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:webview_flutter/webview_flutter.dart'; bool isWalletDeeplink(String url) { try { return Uri.parse(url).queryParameters['uri']?.startsWith('wc:') ?? false; } catch (_) { return false; } } String buildPayUrl(String gatewayUrl, String appDeepLink) { final uri = Uri.parse(gatewayUrl); return uri.replace(queryParameters: { ...uri.queryParameters, 'returnUrl': appDeepLink, 'preferUniversalLinks': '1', }).toString(); } class PayWebView extends StatefulWidget { final String gatewayUrl; final String appDeepLink; final void Function(String? message) onSuccess; final void Function(String? error) onFailure; const PayWebView({super.key, required this.gatewayUrl, required this.appDeepLink, required this.onSuccess, required this.onFailure}); @override State createState() => _PayWebViewState(); } class _PayWebViewState extends State { late final WebViewController _controller; @override void initState() { super.initState(); _controller = WebViewController() ..setJavaScriptMode(JavaScriptMode.unrestricted) ..setNavigationDelegate(NavigationDelegate( // onNavigationRequest accepts a FutureOr, so it can be async — await the // launch and swallow failures (e.g. the wallet app isn't installed). onNavigationRequest: (request) async { if (isWalletDeeplink(request.url)) { try { await launchUrl(Uri.parse(request.url), mode: LaunchMode.externalApplication); } catch (_) { // No app can handle the wallet deeplink (wallet not installed). } return NavigationDecision.prevent; } // Allow https (the checkout) and about:; block any other scheme so the // page can't drive the OS into arbitrary native schemes (tel:, sms:, …). final scheme = Uri.tryParse(request.url)?.scheme.toLowerCase(); if (scheme == 'https' || scheme == 'about') { return NavigationDecision.navigate; } return NavigationDecision.prevent; }, )) ..addJavaScriptChannel('ReactNativeWebView', onMessageReceived: (msg) { try { final json = jsonDecode(msg.message) as Map; final type = json['type'] as String? ?? ''; final success = json['success'] as bool?; if (type == 'PAY_SUCCESS' || success == true) widget.onSuccess(json['message'] as String?); else if (type == 'PAY_FAILURE' || success == false) widget.onFailure(json['error'] as String?); } catch (_) {} }) ..loadRequest(Uri.parse(buildPayUrl(widget.gatewayUrl, widget.appDeepLink))); } @override Widget build(BuildContext context) => WebViewWidget(controller: _controller); } ``` ## Deep Link Registration [#deep-link-registration] Register your `returnUrl` scheme so the OS routes users back after signing in their wallet. ```xml ``` ```xml CFBundleURLTypes CFBundleURLSchemes myapp ``` ## Verifying Payment Status [#verifying-payment-status] After `PAY_SUCCESS`, confirm server-side before marking the order as paid: ```typescript const res = await fetch( `https://api.pay.walletconnect.com/v1/payments/${paymentId}/status`, { headers: { 'Api-Key': process.env.WCP_API_KEY } } ); const { status } = await res.json(); // "succeeded" | "processing" | "failed" | … ``` See the [Payments Status API](/payments/api-reference/2026-02-18/get-v1-payments-id-status) for the full response schema. ## Best Practices [#best-practices] - **Enable JavaScript and DOM storage** — both required. JavaScript renders the checkout; DOM storage backs its session and wallet state. - **Always intercept wallet deeplinks** — URLs with `?uri=wc:…` must be forwarded to the OS. The checkout triggers these as same-frame navigations, so intercepting navigation requests covers it. - **Only intercept `wc:` deeplinks** — block other non-`https:` navigations to prevent arbitrary native app launches. - **Handle both message formats** — check `type === "PAY_SUCCESS"` **and** `success === true` for forward compatibility. - **Always verify server-side** — treat bridge messages as a trigger to check status, not as proof of payment. - **Keep the WebView full-screen or modal** — the checkout is optimized for full viewport rendering. ## Reference Example [#reference-example] } href="https://github.com/reown-com/react-native-examples/tree/main/dapps/appkit-wagmi/src/screens/PayWebView"> Full implementation including success animation, wallet deeplink handling, and error recovery. # Webhook event reference (/payments/webhook-event-reference) This page is the field-level reference for the payment webhook payload, `api_version` `2026-05-18`. It documents every field, its type and nullability, and which stage objects are populated for each event type. For endpoint setup, signature verification, and delivery guarantees, see [Webhooks](/payments/webhooks). **The contract is additive-only.** Within this `api_version`, fields are never removed or renamed, and types and nullability never change. New **optional** fields and new values for extensible strings (such as `fee.kind`) can be added at any time. Ignore fields you don't recognize, and never validate payloads with a schema that rejects unknown fields; strict validation will break your integration. All timestamps in the payload are ISO 8601 UTC strings. ## The event envelope [#the-event-envelope] Every event has the same top-level shape. | Field | Type | Description | |---|---|---| | `id` | string | Unique event identifier, prefixed `evt_`. The deduplication key: delivery is at-least-once, so the same `id` can arrive more than once. Do not deduplicate by `payment_id`; one payment emits multiple events. | | `type` | string | The event type. One of the seven `payment.*` event types; see [the matrix below](#stage-objects-by-event-type). | | `api_version` | string | The payload contract version, `2026-05-18`. Changes within a version are additive-only. | | `created_at` | string | When the event occurred, not when it was delivered. | | `data` | object | The [payment snapshot](#the-payment-snapshot-data) at event time. | ## The payment snapshot (`data`) [#the-payment-snapshot-data] `data` is always a **full snapshot of the payment at the moment the event occurred**, never a delta. Every event type carries the same field set; what varies is `status` and which stage objects are non-null. | Field | Type | Description | |---|---|---| | `payment_id` | string | Payment identifier, the same id used across the Merchant API. | | `merchant_id` | string | Merchant identifier, the same external merchant id used across the Merchant API. | | `live` | boolean | Whether this is a live payment. Test-mode payments carry `false` and are only delivered to test-mode endpoints. Verify `live` is `true` before driving real fulfillment. | | `payment_state_version` | integer | Monotonic per-payment version, starting at `0` on the first event. The ordering guard: ignore any event whose version is lower than or equal to one already processed for the same `payment_id`. See [Out-of-order delivery](/payments/webhooks#out-of-order-delivery). | | `reference_id` | string | The merchant-provided order reference attached at payment creation. Primary reconciliation key against your own records. Not unique: a new payment for the same order (for example a checkout retry) carries the same reference. | | `status` | string | Payment status at event time: `requires_action`, `processing`, `succeeded`, `failed`, `expired`, or `cancelled`. There is no `settled` status; settlement is a stage of a succeeded payment. | | `amount` | [Amount](#amount) | The requested payment amount. | | `created_at` | string | When the payment was created. | | `expires_at` | string | When the payment stops accepting buyer action. | | `processing` | [Processing](#processing) \| null | Populated once the buyer has committed to a payment option. | | `success` | [Success](#success) \| null | Populated once the payment succeeded. | | `failed` | [Failed](#failed) \| null | Populated once the payment failed. | | `cancelled` | [Cancelled](#cancelled) \| null | Populated once the payment was cancelled. | | `expired` | [Expired](#expired) \| null | Populated once the payment expired. | | `settled` | [Settled](#settled) \| null | Populated once merchant settlement completed. | ### Stage objects by event type [#stage-objects-by-event-type] Which stage objects are non-null depends on the event type. Each event type's page carries a full example, taken verbatim from the golden fixtures the payload contract is tested against. | Event type | `status` | `processing` | `success` | `failed` | `cancelled` | `expired` | `settled` | |---|---|---|---|---|---|---|---| | [payment.created](/payments/webhook-events/payment-created) | `requires_action` | null | null | null | null | null | null | | [payment.processing](/payments/webhook-events/payment-processing) | `processing` | present | null | null | null | null | null | | [payment.succeeded](/payments/webhook-events/payment-succeeded) | `succeeded` | present | present | null | null | null | usually null | | [payment.failed](/payments/webhook-events/payment-failed) | `failed` | may be present | null | present | null | null | null | | [payment.expired](/payments/webhook-events/payment-expired) | `expired` | may be present | null | null | null | present | null | | [payment.cancelled](/payments/webhook-events/payment-cancelled) | `cancelled` | null | null | null | present | null | null | | [payment.settled](/payments/webhook-events/payment-settled) | `succeeded` | present | present | null | null | null | present | "May be present" means the payment can fail or expire either before or after processing started: `processing` is `null` when the buyer never committed to a payment option, and populated otherwise. Cancellation is only possible while the payment awaits buyer action, so `payment.cancelled` always carries `processing: null`. On `payment.succeeded`, `settled` is `null` unless settlement had already completed at snapshot time; settlement completion is carried by `payment.settled`. ## Objects [#objects] ### Amount [#amount] An asset amount. Used for `data.amount` and inside the [Processing](#processing), [Fee](#fee), and [Settled](#settled) objects. | Field | Type | Description | |---|---|---| | `unit` | string | The asset: `iso4217/XXX` for fiat currencies (for example `iso4217/USD`) or `caip19/...` for on-chain assets. | | `value` | string | Integer string in the smallest unit of the asset: minor units for fiat, raw base units for tokens. Token decimals are not included in the payload. | ### Fee [#fee] Fee applied to the payment, inside [Processing](#processing). | Field | Type | Description | |---|---|---| | `kind` | string | Extensible string. The only value at launch is `base_plus_percent`. Do not switch exhaustively on it; new kinds can be added within this `api_version`. Whatever the kind, `total_amount` is always present. | | `base_amount` | [Amount](#amount) | The fixed component of the fee. | | `percent` | object | The percentage as an exact rational: `numerator` and `denominator`, both integer strings. For example `29/1000` is 2.9%. | | `percent_amount` | [Amount](#amount) | The percentage component of the fee. | | `total_amount` | [Amount](#amount) | The total fee charged. `base_amount` and `percent_amount` break it down. | ### Processing [#processing] Present once the buyer has committed to a payment option. | Field | Type | Description | |---|---|---| | `processing_at` | string | When the buyer committed to the payment option. | | `option_amount` | [Amount](#amount) | What the buyer pays gross, in the asset of the payment option they selected. | | `fee` | [Fee](#fee) \| null | Fee applied to this payment, or `null` when no fee is configured. | | `settlement_amount` | [Amount](#amount) | What the merchant is expected to receive, net of `fee`. | | `buyer_caip10` | string \| null | The buyer's on-chain account ([CAIP-10](https://chainagnostic.org/CAIPs/caip-10)), or `null` when the payment has no on-chain buyer (for example, payments settled inside an exchange). | | `chain_caip2` | string | The chain the payment executes on ([CAIP-2](https://chainagnostic.org/CAIPs/caip-2)). Needed to interpret transaction ids. | ### Success [#success] Present once the payment succeeded. | Field | Type | Description | |---|---|---| | `succeeded_at` | string | When the payment succeeded. | | `tx_id` | string \| null | On-chain transaction id, or `null` when there is no on-chain transaction. Format is chain-specific; interpret with `processing.chain_caip2`. | ### Failed [#failed] Present once the payment failed. | Field | Type | Description | |---|---|---| | `failed_at` | string | When the payment failed. | | `failure_reason` | string \| null | Human-readable diagnostic, or `null`. Not machine-parseable: values may change without notice. Display it if useful, but never branch on it. | ### Cancelled [#cancelled] Present once the payment was cancelled. | Field | Type | Description | |---|---|---| | `cancelled_at` | string | When the payment was cancelled. | | `cancellation_reason` | string \| null | Human-readable diagnostic, or `null`. Not machine-parseable: values may change without notice. Display it if useful, but never branch on it. | ### Expired [#expired] Present once the payment expired. | Field | Type | Description | |---|---|---| | `expired_at` | string | When the payment expired. | ### Settled [#settled] Present once merchant settlement completed. | Field | Type | Description | |---|---|---| | `settled_at` | string | When settlement completed. | | `tx_id` | string \| null | Settlement transaction id, or `null` when there is no on-chain settlement transaction. Format is chain-specific; interpret with `processing.chain_caip2`. | | `amount` | [Amount](#amount) | What actually settled to the merchant, as opposed to `processing.settlement_amount`, which is the expected net amount at processing time. | ## Next steps [#next-steps] } href="/payments/webhooks"> Endpoint setup, signature verification, and delivery guarantees. } href="/payments/test-mode"> Drive a test payment through every transition and watch these events arrive. # payment.cancelled (/payments/webhook-events/payment-cancelled) `cancelled` is populated. A payment can only be cancelled while it awaits buyer action, so `processing` is always `null`. | `data.status` | Stage objects populated | Stage objects always `null` | |---|---|---| | `cancelled` | [`cancelled`](/payments/webhook-event-reference#cancelled) | `processing`, `success`, `failed`, `expired`, `settled` | Every field is documented in the [event overview](/payments/webhook-event-reference). ```json { "id": "evt_fixture_payment_cancelled", "type": "payment.cancelled", "api_version": "2026-05-18", "created_at": "2026-06-30T10:00:00.271Z", "data": { "payment_id": "pay_fixture_01HZX4V9K3T", "merchant_id": "merchant_fixture_01HZX4V9K3T", "live": true, "payment_state_version": 1, "reference_id": "order_fixture_1042", "status": "cancelled", "amount": { "unit": "iso4217/USD", "value": "1000" }, "created_at": "2026-06-30T09:59:00.084Z", "expires_at": "2026-06-30T10:14:00.000Z", "processing": null, "success": null, "failed": null, "cancelled": { "cancelled_at": "2026-06-30T10:00:00.271Z", "cancellation_reason": "merchant cancelled" }, "expired": null, "settled": null } } ``` # payment.created (/payments/webhook-events/payment-created) Initial snapshot: no lifecycle stage has happened yet, so every stage object is `null` and `payment_state_version` is `0`. | `data.status` | Stage objects populated | Stage objects always `null` | |---|---|---| | `requires_action` | none | `processing`, `success`, `failed`, `cancelled`, `expired`, `settled` | Every field is documented in the [event overview](/payments/webhook-event-reference). ```json { "id": "evt_fixture_payment_created", "type": "payment.created", "api_version": "2026-05-18", "created_at": "2026-06-30T09:59:00.084Z", "data": { "payment_id": "pay_fixture_01HZX4V9K3T", "merchant_id": "merchant_fixture_01HZX4V9K3T", "live": true, "payment_state_version": 0, "reference_id": "order_fixture_1042", "status": "requires_action", "amount": { "unit": "iso4217/USD", "value": "1000" }, "created_at": "2026-06-30T09:59:00.084Z", "expires_at": "2026-06-30T10:14:00.000Z", "processing": null, "success": null, "failed": null, "cancelled": null, "expired": null, "settled": null } } ``` # payment.expired (/payments/webhook-events/payment-expired) `expired` is populated. In this example the payment expired after processing started, so `processing` is populated. | `data.status` | Stage objects populated | Stage objects always `null` | |---|---|---| | `expired` | [`expired`](/payments/webhook-event-reference#expired) ([`processing`](/payments/webhook-event-reference#processing) when the payment had started processing) | `success`, `failed`, `cancelled`, `settled` | Every field is documented in the [event overview](/payments/webhook-event-reference). ```json { "id": "evt_fixture_payment_expired_after_processing", "type": "payment.expired", "api_version": "2026-05-18", "created_at": "2026-06-30T10:14:00.030Z", "data": { "payment_id": "pay_fixture_01HZX4V9K3T", "merchant_id": "merchant_fixture_01HZX4V9K3T", "live": true, "payment_state_version": 2, "reference_id": "order_fixture_1042", "status": "expired", "amount": { "unit": "iso4217/USD", "value": "1000" }, "created_at": "2026-06-30T09:59:00.084Z", "expires_at": "2026-06-30T10:14:00.000Z", "processing": { "processing_at": "2026-06-30T09:59:10.512Z", "option_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "10000000" }, "fee": { "kind": "base_plus_percent", "base_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "0" }, "percent": { "numerator": "29", "denominator": "1000" }, "percent_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "290000" }, "total_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "290000" } }, "settlement_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "9710000" }, "buyer_caip10": "eip155:8453:0x000000000000000000000000000000000000dEaD", "chain_caip2": "eip155:8453" }, "success": null, "failed": null, "cancelled": null, "expired": { "expired_at": "2026-06-30T10:14:00.030Z" }, "settled": null } } ``` # payment.failed (/payments/webhook-events/payment-failed) `failed` is populated. In this example the payment failed before the buyer committed, so `processing` is `null`. | `data.status` | Stage objects populated | Stage objects always `null` | |---|---|---| | `failed` | [`failed`](/payments/webhook-event-reference#failed) ([`processing`](/payments/webhook-event-reference#processing) when the payment had started processing) | `success`, `cancelled`, `expired`, `settled` | Every field is documented in the [event overview](/payments/webhook-event-reference). ```json { "id": "evt_fixture_payment_failed", "type": "payment.failed", "api_version": "2026-05-18", "created_at": "2026-06-30T10:00:00.271Z", "data": { "payment_id": "pay_fixture_01HZX4V9K3T", "merchant_id": "merchant_fixture_01HZX4V9K3T", "live": true, "payment_state_version": 1, "reference_id": "order_fixture_1042", "status": "failed", "amount": { "unit": "iso4217/USD", "value": "1000" }, "created_at": "2026-06-30T09:59:00.084Z", "expires_at": "2026-06-30T10:14:00.000Z", "processing": null, "success": null, "failed": { "failed_at": "2026-06-30T10:00:00.271Z", "failure_reason": "insufficient allowance" }, "cancelled": null, "expired": null, "settled": null } } ``` # payment.processing (/payments/webhook-events/payment-processing) `processing` is populated from this point on. In this example the buyer pays 10 USDC on Base for a $10.00 payment, a 2.9% fee applies, and the merchant is expected to receive 9.71 USDC. `processing.buyer_caip10` is `null` instead when the payment has no on-chain buyer, and `live` is `false` for test-mode payments. | `data.status` | Stage objects populated | Stage objects always `null` | |---|---|---| | `processing` | [`processing`](/payments/webhook-event-reference#processing) | `success`, `failed`, `cancelled`, `expired`, `settled` | Every field is documented in the [event overview](/payments/webhook-event-reference). ```json { "id": "evt_fixture_payment_processing", "type": "payment.processing", "api_version": "2026-05-18", "created_at": "2026-06-30T09:59:10.512Z", "data": { "payment_id": "pay_fixture_01HZX4V9K3T", "merchant_id": "merchant_fixture_01HZX4V9K3T", "live": true, "payment_state_version": 1, "reference_id": "order_fixture_1042", "status": "processing", "amount": { "unit": "iso4217/USD", "value": "1000" }, "created_at": "2026-06-30T09:59:00.084Z", "expires_at": "2026-06-30T10:14:00.000Z", "processing": { "processing_at": "2026-06-30T09:59:10.512Z", "option_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "10000000" }, "fee": { "kind": "base_plus_percent", "base_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "0" }, "percent": { "numerator": "29", "denominator": "1000" }, "percent_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "290000" }, "total_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "290000" } }, "settlement_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "9710000" }, "buyer_caip10": "eip155:8453:0x000000000000000000000000000000000000dEaD", "chain_caip2": "eip155:8453" }, "success": null, "failed": null, "cancelled": null, "expired": null, "settled": null } } ``` # payment.settled (/payments/webhook-events/payment-settled) `settled` is populated, and `status` stays `succeeded`; settlement is a stage, not a status. `settled.amount` is what actually settled to the merchant. | `data.status` | Stage objects populated | Stage objects always `null` | |---|---|---| | `succeeded` | [`processing`](/payments/webhook-event-reference#processing), [`success`](/payments/webhook-event-reference#success), [`settled`](/payments/webhook-event-reference#settled) | `failed`, `cancelled`, `expired` | Every field is documented in the [event overview](/payments/webhook-event-reference). ```json { "id": "evt_fixture_payment_settled", "type": "payment.settled", "api_version": "2026-05-18", "created_at": "2026-06-30T10:05:00.696Z", "data": { "payment_id": "pay_fixture_01HZX4V9K3T", "merchant_id": "merchant_fixture_01HZX4V9K3T", "live": true, "payment_state_version": 3, "reference_id": "order_fixture_1042", "status": "succeeded", "amount": { "unit": "iso4217/USD", "value": "1000" }, "created_at": "2026-06-30T09:59:00.084Z", "expires_at": "2026-06-30T10:14:00.000Z", "processing": { "processing_at": "2026-06-30T09:59:10.512Z", "option_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "10000000" }, "fee": { "kind": "base_plus_percent", "base_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "0" }, "percent": { "numerator": "29", "denominator": "1000" }, "percent_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "290000" }, "total_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "290000" } }, "settlement_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "9710000" }, "buyer_caip10": "eip155:8453:0x000000000000000000000000000000000000dEaD", "chain_caip2": "eip155:8453" }, "success": { "succeeded_at": "2026-06-30T10:00:00.271Z", "tx_id": "0x8f1e5c1b9a4a1d2e3f405162738495a6b7c8d9e0f1a2b3c4d5e6f708192a3b4c" }, "failed": null, "cancelled": null, "expired": null, "settled": { "settled_at": "2026-06-30T10:05:00.696Z", "tx_id": "0x93d2f1a0b9c8e7d6f5a4b3c2d1e0f9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2", "amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "9710000" } } } } ``` # payment.succeeded (/payments/webhook-events/payment-succeeded) `success` is populated, and `processing` carries the committed option. Settlement completion arrives later as [`payment.settled`](/payments/webhook-events/payment-settled). | `data.status` | Stage objects populated | Stage objects always `null` | |---|---|---| | `succeeded` | [`processing`](/payments/webhook-event-reference#processing), [`success`](/payments/webhook-event-reference#success) ([`settled`](/payments/webhook-event-reference#settled) usually `null`) | `failed`, `cancelled`, `expired` | Every field is documented in the [event overview](/payments/webhook-event-reference). ```json { "id": "evt_fixture_payment_succeeded", "type": "payment.succeeded", "api_version": "2026-05-18", "created_at": "2026-06-30T10:00:00.271Z", "data": { "payment_id": "pay_fixture_01HZX4V9K3T", "merchant_id": "merchant_fixture_01HZX4V9K3T", "live": true, "payment_state_version": 2, "reference_id": "order_fixture_1042", "status": "succeeded", "amount": { "unit": "iso4217/USD", "value": "1000" }, "created_at": "2026-06-30T09:59:00.084Z", "expires_at": "2026-06-30T10:14:00.000Z", "processing": { "processing_at": "2026-06-30T09:59:10.512Z", "option_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "10000000" }, "fee": { "kind": "base_plus_percent", "base_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "0" }, "percent": { "numerator": "29", "denominator": "1000" }, "percent_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "290000" }, "total_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "290000" } }, "settlement_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "9710000" }, "buyer_caip10": "eip155:8453:0x000000000000000000000000000000000000dEaD", "chain_caip2": "eip155:8453" }, "success": { "succeeded_at": "2026-06-30T10:00:00.271Z", "tx_id": "0x8f1e5c1b9a4a1d2e3f405162738495a6b7c8d9e0f1a2b3c4d5e6f708192a3b4c" }, "failed": null, "cancelled": null, "expired": null, "settled": null } } ``` # Webhooks (/payments/webhooks) Webhooks push payment lifecycle events to an HTTPS endpoint you control, as they happen. Enhance your integration by registering an endpoint once: we `POST` an event to it whenever a payment is created, starts processing, succeeds, fails, expires, is cancelled, or settles. ## Webhooks vs. polling [#webhooks-vs-polling] Polling [`GET /v1/payments/{id}/status`](/payments/api-reference/latest/get-v1-payments-id-status) is the primary way to validate payment status during the purchase cycle: create the payment, then poll until the status is final. Webhooks come on top as an enhancement. They usually tell you first, and with far fewer requests, so you can update the order status in your UI, notify a customer, or kick off downstream processing the moment something happens. When a webhook event arrives, its payload already contains everything you need. Every event is a full signed snapshot of the payment and carries a monotonic `payment_state_version`, so verifying the signature, deduplicating by `id`, and applying the version guard is enough; there is no need to call the API from inside your handler. Webhook delivery is **at-least-once** and **not guaranteed to be in order** (see [Delivery guarantees](#delivery-guarantees)). A well-built integration works correctly even if a webhook arrives twice, late, out of order, or not at all. ## Events [#events] Every event is named `payment.`: | Event type | Sent when | |---|---| | `payment.created` | A payment was created. | | `payment.processing` | A payment started processing: the buyer has committed funds. | | `payment.succeeded` | A payment succeeded. | | `payment.failed` | A payment failed. | | `payment.expired` | A payment expired before completion. | | `payment.cancelled` | A payment was cancelled. | | `payment.settled` | Merchant settlement completed for a succeeded payment. | ```mermaid flowchart LR C["payment.created"] --> P["payment.processing"] P --> S["payment.succeeded"] --> T["payment.settled"] P --> F["payment.failed"] P --> E["payment.expired"] C --> F C --> E C --> X["payment.cancelled"] ``` When you register an endpoint you choose which event types it receives; by default it receives all seven. `payment.settled` carries `status: "succeeded"`. Settlement is a stage of a succeeded payment, not a seventh status, so don't look for a `settled` value in the `status` field. ## The event payload [#the-event-payload] Every event carries the same envelope, and `data` is always a **full snapshot of the payment at the moment the event occurred**, never a delta. You never need a previous event to interpret the current one. Four fields decide whether your handler is correct: - **`id`** — the event id (`evt_…`). **Your deduplication key**: the same event can arrive more than once. - **`data.payment_state_version`** — a per-payment counter starting at `0`. **Your ordering key**; see [Out-of-order delivery](#out-of-order-delivery). - **`data.status`** — `requires_action`, `processing`, `succeeded`, `failed`, `expired`, or `cancelled`. Branch on this rather than on the event type. - **`data.live`** — `false` for test-mode payments and test deliveries. **Check `live === true` before driving real fulfillment.** Every other field, with types, nullability, and a full example per event type: [Webhook event reference](/payments/webhook-event-reference). A `payment.succeeded` event looks like this: ```json { "id": "evt_fixture_payment_succeeded", "type": "payment.succeeded", "api_version": "2026-05-18", "created_at": "2026-06-30T10:00:00.271Z", "data": { "payment_id": "pay_fixture_01HZX4V9K3T", "merchant_id": "merchant_fixture_01HZX4V9K3T", "live": true, "payment_state_version": 2, "reference_id": "order_fixture_1042", "status": "succeeded", "amount": { "unit": "iso4217/USD", "value": "1000" }, "created_at": "2026-06-30T09:59:00.084Z", "expires_at": "2026-06-30T10:14:00.000Z", "processing": { "processing_at": "2026-06-30T09:59:10.512Z", "option_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "10000000" }, "fee": { "kind": "base_plus_percent", "base_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "0" }, "percent": { "numerator": "29", "denominator": "1000" }, "percent_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "290000" }, "total_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "290000" } }, "settlement_amount": { "unit": "caip19/eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "value": "9710000" }, "buyer_caip10": "eip155:8453:0x000000000000000000000000000000000000dEaD", "chain_caip2": "eip155:8453" }, "success": { "succeeded_at": "2026-06-30T10:00:00.271Z", "tx_id": "0x8f1e5c1b9a4a1d2e3f405162738495a6b7c8d9e0f1a2b3c4d5e6f708192a3b4c" }, "failed": null, "cancelled": null, "expired": null, "settled": null } } ``` **Parse tolerantly.** New fields are added to the payload over time without a version bump; that is the additive-only contract. Strict schema validation that fails on unknown fields **will** break your integration. - Ignore fields you don't recognize, and never reject an event because it contains something new. - Parse timestamps with a full ISO 8601 parser, not a fixed format string. They are UTC with millisecond precision today, but the fractional precision is not part of the contract. - Don't switch exhaustively on `fee.kind`. The only value today is `base_plus_percent`, and new kinds can be added within this `api_version`. Whatever the kind, `fee.total_amount` is always present when a fee applies; `processing.fee` is `null` when none is configured. - Never branch on `failure_reason` or `cancellation_reason`. They are human-readable diagnostics that may change without notice. Display them if useful, and branch on `type` and `status` only. ## Delivery guarantees [#delivery-guarantees] Design your handler around three properties of webhook delivery. Getting these right up front is the difference between an integration that works in a demo and one that works in production. ### At-least-once delivery [#at-least-once-delivery] Every event is delivered *at least* once, which means occasionally more than once. Deduplicate on the event `id`: record each `id` you've processed (with a TTL of a few days), and acknowledge but skip any event whose `id` you've already seen. ### Out-of-order delivery [#out-of-order-delivery] Events for the same payment can arrive out of order. A `payment.succeeded` may land before the `payment.processing` that preceded it, especially when retries are involved. The version guard keeps you safe: **compare `payment_state_version`**. It increases with every state change of a payment, so keep the highest version you've processed per `payment_id` and ignore any event with a version less than or equal to it, because it is stale. Since every event is a full snapshot, a late event you process in version order can never corrupt your state. Drive side effects from the snapshot, not the event type. A `payment.settled` can arrive before the `payment.succeeded` it supersedes, and the guard then rightly drops the older event, so a handler that only fulfills on `type: "payment.succeeded"` never fulfills. Fulfill when `data.status` first becomes `succeeded`, whatever the event's type. **The first event of every payment carries `payment_state_version: 0`.** Represent "no version processed yet" as an *absence* (a missing row or `NULL`), never as `0`. If you initialize a version counter to `0` — the natural default for an integer column or a `?? 0` fallback — the `less than or equal` guard silently drops the first event of every payment, and the integration still looks like it works because later events pass. ### Retries [#retries] An attempt counts as delivered only when your endpoint responds with a **2xx** status **within 15 seconds**. Any other response, including redirects (which are not followed), or a slower one counts as a failure, and the delivery is retried with increasing back-off: | Attempt | Time after previous attempt | |---|---| | 1 | immediate | | 2 | 5 seconds | | 3 | 5 minutes | | 4 | 30 minutes | | 5 | 2 hours | | 6 | 5 hours | | 7 | 10 hours | | 8 | 10 hours | That's roughly **28 hours** of automatic retries. After the final attempt the delivery is marked failed and is **not retried automatically**, but you can recover it yourself from the dashboard: - **Resend one delivery** from the endpoint's delivery history. - **Bulk-resend every failed delivery** since a point in time. - **Replay events the endpoint never received**, for example events sent before the endpoint was created. Replay operations reach back 14 days at most. And if every delivery to an endpoint keeps failing for **5 days**, the endpoint is **disabled** and stops receiving events. Because a misconfigured URL or a disabled endpoint drops deliveries silently, don't rely on noticing an outage. Run a **periodic reconciliation job**: poll [`GET /v1/payments/{id}/status`](/payments/api-reference/latest/get-v1-payments-id-status) for any payment your records still show in a non-final state after its `expires_at` has passed, and [`GET /v1/payments`](/payments/api-reference/latest/get-v1-payments), which returns `settled`, for succeeded payments still awaiting settlement. Use the endpoint's delivery history in the dashboard to debug what went wrong. To stop deliveries entirely (for example, when decommissioning an integration), delete the endpoint from the dashboard's **Webhooks** page. Deletion takes effect immediately and cannot be undone. Process later, acknowledge fast. Verify the signature, durably persist or enqueue the event, then return `200`; don't run business logic before responding. Responses slower than 15 seconds count as failed attempts and cause redundant redeliveries. ## Set up your endpoint [#set-up-your-endpoint] ### Register the endpoint [#register-the-endpoint] 1. In the [dashboard](https://merchant.pay.walletconnect.com), make sure the **Test / Live** selector matches the mode you're setting up, since endpoints are configured separately per mode. 2. Open **Webhooks** and add your endpoint: a publicly reachable **HTTPS** URL, and the event types you want (all seven by default). 3. Copy the **signing secret** (`whsec_…`) and store it in a secret manager. You'll use it to verify every delivery. You can reveal the secret again later, and rotate it from the same page. After a rotation, the old secret stays valid for 24 hours so you can roll over without dropping deliveries. You can register one webhook endpoint per mode. Test and live endpoints are fully separate, each with its own signing secret. ### Verify signatures [#verify-signatures] Every delivery is signed so you can confirm it came from WalletConnect Pay and wasn't tampered with. The signature is a **standard HMAC-SHA256**, so you don't need any SDK to verify it. ### Let your coding agent do it [#let-your-coding-agent-do-it] The fastest path: an AI coding agent (Claude Code, Cursor, Codex, and the like) can implement and verify the handler in one shot. The prompt contains the complete spec plus a test vector to validate the implementation against, so paste it into your agent as-is: Copy prompt ### Or implement it by hand [#or-implement-it-by-hand] The signature arrives in three headers on every delivery: | Header | Contents | |---|---| | `webhook-id` | The delivery's message ID. | | `webhook-timestamp` | Unix timestamp (seconds) of the attempt. | | `webhook-signature` | Space-separated list of signatures, each formatted `v1,`. There can be more than one, for example during the 24-hour secret rotation overlap. | Verification is four steps: 1. **Derive the key.** Take your signing secret, strip the `whsec_` prefix, and base64-decode the rest. The decoded bytes are the HMAC key (using the string itself is the most common mistake). 2. **Compute the digest.** HMAC-SHA256 over the UTF-8 bytes of `{webhook-id}.{webhook-timestamp}.{raw body}`, then base64-encode it. 3. **Compare.** The delivery is authentic if your digest equals any `v1` entry in `webhook-signature`, using a constant-time comparison. 4. **Check the timestamp.** Reject deliveries whose `webhook-timestamp` is more than 5 minutes from the current time, to prevent replay attacks. Dependency-free implementations, standard library only: ```ts tab="Node.js" import { createHmac, timingSafeEqual } from "node:crypto"; const TOLERANCE_S = 5 * 60; export function verifyWebhook(secret: string, headers: Record, rawBody: string) { const id = headers["webhook-id"]; const timestamp = headers["webhook-timestamp"]; const signatures = headers["webhook-signature"]; if (!id || !timestamp || !signatures) throw new Error("missing signature headers"); const skew = Math.abs(Date.now() / 1000 - Number(timestamp)); if (!Number.isFinite(skew) || skew > TOLERANCE_S) throw new Error("timestamp outside tolerance"); const key = Buffer.from(secret.slice("whsec_".length), "base64"); const expected = createHmac("sha256", key) .update(`${id}.${timestamp}.${rawBody}`) .digest("base64"); const ok = signatures.split(" ").some((entry) => { const [version, sig] = entry.split(","); return ( version === "v1" && sig?.length === expected.length && timingSafeEqual(Buffer.from(sig), Buffer.from(expected)) ); }); if (!ok) throw new Error("no matching signature"); return JSON.parse(rawBody); } ``` ```python tab="Python" import base64 import hashlib import hmac import json import time TOLERANCE_S = 5 * 60 def verify_webhook(secret: str, headers: dict, raw_body: bytes) -> dict: msg_id = headers.get("webhook-id") timestamp = headers.get("webhook-timestamp") signatures = headers.get("webhook-signature") if not (msg_id and timestamp and signatures): raise ValueError("missing signature headers") if abs(time.time() - float(timestamp)) > TOLERANCE_S: raise ValueError("timestamp outside tolerance") key = base64.b64decode(secret.removeprefix("whsec_")) signed = f"{msg_id}.{timestamp}.".encode() + raw_body expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode() for entry in signatures.split(" "): version, _, sig = entry.partition(",") if version == "v1" and hmac.compare_digest(sig, expected): return json.loads(raw_body) raise ValueError("no matching signature") ``` ```go tab="Go" package webhooks import ( "crypto/hmac" "crypto/sha256" "encoding/base64" "errors" "fmt" "math" "net/http" "strconv" "strings" "time" ) const toleranceSeconds = 5 * 60 func VerifyWebhook(secret string, headers http.Header, rawBody []byte) error { id := headers.Get("webhook-id") timestamp := headers.Get("webhook-timestamp") signatures := headers.Get("webhook-signature") if id == "" || timestamp == "" || signatures == "" { return errors.New("missing signature headers") } ts, err := strconv.ParseFloat(timestamp, 64) if err != nil || math.Abs(float64(time.Now().Unix())-ts) > toleranceSeconds { return errors.New("timestamp outside tolerance") } key, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(secret, "whsec_")) if err != nil { return err } mac := hmac.New(sha256.New, key) fmt.Fprintf(mac, "%s.%s.", id, timestamp) mac.Write(rawBody) expected := base64.StdEncoding.EncodeToString(mac.Sum(nil)) for _, entry := range strings.Split(signatures, " ") { version, sig, found := strings.Cut(entry, ",") if found && version == "v1" && hmac.Equal([]byte(sig), []byte(expected)) { return nil } } return errors.New("no matching signature") } ``` ```java tab="Java" import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.Base64; public final class WebhookVerifier { private static final long TOLERANCE_S = 5 * 60; public static void verify(String secret, String id, String timestamp, String signatures, byte[] rawBody) throws Exception { long skew = Math.abs(System.currentTimeMillis() / 1000 - Long.parseLong(timestamp)); if (skew > TOLERANCE_S) throw new SecurityException("timestamp outside tolerance"); byte[] key = Base64.getDecoder().decode(secret.substring("whsec_".length())); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(key, "HmacSHA256")); mac.update((id + "." + timestamp + ".").getBytes(StandardCharsets.UTF_8)); byte[] expected = Base64.getEncoder().encode(mac.doFinal(rawBody)); for (String entry : signatures.split(" ")) { String[] parts = entry.split(",", 2); if (parts.length == 2 && parts[0].equals("v1") && MessageDigest.isEqual(parts[1].getBytes(StandardCharsets.UTF_8), expected)) { return; } } throw new SecurityException("no matching signature"); } } ``` ```csharp tab="C#" using System.Linq; using System.Security.Cryptography; using System.Text; public static class WebhookVerifier { private const long ToleranceSeconds = 5 * 60; public static void Verify(string secret, string id, string timestamp, string signatures, byte[] rawBody) { var skew = Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - long.Parse(timestamp)); if (skew > ToleranceSeconds) throw new InvalidOperationException("timestamp outside tolerance"); var key = Convert.FromBase64String(secret["whsec_".Length..]); using var hmac = new HMACSHA256(key); var signed = Encoding.UTF8.GetBytes($"{id}.{timestamp}.").Concat(rawBody).ToArray(); var expected = Encoding.UTF8.GetBytes(Convert.ToBase64String(hmac.ComputeHash(signed))); foreach (var entry in signatures.Split(' ')) { var parts = entry.Split(',', 2); if (parts.Length == 2 && parts[0] == "v1" && CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(parts[1]), expected)) return; } throw new InvalidOperationException("no matching signature"); } } ``` ```php tab="PHP" TOLERANCE_S) { throw new RuntimeException('timestamp outside tolerance'); } $key = base64_decode(substr($secret, strlen('whsec_')), true); $expected = base64_encode(hash_hmac('sha256', "$id.$timestamp.$rawBody", $key, true)); foreach (explode(' ', $signatures) as $entry) { [$version, $sig] = array_pad(explode(',', $entry, 2), 2, ''); if ($version === 'v1' && hash_equals($expected, $sig)) { return json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR); } } throw new RuntimeException('no matching signature'); } ``` ```ruby tab="Ruby" require "base64" require "json" require "openssl" TOLERANCE_S = 5 * 60 def verify_webhook(secret, headers, raw_body) id = headers["webhook-id"] timestamp = headers["webhook-timestamp"] signatures = headers["webhook-signature"] raise "missing signature headers" unless id && timestamp && signatures raise "timestamp outside tolerance" if (Time.now.to_i - timestamp.to_i).abs > TOLERANCE_S key = Base64.decode64(secret.delete_prefix("whsec_")) digest = OpenSSL::HMAC.digest("SHA256", key, "#{id}.#{timestamp}.#{raw_body}") expected = Base64.strict_encode64(digest) ok = signatures.split(" ").any? do |entry| version, sig = entry.split(",", 2) version == "v1" && sig && OpenSSL.secure_compare(sig, expected) end raise "no matching signature" unless ok JSON.parse(raw_body) end ``` Two things trip people up: - **Verify the raw request body**, byte for byte, before any body-parsing middleware runs. Parsing and re-serializing the JSON changes the bytes (even a whitespace difference) and the verification fails. - The timestamp check depends on your server clock being accurate. Reject anything that fails verification with a `400`, and never process an unverified payload. The scheme is the one implemented by [Svix libraries](https://docs.svix.com/receiving/verifying-payloads/how) (they accept the `webhook-*` header names too), so if you already use one, its `verify` function performs exactly these checks and is equally fine. ### Test the delivery [#test-the-delivery] Two ways to see events hit your endpoint before any real payment exists: - **Send a test event.** In the dashboard's **Webhooks** page, send a test event of any type to your endpoint. Test events carry sample data with `live: false`; use them to check signature verification and your 2xx response. - **Run the full flow in [test mode](/payments/test-mode).** Create a test payment and drive it through its lifecycle with the Test Console or the dashboard's simulation actions. Each transition emits the real webhook, from `payment.created` through `payment.succeeded` (or `failed`, `expired`, `cancelled`), and a succeeded test payment settles automatically, so `payment.settled` arrives too. You can verify your handler against every path, including the ones that are hard to produce on demand with real payments. The dashboard shows each endpoint's recent deliveries with response status and timing, which is the first place to look when something doesn't arrive. During local development, expose your handler with a tunnel (e.g. `ngrok`, `cloudflared`) and register the tunnel URL as your test-mode endpoint. ## Allowlist webhook source IPs (optional) [#allowlist-webhook-source-ips-optional] {/* Source: hosted webhook provider's published EU source-IP list (https://docs.svix.com/webhook-ips.json, `eu` block). Verified 2026-07-27. IPv4 entries unchanged since June 2023; review yearly. */} If your webhook endpoint sits behind a firewall, allow inbound HTTPS requests from these addresses. Deliveries always originate from this set. - `52.215.16.239` - `54.216.8.72` - `63.33.109.123` - `2a05:d028:17:8000::/56` Allowlisting is defense in depth. It does not authenticate a delivery and is not a substitute for signature verification: always verify the signature before accepting an event. Two things to get right: - **Allow the whole set, not the address you happen to observe first.** Deliveries are sent from a pool and the source address varies between events. Allowing a single observed address will silently block later deliveries. - **Include the IPv6 range** if your network is dual-stack, otherwise a share of deliveries will be dropped. If deliveries stop after you enable the allowlist, or your firewall logs show traffic from an address outside this set, contact WalletConnect support with the UTC time window and any event ID you have. Do not silently drop the traffic. ## Go live [#go-live] Webhook configuration does **not** carry over from test to live; they are separate environments end to end. When you switch: 1. Flip the dashboard to **Live** and register your production endpoint URL and event types again. 2. Store the **live signing secret**, which is different from your test secret, and make sure your handler uses the secret matching the environment. 3. Confirm your handler checks `data.live === true` before triggering real fulfillment. Test events and test-mode payments always carry `live: false`. 4. Re-verify the safety rails: dedupe by `id`, ordering by `payment_state_version`. ## Next steps [#next-steps] } href="/payments/webhook-event-reference"> Every field of every event type, with types, nullability, and examples. } href="/payments/test-mode"> Simulate every payment status transition and watch the webhooks arrive. } href="/payments/api-reference/latest/get-v1-payments-id-status"> The polling endpoint to confirm state on the critical path. # Report an Issue (/report-an-issue) The WalletConnect Dashboard is your single place to report bugs and share feedback. ## How to Report an Issue [#how-to-report-an-issue] Follow these steps to get in touch with our support team: ### Log in to the WalletConnect Dashboard [#log-in-to-the-walletconnect-dashboard] Go to [dashboard.walletconnect.com](https://dashboard.walletconnect.com) and log in with your account. ### Open the Help Center [#open-the-help-center] Once logged in, click the chat bubble in the bottom-right corner of the page, or choose **Report a bug** from the Help Center sidebar. Help Center chat bubble in the WalletConnect Dashboard ### Report the issue [#report-the-issue] From the help desk modal, select: - **File a bug report** - Submit the issue to our support team. - **Check our docs** - Browse through our documentation for answers. Our team will review your submission and get back to you as soon as possible. ## Support Response Times [#support-response-times] We don't offer guaranteed response times. Our team answers general issues as capacity allows, so replies may take anywhere from a few hours to several days. Thanks for your patience. # Security Information (/security) Security is not just a feature but a fundamental aspect of WalletConnect's architecture. The infrastructure has undergone multiple rounds of third-party security reviews, audits, penetration testing, and threat modeling to ensure the highest standards of protection. Security is viewed as a continuously evolving discipline, with regular system audits to identify and address potential vulnerabilities. The entire WalletConnect system underwent Threat Modeling by Spearbit in 2024, and then an entire ecosystem audit in 2026 to reach SOC2 Type II Certification. ## SOC2 Type II Certification [#soc2-type-ii-certification] WalletConnect underwent SOC2 Type II certification in 2026, demonstrating robust security controls and the ability to secure user data from unauthorized access - using it solely for its intended purpose and with confidentiality, as well as providing consistent availability on all systems and processing data appropriately and within time limits. As a Type II certification, WalletConnect displayed its security and data controls work over a period of time rather than simply on the spot. ## SDK for Wallets [#sdk-for-wallets] WalletConnect's SDK for wallets is an open-source SDK, supporting multiple transport methods, from WebSockets to Universal Links. Its design philosophy prioritizes minimizing third-party dependencies to reduce the attack surface area. To ensure its reliability and security, the SDK for wallets was audited by Trail of Bits. The audit report is available here. This comprehensive security review covered the source code and included a lightweight Threat Model covering upstream and downstream dependencies. ## Third-Party Reviews [#third-party-reviews] The security infrastructure of Reown has undergone multiple rounds of audits by independent security auditing firms, including Trail of Bits, Halborn, and Spearbit. These audits cover both AppKit and WalletKit, along with a comprehensive company-wide Threat Model. | Audit Scope | Auditor | Report | | --- | --- | --- | | WalletConnect SOC2 Type II Certification | AICPA | | | WalletConnect Comprehensive Threat Model | Spearbit | View Report | | SDK for Apps Embedded Wallet Integration Pentest | Halborn | View Report | | SDK for wallets Security Review & Lightweight Threat Model | Trail of Bits | View Report | ## Security disclosures [#security-disclosures] WalletConnect maintains an active bug bounty program to encourage security researchers to responsibly disclose vulnerabilities and help strengthen the systems. To report a vulnerability, please fill out the disclosure form here. # Wallet Verification Results and Attestations (/wallet-verification/attestations) When a user signs, Wallet Verification checks the signature and stores an attestation on the verification. The attestation holds everything you need to re-check the proof independently. ## Verification states [#verification-states] | State | Terminal | Meaning | |-------|----------|---------| | `pending` | No | Created. Waiting for the user to sign. | | `verified` | Yes | The signature checked out. `attestation` is set. | | `failed` | Yes | The signature did not verify. `failure_reason` is set. | | `expired` | Yes | `expires_at` passed without a signature. | | `cancelled` | Yes | You cancelled the verification. The link no longer works. | `failure_reason` is currently always `invalid_signature`. ## Verification object [#verification-object] | Field | Description | |-------|-------------| | `id` | Verification ID, `ver_` followed by 32 hex characters. | | `state` | One of the [states](#verification-states) above. | | `reference_id` | Your identifier from create. | | `purpose` | `withdrawal`, `payout`, `onboarding`, or `re_verification`. | | `chain_id` | CAIP-2 chain ID you pinned, or `null`. | | `expected_address` | Address you pinned, or `null`. | | `expires_at` | When the link stops working. | | `return_url` | Return URL you set, or `null`. | | `created_at` | When the verification was created. | | `metadata` | Your metadata object, echoed back. Never signed. | | `failure_reason` | Set when `state` is `failed`. | | `attestation` | Set when `state` is `verified`. See below. | The create response also includes `url`. No other response returns it. ## Attestation object [#attestation-object] | Field | Description | |-------|-------------| | `address` | Verified address. EIP-55 checksummed for EVM, base58 for Solana. | | `chain_id` | CAIP-2 chain ID the user signed on. | | `message` | The exact text the user signed. | | `signature` | `0x` hex for EVM, base58 for Solana. | | `wallet_type` | `eoa`, `eoa_7702`, `contract`, or `counterfactual`. | | `verification_method` | `ecrecover`, `erc1271`, `erc6492`, or `ed25519`. | | `block_number` | Block the contract check ran at, as a decimal string. `null` for stateless methods. | | `block_hash` | Hash of that block. `null` for stateless methods. | | `verified_at` | When the signature was verified. | `ecrecover` and `ed25519` are stateless. `erc1271` and `erc6492` call the wallet contract, so they record the block. Attestations are kept for 5 years. ## Verify an attestation yourself [#verify-an-attestation-yourself] You can re-check any attestation without trusting Wallet Verification. Pick the check that matches `verification_method`. These examples are illustrative. Use them as a starting point and adapt chain selection, RPC endpoints, and error handling to your stack. Recover the EIP-191 `personal_sign` signer over `message` and compare it to `address`. ```typescript title="verify-ecrecover.ts" import { verifyMessage } from "viem"; const valid = await verifyMessage({ address: attestation.address, message: attestation.message, signature: attestation.signature, }); ``` Call the ERC-6492 universal signature validator on the attestation's chain at `block_number`. viem's `publicClient.verifyMessage` handles both ERC-1271 and ERC-6492. ```typescript title="verify-contract.ts" import { createPublicClient, http } from "viem"; import { mainnet } from "viem/chains"; // match attestation.chain_id const client = createPublicClient({ chain: mainnet, transport: http() }); const valid = await client.verifyMessage({ address: attestation.address, message: attestation.message, signature: attestation.signature, blockNumber: BigInt(attestation.block_number), }); ``` Checking at a past block needs an RPC endpoint that serves historical state. Verify the signature over the UTF-8 bytes of `message` with the address as the public key. ```typescript title="verify-ed25519.ts" import { verifyAsync } from "@noble/ed25519"; import bs58 from "bs58"; const valid = await verifyAsync( bs58.decode(attestation.signature), new TextEncoder().encode(attestation.message), bs58.decode(attestation.address), ); ``` ## Signed message [#signed-message] EVM wallets sign an [EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) (Sign-In with Ethereum) message. Solana wallets sign the equivalent [CAIP-122](https://chainagnostic.org/CAIPs/caip-122) message. ```text title="Signed message format" {page host} wants you to sign in with your {Ethereum|Solana} account: {address} {Requester name} asks you to verify wallet ownership to {purpose text}. URI: {page origin}/s Version: 1 Chain ID: {EVM: chain number, e.g. 1 | Solana: full CAIP-2 id} Nonce: {nonce} Issued At: {created_at} Expiration Time: {expires_at} Request ID: {verification id, ver_…} ``` | Purpose | Purpose text | |---------|--------------| | `withdrawal` | authorise a withdrawal to this wallet | | `payout` | receive payouts at this wallet | | `onboarding` | complete onboarding | | `re_verification` | re-confirm ownership of this wallet | The requester name is the business name from [Customization](/wallet-verification/dashboard#customization), with accents stripped to fit the format. Without one, it reads "The requester". Your `reference_id` and `metadata` are not part of the message. To fetch only the signed text, call `GET /verifications/{id}/message`. It returns `text/plain`, or `409 not_verified` if the verification is not `verified`. # Wallet Verification Dashboard and API Keys (/wallet-verification/dashboard) You manage Wallet Verification in the [WalletConnect Pay merchant dashboard](https://merchant.pay.walletconnect.com/en/api-keys). ## Request access [#request-access] 1. Open the **API keys** page and select the **Wallet Verification** tab. 2. Click **Request access**. You can add an optional message. 3. The status shows **Request received** while the WalletConnect team reviews your request. Once access is enabled, you can create API keys. ## API keys [#api-keys] ![API keys page on the Wallet verification tab, listing two keys with masked values and creation dates](/images/wallet-verification/dashboard-api-keys.png) - Give each key a name of 1–64 characters. - You can have up to 10 active keys. - The full key is shown only once, at creation. Copy it to a secret manager. The list shows a masked key. - Keys start with `wv_` and go in the `Authorization: Bearer` header. Keys can be revoked but not edited. To rotate a key, create a new one, deploy it, then revoke the old one. Requests with a revoked key return `401 unauthorized`. Deploy the new key before you revoke the old one. ## Activity [#activity] The **Activity** page lists every verification on your account with its date, address, wallet, network, reference, and status. Sort by any column and click **Load more** to see older verifications. ![Activity page listing verifications with date, address, wallet, network, reference and status, and an Export CSV button](/images/wallet-verification/dashboard-activity.png) ### Export CSV [#export-csv] Click **Export CSV** to download verifications from the last 90 days. - The file is prepared in the background and downloads automatically when ready, usually within seconds. - If it takes more than 2 minutes, the dashboard shows **Taking longer than usual** with a retry option. - Download links last 15 minutes. Exported files are deleted after 7 days. ## Customization [#customization] The **Customization** page controls how the [hosted page](/wallet-verification/hosted-page) looks to your users. ![Customization page with business name, page title and logo fields, and Preview and Save buttons](/images/wallet-verification/dashboard-customization.png) | Setting | Limit | Where it appears | |---------|-------|------------------| | Business name | Up to 120 characters | Hosted page and the [signed message](/wallet-verification/attestations#signed-message) | | Page title | Up to 120 characters | Hosted page | | Logo | Image upload | Hosted page | Set your business name before you go live. Users see it in their wallet when they sign, which helps them trust the request. ## Integration settings [#integration-settings] Allowed return-URL origins and embedding origins are not in the dashboard yet. Contact your WalletConnect contact to register them. See [Return to your app](/wallet-verification/hosted-page#return-to-your-app) and [Embed in an iframe](/wallet-verification/hosted-page#embed-in-an-iframe). # Wallet Verification User Experience (/wallet-verification/hosted-page) The verification page is where your user connects a wallet and signs the verification message. You get its link as the `url` when you [create a verification](/wallet-verification/quickstart). ## What your user sees [#what-your-user-sees]
![Wallet Verification page asking the user to connect a wallet, with a searchable wallet list and a QR code to connect on mobile](/images/wallet-verification/connect-wallet.png)
The first screen: your business name at the top, the wallet list, and a QR code for mobile wallets.
### Open the link [#open-the-link] The page shows your business name, page title, and logo from [Customization](/wallet-verification/dashboard#customization). ### Connect a wallet [#connect-a-wallet] The user picks a wallet from the list, or on desktop scans the QR code with a mobile wallet. More than 700 wallets connect through WalletConnect. ### Review [#review] The user reviews the address and taps **Verify address**. The page names the wallet that will ask for approval and states that no funds move. ![Review screen showing the Solana network and shortened address, the wallet that will ask for approval, and a Verify address button](/images/wallet-verification/review.png) ### Add personal details [#add-personal-details] Only shown if your account collects user information. After tapping **Verify address**, the user enters their full name, date of birth, and city and country of birth, then accepts the terms. ![Personal details form asking for full name, date of birth, city of birth and country of birth, with an I agree checkbox and a Confirm button](/images/wallet-verification/personal-details.png) ### Sign [#sign] The user signs the message in their wallet. The [signed message](/wallet-verification/attestations#signed-message) names your business and the purpose. ### Done [#done] The page shows **Wallet verified** if you set `expected_address`, or **Wallet added** if you didn't. With a `return_url`, it sends the user back to your app after 5 seconds, or right away when they tap **Return to** your business name. ![Success screen titled Wallet verified, counting down 5 seconds before returning the user to Acme Inc, with a Return to Acme Inc button](/images/wallet-verification/verified.png) ### Errors the user can see [#errors-the-user-can-see] | Error | What it means | |-------|---------------| | Wrong wallet | The connected address does not match `expected_address`. | | Wrong network | The wallet is on a different network than `chain_id`. | | Invalid signature | The signature did not verify. This is terminal: the verification ends as `failed`, and the user needs a fresh link from you. | | Unsupported wallet type | The wallet type is not supported. See [Supported wallets and networks](#supported-wallets-and-networks). | | Unsupported network | The network is not supported. | | Chain temporarily unavailable | The page could not reach the chain. The user can retry. | ## Return to your app [#return-to-your-app] Set `return_url` when you create a verification to send the user back to your app. After a successful verification the page returns the user automatically after 5 seconds, unless it is [in an iframe](#embed-in-an-iframe). The **Return to** button (it shows your business name) on the success and error screens, and the **Cancel** button, navigate to `return_url` exactly as you gave it. Nothing is appended, so look up the result by polling. Without a `return_url`, the success screen tells the user they can close the page, and the other buttons close the tab. The `return_url` must be HTTPS, and its origin must be on your account's allowed list (exact `https://host[:port]`, up to 20 origins). Otherwise create returns `400 invalid_return_url`. See [Integration settings](/wallet-verification/dashboard#integration-settings) to register origins. ## Embed in an iframe [#embed-in-an-iframe] You can show the verification page inside your app in an iframe. The page can only be framed by origins on your account's embedding list. Without one, the page refuses to be framed (`frame-ancestors 'none'`). Embedding origins are `https://host` or `https://*.host`, up to 20. Each host must be a registrable domain. IP addresses, `localhost`, and bare platform suffixes such as `*.vercel.app` are not allowed. See [Integration settings](/wallet-verification/dashboard#integration-settings) to register origins. The page is served from these origins: | Environment | Verification page origin | |-------------|--------------------------| | Production | `https://wallet-verification.walletconnect.com` | | Staging | `https://staging.wallet-verification.walletconnect.com` | When embedded: - **When the user verifies**, the page posts a `verified` message to the parent window right away, without waiting for a click. - **No automatic return** when framed. The 5-second return only runs when the page is not in an iframe. Close the frame or move on when you get `verified`. - **With a `return_url`**, the Return and Cancel buttons navigate the top window. If your iframe is sandboxed, add `allow-top-navigation-by-user-activation`. Otherwise only the iframe navigates. - **Without a `return_url`**, the Return and Cancel buttons post a message to the parent window instead of navigating: ```json title="postMessage payload" { "type": "wallet_verification:return", "state": "verified" } ``` `state` is one of `verified`, `cancelled`, `failed`, `expired`, `not_found`, `pending`, or `unknown`. The message is only sent to an origin on your embedding list, never to `*`. ```javascript title="Listen for the return message" window.addEventListener("message", (event) => { if (event.origin !== "https://wallet-verification.walletconnect.com") return; if (event.data?.type !== "wallet_verification:return") return; // Treat this as a hint. Confirm the result on your backend. closeVerificationFrame(); refreshVerificationStatus(); }); ``` Browsers that do not expose the parent origin, such as Firefox without a referrer, receive no message. Always confirm the result server-side by polling `GET /verifications/{id}`. ## Supported wallets and networks [#supported-wallets-and-networks] | Network | Supported | Not supported | |---------|-----------|---------------| | EVM | Regular accounts (EOA), EIP-7702 accounts, smart contract wallets (ERC-1271), smart wallets that are not deployed yet (ERC-6492) | Multi-signature wallets that need several approvers | | Solana | Regular accounts (ed25519) | Program-derived addresses | An EVM address is the same on every EVM chain. A verification proves control of the address. ## Limitations [#limitations] - Multi-signature wallets that need more than one approver, such as a Safe with a threshold above 1, are not supported yet. Today such a verification ends as `failed`. Multisig support is planned. - Solana program-derived addresses are not supported. - Allowed return-URL and embedding origins are not self-serve yet. See [Integration settings](/wallet-verification/dashboard#integration-settings). # Wallet Verification (/wallet-verification) Wallet Verification lets you confirm that a user controls a wallet address before you rely on it. Your backend creates a verification, the user opens a verification page, connects their wallet, and signs a plain-text message. Wallet Verification checks the signature and stores an attestation that you can read and re-check yourself. The user only signs a message. No funds move, no transaction is sent, and the user pays no gas. ## Who is Wallet Verification for? [#who-is-wallet-verification-for] - **Payout platforms and PSPs** that need to confirm a beneficiary controls the destination wallet before sending a payout or approving a withdrawal. - **Platforms verifying their own customers** that want proof of ownership for the wallets customers link during onboarding or re-verification. - **Regulated institutions** that need proof of control over self-hosted wallets for Travel Rule checks. ## How does Wallet Verification work? [#how-does-wallet-verification-work] ```mermaid sequenceDiagram participant Backend as Your backend participant API as Wallet Verification API participant User as User participant Page as Verification page Backend->>API: POST /verifications API-->>Backend: 201 verification + url Backend->>User: Send the url (link, redirect, or embed) User->>Page: Open link and connect wallet Page->>User: Ask for a signature User->>Page: Sign the message Page->>API: Submit signature API->>API: Check signature and store attestation loop Until the state is terminal Backend->>API: GET /verifications/{id} end API-->>Backend: state verified + attestation ``` 1. Your backend creates a verification with your own `reference_id` and a `purpose`. The response includes a one-time `url`. 2. You send the user that `url` as a link, a redirect, or an embedded iframe. 3. The user opens the [verification page](/wallet-verification/hosted-page), connects a wallet, and signs a message that names your business and the purpose. 4. Wallet Verification checks the signature and stores an [attestation](/wallet-verification/attestations). 5. Your backend polls the verification until it reaches a terminal state, then reads the attestation. Wallet Verification does not send webhooks. Poll `GET /verifications/{id}` to get the result. ## Get started [#get-started] } href="/wallet-verification/quickstart"> Create your first verification and read the result. } href="/wallet-verification/dashboard"> Request access, manage API keys, customize the page, and review activity. } href="/wallet-verification/hosted-page"> What your users see, supported wallets, return URLs, and embedding. } href="/wallet-verification/attestations"> States, the attestation, how to re-check a signature, and the signed message. The API reference is coming soon. # Wallet Verification Quickstart (/wallet-verification/quickstart) This guide takes you from an API key to a verified wallet in five steps. | Environment | API base URL | |-------------|--------------| | Production | `https://api.wallet-verification.walletconnect.com` | | Staging | `https://staging.api.wallet-verification.walletconnect.com` | Use staging for integration testing only; attestations created there are not evidence for compliance. There is no test mode in production. ### Get access and an API key [#get-access-and-an-api-key] In the WalletConnect Pay merchant dashboard, open the **Wallet Verification** tab on the [API keys](https://merchant.pay.walletconnect.com/en/api-keys) page and request access. Once access is enabled, create an API key. The full key is shown only once, so store it in a secret manager. See [Dashboard & API keys](/wallet-verification/dashboard) for details. Send the key as a bearer token on every request: ```bash title="Environment" export WV_API_KEY="wv_your-api-key" export WV_BASE="https://api.wallet-verification.walletconnect.com" ``` A missing, unknown, or revoked key, or an account without access, returns `401 unauthorized`. ### Create a verification [#create-a-verification] ```bash title="Create a verification" curl -X POST "$WV_BASE/verifications" \ -H "Authorization: Bearer $WV_API_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "reference_id": "customer-4821-payout-wallet", "purpose": "payout", "chain_id": "eip155:1", "return_url": "https://app.example.com/wallets" }' ``` | Field | Required | Description | |-------|----------|-------------| | `reference_id` | Yes | Your own identifier, 1–200 printable ASCII characters with no spaces. Not included in the signed message. | | `purpose` | Yes | `withdrawal`, `payout`, `onboarding`, or `re_verification`. Sets the wording of the signed message. | | `chain_id` | No | CAIP-2 chain ID in the `eip155` or `solana` namespace. If omitted, the user chooses Ethereum-compatible or Solana when connecting. | | `expected_address` | No | Pins the wallet. The page and the API refuse any other address. Returns `400 invalid_address` if it does not fit the pinned chain. | | `validity_seconds` | No | How long the link stays valid. 60 to 2,592,000 (30 days). Defaults to 604,800 (7 days). | | `metadata` | No | Object up to 4 KiB, echoed back on the verification. Never signed. Do not put personal data here. | | `return_url` | No | HTTPS URL the page sends the user back to. Up to 2,048 characters, no credentials, and its origin must be registered for your account. See [Return to your app](/wallet-verification/hosted-page#return-to-your-app). | The request body can be up to 16 KiB. Larger bodies return `413 request_error`. A successful request returns `201` with the [verification object](/wallet-verification/attestations#verification-object) plus a `url`: ```json title="201 Created" { "id": "ver_3f9a1c2b7d8e4f6a9b0c1d2e3f4a5b6c", "state": "pending", "reference_id": "customer-4821-payout-wallet", "purpose": "payout", "chain_id": "eip155:1", "expected_address": null, "expires_at": "2026-10-15T10:00:00Z", "return_url": "https://app.example.com/wallets", "created_at": "2026-10-08T10:00:00Z", "metadata": {}, "failure_reason": null, "attestation": null, "url": "https://wallet-verification.walletconnect.com/s/your-session-token" } ``` The `url` is returned only in this response. Store it with the verification `id`. ### Send the user the link [#send-the-user-the-link] Give the user the `url` however fits your product: send it as a link, redirect the browser to it, or embed it in an iframe. The [verification page](/wallet-verification/hosted-page) walks the user through connecting and signing. ### Poll for the result [#poll-for-the-result] Poll the verification until its `state` is terminal: `verified`, `failed`, `expired`, or `cancelled`. ```bash title="Read a verification" curl "$WV_BASE/verifications/ver_3f9a1c2b7d8e4f6a9b0c1d2e3f4a5b6c" \ -H "Authorization: Bearer $WV_API_KEY" ``` Poll every few seconds while the user is on the page, then back off. If the user returns through your `return_url` or the page posts a message to your parent window, poll once more to confirm the result server-side. To find verifications later, list them with `GET /verifications`. Results are newest first and support `limit` (1–100, default 20), an opaque `cursor`, and the filters `state`, `reference_id`, `from` (inclusive), and `to` (exclusive). The response is `{ "data": [...], "next_cursor": "..." }`, and `next_cursor` is `null` on the last page. ### Read the result [#read-the-result] When `state` is `verified`, the `attestation` field holds the address, the exact signed message, the signature, and how it was checked. See [Results & attestations](/wallet-verification/attestations) for every field and how to re-check the signature yourself. ## Idempotency [#idempotency] Send an `Idempotency-Key` header (1–255 characters) on create so you can retry safely. Keys are scoped to your account and kept for 24 hours. - Retrying with the same key and the same body returns `200` with the same verification and **no `url`**. Keep the `url` from the first `201`. - Reusing a key with a different body returns `409 idempotency_key_mismatch`. ## One live session per reference [#one-live-session-per-reference] Each `reference_id` can have only one `pending` verification at a time. Creating another while one is pending returns `409 reference_in_progress`, and the link is not re-issued: ```json title="409 Conflict" { "status": "error", "error": { "code": "reference_in_progress", "message": "A verification for this reference is already in progress.", "details": { "verification_id": "ver_3f9a1c2b7d8e4f6a9b0c1d2e3f4a5b6c", "state": "pending", "expires_at": "2026-10-15T10:00:00Z" } } } ``` Once the earlier verification reaches a terminal state, create a new one with the same `reference_id`. Use the `re_verification` purpose so the signed message says why. ## Cancel a verification [#cancel-a-verification] Cancel a pending verification to stop its link from working: ```bash title="Cancel a verification" curl -X POST "$WV_BASE/verifications/ver_3f9a1c2b7d8e4f6a9b0c1d2e3f4a5b6c/cancel" \ -H "Authorization: Bearer $WV_API_KEY" ``` The state moves to `cancelled`. Cancelling a verification in any other state returns `409 not_cancellable`. ## Error handling [#error-handling] Errors use one envelope. Switch on `code`. The `message` text may change. ```json title="Error envelope" { "status": "error", "error": { "code": "invalid_body", "message": "Human-readable description.", "details": {} } } ``` | Code | HTTP | Meaning | |------|------|---------| | `invalid_body` | 400 | The request body failed validation. | | `invalid_address` | 400 | `expected_address` is not valid for the pinned chain. | | `invalid_return_url` | 400 | `return_url` is malformed or its origin is not registered for your account. | | `invalid_cursor` | 400 | The cursor is invalid or was reused with different filters. | | `request_error` | 400, 413 | The request is malformed, or the body is larger than 16 KiB. | | `unauthorized` | 401 | The API key is missing, unknown, or revoked, or the account has no access. | | `not_found` | 404 | No verification with this ID exists for your account. | | `not_cancellable` | 409 | Only `pending` verifications can be cancelled. | | `not_verified` | 409 | The signed message is only available once the verification is `verified`. | | `reference_in_progress` | 409 | A `pending` verification already exists for this `reference_id`. | | `idempotency_key_mismatch` | 409 | The idempotency key was used with a different body. | | `internal_error` | 500 | Something went wrong on the server. Retry with the same idempotency key. | ## Frequently asked questions [#frequently-asked-questions] The verification moves to `expired` once `expires_at` passes without a signature, and the link stops working. Create a new verification to get a new link. No. The `url` is returned only in the first `201` response. If you lose it, cancel the verification and create a new one. # Best Practices (/wallets/android/best-practices) The purpose of this guide is to show the best practices in regards of the WalletKit client usage. The goal is to provide the best user experience that just works in every circumstances. In order to ensure the best user experience and flawless connection flow, please make sure that WalletKit is initialized immediately after your app launch, especially if launched via a WalletConnect Deep Link. It guarantees that websocket connection is opened immediately and all requests are received by your wallet ## Pairing [#pairing] A pairing is a connection between a wallet and a dapp that has fixed permissions to only allow a dapp to propose a session through it. Dapp can propose infinite number of sessions on one pairing. Wallet must use a pair method from WalletKit client to pair with dapp. ```kotlin val pairingParams = Wallet.Params.Pair(pairingUri) WalletKit.pair(pairingParams, onSuccess = { //Subscribed on the pairing topic successfully. Wallet should await for a session proposal }, onError = { error -> //Some error happens while pairing - check Expected errors section } } ``` ### Pairing State [#pairing-state] A pairing state is a primitive exposed by the WalletKit client for a wallet to indicate whether it should await a session proposal. The pairing state is `true` when a wallet scans a QR and awaits a session proposal. Once the session proposal is received by the wallet, the pairing state is changed to `false`. When `true` wallet should show a loading indicator awaiting a session proposal, when changed to `false` a proposal dialog should be displayed. ```kotlin val coreDelegate = object : CoreClient.CoreDelegate { override fun onPairingState(pairingState: Core.Model.PairingState) { //Here a pairing state is triggered } ...other callbacks } CoreClient.setDelegate(coreDelegate) ``` ### Pairing Expiry [#pairing-expiry] A pairing expiry event is triggered whenever a pairing is expired. The expiry for inactive pairing is 5 mins, whereas for active pairing is 30 days. A pairing becomes active when a session proposal is received and user successfully approves it. This event helps to know when given pairing expires and update UI accordingly. ```kotlin val coreDelegate = object : CoreClient.CoreDelegate { override fun onPairingExpired(expiredPairing: Core.Model.ExpiredPairing) { //Here a pairing expiry is triggered } ...other callbacks } CoreClient.setDelegate(coreDelegate) ``` ### Expected User flow [#expected-user-flow] ### Pairing Flow [#pairing-flow] Wallet pairing with a dApp and showing the session proposal to approve or reject ### Pairing Error [#pairing-error] Wallet showing an error when pairing with a dApp fails ### Expected Errors [#expected-errors] While pairing the following errors might occur: - No Internet connection error or pairing timeout when scanning QR with no Internet connection - User should pair again with Internet connection - Pairing expired error when scanning a QR code with expired pairing - User should refresh a QR code and scan again - Pairing with existing pairing is not allowed - User should refresh a QR code and scan again. I usually happens when user scans an already paired QR code. ## Session Proposal [#session-proposal] A session proposal is a handshake sent by a dapp and it's purpose is to define a session rules. Whenever a user wants to establish a connection between a wallet and a dapp, one should approve a session proposal. ### User Action Feedback [#user-action-feedback] Whenever user approves or rejects a session proposal, wallet should show loading indicators in a moment of the button press until Relay acknowledgement is received for any of this actions. Session approve ```kotlin WalletKit.approveSession(approveProposal, onSuccess = { //Session approval response was sent successfully - update your UI } onError = { error -> //Error while sending session approval - update your UI }) ``` Session reject ```kotlin WalletKit.rejectSession(reject, onSuccess = { //Session rejection response was sent successfully - update your UI }, onError = { error -> //Error while sending session rejection - update your UI }) ``` ### Session Proposal Expiry [#session-proposal-expiry] A session proposal expiry is 5 mins. It means a given proposal is stored for 5 mins in the SDK storage and user has 5 mins for approval or rejection decision. After that time the below event is emitted and proposal modal should be removed from the app's UI. ```kotlin val walletDelegate = object : WalletKit.WalletDelegate { override fun onProposalExpired(proposal: Wallet.Model.ExpiredProposal) { //Here this event is triggered when a proposal expires - update your UI } ...other callbacks } WalletKit.setWalletDelegate(walletDelegate) ``` ### Expected User flow [#expected-user-flow-1] ### Approve or Reject Session Proposal [#approve-or-reject-session-proposal] Wallet pairing with a dApp and showing the session proposal to approve or reject ### Error Handling [#error-handling] Wallet showing an error while approving or rejecting a session proposal ### Expected Errors [#expected-errors-1] While approving or rejecting a session proposal the following errors might occurs: - No Internet connection - It happens when a user tries to approve or reject session proposal with no Internet connection - Session proposal expired - It happens when users tries to approve or reject expired session proposal - Invalid namespaces - It happens when a validation of session namespaces fails - Timeout - It happens when Relay doesn't acknowledge session settle publish within 10s ## Session Request [#session-request] A session request represents the request sent by a dapp to a wallet. ### User Action Feedback [#user-action-feedback-1] Whenever user approves or rejects a session request, wallet should show loading indicators in a moment of the button press until Relay acknowledgement is received for any of this actions. ```kotlin WalletKit.respondSessionRequest(Wallet.Params.SessionRequestResponse, onSuccess = { //Session request response was sent successfully - update your UI }, onError = { error -> //Error while sending session response - update your UI }) ``` ### Session Request Expiry [#session-request-expiry] A session request expiry is defined by a dapp. It's value must be between now() + 5mins and now() + 7 days. After the session request expires the below event is emitted and session request modal should be removed from the app's UI. ```kotlin val walletDelegate = object : WalletKit.WalletDelegate { override fun onRequestExpired(request: Wallet.Model.ExpiredRequest) { //Here this event is triggered when a session request expires - update your UI } ...other callbacks } WalletKit.setWalletDelegate(walletDelegate) ``` ### Expected User flow [#expected-user-flow-2] ### Approve or Reject Session Proposal [#approve-or-reject-session-proposal-1] Wallet showing a dApp signing request for the user to approve or reject ### Error Handling [#error-handling-1] Wallet showing an error while responding to a session request ### Expected Errors [#expected-errors-2] While approving or rejecting a session request the following error might occur: - Invalid session - This error might happen when user approves or rejects a session request on expired session - Session request expired - This error might happen when user approves or rejects a session request that already expires - Timeout - It happens when Relay doesn't acknowledge session settle publish within 10s ## Web Socket Connection State [#web-socket-connection-state] The Web Socket connection state tracks the connection with the relay server, event is emitted whenever a connection state changes. ```kotlin val walletDelegate = object : WalletKit.WalletDelegate { override fun onConnectionStateChange(state: Wallet.Model.ConnectionState) { //Here this event is triggered when a connection state has changed } ...other callbacks } WalletKit.setWalletDelegate(walletDelegate) ``` ### Expected User flow [#expected-user-flow-3] ### Connection State [#connection-state] ![Wallet showing a no internet connection banner when the relay connection drops](/images/mintlify/assets/connection_state.gif) # Chain Abstraction (/wallets/android/chain-abstraction) ## Methods [#methods] The following methods from Wallet SDK are used in implementing chain abstraction. 💡 Chain abstraction is currently in the early access phase and requires the `@ChainAbstractionExperimentalApi` annotation. ### Prepare [#prepare] This method is used to check if chain abstraction is needed. If it is, it will return a `PrepareSuccess.Available` object with the necessary transactions and funding information. If it is not, it will return a `PrepareSuccess.NotRequired` object with the original transaction. Accounts field is a list of CAIP-20 accounts you are sourcing from e.g. Solana account ```kotlin @ChainAbstractionExperimentalApi fun prepare( initialTransaction: Wallet.Model.InitialTransaction, accounts: List, onSuccess: (Wallet.Model.PrepareSuccess) -> Unit, onError: (Wallet.Model.PrepareError) -> Unit ) ``` ### Execute [#execute] This method is used to execute the chain abstraction operation. It broadcasts the bridging and initial transactions and waits for them to be completed. The method returns a `ExecuteSuccess` object with the transaction hash and receipt. ```kotlin @ChainAbstractionExperimentalApi fun execute( prepareAvailable: Wallet.Model.PrepareSuccess.Available, prepareSignedTxs: List, initSignedTx: String, onSuccess: (Wallet.Model.ExecuteSuccess) -> Unit, onError: (Wallet.Model.Error) -> Unit ) ``` ## Usage [#usage] When sending a transaction, first check if chain abstraction is needed using the `prepare` method. If it is needed, you must sign all the fulfillment transactions and use the `execute` method. If the operation is successful, use `execute` method and await the transaction hash and receipt. If the operation is unsuccessful, send the JsonRpcError to the dapp and display the error to the user. ```kotlin val initialTransaction = Wallet.Model.Transaction(...) WalletKit.ChainAbstraction.prepare( initialTransaction, caip10Accounts, onSuccess = { prepareSuccess -> when (prepareSuccess) { is Wallet.Model.PrepareSuccess.Available -> { // If the route is available, present a CA transaction flow //sign route transactions transactionsDetails?.route?.forEach { route -> route.transactionDetails.forEach { transactionDetails -> val signedTransaction = Signer.signHash(transactionDetails.transactionHashToSign, EthAccountDelegate.privateKey) eip155Signatures.add(signedTransaction) } } } //sign initial transaction val signedInitialTx = Signer.signHash(transactionsDetails?.initialDetails.transactionHashToSign, EthAccountDelegate.privateKey) //Call the execute WalletKit.ChainAbstraction.execute(prepareSuccess, eip155Signatures, signedInitialTx onSuccess = { //The execution of the Chain Abstraction is successfull //Send the response to the Dapp or show to the user }, onError = { //Execute error - wallet should send the JsonRpcError to a dapp for given request and display error to the user } ) } is Wallet.Model.PrepareSuccess.NotRequired -> { // user does not need to move funds from other chains, sign and broadcast original transaction } } }, onError = { prepareError -> // One of the possible errors: NoRoutesAvailable, InsufficientFunds, InsufficientGasFunds - wallet should send the JsonRpcError to a dapp for given request and display error to the user } ) ``` For example, check out implementation of chain abstraction in [sample wallet](https://github.com/WalletConnect/WalletConnectKotlinV2/tree/master/sample/wallet) with Kotlin. ## Testing [#testing] To test Chain Abstraction, you can use the [AppKit laboratory](https://lab.reown.com/appkit/?name=wagmi) and try sending any supported [tokens](/wallets/features/chain-abstraction#what-are-the-supported-tokens-and-networks) with any chain abstraction supported wallet. You can also use this [sample wallet](https://appdistribution.firebase.dev/i/076a3bc9669d3bee) for testing. ## ProGuard rules [#proguard-rules] If you encounter issues with minification, add the below rules to your application: ``` -keepattributes *Annotation* -keep class com.sun.jna.** { *; } -keepclassmembers class com.sun.jna.** { native ; *; } -keep class uniffi.** { *; } # Preserve all public and protected fields and methods -keepclassmembers class ** { public *; protected *; } -dontwarn uniffi.** -dontwarn com.sun.jna.** ``` # Analytics (/wallets/android/cloud/analytics) # Explorer Submission (/wallets/android/cloud/explorer-submission) # Relay (/wallets/android/cloud/relay) # Wallet Call API (/wallets/android/eip5792) WalletConnect supports [EIP-5792](https://eips.ethereum.org/EIPS/eip-5792#atomicbatch-capability), which defines new JSON-RPC methods that enable apps to ask a wallet to process a batch of onchain write calls and to check on the status of those calls. Applications can specify that these onchain calls be executed taking advantage of specific capabilities previously expressed by the wallet; an additional, a novel wallet RPC is defined to enable apps to query the wallet for those capabilities. - `wallet_sendCalls`: Requests that a wallet submits a batch of calls. - `wallet_getCallsStatus`: Returns the status of a call batch that was sent via wallet_sendCalls. - `wallet_showCallsStatus`: Requests that a wallet shows information about a given call bundle that was sent with wallet_sendCalls. - `wallet_getCapabilities`: This RPC allows an application to request capabilities from a wallet (e.g. batch transactions, paymaster communication). ## Usage [#usage] ## Capabilities in CAIP-25 Connection Requests [#capabilities-in-caip-25-connection-requests] CAIP-25 defines how capabilities can be expressed in wallet-to-dapp connections. These capabilities control how methods like `wallet_sendCalls` behave. ### Session Properties [#session-properties] In a connection request, dApps can request capabilities through `sessionProperties`. These capabilities can be universal (applying to all chains) or chain-specific: ```json "sessionProperties": { "expiry": "2022-12-24T17:07:31+00:00", "caip154": { "supported": "true" }, "flow-control": { "loose": [], "strict": [], "exoticThirdThing": [] }, "atomic": { "status": "supported" } } ``` ### Scoped Properties [#scoped-properties] For chain-specific capabilities, dapps use `scopedProperties`: ```json "scopedProperties": { "eip155:8453": { "paymasterService": { "supported": true }, "sessionKeys": { "supported": true } }, "eip155:84532": { "auxiliaryFunds": { "supported": true } } } ``` ### Wallet Response [#wallet-response] The wallet's response should specify the capabilities it supports, in accordance with EIP-5792 and CAIP-25: ```json "sessionProperties": { "expiry": "2022-12-24T17:07:31+00:00", "caip154": { "supported": "true" }, "flow-control": { "loose": ["halt", "continue"], "strict": ["continue"] }, "atomic": { "status": "ready" } }, "scopedProperties": { "eip155:1": { "atomic": { "status": "supported" } }, "eip155:137": { "atomic": { "status": "unsupported" } }, "eip155:84532": { "eip155:83532:0x0910e12C68d02B561a34569E1367c9AAb42bd810": { "auxiliaryFunds": { "supported": false }, "atomic": { "status": "supported" } } } } ``` - Capabilities shared across all address in a namespace can be expressed at top-level - Address-specific capabilities can include exceptions to scope-wide capabilities ### Atomic Capability [#atomic-capability] According to [EIP-5792](https://eips.ethereum.org/EIPS/eip-5792), the `atomic` capability specifies how the wallet handles batches of transactions. It has three possible values: - `supported` — The wallet executes calls atomically and contiguously. - `ready` — The wallet can upgrade to support atomic execution, pending user approval. - `unsupported` — The wallet provides no atomicity guarantees. This capability is expressed per chain and is crucial for determining how `wallet_sendCalls` with `atomicRequired: true` will be handled. ### Example [#example] The `wallet_getCapabilities` method is used to request information about what capabilities a wallet supports. Following EIP-5792, here's how it should be implemented: #### Request [#request] ```json { "id": 1, "jsonrpc": "2.0", "method": "wallet_getCapabilities", "params": ["0xd46e8dd67c5d32be8058bb8eb970870f07244567", ["0x2105", "0x14A34"]] } ``` #### Response [#response] The wallet should return a response following EIP-5792, where capabilities are organized by chain ID: ```json { "id": 1, "jsonrpc": "2.0", "result": { "0x2105": { "atomic": { "status": "supported" } }, "0x14A34": { "atomic": { "status": "unsupported" } } } } ``` ### Implementation [#implementation] When implementing `wallet_sendCalls`, wallets must follow these requirements: #### Connection Approval [#connection-approval] - Only approve this method during the connection approval flow if your wallet can implement it correctly - Define the `atomic` capability per chain/account in the CAIP-25 response #### Request Format [#request-format] ```json { "id": 12345, "version": "2.0", "method": "wc_sessionRequest", "params": { "chainId": "caip-2-chain-id", "request": { "method": "wallet_sendCalls", "params": { "from": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "chainId": "0x01", "atomicRequired": true, "calls": [ { "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "value": "0x9184e72a", "data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675" }, { "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "value": "0x182183", "data": "0xfbadbaf01" } ] } } } } ``` #### Core Implementation Requirements [#core-implementation-requirements] - Execute calls in the exact order specified in the request - Do not wait for any calls to be finalized before completing the batch - If the user rejects the request, do not send any calls #### Atomic Execution Behavior [#atomic-execution-behavior] When `atomicRequired` is `true`: - Execute all calls atomically (either all succeed or none have any effect) - Execute all calls contiguously (no other transactions between batch calls) - If your wallet can upgrade from `ready` to `supported` atomicity, do so before executing When `atomicRequired` is `false`: - You may execute calls sequentially without atomicity guarantees - You may execute atomically if your wallet supports it - You may upgrade to `supported` atomicity and execute atomically #### Response Enrichment [#response-enrichment] To enhance the user experience and eliminate the need for app switching, wallets can enrich the wallet_sendCalls response with caip2 id and transactionHash to let the Universal Provider resolve the transaction hash. ```json { "id": "...", "capabilities": { "caip345": { "caip2": "eip155:1", "transactionHashes": ["..."], } } } ``` ### Example [#example-1] To enhance the user experience and eliminate the need for app switching, wallets can enrich the wallet_sendCalls response with caip2 id and transactionHash to let the Universal Provider resolve the transaction hash. To implement this functionality, the response for wallet_sendCalls should be enriched with capabilities: ```json { "id": "...", "capabilities": { "caip345": { "caip2": "eip155:1", "transactionHashes": ["..."], } } } ``` ### Response Format [#response-format] The response format for `wallet_getCallsStatus` varies based on the execution method: For non-atomic execution, include all transactions in the receipts array, even those that were included on-chain but eventually reverted. #### For Atomic Execution [#for-atomic-execution] ```json { "receipts": [/* single receipt or array of receipts */], "atomic": true } ``` #### For Non-Atomic Execution [#for-non-atomic-execution] ```json { "receipts": [/* array of receipts for all transactions */], "atomic": false } ``` ## References [#references] - EIP-5792: https://eips.ethereum.org/EIPS/eip-5792#atomicbatch-capability - CAIP-25 namespaces: https://github.com/ChainAgnostic/namespaces/blob/main/eip155/caip25.md # Installation (/wallets/android/installation) Add the `jitpack.io` Maven repository to your `root/build.gradle.kts` file. For example: ```groovy allprojects { repositories { mavenCentral() maven { url "https://jitpack.io" } } } ``` In `app/build.gradle.kts` add the WalletKit package and its dependencies: ```groovy implementation("com.reown:android-core:release_version") implementation("com.reown:walletkit:release_version") ``` ## ProGuard rules [#proguard-rules] If you encounter issues with minification, add the below rules to your application: ``` -keepattributes *Annotation* -keep class com.sun.jna.** { *; } -keepclassmembers class com.sun.jna.** { native ; *; } -keep class uniffi.** { *; } # Preserve all public and protected fields and methods -keepclassmembers class ** { public *; protected *; } -dontwarn uniffi.** -dontwarn com.sun.jna.** ``` ## Next Steps [#next-steps] Now that you've installed Wallet SDK, you're ready to start integrating it. The next section will walk you through the process of setting up your project to use the SDK. # Link Mode (/wallets/android/link-mode) The Wallet SDK Link Mode is a low latency mechanism for transporting [One-Click Auth](/wallets/android/one-click-auth) requests and session requests over Universal Links, reducing the need for a WebSocket connection with the Relay. This significantly enhances the user experience when connecting native dApps to native wallets by reducing the latency associated with network connections, especially when the user has an unstable internet connection. To support Link Mode add a universal link for your wallet in Cloud project configuration dashboard, configure your AppMetaData `appLink` with a valid universal link and set the `linkMode` property to `true`: Make sure that [1-Click Auth](/wallets/android/one-click-auth) is implemented before enabling Link Mode. ```kotlin val appMetaData = Core.Model.AppMetaData( ... appLink = "https://example.com/example_wallet", linkMode = true ) CoreClient.initialize( metaData: appMetaData, ... ) WalletKit.initialize(Wallet.Params.Init(core = CoreClient)) ``` Once link mode and app link are properly configured and the user interacts with a link mode supporting dApp, your wallet will receive requests over app links. You must pass these requests to WalletKit so it can process them: ```kotlin val url = intent.dataString WalletKit.dispatchEnvelope(url) { error -> //handle error } ``` Ensure to handle incoming app links in your Activity onCreate method and in onNewIntent callback. Ensure that your App Link is properly configured in your app's Manifest file with the `autoVerify` set to `true`: ``` ``` For more information on how to configure app links for your app, refer to the [Android Documentation](https://developer.android.com/training/app-links/verify-android-applinks). For enabling links to app content check [this](https://developer.android.com/training/app-links/deep-linking) documentation page. For more information on how to interact with other apps using intents, see [Android Intent Documentation](https://developer.android.com/training/basics/intents). # Mobile Linking (/wallets/android/mobile-linking) This feature is only relevant to native platforms. ## Usage [#usage] Mobile Linking allows your wallet to automatically redirect back to the Dapp allowing for less user interactions and hence a better UX for your users. ### Establishing Communication Between Mobile Wallets and Apps [#establishing-communication-between-mobile-wallets-and-apps] When integrating a wallet with a mobile application, it's essential to understand how they communicate. The process involves two main steps: 1. **QR Code Handshake:** The mobile app (Dapp) generates a unique URI (Uniform Resource Identifier) and displays it as a QR code. This URI acts like a secret handshake. When the user scans the QR code using their wallet app, they establish a connection. It's like saying, "Hey, let's chat!" 2. **Deep Links and Universal Links:** The URI from the QR code allows the wallet app to create a [deep link](https://support.google.com/google-ads/answer/10023042?hl=en#:~:text=Deep%20links%20send%20mobile%20device,%2C%20Shopping%2C%20and%20Display%20campaigns.) or [universal link](https://developer.apple.com/ios/universal-links/). These links work on both Android and iOS. They enable seamless communication between the wallet and the app. **Developers should prefer Deep Linking over Universal Linking.** Universal Linking may redirect the user to a browser, which might not provide the intended user experience. Deep Linking ensures the user is taken directly to the app. ### Key Behavior to Address [#key-behavior-to-address] In some scenarios, wallets use redirect metadata provided in session proposals to open applications. This can cause unintended behavior, such as: Redirecting to the wrong app when multiple apps share the same redirect metadata (e.g., a desktop and mobile version of the same Dapp). Opening an unrelated application if a QR code is scanned on a different device than where the wallet is installed. #### Recommended Approach [#recommended-approach] To avoid this behavior, wallets should: - **Restrict Redirect Metadata to Deep Link Use Cases**: Redirect metadata should only be used when the session proposal is initiated through a deep link. QR code scans should not trigger app redirects using session proposal metadata. The connection and sign request flows are similar across platforms. ### Connection Flow [#connection-flow] - **Dapp Prompts User:** The Dapp asks the user to connect. - **User Chooses Wallet:** The user selects a wallet from a list of compatible wallets. - **Redirect to Wallet:** The user is redirected to their chosen wallet. - **Wallet Approval:** The wallet prompts the user to approve or reject the session (similar to granting permission). - **Return to Dapp:** - **Manual Return:** The wallet asks the user to manually return to the Dapp. - **Automatic Return:** Alternatively, the wallet automatically takes the user back to the Dapp. - **User Reunites with Dapp:** After all the interactions, the user ends up back in the Dapp. ![Mobile linking flow where the dApp sends the user to the wallet to connect and back](/images/mintlify/w3w/mobileLinking-light.png) ### Sign Request Flow [#sign-request-flow] When the Dapp needs the user to sign something (like a transaction), a similar pattern occurs: - **Automatic Redirect:** The Dapp automatically sends the user to their previously chosen wallet. - **Approval Prompt:** The wallet asks the user to approve or reject the request. - **Return to Dapp:** - **Manual Return:** The wallet asks the user to manually return to the Dapp. - **Automatic Return:** Alternatively, the wallet automatically takes the user back to the Dapp. - **User Reconnects:** Eventually, the user returns to the Dapp. ![Mobile linking flow where the dApp sends the user to the wallet to sign a message](/images/mintlify/w3w/mobileLinking_sign-light.png) ## Platform preparations [#platform-preparations] In order for Dapps to be able to trigger your wallet for a connection or sign request using deep links you first need to add your own wallet to the Explorer by login to your [WalletConnect Dashboard](https://dashboard.walletconnect.com/sign-in) account, declare a deep link and define an [``](https://developer.android.com/training/app-links/deep-linking#adding-filters) in your wallet's Manifest.xml with the same deep link added in Explorer: ```xml ``` Dapps developers must do the same for their own custom schemes if they want the wallet to be able to navigate back after a session approval or a sign request response ## Integration [#integration] #### Wallet Support [#wallet-support] **Disclaimer:** The below solution is designed for the communication between native Android Dapps and native Android wallets. In the case of mobile browser Dapps and native Android wallets communication, we recommend moving wallets into the background after both approving and rejecting sessions or approving and rejecting requests to persist smooth deep-link UX. In order to add support for mobile linking within your wallet and receive session proposals, register following deep link in your mobile wallet using intent filters in your Activity/Fragment or deepLink tag in your navigation graph. To support universal native modal and WalletConnectModal register: `wc://` Deep link example: `examplewallet://wc?uri={pairingUri}` To receive signing request in your Wallet, you'll need to initialize Kotlin SDK with the `Redirect` object where you pass a deep link that redirects to your wallet when it comes to receiving signing request from Dapp. ```kotlin val redirect = "examplewallet://request" //should be unique for your wallet val appMetaData = Core.Model.AppMetaData( name = "Wallet Name", description = "Wallet Description", url = "Wallet Url", icons = listOfIconUrlStrings, redirect = redirect ) CoreClient.initialize(projectId = projectId, connectionType = connectionType, application = application, metaData = appMetaData) val init = Wallet.Params.Init(coreClient = CoreClient) WalletKit.initialize(init) ``` Redirect when responding to a session proposal: ```kotlin WalletKit.approveSession(approveProposal, onSuccess = { // trigger deeplink: proposal.redirect } ) ``` Redirect when responding to a request: ```kotlin val redirect = WalletKit.getActiveSessionByTopic(sessionRequest.topic)?.redirect?.toUri() WalletKit.respondSessionRequest(response, onSuccess = { // trigger deeplink: redirect } ) ``` **Heads-up:** To make this flow working well, Wallet must register one of its Android components with the same deep link that it initialized with. To check the flow implementation described above have a look on our sample wallet: https://github.com/WalletConnect/WalletConnectKotlinV2/tree/master/sample/wallet #### Dapp Support [#dapp-support] To send session proposals to mobile wallet user the pairing URI as deep link that triggers a wallet to open and consume pairing URI ```kotlin requireActivity().startActivity(Intent(Intent.ACTION_VIEW, deeplinkPairingUri.toUri())) ``` In order to add support for mobile linking within your Dapp and receive signing request responses from wallet, you'll need to initialize Kotlin SDK with the `Redirect` object where you pass a deep link that redirects to your Dapp when it comes to receiving signing request responses from wallet. ```kotlin val redirect = "kotlin-dapp-wc://request" //should be unique for your Dapp val appMetaData = Core.Model.AppMetaData( name = "Dapp Name", description = "Dapp Description", url = "Dapp URL", icons = listOfIconUrlStrings, redirect = redirect ) CoreClient.initialize(projectId = projectId, connectionType = connectionType, application = application, metaData = appMetaData) val init = Sign.Params.Init(core = CoreClient) SignClient.initialize(init) ``` **Heads-up:** To make this flow working well, Dapp must register one of its Android components with the same deep link that it initialized with. To check the flow implementation described above have a look on our Sample Dapp: https://github.com/WalletConnect/WalletConnectKotlinV2/tree/master/sample/dapp #### References [#references] - https://developer.android.com/guide/navigation/navigation-deep-link#implicit - https://developer.android.com/training/app-links#deep-links # One-click Auth (/wallets/android/one-click-auth) ## Introduction [#introduction] This section outlines an innovative protocol method that facilitates the initiation of a Sign session and the authentication of a wallet through a [Sign-In with Ethereum](https://eips.ethereum.org/EIPS/eip-4361) (SIWE) message, enhanced by [ReCaps](https://eips.ethereum.org/EIPS/eip-5573) (ReCap Capabilities). This enhancement not only offers immediate authentication for dApps, paving the way for prompt user logins, but also integrates informed consent for authorization. Through this mechanism, dApps can request the delegation of specific capabilities to perform actions on behalf of the wallet user. These capabilities, encapsulated within SIWE messages as ReCap URIs, detail the scope of actions authorized by the user in an explicit and human-readable form. By incorporating ReCaps, this method extends the utility of SIWE messages, allowing dApps to combine authentication with a nuanced authorization model. This model specifies the actions a dApp is authorized to execute on the user's behalf, enhancing security and user autonomy by providing clear consent for each delegated capability. As a result, dApps can utilize these consent-backed messages to perform predetermined actions, significantly enriching the interaction between dApps, wallets, and users within the Ethereum ecosystem. ![Regular connect and sign flow compared with the one-click authenticated sessions flow](/images/mintlify/w3w/authenticatedSessions-light.png) ## Handling Authentication Requests [#handling-authentication-requests] To handle incoming authentication requests, set up WalletKit.WalletDelegate. The onSessionAuthenticate callback will notify you of any authentication requests that need to be processed, allowing you to either approve or reject them based on your application logic. ```kotlin override val onSessionAuthenticate: ((Wallet.Model.SessionAuthenticate, Wallet.Model.VerifyContext) -> Unit) get() = { sessionAuthenticate, verifyContext -> // Triggered when wallet receives the session authenticate sent by a Dapp // Process the authentication request here // This involves displaying UI to the user } ``` ## Authentication Objects/Payloads [#authentication-objectspayloads] #### Responding to Authentication Requests [#responding-to-authentication-requests] To interact with authentication requests, build authentication objects (Wallet.Model.Cacao). It involves the following steps: - **Creating an Authentication Payload Params** - Generate an authentication payload params that matches your application's supported chains and methods. - **Formatting Authentication Messages** - Format the authentication message using the payload and the user's account. - **Signing the Authentication Message** - Sign the formatted message to create a verifiable authentication object. Example: ```kotlin override val onSessionAuthenticate: ((Wallet.Model.SessionAuthenticate, Wallet.Model.VerifyContext) -> Unit) get() = { sessionAuthenticate, verifyContext -> val auths = mutableListOf() val authPayloadParams = WalletKit.generateAuthPayloadParams( sessionAuthenticate.payloadParams, supportedChains = listOf("eip155:1", "eip155:137", "eip155:56"), // Note: Only EVM chains are supported supportedMethods = listOf("personal_sign", "eth_signTypedData", "eth_sign") ) authPayloadParams.chains.forEach { chain -> val issuer = "did:pkh:$chain:$address" val formattedMessage = WalletKit.formatAuthMessage(Wallet.Params.FormatAuthMessage(authPayloadParams, issuer)) val signature = signMessage(message: formattedMessage, privateKey: privateKey) //Note: Assume `signMessage` is a function you've implemented to sign messages. val auth = WalletKit.generateAuthObject(authPayloadParams, issuer, signature) auths.add(auth) } } ``` ## Approving Authentication Requests [#approving-authentication-requests] 1. The recommended approach for secure authentication across multiple chains involves signing a SIWE (Sign-In with Ethereum) message for each chain and account. However, at a minimum, one SIWE message must be signed to establish a session. It is possible to create a session for multiple chains with just one issued authentication object. 2. Sometimes a dapp may want to only authenticate the user without creating a session, not every approval will result with a new session. To approve an authentication request, construct Wallet.Model.Cacao instances for each supported chain, sign the authentication messages, generate AuthObjects and call approveSessionAuthenticate with the request ID and the authentication objects. ```kotlin val approveAuthenticate = Wallet.Params.ApproveSessionAuthenticate(id = sessionAuthenticate.id, auths = auths) WalletKit.approveSessionAuthenticate(approveProposal, onSuccess = { //Redirect back to the dapp if redirect is set: sessionAuthenticate.participant.metadata?.redirect }, onError = { error -> //Handle error } ) ``` ## Rejecting Authentication Requests [#rejecting-authentication-requests] If the authentication request cannot be approved or if the user chooses to reject it, use the rejectSessionAuthenticate method. ```kotlin val rejectParams = Wallet.Params.RejectSessionAuthenticate( id = sessionAuthenticate.id, reason = "Reason" ) WalletKit.rejectSessionAuthenticate(rejectParams, onSuccess = { //Success }, onError = { error -> //Handle error } ) ``` ## Testing One-click Auth [#testing-one-click-auth] You can use [AppKit Lab](https://lab.reown.com/appkit/?name=siwx-ethers) to test and verify that your wallet supports One-click Auth properly. # Resources (/wallets/android/resources) Valuable assets for developers and users interested in integrating Wallet SDK into their applications. - [Awesome WalletConnect](https://github.com/WalletConnect/awesome-walletconnect) - Community-curated collection of WalletConnect-enabled wallets, libraries, and tools. - [AppKit Laboratory](https://lab.reown.com/) - A place to test your wallet integrations against various setups of AppKit. - [Wallet SDK GitHub](https://github.com/WalletConnect/walletconnect-monorepo/tree/v2.0/packages/web3wallet) - Wallet SDK GitHub repository. ### Wallet Resources [#wallet-resources] To check more in details go and visit our [Wallet SDK Kotlin implementation app](https://github.com/reown-com/reown-kotlin/tree/develop/sample/wallet). Sample Wallet and Dapp .apk files can be found under the latest release tag in [Kotlin's V2 repository](https://github.com/reown-com/reown-kotlin/tags) If you need to test your app's integration, you can use one of our following demo dapps. **Sign** - [React dApp (with standalone client) - v2](https://github.com/WalletConnect/web-examples/tree/main/advanced/dapps/react-dapp-v2) ([Demo](https://react-app.reown.com/)) ### Dapp Resources [#dapp-resources] Sample Wallet and Dapp .apk files can be found under the latest release tag in [Kotlin's V2 repository](https://github.com/reown-com/reown-kotlin/tags) **Sign** - [React dApp (with standalone client) - v2](https://github.com/WalletConnect/web-examples/tree/main/advanced/dapps/react-dapp-v2) ([Demo](https://react-app.reown.com/)) # Usage (/wallets/android/usage) This section provides instructions on how to initialize the WalletKit client, approve sessions with supported namespaces, and respond to session requests, enabling easy integration of Web3 wallets with dapps through a simple and intuitive interface. ## Content [#content] Links to sections on this page. Some sections are platform specific and are only visible when the platform is selected. To view a summary of useful platform specific topics, check out **Extra (Platform Specific)** under this section. **[Initialization](#initialization)**: Creating a new WalletKit instance and initializing it with a projectId from [WalletConnect Dashboard](https://dashboard.walletconnect.com). **Session**: Connection between a dapp and a wallet. - [Namespace Builder](#namespace-builder): Namespace Builder is a helper utility that greatly reduces the complexity of parsing the required and optional namespaces. It accepts as parameters a session proposal along with your user's chains/methods/events/accounts and returns a ready-to-use object - [Session Approval](#session-approval): Approving a session sent from a dapp - [Session Rejection](#session-rejection): Rejecting a session sent from a dapp - [Responding to Session Requests](#responding-to-session-requests): Responding to session requests sent from a dapp - [Updating a Session](#updating-a-session): Updating a session sent between a dapp and wallet - [Extending a Session](#extending-a-session): Extending a session between a dapp and wallet - [Session Disconnect](#session-disconnect): Disconnecting a session between a dapp and wallet - [Register Device Token](#register-device-token) Enabling Wallet Push Notifications by registering a device token. - [WalletKit.WalletDelegate](#walletkitwalletdelegate) Setting and overriding functions through WalletKit delegate. Also includes instructions about VerifyContext. - [Format Message](#format-message) Receiving formatted SIWE message To check the full list of platform specific instructions for your preferred platform, go to [Extra (Platform Specific)](#extra-platform-specific) and select your platform. ## Initialization [#initialization] ```kotlin val projectId = "" // Get Project ID at https://dashboard.walletconnect.com/ val connectionType = ConnectionType.AUTOMATIC or ConnectionType.MANUAL val telemetryEnabled: Boolean = true val appMetaData = Core.Model.AppMetaData( name = "Wallet Name", description = "Wallet Description", url = "Wallet URL", icons = /*list of icon url strings*/, redirect = "kotlin-wallet-wc:/request" // Custom Redirect URI ) CoreClient.initialize(projectId = projectId, connectionType = connectionType, application = this, metaData = appMetaData, telemetryEnabled = telemetryEnabled) val initParams = Wallet.Params.Init(core = CoreClient) WalletKit.initialize(initParams) { error -> // Error will be thrown if there's an issue during initialization } ``` The WalletKit client will always be responsible for exposing accounts (CAIP10 compatible) to a Dapp and therefore is also in charge of signing. To initialize the WalletKit client, create a `Wallet.Params.Init` object in the Android Application class with the Core Client. The `Wallet.Params.Init` object will then be passed to the `WalletKit`initialize function. The telemetry feature aims to improve the reliability and observability of connection flows between decentralized applications (dapps) and wallets. It focuses solely on collecting data about code execution and error codes, without tracking any sensitive user information like amounts, accounts etc. It provides a comprehensive tracing system for three key use cases: - Subscribing to a Pairing Topic - Approving a Session - Approving an Authenticated Session Each execution trace consists of: - Trace Events: Collected to verify the proper execution of code. - Error Events: Captured when errors occur during the trace, halting the execution trace. When an error event is encountered, it is stored locally within the SDK along with all preceding trace events. These stored events are then transmitted to the server whenever the SDK is initialized. Error event tracing is enabled by default. Telemetry Enabled (telemetryEnabled = true): - The SDK stores events and sends them to the server. Telemetry Disabled (telemetryEnabled = false): - The SDK stops storing new events and deletes all unsent events from local storage upon the next initialization. Important Note: Since the SDK only stores abstract trace and error data, user identification is not possible. Example of the error events: ```json [ { "eventId": "69e53f11-fd4b-4efc-8d36-1f60a9ac8207", "bundleId": "com.wallet.example", "timestamp": 1689611327943, "props": { "event": "ERROR", "type": "pairing_already_exists", "properties": { "topic": "topic1", "trace": [ "pairing_started", "pairing_uri_validation_success", "pairing_uri_not_expired", "existing_pairing", "pairing_not_expired", "pairing_not_expired" ] } } }, { "eventId": "69e53f11-fd4b-4efc-8d36-2321312fds", "bundleId": "com.wallet.example", "timestamp": 16896113234323, "props": { "event": "ERROR", "type": "session_approve_namespace_validation_failure", "properties": { "topic": "topic2", "trace": ["session_approve_started", "proposal_not_expired"] } } } ] ``` ## Session [#session] A session is a connection between a dapp and a wallet. It is established when a user approves a session proposal from a dapp. A session is active until the user disconnects from the dapp or the session expires. ### Namespace Builder [#namespace-builder] With WalletKit 1.7.0 we've published a helper utility that greatly reduces the complexity of parsing the required and optional namespaces. It accepts as parameters a session proposal along with your wallet's chains, methods, events, and accounts (supported namespaces) and returns ready-to-use namespaces object that has to be passed into `Wallet.Params.SessionApprove` when approving a session. ```kotlin val supportedNamespaces: Wallet.Model.Namespaces.Session = /* a map of all supported namespaces created by a wallet */ val sessionProposal: Wallet.Model.SessionProposal = /* an object received by `fun onSessionProposal(sessionProposal: Wallet.Model.SessionProposal)` in `WalletKit.WalletDelegate` */ val sessionNamespaces = WalletKit.generateApprovedNamespaces(sessionProposal, supportedNamespaces) val approveParams: Wallet.Params.SessionApprove = Wallet.Params.SessionApprove(proposerPublicKey, sessionNamespaces) WalletKit.approveSession(approveParams) { error -> /*callback for error while approving a session*/ } ``` Examples of supported namespaces: ```kotlin val supportedNamespaces = mapOf( "eip155" to Wallet.Model.Namespace.Session( chains = listOf("eip155:1", "eip155:137", "eip155:3"), methods = listOf("personal_sign", "eth_sendTransaction", "eth_signTransaction"), events = listOf("chainChanged"), accounts = listOf("eip155:1:0x57f48fAFeC1d76B27e3f29b8d277b6218CDE6092", "eip155:137:0x57f48fAFeC1d76B27e3f29b8d277b6218CDE6092", "eip155:3:0x57f48fAFeC1d76B27e3f29b8d277b6218CDE6092") ) ) val anotherSupportedNamespaces = mapOf( "eip155" to Wallet.Model.Namespace.Session( chains = listOf("eip155:1", "eip155:2", "eip155:4"), methods = listOf("personal_sign", "eth_sendTransaction", "eth_signTransaction"), events = listOf("chainChanged", "accountsChanged"), accounts = listOf("eip155:1:0x57f48fAFeC1d76B27e3f29b8d277b6218CDE6092", "eip155:2:0x57f48fAFeC1d76B27e3f29b8d277b6218CDE6092", "eip155:4:0x57f48fAFeC1d76B27e3f29b8d277b6218CDE6092") ), "cosmos" to Wallet.Model.Namespace.Session( chains = listOf("cosmos:cosmoshub-4"), methods = listOf("cosmos_method"), events = listOf("cosmos_event"), accounts = listOf("cosmos:cosmoshub-4:cosmos1hsk6jryyqjfhp5dhc55tc9jtckygx0eph6dd02") ) ) ``` ### EVM methods & events [#evm-methods--events] In @walletconnect/ethereum-provider, (our abstracted EVM SDK for apps) we support by default the following Ethereum methods and events: ```ts { //... methods: [ "eth_accounts", "eth_requestAccounts", "eth_sendRawTransaction", "eth_sign", "eth_signTransaction", "eth_signTypedData", "eth_signTypedData_v3", "eth_signTypedData_v4", "eth_sendTransaction", "personal_sign", "wallet_switchEthereumChain", "wallet_addEthereumChain", "wallet_getPermissions", "wallet_requestPermissions", "wallet_registerOnboarding", "wallet_watchAsset", "wallet_scanQRCode", "wallet_sendCalls", "wallet_getCallsStatus", "wallet_showCallsStatus", "wallet_getCapabilities", ], events: [ "chainChanged", "accountsChanged", "message", "disconnect", "connect", ] } ``` ### Session Approval [#session-approval] Addresses provided in `accounts` array should follow [CAIP-10](https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-10.md) semantics. ```kotlin val proposerPublicKey: String = /*Proposer publicKey from SessionProposal object*/ val namespace: String = /*Namespace identifier, see for reference: https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-2.md#syntax*/ val accounts: List = /*List of accounts on chains*/ val methods: List = /*List of methods that wallet approves*/ val events: List = /*List of events that wallet approves*/ val namespaces: Map = mapOf(namespace, Wallet.Model.Namespaces.Session(accounts, methods, events)) val approveParams: Wallet.Params.SessionApprove = Wallet.Params.SessionApprove(proposerPublicKey, namespaces) WalletKit.approveSession(approveParams) { error -> /*callback for error while approving a session*/ } ``` To send an approval, pass a Proposer's Public Key along with the map of namespaces to the `WalletKit.approveSession` function. ### Session Rejection [#session-rejection] ```kotlin val proposerPublicKey: String = /*Proposer publicKey from SessionProposal object*/ val rejectionReason: String = /*The reason for rejecting the Session Proposal*/ val rejectionCode: String = /*The code for rejecting the Session Proposal*/ For reference use CAIP-25: https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-25.md val rejectParams: Wallet.Params.SessionReject = SessionReject(proposerPublicKey, rejectionReason, rejectionCode) WalletKit.rejectSession(rejectParams) { error -> /*callback for error while rejecting a session*/ } ``` To send a rejection for the Session Proposal, pass a proposerPublicKey, rejection reason and rejection code to the `WalletKit.rejectSession` function. ### Responding to Session requests [#responding-to-session-requests] ```kotlin val sessionTopic: String = /*Topic of Session*/ val jsonRpcResponse: Wallet.Model.JsonRpcResponse.JsonRpcResult = /*Active Session Request ID along with request data*/ val result = Wallet.Params.SessionRequestResponse(sessionTopic = sessionTopic, jsonRpcResponse = jsonRpcResponse) WalletKit.respondSessionRequest(result) { error -> /*callback for error while responding session request*/ } ``` To respond to JSON-RPC method that were sent from Dapps for a session, submit a `Wallet.Params.SessionRequestResponse` with the session's topic and request ID along with the respond data to the `WalletKit.respondSessionRequest` function. ### Updating a Session [#updating-a-session] NOTE: addresses provided in `accounts` array should follow [CAIP10](https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-10.md) semantics. ```kotlin val sessionTopic: String = /*Topic of Session*/ val namespace: String = /*Namespace identifier, see for reference: https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-2.md#syntax*/ val accounts: List = /*List of accounts on chains*/ val methods: List = /*List of methods that wallet approves*/ val events: List = /*List of events that wallet approves*/ val namespaces: Map = mapOf(namespace, Wallet.Model.Namespaces.Session(accounts, methods, events)) val updateParams = Wallet.Params.SessionUpdate(sessionTopic, namespaces) WalletKit.updateSession(updateParams) { error -> /*callback for error while sending session update*/ } ``` To update a session with namespaces, submit a `Wallet.Params.SessionUpdate` object with the session's topic and namespaces to update session with to `WalletKit.updateSession`. ### Extending a Session [#extending-a-session] ```kotlin val sessionTopic: String = /*Topic of Session*/ val extendParams = Wallet.Params.SessionExtend(sessionTopic = sessionTopic) WalletKit.extendSession(extendParams) { error -> /*callback for error while extending a session*/ } ``` To extend a session, create a `Wallet.Params.SessionExtend` object with the session's topic to update the session with to `WalletKit.extendSession`. Session is extended by 7 days. ### Emitting a Session [#emitting-a-session] To emit an event, call emitSessionEvent() as follows: ```kotlin val sessionTopic: String = /*Topic of Session*/ val event: Wallet.Model.SessiomEvent = SessionEvent(name = "accountsChanged", data = "0x000000000") val sessionEmit = Wallet.Params.SessionEmit(topic = sessionTopic, chainId = "eip155:1", event = event) WalletKit.emitSessionEvent(sessionEmit) { error -> /*callback for error while emiting an event*/ } ``` ### Session Disconnect [#session-disconnect] ```kotlin val disconnectionReason: String = /*The reason for disconnecting the Session*/ val disconnectionCode: String = /*The code for disconnecting the Session*/ val sessionTopic: String = /*Topic from the Session*/ For reference use CAIP-25: https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-25.md val disconnectParams = Wallet.Params.SessionDisconnect(sessionTopic, disconnectionReason, disconnectionCode) WalletKit.disconnectSession(disconnectParams) { error -> /*callback for error while disconnecting a session*/ } ``` To disconnect from un active session, pass a disconnection reason with code and the Session topic to the `WalletKit.disconnectSession` function. ## Extra (Platform Specific) [#extra-platform-specific] #### WalletKit.WalletDelegate [#walletkitwalletdelegate] ```kotlin val walletDelegate = object : WalletKit.WalletDelegate { override fun onSessionProposal(sessionProposal: Wallet.Model.SessionProposal, verifyContext: Wallet.Model.VerifyContext) { // Triggered when wallet receives the session proposal sent by a Dapp } fun onSessionAuthenticate(sessionAuthenticate: Wallet.Model.SessionAuthenticate, verifyContext: Wallet.Model.VerifyContext) { // Triggered when wallet receives the session authenticate sent by a Dapp } override fun onSessionRequest(sessionRequest: Wallet.Model.SessionRequest, verifyContext: Wallet.Model.VerifyContext) { // Triggered when a Dapp sends SessionRequest to sign a transaction or a message } override fun onAuthRequest(authRequest: Wallet.Model.AuthRequest, verifyContext: Wallet.Model.VerifyContext) { // Triggered when Dapp / Requester makes an authorization request } override fun onSessionDelete(sessionDelete: Wallet.Model.SessionDelete) { // Triggered when the session is deleted by the peer } override fun onSessionSettleResponse(settleSessionResponse: Wallet.Model.SettledSessionResponse) { // Triggered when wallet receives the session settlement response from Dapp } override fun onSessionUpdateResponse(sessionUpdateResponse: Wallet.Model.SessionUpdateResponse) { // Triggered when wallet receives the session update response from Dapp } override fun onConnectionStateChange(state: Wallet.Model.ConnectionState) { //Triggered whenever the connection state is changed } override fun onError(error: Wallet.Model.Error) { // Triggered whenever there is an issue inside the SDK } } WalletKit.setWalletDelegate(walletDelegate) ``` `Wallet.Event.VerifyContext` provides a domain verification information about SessionProposal, SessionRequest and AuthRequest. It consists of origin of a Dapp from where the request has been sent, validation Enum that says whether origin is VALID, INVALID or UNKNOWN and verify url server. ```kotlin data class VerifyContext( val id: Long, val origin: String, val validation: Model.Validation, val verifyUrl: String ) enum class Validation { VALID, INVALID, UNKNOWN } ``` The WalletKit needs a `WalletKit.WalletDelegate` passed to it for it to be able to expose asynchronous updates sent from the Dapp. #### Format message [#format-message] To receive formatted SIWE message, call formatMessage method with following parameters: ```kotlin val payloadParams: Wallet.Params.PayloadParams = //PayloadParams received in the onAuthRequest callback val issuer = //MUST be the same as send with the respond methods and follows: https://github.com/w3c-ccg/did-pkh/blob/main/did-pkh-method-draft.md val formatMessage = Wallet.Params.FormatMessage(event.payloadParams, issuer) WalletKit.formatMessage(formatMessage) ``` #### Register Device Token [#register-device-token] This method enables wallets to receive push notifications from WalletConnect's Push Server via [Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging). This means you will have to setup your project with Firebase before being able to call registerDeviceToken method. Make sure that a service extending the FirebaseMessagingService is added to your manifest as per the [Firebase FCM documentation](https://firebase.google.com/docs/cloud-messaging/android/client#manifest) as well as any other setup Firebase requires [Firebase setup documentation](https://firebase.google.com/docs/android/setup). To register a wallet to receive WalletConnect push notifications, call `WalletKit.registerDeviceToken` and pass the Firebase Access Token. ```kotlin val firebaseAccessToken: String = //FCM access token received through the Firebase Messaging SDK WalletKit.registerDeviceToken( firebaseAccessToken, onSuccess = { // callback triggered once registered successfully with the Push Server }, onError = { error: Wallet.Model.Error -> // callback triggered if there's an exception thrown during the registration process }) ``` # Verify API (/wallets/android/verify) Verify API is a security-focused feature that allows wallets to notify end-users when they may be connecting to a suspicious or malicious domain, helping to prevent phishing attacks across the industry. Once a wallet knows whether an end-user is on uniswap.com or eviluniswap.com, it can help them to detect potentially harmful connections through Verify's combined offering of WalletConnect domain registry. When a user initiates a connection with an application, Verify API enables wallets to present their users with four key states that can help them determine whether the domain they’re about to connect to might be malicious. These are:
![Wallet connection requests showing the Verify states domain match, unverified, mismatch and threat](/images/mintlify/verify-banner.png)
Verify Banner
## Disclaimer [#disclaimer] Verify API helps wallets detect suspicious or malicious domains, but it may not catch every threat. Use it as one more layer of protection alongside your wallet's other security measures. ## Domain risk detection [#domain-risk-detection] The Verify security system will discriminate session proposals & session requests with distinct validations that can be either `VALID`, `INVALID` or `UNKNOWN`. - Domain match: The domain linked to this request has been verified as this application's domain. - This interface appears when the domain a user is attempting to connect to has been ‘verified’ in our domain registry as the registered domain of the application the user is trying to connect to, and the domain has not returned as suspicious from either of the security tools we work with. The `verifyContext` included in the request will have a validation of `VALID`. - Unverified: The domain sending the request cannot be verified. - This interface appears when the domain a user is attempting to connect to has not been verified in our domain registry, but the domain has not returned as suspicious from either of the security tools we work with. The `verifyContext` included in the request will have a validation of `UNKNOWN`. - Mismatch: The application's domain doesn't match the sender of this request. - This interface appears when the domain a user is attempting to connect to has been flagged as a different domain to the one this application has verified in our domain registry, but the domain has not returned as suspicious from either of the security tools we work with. The `verifyContext` included in the request will have a validation of `INVALID` - Threat: This domain is flagged as malicious and potentially harmful. - This interface appears when the domain a user is attempting to connect to has been flagged as malicious on one or more of the security tools we work with. The `verifyContext` included in the request will contain parameter `isScam` with value `true`. ### Reading `verifyContext` by connection type [#reading-verifycontext-by-connection-type] How your wallet should read `verifyContext` depends on how the dApp connects: - **Web dApp over QR code or deep link (relay):** This is the full Verify API, including scam checks. Show all four states: `VALID` as Domain match, `UNKNOWN` as Cannot verify, `INVALID` as Mismatch, and `isScam` as Security risk (ideally blocking or requiring the user to confirm). - **Native dApp over relay:** Native apps can't create a Verify attestation, so `UNKNOWN` is expected here. We suggest a neutral "Cannot verify" label rather than an alarming warning. - **[Link Mode](/wallets/android/link-mode) (native to native):** The domain check above applies, with no scam check. `INVALID` means the dApp's universal link domain doesn't match its `metadata.url`. The wallet's own Link Mode setup also needs to be complete, or the result falls back to `INVALID`. ### Implementation [#implementation] `WalletKit.WalletDelegate` passes a `Wallet.Model.VerifyContext` to `onSessionProposal`, `onSessionAuthenticate` and `onSessionRequest`: ```kotlin data class VerifyContext( val id: Long, val origin: String, val validation: Validation, val verifyUrl: String, val isScam: Boolean?, ) enum class Validation { VALID, INVALID, UNKNOWN } ``` Map it to one of the four states once, then use that state in each callback. ```kotlin enum class VerifyState { THREAT, MISMATCH, UNVERIFIED, DOMAIN_MATCH } fun Wallet.Model.VerifyContext.toVerifyState(): VerifyState = when { // Threat: only set over relay, since Link Mode has no scam check isScam == true -> VerifyState.THREAT validation == Wallet.Model.Validation.VALID -> VerifyState.DOMAIN_MATCH validation == Wallet.Model.Validation.INVALID -> VerifyState.MISMATCH // UNKNOWN: expected for native dApps over relay. Link Mode never returns UNKNOWN else -> VerifyState.UNVERIFIED } val walletDelegate = object : WalletKit.WalletDelegate { // Session proposals from a web or native dApp override fun onSessionProposal(sessionProposal: Wallet.Model.SessionProposal, verifyContext: Wallet.Model.VerifyContext) { val state = verifyContext.toVerifyState() // show the state on the approval screen } // One-click auth requests can arrive over relay or Link Mode override val onSessionAuthenticate: ((Wallet.Model.SessionAuthenticate, Wallet.Model.VerifyContext) -> Unit) get() = { sessionAuthenticate, verifyContext -> val state = verifyContext.toVerifyState() val isLinkMode = sessionAuthenticate.participant.metadata?.linkMode == true // in Link Mode, MISMATCH means the universal link domain doesn't match metadata.url } override fun onSessionRequest(sessionRequest: Wallet.Model.SessionRequest, verifyContext: Wallet.Model.VerifyContext) { val state = verifyContext.toVerifyState() val isLinkMode = sessionRequest.peerMetaData?.linkMode == true // show the state on the signing screen } // ...other WalletDelegate callbacks } ``` WalletKit doesn't expose the transport a request arrived on. To detect Link Mode, read `linkMode` from the dApp's metadata, as shown above. Present each state like this: - `THREAT`: Block the request, or require the user to explicitly accept the risk. Check before anything else, so the user doesn't also see a Mismatch warning. - `MISMATCH`: Show a warning and proceed only if the user accepts the risk. - `UNVERIFIED`: Show a neutral "Cannot verify" label. Don't block the request, since native dApps over relay always land here. - `DOMAIN_MATCH`: Show a verified badge and proceed as normal. # Analytics (/wallets/c-sharp/cloud/analytics) # Explorer Submission (/wallets/c-sharp/cloud/explorer-submission) # Relay (/wallets/c-sharp/cloud/relay) # Installation (/wallets/c-sharp/installation) Install the Wallet SDK client package via Nuget. ```bash dotnet add package Reown.WalletKit ``` ## Next Steps [#next-steps] Now that you've installed Wallet SDK, you're ready to start integrating it. The next section will walk you through the process of setting up your project to use the SDK. # Usage (/wallets/c-sharp/usage) This section provides instructions on how to initialize the WalletKit client, approve sessions with supported namespaces, and respond to session requests, enabling easy integration of Web3 wallets with dapps through a simple and intuitive interface. ## Content [#content] Links to sections on this page. Some sections are platform specific and are only visible when the platform is selected. To view a summary of useful platform specific topics, check out **Extra (Platform Specific)** under this section. **[Initialization](#initialization)**: Creating a new WalletKit instance and initializing it with a projectId from [WalletConnect Dashboard](https://dashboard.walletconnect.com). **Session**: Connection between a dapp and a wallet. - [Namespace Builder](#namespace-builder): Namespace Builder is a helper utility that greatly reduces the complexity of parsing the required and optional namespaces. It accepts as parameters a session proposal along with your user's chains/methods/events/accounts and returns a ready-to-use object - [Session Approval](#session-approval): Approving a session sent from a dapp - [Session Rejection](#session-rejection): Rejecting a session sent from a dapp - [Responding to Session Requests](#responding-to-session-requests): Responding to session requests sent from a dapp - [Updating a Session](#updating-a-session): Updating a session sent between a dapp and wallet - [Extending a Session](#extending-a-session): Extending a session between a dapp and wallet - [Session Disconnect](#session-disconnect): Disconnecting a session between a dapp and wallet ## Initialization [#initialization] First you must setup a `Core` instance with a specific `Name` and `ProjectId`. You may optionally specify other `CoreOption` values, such as `RelayUrl` and `Storage` ```csharp var options = new CoreOptions() { ProjectId = "...", Name = "my-app", } var core = new CoreClient(options); ``` Next, you must define a `Metadata` object which describes your Wallet. This includes a `Name`, `Description`, `Url` and `Icons` url. ```csharp var metadata = new Metadata() { Description = "An example wallet to showcase Wallet SDK", Icons = new[] { "https://walletconnect.com/meta/favicon.ico" }, Name = $"wallet-csharp-test", Url = "https://walletconnect.com", }; ``` Once you have both the `Core` and `Metadata` objects, you can initialize the `WalletKitClient` ```csharp var sdk = await WalletKitClient.Init(core, metadata, metadata.Name); ``` ## Session [#session] A session is a connection between a dapp and a wallet. It is established when a user approves a session proposal from a dapp. A session is active until the user disconnects from the dapp or the session expires. ### Namespace Builder [#namespace-builder] To build a namespace mapping for either proposing a session **OR** approving a session, you can use .NET dictionary + class constructors directly, or use the built-in builder methods ### C# Constructor Style [#c-constructor-style] ```csharp var TestNamespaces = new Namespaces() { { "eip155", new Namespace() { Accounts = new [] { "eip155:1:0xab16a96d359ec26a11e2c2b3d8f8b8942d5bfcdb" }, Chains = new []{ "eip155:1" }, Methods = new[] { "eth_signTransaction" }, Events = new[] { "chainChanged" } } }, }; ``` ### Builder Style [#builder-style] ```csharp var TestNamespaces = new Namespaces() .WithNamespace("eip155", new Namespace() .WithChain("eip155:1") .WithMethod("eth_signTransaction") .WithEvent("chainChanged") .WithAccount("eip155:1:0xab16a96d359ec26a11e2c2b3d8f8b8942d5bfcdb") ); ``` The `Namespaces` mapping is required when approving a proposed session from a dApp. Because of this, you may also construct a `Namespaces` from a `RequiredNamespaces`, which auto-populates all `Methods`, `Events` and `Chains` from the given `RequiredNamespaces`. This is provided for convenience. ### RequiredNamespaces [#requirednamespaces] ```csharp sdk.SessionProposed += async (sender, @event) => { var proposal = @event.Proposal; var requiredNamespaces = proposal.RequiredNamespaces; var approvedNamespaces = new Namespaces(requiredNamespaces); approvedNamespaces["eip155"].WithAccount("eip155:1:0xab16a96d359ec26a11e2c2b3d8f8b8942d5bfcdb"); }; ``` The `RequiredNamespaces` is required when setting up a session between a dApp and Wallet. The dApp will provide a `RequiredNamespaces` when proposing the session. The `RequiredNamespaces` and `ProposedNamespace` use the same style constructors + builder functions as `Namespaces` and `Namespace`. ### EVM methods & events [#evm-methods--events] In @walletconnect/ethereum-provider, (our abstracted EVM SDK for apps) we support by default the following Ethereum methods and events: ```ts { //... methods: [ "eth_accounts", "eth_requestAccounts", "eth_sendRawTransaction", "eth_sign", "eth_signTransaction", "eth_signTypedData", "eth_signTypedData_v3", "eth_signTypedData_v4", "eth_sendTransaction", "personal_sign", "wallet_switchEthereumChain", "wallet_addEthereumChain", "wallet_getPermissions", "wallet_requestPermissions", "wallet_registerOnboarding", "wallet_watchAsset", "wallet_scanQRCode", "wallet_sendCalls", "wallet_getCallsStatus", "wallet_showCallsStatus", "wallet_getCapabilities", ], events: [ "chainChanged", "accountsChanged", "message", "disconnect", "connect", ] } ``` ### Session Approval [#session-approval] Wallets can pair an incoming session using the session's Uri. Pairing a session lets the Wallet obtain the connection proposal which can then be approved or denied. ```csharp var uri = "..."; await sdk.Pair(uri); ``` The wallet can then approve the proposal by constructing an approved `Namespaces`. The approved `Namespaces` should include the `RequiredNamespaces` under `proposal.RequiredNamespaces`, and may optionally include any optional namespaces specified under `proposal.OptionalNamespaces` ```csharp sdk.SessionProposed += async (sender, @event) => { var proposal = @event.Proposal; var requiredNamespaces = proposal.RequiredNamespaces; var approvedNamespaces = new Namespaces(requiredNamespaces); approvedNamespaces["eip155"].WithAccount("eip155:1:0xab16a96d359ec26a11e2c2b3d8f8b8942d5bfcdb"); var sessionData = await sdk.ApproveSession(proposal.Id, approvedNamespaces); var sessionTopic = sessionData.Topic; }; ``` You may also just provide the addresses that will connect, and the SDK will create this approved `Namespaces` for you. This function **will not approve optional namespaces** ```csharp sdk.SessionProposed += async (sender, @event) => { var proposal = @event.Proposal; var sessionData = await sdk.ApproveSession(proposal, new[] { "eip155:1:0xab16a96d359ec26a11e2c2b3d8f8b8942d5bfcdb" }); var sessionTopic = sessionData.Topic; }; ``` or ```csharp sdk.SessionProposed += async (sender, @event) => { var proposal = @event.Proposal; var sessionData = await sdk.ApproveSession(proposal, "eip155:1:0xab16a96d359ec26a11e2c2b3d8f8b8942d5bfcdb"); var sessionTopic = sessionData.Topic; }; ``` ### Session Rejection [#session-rejection] The wallet can reject the proposal using the following: ```csharp sdk.SessionProposed += async (sender, @event) => { var proposal = @event.Proposal; await sdk.RejectSession(proposal, "User rejected"); }; ``` ### Responding to Session requests [#responding-to-session-requests] Responding to session requests is very similar to sending session requests. See dApp usage on how sending session requests works. All custom session requests requires a request class **and** response class to be created that matches the `params` field type in the custom session request. C# is a static typed language, so these types must be given whenever you do a session request (or do any querying for session requests). Currently, **WalletKit does not automatically assume the object type for `params` is an array**. This is very important, since most EVM RPC requests have `params` as an array type. **Use `List` to workaround this**. For example, for `eth_sendTransaction`, use `List` instead of `Transaction`. Newtonsoft.Json is used for JSON serialization/deserialization, therefore you can use Newtonsoft.Json attributes when defining fields in your request/response classes. ### Building a Response type [#building-a-response-type] Create a class for the response and populate it with the JSON properties the response object has. For this example, we will use `eth_getTransactionReceipt` The `params` field for `eth_getTransactionReceipt` has the object type ```csharp using Newtonsoft.Json; using System.Numerics; [RpcMethod("eth_getTransactionReceipt"), RpcRequestOptions(Clock.ONE_MINUTE, 99995)] public class TransactionReceipt { [JsonProperty("transactionHash")] public string TransactionHash; [JsonProperty("transactionIndex")] public BigInteger TransactionIndex; [JsonProperty("blockHash")] public string BlockHash; [JsonProperty("blockNumber")] public BigInteger BlockNumber; [JsonProperty("from")] public string From; [JsonProperty("to")] public string To; [JsonProperty("cumulativeGasUsed")] public BigInteger CumulativeGasUsed; [JsonProperty("effectiveGasPrice ")] public BigInteger EffectiveGasPrice ; [JsonProperty("gasUsed")] public BigInteger GasUsed; [JsonProperty("contractAddress")] public string ContractAddress; [JsonProperty("logs")] public object[] Logs; [JsonProperty("logsBloom")] public string LogBloom; [JsonProperty("type")] public BigInteger Type; [JsonProperty("status")] public BigInteger Status; } ``` The `RpcMethod` class attributes defines the rpc method this response uses, this is optional. The `RpcResponseOptions` class attributes define the expiry time and tag attached to the response, **this is required**. ### Sending a response [#sending-a-response] To respond to requests from a dApp, you must define the class representing the request object type. The request type for `eth_getTransactionReceipt` is the following: ```csharp [RpcMethod("eth_getTransactionReceipt"), RpcRequestOptions(Clock.ONE_MINUTE, 99994)] public class EthGetTransactionReceipt : List { public EthGetTransactionReceipt(params string[] hashes) : base(hashes) { } // needed for proper json deserialization public EthGetTransactionReceipt() { } } ``` We can handle the `eth_getTransactionReceipt` session request by doing the following: ```csharp walletClient.Engine.SessionRequestEvents().OnRequest += OnEthTransactionReceiptRequest; private Task OnEthTransactionReceiptRequest(RequestEventArgs e) { // logic for request goes here // set e.Response to return a response } ``` The callback function gets invoked whenever the wallet receives the `eth_getTransactionReceipt` request from a connected dApp. You may optionally filter further which requests are handled using the `FilterRequests` function ```csharp walletClient.Engine.SessionRequestEvents() .FilterRequests(r => r.Topic == sessionTopic) .OnRequest += OnEthTransactionReceiptRequest; ``` The callback returns a `Task`, so the callback can be made async. To return a response, **you must** set the `Response` field in `RequestEventArgs` with the desired response. ```csharp private async Task OnEthTransactionReceiptRequest(RequestEventArgs e) { var txHash = e.Request.Params[0]; var receipt = await EthGetTransactionReceipt(txHash); e.Response = receipt; } ``` ### Updating a Session [#updating-a-session] Update a session, adding/removing additional namespaces in the given topic. ```csharp var newNamespaces = new Namespaces(...); var request = await walletClient.UpdateSession(sessionTopic, newNamespaces); await request.Acknowledged(); ``` ### Extending a Session [#extending-a-session] Extend a session's expiry time so the session remains open ```csharp var request = await walletClient.Extend(sessionTopic); await request.Acknowledged(); ``` ### Session Disconnect [#session-disconnect] To disconnect a session, use the `Disconnect` function. You may optional provide a reason for the disconnect. Disconnecting requires the `topic` of the session to be given. This can be found in the `SessionStruct` object given when a session has been given approval by the Wallet. ```csharp var sessionTopic = sessionData.Topic; await walletClient.Disconnect(sessionTopic); // or await walletClient.Disconnect(sessionTopic, Error.FromErrorType(ErrorType.USER_DISCONNECTED)); ``` # Verify API (/wallets/c-sharp/verify) Verify API is a security-focused feature that allows wallets to notify end-users when they may be connecting to a suspicious or malicious domain, helping to prevent phishing attacks across the industry. Once a wallet knows whether an end-user is on uniswap.com or eviluniswap.com, it can help them to detect potentially harmful connections through Verify's combined offering of WalletConnect's domain registry. When a user initiates a connection with an application, Verify API enables wallets to present their users with four key states that can help them determine whether the domain they’re about to connect to might be malicious. These are:
![Wallet connection requests showing the Verify states domain match, unverified, mismatch and threat](/images/mintlify/verify-banner.png)
Verify Banner
## Disclaimer [#disclaimer] Verify API helps wallets detect suspicious or malicious domains, but it may not catch every threat. Use it as one more layer of protection alongside your wallet's other security measures. ## Domain risk detection [#domain-risk-detection] The Verify security system will discriminate session proposals & session requests with distinct validations that can be either `VALID`, `INVALID` or `UNKNOWN`. - Domain match: The domain linked to this request has been verified as this application's domain. - This interface appears when the domain a user is attempting to connect to has been ‘verified’ in our domain registry as the registered domain of the application the user is trying to connect to, and the domain has not returned as suspicious from either of the security tools we work with. The `verifyContext` included in the request will have a validation of `VALID`. - Unverified: The domain sending the request cannot be verified. - This interface appears when the domain a user is attempting to connect to has not been verified in our domain registry, but the domain has not returned as suspicious from either of the security tools we work with. The `verifyContext` included in the request will have a validation of `UNKNOWN`. - Mismatch: The application's domain doesn't match the sender of this request. - This interface appears when the domain a user is attempting to connect to has been flagged as a different domain to the one this application has verified in our domain registry, but the domain has not returned as suspicious from either of the security tools we work with. The `verifyContext` included in the request will have a validation of `INVALID` - Threat: This domain is flagged as malicious and potentially harmful. - This interface appears when the domain a user is attempting to connect to has been flagged as malicious on one or more of the security tools we work with. The `verifyContext` included in the request will contain parameter `isScam` with value `true`. ### Reading `verifyContext` by connection type [#reading-verifycontext-by-connection-type] How your wallet should read `verifyContext` depends on how the dApp connects: - **Web dApp over QR code or deep link (relay):** This is the full Verify API, including scam checks. Show all four states: `VALID` as Domain match, `UNKNOWN` as Cannot verify, `INVALID` as Mismatch, and `isScam` as Security risk (ideally blocking or requiring the user to confirm). - **Native dApp over relay:** Native apps can't create a Verify attestation, so `UNKNOWN` is expected here. We suggest a neutral "Cannot verify" label rather than an alarming warning. ### Implementation [#implementation] `Reown.Core.Models.Verify.VerifiedContext` provides a domain verification information about `SessionProposal`, `SessionRequest` and `AuthRequest`. It consists of origin of an app from where the request has been sent, validation Enum that says whether origin is `VALID`, `INVALID` or `UNKNOWN` and verify url server. ```csharp public class VerifiedContext { [JsonProperty("origin")] public string Origin; [JsonProperty("validation")] private string _validation; public string ValidationString => _validation; public Validation Validation { get { return FromString(); } set { _validation = AsString(value); } } [JsonProperty("verifyUrl")] public string VerifyUrl { get; set; } private Validation FromString() { switch (ValidationString.ToLowerInvariant()) { case "VALID": return Validation.Valid; case "INVALID": return Validation.Invalid; default: return Validation.Unknown; } } private string AsString(Validation str) { switch (str) { case Validation.Invalid: return "INVALID"; case Validation.Valid: return "VALID"; default: return "UNKNOWN"; } } } public enum Validation { Unknown, Valid, Invalid, } ``` # ADI Chain (/wallets/chains/adi) ADI Chain is a fully EVM-compatible blockchain. It uses the standard Ethereum JSON-RPC methods for all wallet interactions. ## Network / Chain Information [#network--chain-information] | CAIP-2 | Chain ID | Name | RPC Endpoint | Explorer | Namespace | | -------------- | -------- | --------- | ------------------------------- | --------------------------------- | --------- | | `eip155:36900` | `36900` | ADI Chain | `https://rpc.adifoundation.ai` | `https://explorer.adifoundation.ai` | `eip155` | ## RPC Methods [#rpc-methods] As an EVM-compatible chain, ADI Chain supports all standard Ethereum JSON-RPC methods. Wallets implementing ADI Chain support should refer to the [EVM RPC documentation](/wallets/chains/evm) for the complete list of supported methods, including: - `personal_sign` - Sign a message - `eth_sign` - Sign data - `eth_signTypedData` / `eth_signTypedData_v4` - Sign typed data (EIP-712) - `eth_sendTransaction` - Send a transaction - `eth_signTransaction` - Sign a transaction without broadcasting - `eth_sendRawTransaction` - Broadcast a signed transaction For detailed method specifications and examples, see the [EVM Chain Support](/wallets/chains/evm) page. ## Additional Resources [#additional-resources] - [ADI Explorer](https://explorer.adifoundation.ai) - [ADI Bridge](https://bridge.adifoundation.ai) - [ADI RPC Endpoint](https://rpc.adifoundation.ai) # Bitcoin (/wallets/chains/bitcoin) We define an account as the group of addresses derived using the same account value in their [derivation paths](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#user-content-Path_levels). We use the first address of the [external chain](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#examples) ("first external address"), as the identifier for an account. An account's total balance is defined as the sum of all unspent transaction outputs (UTXOs) belonging to its entire group of addresses. 1. Dapps **must** only display the first external address as a connected account. 2. Wallets **must** only offer to connect the first external address(es). #### Account Definition [#account-definition] The derivation path levels in the [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#path-levels), [BIP49](https://github.com/bitcoin/bips/blob/master/bip-0049.mediawiki#user-content-Public_key_derivation), [BIP84](https://github.com/bitcoin/bips/blob/master/bip-0084.mediawiki#public-key-derivation), [BIP86](https://github.com/bitcoin/bips/blob/master/bip-0086.mediawiki#user-content-Public_key_derivation) standards are: ``` m / purpose' / coin_type' / account' / change / address_index ``` Addresses with different `purpose`, `change` and `address_index` values are considered to belong to the same account. Valid `purpose` values are 44, 49, 84 and 86. We use the first external Native SegWit (purpose = 84) address as the default account identifier. For a specific seed phrase and path `m/84'/0'/0'/0/0` we get account 0 with identifier `bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu`. Its total balance is the sum of all UTXO balances on all addresses with derivation paths: * `m/44'/0'/0'/change/address_index` * `m/49'/0'/0'/change/address_index` * `m/84'/0'/0'/change/address_index` * `m/86'/0'/0'/change/address_index` If the wallet user changes to account 1 we get path `m/84'/0'/1'/0/0` with identifier `bc1qku0qh0mc00y8tk0n65x2tqw4trlspak0fnjmfz`. Its total balance is the sum of all UTXO balances on all addresses with derivation paths: * `m/44'/0'/1'/change/address_index` * `m/49'/0'/1'/change/address_index` * `m/84'/0'/1'/change/address_index` * `m/86'/0'/1'/change/address_index` ## sendTransfer [#sendtransfer] This method is used to sign and submit a transfer of any `amount` of Bitcoin to a single `recipientAddress`, optionally including a `changeAddress` for the change amount and `memo` set as an OP_RETURN output by supporting wallets. The transaction will be signed and broadcast upon user approval. ### Parameters [#parameters] * `Object` * `account` : `String` - *(Required)* The connected account's first external address. * `recipientAddress` : `String` - *(Required)* The recipient's public address. * `amount` : `String` - *(Required)* The amount of Bitcoin to send, denominated in satoshis (Bitcoin base unit). * `changeAddress` : `String` - *(Optional)* The sender's public address to receive change. * `memo` : `String` - *(Optional)* The OP_RETURN value as a hex string without 0x prefix, maximum 80 bytes. ### Returns [#returns] * `Object` * `txid` : `String` - *(Required)* The transaction id as a hex string without 0x prefix. ### Example [#example] The example below specifies a simple transfer of 1.23 BTC (123000000 Satoshi). ```javascript // Request { "id": 1, "jsonrpc": "2.0", "method": "sendTransfer", "params": { "account": "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu", "recipientAddress": "bc1pmzfrwwndsqmk5yh69yjr5lfgfg4ev8c0tsc06e", "amount": "123000000", "memo": "636861726c6579206c6f766573206865" } } // Result { "id": 1, "jsonrpc": "2.0", "result": { "txid": "f007551f169722ce74104d6673bd46ce193c624b8550889526d1b93820d725f7" } } ``` ## getAccountAddresses [#getaccountaddresses] This method returns all current addresses needed for a dapp to fetch all UTXOs, calculate the total balance and prepare transactions. Dapps will typically use an indexing service to query for balances and UTXOs for all addresses returned by this method, such as: * [Blockbook API](https://github.com/trezor/blockbook/blob/master/docs/api.md#get-address) * [Bitcore API](https://github.com/bitpay/bitcore/blob/master/packages/bitcore-node/docs/api-documentation.md#address) We recognize that there are two broad classes of wallets in use today: 1. Wallets that generate a new change or receive address for every transaction ("dynamic wallet"). 2. Wallets that reuse the first external address for every transaction ("static wallet"). #### Implementation Details [#implementation-details] * All wallets **should** include the first external address and all addresses with one or more UTXOs, unless they're filtered by `intentions`. * Dynamic wallets **should** include minimum 2 unused change and receive addresses. Otherwise dapps may have to request [getAccountAddresses](#getaccountaddresses) after every transaction to discover the new addresses and keep track of the user's total balance. * All wallets **must** return fewer than 20 unused change and receive addresses to avoid breaking the [gap limit](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#address-gap-limit). ### Parameters [#parameters-1] * `Object` * `account` : `String` - *(Required)* The connected account's first external address. * `intentions` : `String[]` - *(Optional)* Filter what addresses to return, e.g. "payment" or "ordinal". ### Returns [#returns-1] * `Array` * `Object` * `address` : `String` - *(Required)* Public address belonging to the account. * `publicKey` : `String` - *(Optional)* Public key for the derivation path in hex, without 0x prefix. * `path` : `String` - *(Optional)* Derivation path of the address e.g. "m/84'/0'/0'/0/0". * `intention` : `String` - *(Optional)* Intention of the address, e.g. "payment" or "ordinal". ### Session Properties [#session-properties] In a connection request, it is recommended to serialize the response to `getAccountAddresses` in `session.sessionProperties.bip122_getAccountAddresses`. This allows dapps to consume an active session without requiring a context switch to re-request all addresses and associated public keys from the wallet. ### Example: Dynamic Wallet [#example-dynamic-wallet] The example below specifies a result from a dynamic wallet. For the sake of this example, receive and change addresses with index 3-4 are considered unused and addresses with paths `m/49'/0'/0'/0/7` and `m/84'/0'/0'/0/2` are considered to have UTXOs. Assuming the dapp monitors all returned addresses for balance changes, a new request to `getAccountAddresses` is only needed when all UTXOs in provided addresses have been spent, or when all provided `receive` addresses or `change` addresses have been used. ```javascript // Request { "id": 1, "jsonrpc": "2.0", "method": "getAccountAddresses", "params": { "account": "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu" } } // Result { "id": 1, "jsonrpc": "2.0", "result": [ { "address": "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu", "publicKey": "0330d54fd0dd420a6e5f8d3624f5f3482cae350f79d5f0753bf5beef9c2d91af3c", "path": "m/84'/0'/0'/0/0" }, { "address": "3KHhcgwPgYF9hE77zaKy2G36dpkcNtvQ33", "publicKey": "03b90230ca20150142bc2849a3df4517073978f32466214a0ebc00cac52f996989", "path": "m/49'/0'/0'/0/7" }, { "address": "bc1qp59yckz4ae5c4efgw2s5wfyvrz0ala7rgvuz8z", "publicKey": "038ffea936b2df76bf31220ebd56a34b30c6b86f40d3bd92664e2f5f98488dddfa", "path": "m/84'/0'/0'/0/2" }, { "address": "bc1qgl5vlg0zdl7yvprgxj9fevsc6q6x5dmcyk3cn3", "publicKey": "03de7490bcca92a2fb57d782c3fd60548ce3a842cad6f3a8d4e76d1f2ff7fcdb89", "path": "m/84'/0'/0'/0/3" }, { "address": "bc1qm97vqzgj934vnaq9s53ynkyf9dgr05rargr04n", "publicKey": "03995137c8eb3b223c904259e9b571a8939a0ec99b0717684c3936407ca8538c1b", "path": "m/84'/0'/0'/0/4" }, { "address": "bc1qv6vaedpeke2lxr3q0wek8dd7nzhut9w0eqkz9z", "publicKey": "03d0d243b6a3176fa20fa95cd7fb0e8e0829b83fc2b52053633d088c1a4ba91edf", "path": "m/84'/0'/0'/1/3" }, { "address": "bc1qetrkzfslk0d4kqjnu29fdh04tkav9vj3k36vuh", "publicKey": "02a8dee7573bcc7d3c1e9b9e267dbf0cd717343c31d322c5b074a3a97090a0d952", "path": "m/84'/0'/0'/1/4" } ] } ``` ### Example: Static Wallet [#example-static-wallet] The example below specifies a response from a static wallet. The returned address is used for both change and payments. It's the only address with UTXOs. ```javascript // Request { "id": 1, "jsonrpc": "2.0", "method": "getAccountAddresses", "params": { "account": "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu" } } // Result { "id": 1, "jsonrpc": "2.0", "result": [ { "address": "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu", "publicKey": "0330d54fd0dd420a6e5f8d3624f5f3482cae350f79d5f0753bf5beef9c2d91af3c", "path": "m/84'/0'/0'/0/0" } ] } ``` ## signPsbt [#signpsbt] This method can be used to request the signature of a Partially Signed Bitcoin Transaction (PSBT) and covers use-cases e.g. involving multiple-recipient transactions, requiring granular control over which UTXOs to spend or how to route change. ### Parameters [#parameters-2] * `Object` * `account` : `String` - *(Required)* The connected account's first external address. * `psbt` : `String` - *(Required)* Base64 encoded string of the PSBT to sign. * `signInputs` : `Array` * `Object` * `address` : `String` - *(Required)* The address whose private key to use for signing. * `index` : `Integer` - *(Required)* Specifies which input to sign. * `sighashTypes` : `Integer[]` - *(Optional)* Specifies which part(s) of the transaction the signature commits to. Default is `[1]`. * `broadcast` : `Boolean` - *(Optional)* Whether to finalize and broadcast the transaction after signing it. Default is `false`. ### Returns [#returns-2] * `Object` * `psbt` : `String` - *(Required)* The base64 encoded signed PSBT. * `txid` : `String` - *(Optional)* The transaction ID as a hex-encoded string, without 0x prefix. This must be returned if the transaction was broadcasted. ## signMessage [#signmessage] This method is used to sign a message with one of the connected account's addresses. ### Parameters [#parameters-3] * `Object` * `account` : `String` - *(Required)* The connected account's first external address. * `message` : `String` - *(Required)* The message to be signed by the wallet. * `address` : `String` - *(Optional)* The address whose private key to use for signing the message. * `protocol` : `"ecdsa" | "bip322"` - *(Optional)* Preferred signature type. Default is `"ecdsa"`. ### Returns [#returns-3] * `Object` * `address` : `String` - *(Required)* The Bitcoin address used to sign the message. * `signature` : `String` - *(Required)* Hex encoded bytes of the signature, without 0x prefix. * `messageHash` : `String` - *(Optional)* Hex encoded bytes of the message hash, without 0x prefix. ## Events [#events] ### bip122_addressesChanged [#bip122_addresseschanged] This event is used by wallets to notify dapps about connected accounts' current addresses, for example all addresses with a UTXO and a few unused addresses. The event data has the same format as the [getAccountAddresses](#getaccountaddresses) result. #### Implementation Details [#implementation-details-1] * Wallets **should** emit a `bip122_addressesChanged` event immediately after connection approval of a BIP122 chain. * Wallets **should** emit a `bip122_addressesChanged` event whenever a UTXO is spent or created for a connected account's addresses. * Dapps **should** listen for `bip122_addressesChanged` events, collect and monitor all addresses for UTXO and balance changes. Example [session_event](https://specs.walletconnect.com/2.0/specs/clients/sign/session-events#session_event) payload as received by a dapp: ``` { "id": 1675759795769537, "topic": "95d6aca451b8e3c6d9d176761bf786f1cc0a6d38dffd31ed896306bb37f6ae8d", "params": { "event": { "name": "bip122_addressesChanged", "data": [ { "address": "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu", "publicKey": "0330d54fd0dd420a6e5f8d3624f5f3482cae350f79d5f0753bf5beef9c2d91af3c", "path": "m/84'/0'/0'/0/0" }, { "address": "3KHhcgwPgYF9hE77zaKy2G36dpkcNtvQ33", "publicKey": "03b90230ca20150142bc2849a3df4517073978f32466214a0ebc00cac52f996989", "path": "m/49'/0'/0'/0/7" }, { "address": "bc1qp59yckz4ae5c4efgw2s5wfyvrz0ala7rgvuz8z", "publicKey": "038ffea936b2df76bf31220ebd56a34b30c6b86f40d3bd92664e2f5f98488dddfa", "path": "m/84'/0'/0'/0/2" }, { "address": "bc1qgl5vlg0zdl7yvprgxj9fevsc6q6x5dmcyk3cn3", "publicKey": "03de7490bcca92a2fb57d782c3fd60548ce3a842cad6f3a8d4e76d1f2ff7fcdb89", "path": "m/84'/0'/0'/0/3" }, { "address": "bc1qm97vqzgj934vnaq9s53ynkyf9dgr05rargr04n", "publicKey": "03995137c8eb3b223c904259e9b571a8939a0ec99b0717684c3936407ca8538c1b", "path": "m/84'/0'/0'/0/4" }, { "address": "bc1qv6vaedpeke2lxr3q0wek8dd7nzhut9w0eqkz9z", "publicKey": "03d0d243b6a3176fa20fa95cd7fb0e8e0829b83fc2b52053633d088c1a4ba91edf", "path": "m/84'/0'/0'/1/3" }, { "address": "bc1qetrkzfslk0d4kqjnu29fdh04tkav9vj3k36vuh", "publicKey": "02a8dee7573bcc7d3c1e9b9e267dbf0cd717343c31d322c5b074a3a97090a0d952", "path": "m/84'/0'/0'/1/4" } ] }, "chainId": "bip122:000000000019d6689c085ae165831e93" } } ``` # Canton (/wallets/chains/canton) These are the methods that wallets should implement to handle Canton transactions and messages via WalletConnect. ## Network / Chain Information [#network--chain-information] - **Namespace:** `canton` - **CAIP-2:** `canton:` (e.g. `canton:devnet`, `canton:production`) - **CAIP-10 Account:** `canton::` (e.g. `canton:devnet:operator%3A%3A1220abc...`) Unlike most chains, Canton does not have fixed mainnet/testnet identifiers. Network IDs are **operator-defined** — each wallet is configured with one or more networks, and the `network-id` used in CAIP-2 identifiers comes from that configuration. dApps should **not** hardcode specific chain IDs in the session proposal. Instead, request the `canton` namespace without specifying `chains`, and work with whatever network the wallet provides in the approved session. The network ID and party ID are available directly from the session's `canton.accounts` array as CAIP-10 strings (e.g. `canton:production:operator%3A%3A1220abc...`). For full network details, use [`canton_getActiveNetwork`](#canton_getactivenetwork). ## Registered Methods & Events [#registered-methods--events] ```typescript const CANTON_WC_METHODS = [ 'canton_prepareSignExecute', 'canton_listAccounts', 'canton_getPrimaryAccount', 'canton_getActiveNetwork', 'canton_status', 'canton_ledgerApi', 'canton_signMessage', ] const CANTON_WC_EVENTS = ['accountsChanged', 'statusChanged', 'chainChanged'] ``` ### Auto-Approve vs Manual-Approve [#auto-approve-vs-manual-approve] Read-only methods are auto-approved by the wallet. Methods that mutate the ledger or perform sensitive operations require explicit user approval. | Method | Approval | | -------------------- | ------------ | | `canton_listAccounts` | Auto-approve | | `canton_getPrimaryAccount` | Auto-approve | | `canton_getActiveNetwork` | Auto-approve | | `canton_status` | Auto-approve | | `canton_ledgerApi` | Auto-approve | | `canton_prepareSignExecute` | Manual | | `canton_signMessage` | Manual | ## Method Name Mapping (dApp SDK) [#method-name-mapping-dapp-sdk] The dApp SDK's `WalletConnectTransport` maps SDK method names before sending over WC: | SDK method | WC method (on the wire) | | ------------------------ | ------------------------ | | `canton_prepareExecute` | `canton_prepareSignExecute` | | `canton_prepareExecuteAndWait` | `canton_prepareSignExecute` | All other methods (`canton_listAccounts`, `canton_status`, `canton_ledgerApi`, etc.) are sent as-is. Both SDK methods resolve with the same response — over WalletConnect, every submission blocks until the transaction completes. ## RPC Methods [#rpc-methods] ### canton_prepareSignExecute [#canton_preparesignexecute] Prepare, sign, and execute a Canton ledger transaction. This is the primary method for submitting commands that mutate ledger state. The wallet performs the full prepare → sign → execute cycle and responds when the transaction is complete. #### Request [#request] ```typescript interface CantonPrepareSignExecuteRequest { method: 'canton_prepareSignExecute'; params: CantonPrepareParams; } interface CantonPrepareParams { commandId?: string; // auto-generated (UUIDv4) if omitted commands?: { [k: string]: unknown }; actAs?: string[]; // defaults to [primaryWallet.partyId] if omitted readAs?: string[]; // defaults to [] if omitted disclosedContracts?: Array<{ templateId?: string; contractId?: string; createdEventBlob: string; synchronizerId?: string; }>; packageIdSelectionPreference?: string[]; } ``` #### Example Request [#example-request] ```json { "topic": "", "chainId": "canton:devnet", "request": { "method": "canton_prepareSignExecute", "params": { "commands": { "0": { "ExerciseCommand": { "templateId": "#:Module:Template", "contractId": "00abcdef...", "choice": "Transfer", "choiceArgument": { "receiver": "bob::1220..." } } } }, "commandId": "d290f1ee-6c54-4b01-90e6-d701748f0851", "actAs": ["operator::1220abc..."], "readAs": [], "disclosedContracts": [ { "templateId": "#:Module:Template", "contractId": "00abcdef...", "createdEventBlob": "", "synchronizerId": "wallet::1220e7b..." } ], "packageIdSelectionPreference": [""] } } } ``` #### Signing Providers [#signing-providers] Wallets support multiple signing backends. The signing provider determines the Ledger API flow used: | Provider | Flow | | ---------------- | -------------------------------------------------------------------- | | `participant` | Single call to `POST /v2/commands/submit-and-wait` (participant signs internally) | | `wallet-kernel` | `POST /v2/interactive-submission/prepare` → local Ed25519 sign → `POST /v2/interactive-submission/execute` | | `blockdaemon` | `POST /v2/interactive-submission/prepare` → sign via Blockdaemon API → `POST /v2/interactive-submission/execute` | #### Success Response [#success-response] ```json { "id": 1234, "jsonrpc": "2.0", "result": { "status": "executed", "commandId": "d290f1ee-...", "payload": { "updateId": "tx-update-id", "completionOffset": 42 } } } ``` #### Error Response [#error-response] ```json { "id": 1234, "jsonrpc": "2.0", "error": { "code": 5001, "message": "Transaction execution failed: INVALID_ARGUMENT: ..." } } ``` #### User Rejected Response [#user-rejected-response] ```json { "id": 1234, "jsonrpc": "2.0", "error": { "code": 5000, "message": "User rejected" } } ``` --- ### canton_listAccounts [#canton_listaccounts] Retrieve all configured wallet accounts. #### Request [#request-1] ```json { "topic": "", "chainId": "canton:devnet", "request": { "method": "canton_listAccounts", "params": {} } } ``` #### Response [#response] ```json { "id": 1235, "jsonrpc": "2.0", "result": [ { "primary": true, "partyId": "operator::1220abc...", "status": "allocated", "hint": "operator", "publicKey": "", "namespace": "1220abc...", "networkId": "canton:production", "signingProviderId": "participant", "disabled": false } ] } ``` #### Wallet Type [#wallet-type] ```typescript interface Wallet { primary: boolean; partyId: string; status: 'initialized' | 'allocated' | 'removed'; hint: string; publicKey: string; namespace: string; networkId: string; signingProviderId: string; externalTxId?: string; topologyTransactions?: string; disabled?: boolean; reason?: string; } ``` --- ### canton_getPrimaryAccount [#canton_getprimaryaccount] Retrieve the primary wallet account (where `primary === true`). #### Request [#request-2] ```json { "topic": "", "chainId": "canton:devnet", "request": { "method": "canton_getPrimaryAccount", "params": {} } } ``` #### Response [#response-1] ```json { "id": 1236, "jsonrpc": "2.0", "result": { "primary": true, "partyId": "operator::1220abc...", "status": "allocated", "hint": "operator", "publicKey": "", "namespace": "1220abc...", "networkId": "canton:production", "signingProviderId": "participant" } } ``` --- ### canton_getActiveNetwork [#canton_getactivenetwork] Retrieve the currently active network configuration. #### Request [#request-3] ```json { "topic": "", "chainId": "canton:devnet", "request": { "method": "canton_getActiveNetwork", "params": {} } } ``` #### Response [#response-2] ```json { "id": 1237, "jsonrpc": "2.0", "result": { "networkId": "canton:production", "ledgerApi": "http://127.0.0.1:5003" } } ``` --- ### canton_status [#canton_status] Check the wallet's connectivity to the Canton ledger. #### Request [#request-4] ```json { "topic": "", "chainId": "canton:devnet", "request": { "method": "canton_status", "params": {} } } ``` #### Response (ledger reachable) [#response-ledger-reachable] ```json { "id": 1238, "jsonrpc": "2.0", "result": { "provider": { "id": "remote-da", "version": "3.4.0", "providerType": "remote" }, "connection": { "isConnected": true, "isNetworkConnected": true }, "network": { "networkId": "canton:production", "ledgerApi": "http://127.0.0.1:5003", "accessToken": "" // optional but recommended } } } ``` #### Response (ledger unreachable) [#response-ledger-unreachable] ```json { "id": 1238, "jsonrpc": "2.0", "result": { "provider": { "id": "remote-da", "version": "3.4.0", "providerType": "remote" }, "connection": { "isConnected": true, "isNetworkConnected": false, "reason": "Ledger unreachable" } } } ``` --- ### canton_ledgerApi [#canton_ledgerapi] Proxy raw Canton Ledger API requests through the wallet. The wallet authenticates and forwards the request. #### Request [#request-5] ```typescript interface CantonLedgerApiRequest { method: 'canton_ledgerApi'; params: CantonLedgerApiParams; } interface CantonLedgerApiParams { requestMethod: 'GET' | 'POST'; resource: string; body?: string | object; } ``` #### Example Request [#example-request-1] ```json { "topic": "", "chainId": "canton:devnet", "request": { "method": "canton_ledgerApi", "params": { "requestMethod": "POST", "resource": "/v2/state/active-contracts", "body": { "filter": { "filtersByParty": { "operator::1220abc...": { "cumulative": { "templateFilters": [] } } } } } } } } ``` #### Response [#response-3] ```json { "id": 1239, "jsonrpc": "2.0", "result": {} } ``` The `result` field contains the raw Ledger API JSON response as-is. --- ### canton_signMessage [#canton_signmessage] Sign an arbitrary message with the wallet's Ed25519 private key. #### Request [#request-6] ```typescript interface CantonSignMessageRequest { method: 'canton_signMessage'; params: { message: string; }; } ``` #### Example Request [#example-request-2] ```json { "topic": "", "chainId": "canton:devnet", "request": { "method": "canton_signMessage", "params": { "message": "Please sign this message to verify your identity" } } } ``` #### Success Response [#success-response-1] ```json { "id": 1240, "jsonrpc": "2.0", "result": { "signature": "", "publicKey": "" } } ``` ## Events [#events] ### accountsChanged [#accountschanged] Emitted when wallet accounts are added, removed, or modified. ```json { "name": "accountsChanged", "data": [ { "primary": true, "partyId": "operator::1220abc...", "status": "allocated", "hint": "operator", "publicKey": "...", "namespace": "1220abc...", "networkId": "canton:production", "signingProviderId": "participant" } ] } ``` ### statusChanged [#statuschanged] Emitted when the wallet's connectivity status changes. ```json { "name": "statusChanged", "data": { "provider": { "id": "remote-da", "providerType": "remote" }, "connection": { "isConnected": true, "isNetworkConnected": true }, "network": { "networkId": "canton:production" } } } ``` ### chainChanged [#chainchanged] Emitted when the wallet switches to a different network. ```json { "name": "chainChanged", "data": { "chainId": "canton:production" } } ``` ## Session Lifecycle [#session-lifecycle] ### Pairing [#pairing] The dApp creates a pairing URI and delivers it to the wallet: ```typescript const { uri, approval } = await signClient.connect({ optionalNamespaces: { canton: { methods: CANTON_WC_METHODS, events: CANTON_WC_EVENTS, }, }, }) ``` ### Session Approval [#session-approval] The wallet builds approved namespaces including the CAIP-10 account with the URL-encoded partyId: ```json { "canton": { "chains": ["canton:devnet"], "accounts": ["canton:devnet:operator%3A%3A1220abc..."], "methods": ["canton_prepareSignExecute", "canton_listAccounts", "canton_getPrimaryAccount", "canton_getActiveNetwork", "canton_status", "canton_ledgerApi", "canton_signMessage"], "events": ["accountsChanged", "statusChanged", "chainChanged"] } } ``` ## Error Codes [#error-codes] | Code | Meaning | | ------ | ----------------------------------------- | | `5000` | User rejected | | `5001` | Execution / handler error | | `5100` | Canton namespace not found in proposal | | `6000` | Wallet disconnected | ## Notes & Considerations [#notes--considerations] - All requests and responses comply with JSON-RPC structure (`id`, `jsonrpc`, etc.). - Canton uses Ed25519 signing for transaction authentication. - The `ledgerApi` method acts as a transparent proxy — the wallet handles authentication with the Canton Ledger API. Only `GET` and `POST` are supported; other HTTP methods will return a `5001` error. - Party IDs in CAIP-10 accounts are URL-encoded (e.g. `operator::1220abc...` becomes `operator%3A%3A1220abc...`). - The `canton_prepareSignExecute` method always performs the full prepare → sign → execute cycle synchronously, responding only when the transaction is complete. - The WC session `chainId` (e.g. `canton:devnet`) may differ from the `networkId` in wallet/network records (e.g. `canton:production`). The `chainId` identifies the chain at pairing time, while `networkId` reflects the wallet's internal network configuration. # Ethereum (/wallets/chains/evm) ## personal_sign [#personal_sign] The sign method calculates an Ethereum specific signature with:`sign(keccak256("\x19Ethereum Signed Message:\n" + len(message) + message)))`. By adding a prefix to the message makes the calculated signature recognizable as an Ethereum specific signature. This prevents misuse where a malicious DApp can sign arbitrary data (e.g. transaction) and use the signature to impersonate the victim. **Note** See ecRecover to verify the signature. ### Parameters [#parameters] message, account 1. `DATA`, N Bytes - message to sign. 2. `DATA`, 20 Bytes - address. ### Returns [#returns] `DATA`: Signature ### Example [#example] ```javascript // Request { "id": 1, "jsonrpc": "2.0", "method": "personal_sign", "params":["0xdeadbeaf","0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"], } // Result { "id": 1, "jsonrpc": "2.0", "result": "0xa3f20717a250c2b0b729b7e5becbff67fdaef7e0699da4de7ca5895b02a170a12d887fd3b17bfdce3481f10bea41f45ba9f709d39ce8325427b57afcfc994cee1b" } ``` ## eth_sign [#eth_sign] The sign method calculates an Ethereum specific signature with: `sign(keccak256("\x19Ethereum Signed Message:\n" + len(message) + message)))`. By adding a prefix to the message makes the calculated signature recognizable as an Ethereum specific signature. This prevents misuse where a malicious DApp can sign arbitrary data (e.g. transaction) and use the signature to impersonate the victim. **Note** the address to sign with must be unlocked. ### Parameters [#parameters-1] account, message 1. `DATA`, 20 Bytes - address. 2. `DATA`, N Bytes - message to sign. ### Returns [#returns-1] `DATA`: Signature ### Example [#example-1] ```javascript // Request { "id": 1, "jsonrpc": "2.0", "method": "eth_sign", "params": ["0x9b2055d370f73ec7d8a03e965129118dc8f5bf83", "0xdeadbeaf"], } // Result { "id": 1, "jsonrpc": "2.0", "result": "0xa3f20717a250c2b0b729b7e5becbff67fdaef7e0699da4de7ca5895b02a170a12d887fd3b17bfdce3481f10bea41f45ba9f709d39ce8325427b57afcfc994cee1b" } ``` An example how to use solidity ecrecover to verify the signature calculated with `eth_sign` can be found [here](https://gist.github.com/bas-vk/d46d83da2b2b4721efb0907aecdb7ebd). The contract is deployed on the testnet Ropsten and Rinkeby. ## eth_signTypedData [#eth_signtypeddata] Calculates an Ethereum-specific signature in the form of `keccak256("\x19Ethereum Signed Message:\n" + len(message) + message))` By adding a prefix to the message makes the calculated signature recognizable as an Ethereum specific signature. This prevents misuse where a malicious DApp can sign arbitrary data (e.g. transaction) and use the signature to impersonate the victim. **Note** the address to sign with must be unlocked. ### Parameters [#parameters-2] account, message 1. `DATA`, 20 Bytes - address. 2. `DATA`, N Bytes - message to sign containing type information, a domain separator, and data ### Example Parameters [#example-parameters] ```javascript [ "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", { types: { EIP712Domain: [ { name: "name", type: "string", }, { name: "version", type: "string", }, { name: "chainId", type: "uint256", }, { name: "verifyingContract", type: "address", }, ], Person: [ { name: "name", type: "string", }, { name: "wallet", type: "address", }, ], Mail: [ { name: "from", type: "Person", }, { name: "to", type: "Person", }, { name: "contents", type: "string", }, ], }, primaryType: "Mail", domain: { name: "Ether Mail", version: "1", chainId: 1, verifyingContract: "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", }, message: { from: { name: "Cow", wallet: "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", }, to: { name: "Bob", wallet: "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", }, contents: "Hello, Bob!", }, }, ]; ``` ### Returns [#returns-2] `DATA`: Signature ### Example [#example-2] ```javascript // Request { "id": 1, "jsonrpc": "2.0", "method": "eth_signTypedData", "params": ["0x9b2055d370f73ec7d8a03e965129118dc8f5bf83", {see above}], } ' // Result { "id": 1, "jsonrpc": "2.0", "result": "0x4355c47d63924e8a72e509b65029052eb6c299d53a04e167c5775fd466751c9d07299936d304c153f6443dfa05f40ff007d72911b6f72307f996231605b915621c" } ``` ## eth_sendTransaction [#eth_sendtransaction] Creates new message call transaction or a contract creation, if the data field contains code. ### Parameters [#parameters-3] 1. `Object` - The transaction object 2. `from`: `DATA`, 20 Bytes - The address the transaction is send from. 3. `to`: `DATA`, 20 Bytes - (optional when creating new contract) The address the transaction is directed to. 4. `data`: `DATA` - The compiled code of a contract OR the hash of the invoked method signature and encoded parameters. For details see [Ethereum Contract ABI](https://docs.soliditylang.org/en/latest/abi-spec.html) 5. `gas`: `QUANTITY` - (optional, default: 90000) Integer of the gas provided for the transaction execution. It will return unused gas. 6. `gasPrice`: `QUANTITY` - (optional, default: To-Be-Determined) Integer of the gasPrice used for each paid gas 7. `value`: `QUANTITY` - (optional) Integer of the value sent with this transaction 8. `nonce`: `QUANTITY` - (optional) Integer of a nonce. This allows to overwrite your own pending transactions that use the same nonce. ### Example Parameters [#example-parameters-1] ```javascript [ { from: "0xb60e8dd61c5d32be8058bb8eb970870f07233155", to: "0xBDE1EAE59cE082505bB73fedBa56252b1b9C60Ce", data: "0x", gasPrice: "0x029104e28c", gas: "0x5208", value: "0x00", }, ]; ``` ### Returns [#returns-3] `DATA`, 32 Bytes - the transaction hash, or the zero hash if the transaction is not yet available. Use `eth_getTransactionReceipt` to get the contract address, after the transaction was mined, when you created a contract. ### Example [#example-3] ```javascript // Request { "id": 1, "jsonrpc": "2.0", "method": "eth_sendTransaction", "params":[{see above}], } // Result { "id": 1, "jsonrpc": "2.0", "result": "0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331" } ``` ## eth_signTransaction [#eth_signtransaction] Signs a transaction that can be submitted to the network at a later time using with `eth_sendRawTransaction` ### Parameters [#parameters-4] 1. `Object` - The transaction object 2. `from`: `DATA`, 20 Bytes - The address the transaction is send from. 3. `to`: `DATA`, 20 Bytes - (optional when creating new contract) The address the transaction is directed to. 4. `data`: `DATA` - The compiled code of a contract OR the hash of the invoked method signature and encoded parameters. For details see [Ethereum Contract ABI](https://docs.soliditylang.org/en/latest/abi-spec.html) 5. `gas`: `QUANTITY` - (optional, default: 90000) Integer of the gas provided for the transaction execution. It will return unused gas. 6. `gasPrice`: `QUANTITY` - (optional, default: To-Be-Determined) Integer of the gasPrice used for each paid gas 7. `value`: `QUANTITY` - (optional) Integer of the value sent with this transaction 8. `nonce`: `QUANTITY` - (optional) Integer of a nonce. This allows to overwrite your own pending transactions that use the same nonce. ### Example Parameters [#example-parameters-2] ```javascript [ { from: "0xb60e8dd61c5d32be8058bb8eb970870f07233155", to: "0xd46e8dd67c5d32be8058bb8eb970870f07244567", data: "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675", gas: "0x76c0", // 30400 gasPrice: "0x9184e72a000", // 10000000000000 value: "0x9184e72a", // 2441406250 nonce: "0x117", // 279 }, ]; ``` ### Returns [#returns-4] `DATA` - the signed transaction data ### Example [#example-4] ```javascript // Request { "id": 1, "jsonrpc": "2.0", "method": "eth_signTransaction", "params":[{see above}], } // Result { "id": 1, "jsonrpc": "2.0", "result": "0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331" } ``` ## eth_sendRawTransaction [#eth_sendrawtransaction] Creates new message call transaction or a contract creation for signed transactions. ### Parameters [#parameters-5] 1. `DATA`, the signed transaction data. ### Returns [#returns-5] `DATA`, 32 Bytes - the transaction hash, or the zero hash if the transaction is not yet available. Use `eth_getTransactionReceipt` to get the contract address, after the transaction was mined, when you created a contract. ### Example [#example-5] ```javascript // Request { "id": 1, "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params":[ "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f07244567" ], } // Result { "id": 1, "jsonrpc": "2.0", "result": "0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331" } ``` # Chain Support (/wallets/chains/overview) The Wallet SDK is built to be **chain-agnostic** — it supports integrations across multiple blockchain ecosystems by working closely with each chain's foundations and developer communities to standardize namespaces, transaction flows, and JSON-RPC methods. ## Ecosystem Reference Pages [#ecosystem-reference-pages] - [EVM](/wallets/chains/evm) - [Solana](/wallets/chains/solana) - [Bitcoin](/wallets/chains/bitcoin) - [SUI](/wallets/chains/sui) - [Stacks](/wallets/chains/stacks) - [TON](/wallets/chains/ton) - [Tron](/wallets/chains/tron) - [ADI Chain](/wallets/chains/adi) - [Canton](/wallets/chains/canton) - [Stellar](/wallets/chains/stellar) ## Adding New Chain Support [#adding-new-chain-support] Interested in adding support for a new blockchain ecosystem? We work closely with chain foundations and developer communities to standardize integration specifications. **Contact us to start the process:** [sales@walletconnect.com](mailto:sales@walletconnect.com) # Solana (/wallets/chains/solana) ## solana_getAccounts [#solana_getaccounts] This method returns an Array of public keys available to sign from the wallet. ### Parameters [#parameters] none ### Returns [#returns] `Array` - Array of accounts: * `Object` : * `pubkey` : `String` - public key for keypair ### Example [#example] ```typescript // Request { "id": 1, "jsonrpc": "2.0", "method": "solana_getAccounts", "params": {} } // Result { "id": 1, "jsonrpc": "2.0", "result": [{ "pubkey": "722RdWmHC5TGXBjTejzNjbc8xEiduVDLqZvoUGz6Xzbp" }] } ``` ## solana_requestAccounts [#solana_requestaccounts] This method returns an Array of public keys available to sign from the wallet. ### Parameters [#parameters-1] none ### Returns [#returns-1] `Array` - Array of accounts: * `Object` : * `pubkey` : `String` - public key for keypair ### Example [#example-1] ```typescript // Request { "id": 1, "jsonrpc": "2.0", "method": "solana_getAccounts", "params": {} } // Result { "id": 1, "jsonrpc": "2.0", "result": [{ "pubkey": "722RdWmHC5TGXBjTejzNjbc8xEiduVDLqZvoUGz6Xzbp" }] } ``` ## solana_signMessage [#solana_signmessage] This method returns a signature for the provided message from the requested signer address. ### Parameters [#parameters-2] `Object` - Signing parameters: * `message` : `String` - the message to be signed (base58 encoded) * `pubkey` : `String` - public key of the signer ### Returns [#returns-2] `Object`: * `signature` : `String` - corresponding signature for signed message ### Example [#example-2] ```javascript // Request { "id": 1, "jsonrpc": "2.0", "method": "solana_signMessage", "params": { "message": "37u9WtQpcm6ULa3VtWDFAWoQc1hUvybPrA3dtx99tgHvvcE7pKRZjuGmn7VX2tC3JmYDYGG7", "pubkey": "AqP3MyNwDP4L1GJKYhzmaAUdrjzpqJUZjahM7kHpgavm" } } // Result { "id": 1, "jsonrpc": "2.0", "result": { signature: "2Lb1KQHWfbV3pWMqXZveFWqneSyhH95YsgCENRWnArSkLydjN1M42oB82zSd6BBdGkM9pE6sQLQf1gyBh8KWM2c4" } } ``` ## solana_signTransaction [#solana_signtransaction] This method returns a signature over the provided instructions by the targeted public key. Refer always to `transaction` param. The deprecated parameters are not compatible with versioned transactions. ### Parameters [#parameters-3] `Object` - Signing parameters:
* `transaction` : `String` - base64-encoded serialized transaction
* **\[deprecated]** `feePayer` : `String | undefined` - public key of the transaction fee payer
* **\[deprecated]** `instructions` : `Array` of `Object` or `undefined` - instructions to be atomically executed:
- `Object` - instruction
- `programId` : `String` - public key of the on chain program
- `data` : `String | undefined` - encoded calldata for instruction
- `keys` : `Array` of `Object` - account metadata used to define instructions
- `Object` - key
- `isSigner` : `Boolean` - true if an instruction requires a transaction signature matching `pubkey`
- `isWritable` : `Boolean` - true if the `pubkey` can be loaded as a read-write account
- `pubkey` : `String` - public key of authorized program
* **\[deprecated]** `recentBlockhash` : `String | undefined` - a recent blockhash
* **\[deprecated]** `signatures` : `Array` of `Object` or `undefined` - (optional) previous partial signatures for this instruction set
- `Object` - partial signature
- `pubkey` : `String` - pubkey of the signer
- `signature` : `String` - signature matching `pubkey`
### Returns [#returns-3] `Object`: * `signature`: `String` - corresponding signature for signed instructions * `transaction`?: `String | undefined` - optional: base64-encoded serialized transaction ### Example [#example-3] ```typescript // Request { "id": 1, "jsonrpc": "2.0", "method": "solana_signTransaction", "params": { "feePayer": "AqP3MyNwDP4L1GJKYhzmaAUdrjzpqJUZjahM7kHpgavm", "instructions": [{ "programId": "Vote111111111111111111111111111111111111111", "data": "37u9WtQpcm6ULa3VtWDFAWoQc1hUvybPrA3dtx99tgHvvcE7pKRZjuGmn7VX2tC3JmYDYGG7", "keys": [{ "isSigner": true, "isWritable": true, "pubkey": "AqP3MyNwDP4L1GJKYhzmaAUdrjzpqJUZjahM7kHpgavm" }] }], "recentBlockhash": "2bUz6wu3axM8cDDncLB5chWuZaoscSjnoMD2nVvC1swe", "signatures": [{ "pubkey": "AqP3MyNwDP4L1GJKYhzmaAUdrjzpqJUZjahM7kHpgavm", "signature": "2Lb1KQHWfbV3pWMqXZveFWqneSyhH95YsgCENRWnArSkLydjN1M42oB82zSd6BBdGkM9pE6sQLQf1gyBh8KWM2c4" }], "transaction": "r32f2..FD33r" } } // Result { "id": 1, "jsonrpc": "2.0", "result": { signature: "2Lb1KQHWfbV3pWMqXZveFWqneSyhH95YsgCENRWnArSkLydjN1M42oB82zSd6BBdGkM9pE6sQLQf1gyBh8KWM2c4" } } ``` ## solana_signAllTransactions [#solana_signalltransactions] This method is responsible for signing a list of transactions. The wallet must sign all transactions and return the signed transactions in the same order as received. Wallets must sign all transactions or return an error if it is not possible to sign any of them. ### Parameters [#parameters-4] `Object` - Signing parameters: * `transactions` : `String[]` - base64-encoded serialized list of transactions
### Returns [#returns-4] `Object`: * `transactions` : `String[]` - base64-encoded serialized list of signed transactions in the same order as received
### Example [#example-4] ```typescript // Request { "id": 1, "jsonrpc": "2.0", "method": "solana_signAllTransactions", "params": { "transactions": string[] } } // Response { "id": 1, "jsonrpc": "2.0", "result": { "transactions": string[] } } ``` ## solana_signAndSendTransaction [#solana_signandsendtransaction] This method is responsible for signing and sending a transaction to the Solana network. The wallet must sent the transaction and return the signature that can be used as a transaction id. ### Parameters [#parameters-5] `Object` - transaction and options:
* `transaction` : `String` - the whole transaction serialized and encoded with base64
* `sendOptions` : `Object` - options for sending the transaction
* `skipPreflight` : `Boolean` - skip preflight checks
* `preflightCommitment` : `'processed' | 'confirmed' | 'finalized' | 'recent' | 'single' | 'singleGossip' | 'root' | 'max'` - preflight commitment level
* `maxRetries` : `Number` - maximum number of retries
* `minContextSlot` : `Number` - minimum context slot
### Returns [#returns-5] `Object`: * `signature` : `String`, - the signature of the transaction encoded with base58 used as transaction id
### Example [#example-5] ```typescript // Request { "id": 1, "jsonrpc": "2.0", "method": "solana_signAndSendTransaction", "params": { "transaction": string, "sendOptions": { "skipPreflight"?: boolean, "preflightCommitment"?: 'processed' | 'confirmed' | 'finalized' | 'recent' | 'single' | 'singleGossip' | 'root' | 'max', "maxRetries"?: number, "minContextSlot"?: number, } } } // Response { "id": 1, "jsonrpc": "2.0", "result": { "signature": string } } ``` # Stacks (/wallets/chains/stacks) These are the methods that wallets should implement to handle Stacks transfers and messages via WalletConnect. ## Core Methods (common) [#core-methods-common] ### stx_getAddresses [#stx_getaddresses] Retrieve active account addresses; primarily Stacks-focused. #### Request [#request] ```json { "id": 1, "jsonrpc": "2.0", "method": "stx_getAddresses", "params": {} } ``` #### Response [#response] ```json { "jsonrpc": "2.0", "id": 1, "result": { "addresses": [ { "symbol": "STX", "address": "SP…" } ] } } ``` **Notes:** - Use this first to select the wallet's active address. - Filter on `symbol: "STX"` or by address prefix (SP for mainnet, ST for testnet). ## Stacks Methods [#stacks-methods] ### stx_transferStx [#stx_transferstx] Transfer STX. #### Request [#request-1] ```json { "id": 1, "jsonrpc": "2.0", "method": "stx_transferStx", "params": { "sender": "SP3F7GQ48JY59521DZEE6KABHBF4Q33PEYJ823ZXQ", "recipient": "SP3F7GQ48JY59521DZEE6KABHBF4Q33PEYJ823ZXQ", "amount": "100000000000", "memo": "", "network": "mainnet" } } ``` #### Parameters [#parameters] | Parameter | Required? | Data Type | Description | |-----------|------|-----------|-------------| | `sender` | Required | `string` | The stacks address of sender (required for multi-account scenarios) | | `recipient` | Required | `string` | Stacks address | | `amount` | Required | `string` | micro-STX (uSTX) | | `memo` | Optional | `string` | Memo string to be included with the transfer transaction | | `network` | Optional | `string` | "mainnet" \| "testnet" \| "devnet" | #### Response [#response-1] ```json { "jsonrpc": "2.0", "id": 1, "result": { "txid": "1234567890abcdef1234567890abcdef12345678", "transaction": "0x…" } } ``` ### stx_signTransaction [#stx_signtransaction] Sign a Stacks transaction. Optional broadcast. #### Request [#request-2] ```json { "id": 1, "jsonrpc": "2.0", "method": "stx_signTransaction", "params": { "transaction": "0x…", "broadcast": false, "network": "mainnet" } } ``` #### Parameters [#parameters-1] | Parameter | Required? | Data Type | Description | |-----------|------|-----------|-------------| | `transaction` | Required | `string` | hex transaction | | `broadcast` | Optional | `boolean` | default false | | `network` | Optional | `string` | "mainnet" \| "testnet" \| "devnet" | #### Response [#response-2] ```json { "jsonrpc": "2.0", "id": 1, "result": { "signature": "0x…", "transaction": "0x…", "txid": "1234567890abcdef1234567890abcdef12345678" } } ``` **Note:** `txid` is present if broadcast=true ### stx_signMessage [#stx_signmessage] Sign arbitrary message; supports structured (SIP-018). #### Request [#request-3] ```json { "id": 1, "jsonrpc": "2.0", "method": "stx_signMessage", "params": { "address": "SP3F7GQ48JY59521DZEE6KABHBF4Q33PEYJ823ZXQ", "message": "message", "messageType": "utf8", "network": "mainnet", "domain": "example.com" } } ``` #### Parameters [#parameters-2] | Parameter | Required? | Data Type | Description | |-----------|------|-----------|-------------| | `address` | Required | `string` | The stacks address of sender | | `message` | Required | `string` | Utf-8 string representing the message to be signed by the wallet | | `messageType` | Optional | `string` | Type of message for signing: `utf8` for basic string or `structured` for structured data | | `network` | Optional | `string` | Network for signing: `mainnet`, `testnet`, `signet`, `devnet` (note: redundant since chainId is provided) | | `domain` | Optional | `string` | Domain tuple per SIP-018 (for structured messages only) | #### Response [#response-3] ```json { "jsonrpc": "2.0", "id": 1, "result": { "signature": "0x…" } } ``` ### stx_signStructuredMessage [#stx_signstructuredmessage] Domain-bound structured signing (SIP-018). #### Request [#request-4] ```json { "id": 1, "jsonrpc": "2.0", "method": "stx_signStructuredMessage", "params": { "message": "message", "domain": "domain" } } ``` #### Parameters [#parameters-3] | Parameter | Required? | Data Type | Description | |-----------|------|-----------|-------------| | `message` | Required | `string \| object` | message to be signed | | `domain` | Required | `string \| object` | domain for structured signing | #### Response [#response-4] ```json { "jsonrpc": "2.0", "id": 1, "result": { "signature": "0x…", "publicKey": "0x04…" } } ``` **Note:** `publicKey` is optional ### stx_callContract [#stx_callcontract] Wrapper method for `stx_signTransaction` that calls a Stacks contract. #### Request [#request-5] ```json { "id": 1, "jsonrpc": "2.0", "method": "stx_callContract", "params": { "contract": "SP3F7GQ48JY59521DZEE6KABHBF4Q33PEYJ823ZXQ.my-contract", "functionName": "get-balance", "functionArgs": [] } } ``` #### Parameters [#parameters-4] | Parameter | Required? | Data Type | Description | |-----------|------|-----------|-------------| | `contract` | Required | `string` | Fully qualified contract identifier, including Stacks address and contract name | | `functionName` | Required | `string` | Name of the function to call | | `functionArgs` | Required | `string[]` | Arguments to pass to the contract function, encoded as strings | #### Response [#response-5] ```json { "jsonrpc": "2.0", "id": 1, "result": { "txid": "stack_tx_id", "transaction": "raw_tx_hex" } } ``` - `txid` - is used to identify the transaction on the explorer - `transaction` - hex-encoded raw transaction ## Session Properties [#session-properties] In a connection request, it is recommended to serialize the response to `stx_getAddresses` in `session.sessionProperties.stacks_getAddresses`. This allows dapps to consume an active session without requiring a context switch to re-request all addresses and associated public keys from the wallet. # Stellar (/wallets/chains/stellar) These are the methods that wallets should implement to handle Stellar transactions and messages via WalletConnect. The Stellar RPC standard is a proposal still under review and specifications may change. Implementation details and method signatures are subject to updates. ## Network / Chain Information [#network--chain-information] | Item | Form | | ------- | -------------------------------------------------------------------------------------------------------- | | CAIP-2 | `stellar:pubnet` OR `stellar:testnet` | | CAIP-10 | `stellar:pubnet:G…` — base32 StrKey account ID (56 chars, version byte `0x30`) | | CAIP-19 | `stellar:pubnet/slip44:148` (XLM) or `stellar:pubnet/asset:{code}-{issuer}` (issued assets) | The CAIP-2 reference (`pubnet` / `testnet`) matches the [Stellar CAIP-2 namespace draft](https://github.com/ChainAgnostic/namespaces/blob/main/stellar/caip2.md). It is **not** the network passphrase — that is a separate signing-domain constant wallets bind into every signature, derived from the chain (see [Signing semantics](#signing-semantics)). ### Account format [#account-format] Account IDs returned to the dApp are **CAIP-10 strings**, e.g.: ```text stellar:pubnet:GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN ``` Wallets MUST return the **G… StrKey** form (Ed25519 public key + CRC16 checksum, base32-encoded). Wallets MUST NOT return: - Muxed account (`M…`) IDs — these require a separate spec (CAP-27) and are not universally supported. - Pre-auth (`T…`) or signer-hash (`X…`) StrKey forms — these are not accounts. - Raw 32-byte public keys without StrKey encoding. ### XDR encoding convention [#xdr-encoding-convention] All transaction payloads cross the wire as **base64-encoded XDR strings**, matching SDF's reference SDKs and Horizon's `/transactions?tx=…` parameter. Specifically: - `stellar_signXDR` and `stellar_signAndSubmitXDR` accept and return a base64-encoded **`TransactionEnvelope`** XDR. - The envelope's discriminant determines tx version: `ENVELOPE_TYPE_TX_V0`, `ENVELOPE_TYPE_TX`, or `ENVELOPE_TYPE_TX_FEE_BUMP`. - Wallets MUST accept all three; wallets MAY emit signatures only on V1 and fee-bump envelopes (V0 is deprecated). ## Session Proposal [#session-proposal] A standard WalletConnect session proposal for a Stellar-enabled dApp: ```json { "optionalNamespaces": { "stellar": { "chains": ["stellar:pubnet"], "methods": [ "stellar_signXDR", "stellar_signAndSubmitXDR", "stellar_signMessage", "stellar_signAuthEntry" ], "events": ["accountsChanged", "chainChanged"] } } } ``` | Property | Optional methods | | ------------------ | --------------------------- | | Sign transaction | `stellar_signXDR` | | Sign a message | `stellar_signMessage` | | Sign and Submit | `stellar_signAndSubmitXDR` | | Soroban | `stellar_signAuthEntry` | ## RPC Methods [#rpc-methods] ### stellar_signXDR [#stellar_signxdr] Asks the wallet to attach a signature to a Stellar `TransactionEnvelope` and return the resulting envelope **without broadcasting it**. The dApp (or a relayer it trusts) is responsible for submission. This is the **primary method** for fee-abstracted flows: the dApp constructs an inner transaction whose `source_account` is the buyer; the wallet signs as the buyer; a separate fee-source wraps the result in a `FeeBumpTransactionEnvelope` and submits. #### Parameters [#parameters] `Object`: | Field | Type | Required | Description | | --------- | ----------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------- | | `xdr` | `string` (base64) | yes | The unsigned (or partially-signed) `TransactionEnvelope` XDR to sign. | | `chain` | `string` (CAIP-2) | yes | Must equal the session's selected chain — `stellar:pubnet`. Wallet MUST reject signing if the encoded `network_id` inside the tx does not match this chain. | | `account` | `string` (CAIP-10)| yes | The account that should sign. Wallet MUST reject if it doesn't custody this account. | This method **signs only**. To sign and broadcast in a single round-trip, use [`stellar_signAndSubmitXDR`](#stellar-signandsubmitxdr). #### Returns [#returns] `Object`: | Field | Type | Description | | --------------- | ------------------ | --------------------------------------------------------------------------------- | | `signedXDR` | `string` (base64) | The signed `TransactionEnvelope` XDR. Existing signatures in the input are preserved. | | `signerAddress` | `string` (CAIP-10) | The account that signed (echoes `account`). | #### Example [#example] ```json // Request { "id": 1, "jsonrpc": "2.0", "method": "stellar_signXDR", "params": { "xdr": "AAAAAgAAAACz/ZNn8sJpz0r1A/8mO0wQVjEPFNG8mU3sk1Wk7TPxIQAAAGQAGYGzAAAACgAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAEsbESgFLrQc4j7yo2Up/EWNqQhgvBYGgYNCu9EuRRl+AAAAAVVTREMAAAAA...", "chain": "stellar:pubnet", "account": "stellar:pubnet:GCZ73GTH6LBGTT2K6UB76JR3JQIKMMIPCTI3ZGKN5SJVLJ65GPYSCIBQ" } } // Response { "id": 1, "jsonrpc": "2.0", "result": { "signedXDR": "AAAAAgAAAACz/ZNn8sJpz0r1A/8mO0wQVjEPFNG8mU3sk1Wk7TPxIQAAAGQAGYGzAAAACgAAAAAAAAAAAAAA...AAAAAEFNB7s=", "signerAddress": "stellar:pubnet:GCZ73GTH6LBGTT2K6UB76JR3JQIKMMIPCTI3ZGKN5SJVLJ65GPYSCIBQ" } } ``` ### stellar_signAndSubmitXDR [#stellar_signandsubmitxdr] Asks the wallet to sign and submit a transaction in one step. The wallet broadcasts via its configured RPC (Horizon or Stellar RPC) and returns the resulting transaction hash. Use this method when the dApp does **not** operate a relayer (i.e. the buyer is paying their own XLM fee directly). #### Parameters [#parameters-1] `Object`: | Field | Type | Required | Description | | ------------------ | ------------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `xdr` | `string` (base64) | yes | The unsigned `TransactionEnvelope` XDR. | | `chain` | `string` (CAIP-2) | yes | Must equal the session's selected chain. | | `account` | `string` (CAIP-10) | yes | Signing account. | | `waitForInclusion` | `boolean` | no | If `true`, wallet waits up to ledger-close time before responding and returns `successful`. If `false` (default), wallet responds as soon as it receives the submission ack from its RPC. | #### Returns [#returns-1] `Object`: | Field | Type | Description | | ------------ | ------------------ | ------------------------------------------------------------------------------------------------ | | `tx_hash` | `string` (hex, 64) | The hash of the submitted transaction. | | `signedXDR` | `string` (base64) | The final signed `TransactionEnvelope` XDR (so the dApp can independently verify the hash). | | `successful` | `boolean` | Optional. Present only when `waitForInclusion: true`. `true` if the tx landed and `successful=true` in its result envelope. | #### Example [#example-1] ```json // Request { "id": 2, "jsonrpc": "2.0", "method": "stellar_signAndSubmitXDR", "params": { "xdr": "AAAAAgAAAACz/ZNn8sJpz0r1A/8mO0wQVjEPFNG8mU3sk1Wk7TPxIQAAAGQAGYGzAAAA...", "chain": "stellar:pubnet", "account": "stellar:pubnet:GCZ73GTH6LBGTT2K6UB76JR3JQIKMMIPCTI3ZGKN5SJVLJ65GPYSCIBQ", "waitForInclusion": true } } // Response { "id": 2, "jsonrpc": "2.0", "result": { "tx_hash": "3389e9f0f1a54f04a78fd09a7e0fc0d44f1eecbe8c33a3d56a39c8b46d2a8b48", "signedXDR": "AAAAAgAAAACz/ZNn8sJpz0r1...AAAAAEFNB7s=", "successful": true } } ``` ### stellar_signMessage [#stellar_signmessage] Asks the wallet to sign an arbitrary message under a Stellar account's Ed25519 key, **outside** the context of a Stellar transaction. This enables [SEP-10 web auth](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0010.md)-style sign-in flows and dApp session attestation. To prevent a malicious dApp from getting a wallet to sign a payload that is also a valid transaction body, wallets MUST prepend a domain-separating prefix before signing: ```text sign(Ed25519, sha256("Stellar Signed Message:\n" || message)) ``` The fixed UTF-8 prefix `"Stellar Signed Message:\n"` (with the trailing newline) is concatenated **directly** with the message bytes — no `0x00` separator and no length prefix — then SHA-256 hashed and Ed25519-signed. This matches the finalized [SEP-53](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0053.md) convention (the same domain-separation approach as Bitcoin/Ethereum signed messages) and ensures cross-context replay is impossible — a SEP-10 challenge transaction would never collide with a `stellar_signMessage` payload. #### Parameters [#parameters-2] `Object`: | Field | Type | Required | Description | | ----------------- | ----------------------------- | -------- | --------------------------------------------------------------------------------------------- | | `message` | `string` (utf-8 OR base64) | yes | The payload to sign. If `messageEncoding: "base64"`, decoded as raw bytes; default `"utf-8"`. | | `messageEncoding` | `"utf-8"` \| `"base64"` | no | Defaults to `"utf-8"`. | | `chain` | `string` (CAIP-2) | yes | `stellar:pubnet` (signature is network-agnostic, but the session context is). | | `account` | `string` (CAIP-10) | yes | Signing account. | #### Returns [#returns-2] `Object`: | Field | Type | Description | | --------------- | ------------------ | ---------------------------------------------- | | `signature` | `string` (base64) | 64-byte Ed25519 signature, base64-encoded. | | `signerAddress` | `string` (CAIP-10) | Signing account (echoes input). | #### Example [#example-2] ```json // Request { "id": 3, "jsonrpc": "2.0", "method": "stellar_signMessage", "params": { "message": "pay-core://sign-in?nonce=8c4f1a2b&exp=1747746000", "messageEncoding": "utf-8", "chain": "stellar:pubnet", "account": "stellar:pubnet:GCZ73GTH6LBGTT2K6UB76JR3JQIKMMIPCTI3ZGKN5SJVLJ65GPYSCIBQ" } } // Response { "id": 3, "jsonrpc": "2.0", "result": { "signature": "iJ7rH9N2T5q3Vh8U8a3l1eC9bD0fK6mPq9R5/4tZv1c9Ek2y0sJgPpVxT8aBhYf3LqW1uAYR7s2qNlDe6cZyAA==", "signerAddress": "stellar:pubnet:GCZ73GTH6LBGTT2K6UB76JR3JQIKMMIPCTI3ZGKN5SJVLJ65GPYSCIBQ" } } ``` **Anti-pattern:** Do NOT sign raw bytes without the domain prefix. Wallets that do so MUST be considered non-compliant — they expose users to transaction-impersonation attacks. ### stellar_signAuthEntry (Soroban) [#stellar_signauthentry-soroban] Signs a Soroban `SorobanAuthorizationEntry`, enabling Soroban contract authorizations to be co-signed by an address that is **not** the transaction's source account. This is the Stellar analogue to Ethereum's EIP-712 typed-data signing for permits / meta-transactions: a user authorizes a specific contract invocation tree, a separate party submits the transaction that consumes the authorization. The signing payload is the `HashIDPreimage::SOROBAN_AUTHORIZATION` preimage, computed as: ```text sign(Ed25519, sha256(xdr(HashIDPreimageSorobanAuthorization { network_id, nonce, signature_expiration_ledger, invocation, }))) ``` All four fields are pulled from the `SorobanCredentials::SOROBAN_CREDENTIALS_ADDRESS` block inside the auth entry. `network_id` is bound by the wallet from the session's CAIP-2 chain (NOT trusted from the request). #### Parameters [#parameters-3] `Object`: | Field | Type | Required | Description | | ----------- | ------------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `authEntry` | `string` (base64) | yes | The unsigned `SorobanAuthorizationEntry` XDR. Its `credentials` MUST be of type `SOROBAN_CREDENTIALS_ADDRESS` with an empty `signature` SCVal. `SOROBAN_CREDENTIALS_SOURCE_ACCOUNT` entries are not signable via this method — they are authorized implicitly by signing the enclosing transaction. | | `chain` | `string` (CAIP-2) | yes | Must equal the session's selected chain. | | `account` | `string` (CAIP-10) | yes | The account that should sign. Wallet MUST verify it matches `credentials.address` inside the entry; reject with `4302` otherwise. | The wallet MUST also reject (`4304` — `AUTH_EXPIRED`) if `signature_expiration_ledger` is ≤ the current ledger sequence as known to the wallet, with a small safety margin to account for propagation. #### Returns [#returns-3] `Object`: | Field | Type | Description | | ----------------- | ------------------ | -------------------------------------------------------------------------------------------------------------------- | | `signedAuthEntry` | `string` (base64) | The updated `SorobanAuthorizationEntry` XDR with the `signature` SCVal populated. Other fields (nonce, expiration, invocation) MUST be byte-identical to the input. | | `signerAddress` | `string` (CAIP-10) | Echoes `account`. | The `signature` SCVal follows Stellar's account-contract signer convention: an `SCMap` with keys `"public_key"` (32-byte Ed25519 pubkey as `SCBytes`) and `"signature"` (64-byte Ed25519 signature as `SCBytes`). Wallets MUST NOT emit a raw 64-byte signature without the map wrapper — Soroban host code rejects it. #### Example [#example-3] ```json // Request — dApp wants the user to authorize a transfer(from=user, to=merchant, amount=10_0000000) invocation { "id": 4, "jsonrpc": "2.0", "method": "stellar_signAuthEntry", "params": { "authEntry": "AAAAAQAAAAAAAAAAs/2TZ/LCac9K9QP/JjtMEFYxDxTRvJlN7JNVpO0z8SEAAAAAAAAAAQAGgaUAAAAAAAAAAa1uVUtkbThwc1ZmTGdEYzVlbnVsbAAAAAAAAAAIdHJhbnNmZXIAAAADAAAAEgAAAAAAAAAAs/2TZ/LCac9K9QP/JjtMEFYxDxTRvJlN7JNVpO0z8SEAAAASAAAAAAAAAABLGxEoBS60HOI+8qNlKfxFjakIYLwWBoGDQrvRLkUZfgAAAAoAAAAAAAAAAAAAAAAF9eEAAAAAAAAAAAA=", "chain": "stellar:pubnet", "account": "stellar:pubnet:GCZ73GTH6LBGTT2K6UB76JR3JQIKMMIPCTI3ZGKN5SJVLJ65GPYSCIBQ" } } // Response — same entry, signature SCVal now populated with the account-contract signer map { "id": 4, "jsonrpc": "2.0", "result": { "signedAuthEntry": "AAAAAQAAAAAAAAAAs/2TZ/LCac9K9QP/JjtMEFYxDxTRvJlN7JNVpO0z8SEAAAAAAAAAAQAGgaUAAAAAAAAAAa1uVUtkbThwc1ZmTGdEYzVlbnVsbAAAAAAAAAAIdHJhbnNmZXIAAAADAAAAEgAAAAAAAAAAs/2TZ/LCac9K9QP/JjtMEFYxDxTRvJlN7JNVpO0z8SEAAAASAAAAAAAAAABLGxEoBS60HOI+8qNlKfxFjakIYLwWBoGDQrvRLkUZfgAAAAoAAAAAAAAAAAAAAAAF9eEAAAARAAAAAQAAAAIAAAAPAAAACnB1YmxpY19rZXkAAAAAAA0AAAAgs/2TZ/LCac9K9QP/JjtMEFYxDxTRvJlN7JNVpO0z8SEAAAAPAAAACXNpZ25hdHVyZQAAAAAAAA0AAABAi3hvR9N+a5q1Vh8U8a3l1eC9bD0fK6mPq9R5/4tZv1c9Ek2y0sJgPpVxT8aBhYf3LqW1uAYR7s2qNlDe6cZyAA==", "signerAddress": "stellar:pubnet:GCZ73GTH6LBGTT2K6UB76JR3JQIKMMIPCTI3ZGKN5SJVLJ65GPYSCIBQ" } } ``` ## Events [#events] | Event | Payload | Notes | | ----------------- | ------------------------------------ | -------------------------------------------------------------------------------------------- | | `accountsChanged` | `{ accounts: string[] }` (CAIP-10) | Emitted when the user changes the active account in their wallet, or revokes access for an account. | | `chainChanged` | `{ chainId: string }` (CAIP-2) | Emitted when the wallet switches the active network (e.g. `stellar:pubnet` ↔ `stellar:testnet`). | ## Signing semantics [#signing-semantics] ### Network passphrase binding [#network-passphrase-binding] Every Stellar transaction signature is computed over: ```text sign(Ed25519, sha256(network_id || envelope_payload)) ``` where `network_id = sha256("Public Global Stellar Network ; September 2015")` for pubnet. This is **inside** the XDR envelope and is the protocol-level replay protection across networks. Wallets MUST: 1. Decode the envelope's signing payload, **not** the wire bytes, before signing. 2. Compute `network_id` from the network the session belongs to (`stellar:pubnet` → pubnet passphrase). Wallets MUST NOT trust a `network_id` embedded in the request — only the CAIP-2 chain identifier. 3. Refuse to sign if the decoded envelope's internal network reference (when present, e.g. on fee-bump inner txs) does not match the session chain. ### Fee-bump envelopes [#fee-bump-envelopes] When the dApp passes a `FeeBumpTransactionEnvelope` to `stellar_signXDR`: - The wallet signs **only the inner tx**, not the outer fee-bump envelope. The outer envelope is signed by the `fee_source` account (typically a different party — the relayer). - Wallets MUST validate that the inner tx's `source_account` is in fact the `account` parameter. - Wallets MAY warn the user that fees are being paid by a different account (`fee_source`), and SHOULD display both the inner source and outer fee source in the signing UI. ### Computing the tx hash and explorer discoverability [#computing-the-tx-hash-and-explorer-discoverability] The transaction hash is **deterministic from the signed envelope** — signatures are computed over the hash, they are not part of it. As soon as a dApp receives `signedXDR` from `stellar_signXDR`, it can derive the same hash the network will use. ```text tx_hash = sha256( network_id ‖ ENVELOPE_TYPE ‖ tx_payload_xdr ) ``` | Component | Value | | ---------------- | ---------------------------------------------------------------------------------------------------------------- | | `network_id` | `sha256("Public Global Stellar Network ; September 2015")` — 32 bytes, fixed for pubnet | | `ENVELOPE_TYPE` | XDR-encoded `EnvelopeType` enum (4 bytes, big-endian): `2` (`ENVELOPE_TYPE_TX`) for normal txs, `5` (`ENVELOPE_TYPE_TX_FEE_BUMP`) for fee-bump txs | | `tx_payload_xdr` | XDR-encoded **`Transaction`** struct (the inner body — NOT the full envelope with its signatures) | Adding, removing, or reordering signatures does NOT change the hash. Reference computation: ```typescript import { TransactionBuilder, Networks } from "@stellar/stellar-sdk"; const { signedXDR } = await session.request({ topic, chainId: "stellar:pubnet", request: { method: "stellar_signXDR", params: { xdr, chain, account } }, }); const tx = TransactionBuilder.fromXDR(signedXDR, Networks.PUBLIC); const txHash = tx.hash().toString("hex"); // 64-char hex ``` **Inner hash vs. fee-bump hash.** When `stellar_signXDR` is used inside a fee-abstraction flow (the wallet signs an inner tx, a relayer wraps it in a `FeeBumpTransaction` before submitting), the hash the dApp computes from the inner tx (`H_inner`) is **not** the hash that lands on-chain (`H_fb`). Horizon resolves **either hash** to the same transaction record — a `GET /transactions/{hash}` request works whether you pass `H_inner` or `H_fb`, and both are exposed on the returned fee-bump record. For stable UX, prefer `H_fb` for explorer links once submission is confirmed; `H_inner` works as an immediate optimistic identifier between sign-time and submission. Note that Horizon will **404** on an `H_inner` lookup until the wrapping fee-bump transaction has been submitted and included in a ledger. ## Additional Resources [#additional-resources] - [CAIP-2](https://chainagnostic.org/CAIPs/caip-2) and [CAIP-10](https://chainagnostic.org/CAIPs/caip-10) — chain and account identifiers. - [Stellar CAIP-2 namespace draft](https://github.com/ChainAgnostic/namespaces/blob/main/stellar/caip2.md). - [Stellar SEP-7](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0007.md), [SEP-10](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0010.md), [SEP-53](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0053.md). - [Freighter — WalletConnect (mobile)](https://docs.freighter.app/mobile-walletconnect/mobile). - [Stellar XDR reference](https://developers.stellar.org/docs/encyclopedia/xdr). - [Fee-bump transactions](https://developers.stellar.org/docs/learn/encyclopedia/transactions-specialized/fee-bump-transactions). # Sui (/wallets/chains/sui) These are the methods that wallets should implement to handle Sui transactions and messages via WalletConnect. The SUI RPC standard is still under review and specifications may change. Implementation details and method signatures are subject to updates. ## sui_getAccounts [#sui_getaccounts] This method returns an Array of public keys and addresses available to sign from the wallet. ### Parameters [#parameters] none ### Returns [#returns] `Array` - Array of accounts: - `Object` : - `pubkey` : `String` - public key for keypair - `address` : `String` - the Sui address ### Example [#example] ```typescript // Request { "id": 1, "jsonrpc": "2.0", "method": "sui_getAccounts", "params": {} } // Result { "id": 1, "jsonrpc": "2.0", "result": [{ "pubkey": "AC68P56WCCTF0nUEX31/V5b1wqiD1pvfc8Fql8dPIPDA", "address":"0x3cd077f41680eebca0176baad3915b2ea26dbbdfd10161865234732bb1f2ac50" }] } ``` ### Session Properties [#session-properties] In a connection request, it is recommended to serialize the response to `getAccounts` in `session.sessionProperties.sui_getAccounts`. This allows dapps to consume an active session without requiring a context switch to re-request all addresses and associated public keys from the wallet. ## sui_signTransaction [#sui_signtransaction] Sign a Sui transaction without executing it. #### Parameters [#parameters-1] 1. `transaction` (object) - The transaction to sign: - `transaction` (string) - The base64 encoded, BCS encoded, transaction data - `address` (string) - The sender's Sui address #### Returns [#returns-1] `object` - The signed transaction: - `signature` (string) - The base64 encoded signature - `transactionBytes` (string) - The base64 encoded signed transaction bytes #### Example [#example-1] ```javascript // Request { "jsonrpc": "2.0", "id": 1, "method": "sui_signTransaction", "params": { "transaction": "AAACAAhkAAAAAAAAAAAgcfGPMPqXhXLvgkjSYSgtJoBBfJN4xPm3bwZGapDhVIICAgABAQAAAQEDAAAAAAEBAHHxjzD6l4Vy74JI0mEoLSaAQXyTeMT5t28GRmqQ4VSCAq3fqx8mNL6p13BcS9bG74Gbh1dowEtQ", "address": "0xd5f647edb77d4fda31d0304506447fb3c92e55aaf77bc5ed4b77c332dd4605fa" } } // Response { "jsonrpc": "2.0", "result": { "signature": "ACRvdr3yI2mdpeOK+NsJIimdNGcE9R//jjT3HALZ17fFyu818op4jZi/64lPBjpKMDX6ZtxnCFZExTOFdpi3MwEZXLv/ORduxMYX0fw8dbHlnWC8WG0ymrlAmARpEibbhw==", "transactionBytes": "AAACAAhkAAAAAAAAAAAg1fZH7bd9T9ox0DBFBkR/s8kuVar3e8XtS3fDMt1GBfoCAgABAQAAAQEDAAAAAAEBANX2R+23fU/aMdAwRQZEf7PJLlWq93vF7Ut3wzLdRgX6At/pRJzj2VpZgqXpSvEtd3GzPvt99hR8e/yOCGz/8nbRmA7QFAAAAAAgBy5vStJizn76LmJTBlDiONdR/2rSuzzS4L+Tp/Zs4hZ8cBxYkcSlxBD6QXvgS11E6d+DNek8LiA/beba6iH3l5gO0BQAAAAAIMpdmZjiqJ5GG9di1MAgD4S3uRr2gaMC7S1WsaeBwNIx1fZH7bd9T9ox0DBFBkR/s8kuVar3e8XtS3fDMt1GBfroAwAAAAAAAECrPAAAAAAAAA==" }, "id": 1 } ``` ### sui_signAndExecuteTransaction [#sui_signandexecutetransaction] Sign and execute a Sui transaction. #### Parameters [#parameters-2] 1. `transaction` (object) - The transaction to sign and execute: - `transaction` (string) - The base64 encoded, BCS encoded, transaction data - `address` (string) - The sender's Sui address #### Returns [#returns-2] `object` - The transaction result: - `digest` (string) - The transaction digest that can be used to look up the transaction in the explorer #### Example [#example-2] ```javascript // Request { "jsonrpc": "2.0", "id": 1, "method": "sui_signAndExecuteTransaction", "params": { "transaction": "AAACAAhkAAAAAAAAAAAgcfGPMPqXhXLvgkjSYSgtJoBBfJN4xPm3bwZGapDhVIICAgABAQAAAQEDAAAAAAEBAHHxjzD6l4Vy74JI0mEoLSaAQXyTeMT5t28GRmqQ4VSCAq3fqx8mNL6p13BcS9bG74Gbh1dowEtQ", "address": "0xd5f647edb77d4fda31d0304506447fb3c92e55aaf77bc5ed4b77c332dd4605fa" } } // Response { "jsonrpc": "2.0", "result": { "digest": "GBqPRFR9sYfWA8rt2wCkcgZrctyYMj8Ufunxkjg5G8zt" }, "id": 1 } ``` ### sui_signPersonalMessage [#sui_signpersonalmessage] Sign a personal message. #### Parameters [#parameters-3] 1. `message` (object) - The message to sign: - `message` (string) - The message to sign (plain text) - `address` (string) - The account address to sign with #### Returns [#returns-3] `object` - The signed message: - `signature` (string) - The base64 encoded signature #### Example [#example-3] ```javascript // Request { "jsonrpc": "2.0", "id": 1, "method": "sui_signPersonalMessage", "params": { "message": "This is a message to be signed for SUI", "address": "0xd5f647edb77d4fda31d0304506447fb3c92e55aaf77bc5ed4b77c332dd4605fa" } } // Response { "jsonrpc": "2.0", "result": { "signature": "APsZ7PvuAynXYxxfeo0Py4DWOnrUpwqHhJJ1F8aGB2nmS5Wv9dvVo8Gr7DKaXwPMqFaFNKsHb0Hej07R0L0NpQsZXLv/ORduxMYX0fw8dbHlnWC8WG0ymrlAmARpEibbhw==" }, "id": 1 } ``` ## Additional Resources [#additional-resources] For more information about Sui RPC methods and implementation details, please refer to the [official Sui documentation](https://docs.sui.io/sui-api-ref). # TON (/wallets/chains/ton) ## Network / Chain Information [#network--chain-information] | CAIP-2 | Chain ID | Name | RPC Endpoint | Namespace | | ---------- | -------- | ----------- | ---------------------------------------------- | --------- | | `ton:-239` | `-239` | TON Mainnet | `https://toncenter.com/api/v2/jsonRPC` | `ton` | | `ton:-3` | `-3` | TON Testnet | `https://testnet.toncenter.com/api/v2/jsonRPC` | `ton` | ## RPC Methods [#rpc-methods] Wallets must support the following JSON-RPC methods over WalletConnect sessions. No events are required. ## ton_sendMessage [#ton_sendmessage] Submit one or more transaction messages to the TON network. ### Request [#request] ```typescript interface TonSendMessageRequest { method: 'ton_sendMessage'; params: TonSendTransactionParams[]; } interface TonSendTransactionParams { valid_until?: number; // optional UNIX timestamp from?: string; // optional sender address (TEP-123 format) messages: TonTransactionMessage[]; } interface TonTransactionMessage { address: string; // recipient in TEP-123 format amount: number | string; // value in nanotons payload?: string; // optional base64 BoC stateInit?: string; // optional base64 BoC } ``` ### Example Request [#example-request] ```json { "id": 123, "jsonrpc": "2.0", "params": { "chainId": "ton:-239", "request": { "method": "ton_sendMessage", "params": [ { "valid_until": 1658253458, "from": "EQDmnxDMhId6v1Ofg_h5KR5coWlFG6e86Ro3pc7Tq4CA0-Jn", "messages": [ { "address": "EQBBJBB3HagsujBqVfqeDUPJ0kXjgTPLWPFFffuNXNiJL0aA", "amount": "20000000", "stateInit": "base64boc..." }, { "address": "EQDmnxDMhId6v1Ofg_h5KR5coWlFG6e86Ro3pc7Tq4CA0-Jn", "amount": "60000000", "payload": "base64boc..." } ] } ] } } } ``` ### Success Response [#success-response] ```json { "jsonrpc": "2.0", "id": 123, "result": "base64bocEncodedTransaction" } ``` ### Error Response [#error-response] ```json { "jsonrpc": "2.0", "id": 123, "error": { "code": , "message": "" } } ``` ## ton_signData [#ton_signdata] Sign an off-chain payload (text, binary, or cell) for authentication or verification by dApps. ### Request [#request-1] ```typescript interface TonSignDataRequest { method: 'ton_signData'; params: TonSignDataParams[]; } type TonSignDataParams = | { type: 'text'; text: string; from?: string } | { type: 'binary'; bytes: string; from?: string } | { type: 'cell'; schema: string; cell: string; from?: string }; ``` ### Example Request [#example-request-1] ```json { "id": 123, "jsonrpc": "2.0", "params": { "chainId": "ton:-239", "request": { "method": "ton_signData", "params": [ { "type": "text", "text": "Confirm new 2FA number:\\n+1 234 567 8901", "from": "EQDmnxDMhId6v1Ofg_h5KR5coWlFG6e86Ro3pc7Tq4CA0-Jn" } ] } } } ``` ### Success Response [#success-response-1] ```json { "jsonrpc": "2.0", "id": 123, "result": { "signature": "base64_signature", "address": "raw_wallet_address", "timestamp": 1658253458, "domain": "yourapp.com", "payload": { "type": "text", "text": "Confirm new 2FA number:\\n+1 234 567 8901" } } } ``` ### Error Response [#error-response-1] ```json { "jsonrpc": "2.0", "id": 123, "error": { "code": , "message": "" } } ``` ## Session Properties [#session-properties] Wallets must include `ton_getPublicKey` and `ton_getStateInit` in the session properties when approving a session. This is mandatory for TON Connect compatibility. When approving a session, wallets must serialize the following properties into `session.sessionProperties`: - `ton_getPublicKey`: The Ed25519 public key of the wallet (hex-encoded) - `ton_getStateInit`: The StateInit of the wallet contract (base64-encoded BoC) These properties are essential for TON Connect support because: - The public key is required for signature verification - The StateInit is needed to compute and verify the wallet address, as TON addresses are derived from the contract code and initial data ### Example Session Approval [#example-session-approval] ```typescript // When approving a session, include the TON session properties const session = await walletKit.approveSession({ id: proposal.id, namespaces: approvedNamespaces, sessionProperties: { ton_getPublicKey: "a1b2c3d4e5f6...", // hex-encoded Ed25519 public key ton_getStateInit: "te6cckEBAQEA..." // base64-encoded StateInit BoC } }); ``` This allows dApps to consume an active session without requiring additional requests to retrieve the wallet's public key and state initialization data. ## Notes & Considerations [#notes--considerations] * If `from` is omitted, the wallet should prompt the user to select an address. * All requests and responses must comply with JSON-RPC structure (`id`, `jsonrpc`, etc.). * Signature verification can be done using `ed25519.verify` on the original bytes. * `stateInit` support is needed when your wallet supports contract deployment flows. * The `domain` field in responses indicates the originating application (dApp) domain. # Tron (/wallets/chains/tron) These are the methods that wallets should implement to handle Tron transactions and messages via WalletConnect. ## Network / Chain Information [#network--chain-information] | CAIP-2 | Chain ID | Name | RPC Endpoint | Namespace | | ----------------- | ---------------- | ------------- | --------------------------- | --------- | | `tron:0x2b6653dc` | `0x2b6653dc` | Tron Mainnet | `https://api.trongrid.io` | `tron` | | `tron:0xcd8690dc` | `0xcd8690dc` | Tron Shasta | `https://api.shasta.trongrid.io` | `tron` | | `tron:0x94a9059e` | `0x94a9059e` | Tron Nile | `https://nile.trongrid.io` | `tron` | ## Session Properties [#session-properties] To enable the new simplified transaction structure, wallets should include `tron_method_version: "v1"` in their `sessionProperties` during the connection handshake: ```json { "sessionProperties": { "tron_method_version": "v1" } } ``` When `tron_method_version` is set to `"v1"`, the transaction structure is simplified to remove the nested `transaction.transaction` format. If not set, the legacy nested format is used for backward compatibility. ### tron_signTransaction [#tron_signtransaction] Sign a Tron transaction without executing it. #### Parameters [#parameters] - The transaction to sign: - `address` (string) - The sender's Tron address - `transaction` (object) - The transaction object to sign #### Returns [#returns] - The signed transaction: - `txID` (string) - The transaction ID (deterministically derived from raw transaction) - `signature` (array) - Array of signature strings - `raw_data` (object) - The raw transaction data - `raw_data_hex` (string) - The hex-encoded raw transaction data - `visible` (boolean) - Whether addresses are in visible format #### Example (New Format with tron_method_version: "v1") [#example-new-format-with-tron_method_version-v1] Request with the simplified format: ```json { "request": { "method": "tron_signTransaction", "params": { "address": "TKZRPqoV7WLFvjhT4cEyBLv27Rvv1RNWGj", "transaction": { "visible": false, "txID": "539f218871fdd87e94eb03a0dd617107ba722005f37a5ddb82cb65aa4f3b73b0", "raw_data": { "contract": [ { "parameter": { "value": { "data": "095ea7b300000000000000000000000069319ea845b1c35a1f7b0e1429f4f303e8f791330000000000000000000000000000000000000000000000000000000000000000", "owner_address": "4169319ea845b1c35a1f7b0e1429f4f303e8f79133", "contract_address": "41eca9bc828a3005b9a3b909f2cc5c2a54794de05f" }, "type_url": "type.googleapis.com/protocol.TriggerSmartContract" }, "type": "TriggerSmartContract" } ], "ref_block_bytes": "7803", "ref_block_hash": "16138f9255a1db91", "expiration": 1756201572000, "fee_limit": 200000000, "timestamp": 1756201512720 }, "raw_data_hex": "0a027803220816138f9255a1db9140a0ad95ae8e335aae01081f12a9010a31747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e54726967676572536d617274436f6e747261637412740a154169319ea845b1c35a1f7b0e1429f4f303e8f79133121541eca9bc828a3005b9a3b909f2cc5c2a54794de05f2244095ea7b300000000000000000000000069319ea845b1c35a1f7b0e1429f4f303e8f79133000000000000000000000000000000000000000000000000000000000000000007090de91ae8e3390018084af5f" } }, "expiryTimestamp": 1756201811 }, "chainId": "tron:0xcd8690dc" } ``` - Response: ```json { "visible": false, "txID": "539f218871fdd87e94eb03a0dd617107ba722005f37a5ddb82cb65aa4f3b73b0", "raw_data": { "contract": [ { "parameter": { "value": { "data": "095ea7b300000000000000000000000069319ea845b1c35a1f7b0e1429f4f303e8f791330000000000000000000000000000000000000000000000000000000000000000", "owner_address": "4169319ea845b1c35a1f7b0e1429f4f303e8f79133", "contract_address": "41eca9bc828a3005b9a3b909f2cc5c2a54794de05f" }, "type_url": "type.googleapis.com/protocol.TriggerSmartContract" }, "type": "TriggerSmartContract" } ], "ref_block_bytes": "7803", "ref_block_hash": "16138f9255a1db91", "expiration": 1756201572000, "fee_limit": 200000000, "timestamp": 1756201512720 }, "raw_data_hex": "0a027803220816138f9255a1db9140a0ad95ae8e335aae01081f12a9010a31747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e54726967676572536d617274436f6e747261637412740a154169319ea845b1c35a1f7b0e1429f4f303e8f79133121541eca9bc828a3005b9a3b909f2cc5c2a54794de05f2244095ea7b300000000000000000000000069319ea845b1c35a1f7b0e1429f4f303e8f79133000000000000000000000000000000000000000000000000000000000000000007090de91ae8e3390018084af5f", "signature": [ "1c2dd921c15fd83ca1dec4fd999b801f08c8bb073702f4bfafa4132a6e129421ed6267ec81c7dd2e4ef04ce077b101186ec2cda86d69f9f44255c216398cc9c601" ] } ``` ### tron_signMessage [#tron_signmessage] Sign a personal message. #### Parameters [#parameters-1] The message to sign: - `message` (string) - The message to sign (plain text) - `address` (string) - The account address to sign with #### Returns [#returns-1] The signed message: - `signature` (string) - The signature string #### Example [#example] - Request: ```json { "request": { "method": "tron_signMessage", "params": { "address": "TXUEmLr...", "message": "This is a message to be signed for Tron" }, "expiryTimestamp": 1758269816 }, "chainId": "tron:0xcd8690dc" } ``` - dApp result (what client.request(...) resolves to): ```json { "signature": "0x1ec623ee6e4716f5a116d0a2755b158ac05dfbc3e9118cca..." } ``` The methods below are not part of the required wallet surface in the Reown official Tron Wallet example. dApps may perform these directly against a Tron node or gateway. Wallets may implement them for convenience, but they're not required. ### tron_sendTransaction (optional) [#tron_sendtransaction-optional] Broadcast a signed transaction to the Tron network. #### Parameters [#parameters-2] The signed transaction object: - `txID` (string) - The transaction ID - `signature` (array) - Array of signature strings - `raw_data` (object) - The raw transaction data - `raw_data_hex` (string) - The hex-encoded raw transaction data #### Returns [#returns-2] The transaction result: - `result` (boolean) - Whether the transaction was successfully broadcast - `txid` (string) - The transaction ID that can be used to look up the transaction #### Example [#example-1] - Request: ```json { "jsonrpc": "2.0", "id": 1, "method": "tron_sendTransaction", "params": { "signedTransaction": { "txID": "66e79c6993f29b02725da54ab146ffb0453ee6a43b4083568ad9585da305374a", "signature": [ "7e760cef94bc82a7533bc1e8d4ab88508c6e13224cd50cc8da62d3f4d4e19b99514f..." ], "raw_data_hex": "0a02885b2208baa1c278fd0a309f4090c1dbe5e7325aae01081f12a9010a31747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e54726967676572536d617274436f6e747261637412740a15411cb0b7348eded93b8d0816bbeb819fc1d7a51f31121541a614f803b6fd780986a42c78ec9c7f77e6ded13c2244095ea7b30000000000000000000000001cb0b7348eded93b8d0816bbeb819fc1d7a51f3100000000000000000000000000000000000000000000000000000000000000007082f4d7e5e73290018084af5f" } } } ``` - Response: ```json { "jsonrpc": "2.0", "result": { "result": true, "txid": "66e79c6993f29b02725da54ab146ffb0453ee6a43b4083568ad9585da305374a" }, "id": 1 } ``` ### tron_getBalance (optional) [#tron_getbalance-optional] Get the TRX balance of a Tron address. #### Parameters [#parameters-3] 1. `address` (string) - The Tron address to query #### Returns [#returns-3] `number` - The balance in SUN (1 TRX = 1,000,000 SUN) #### Example [#example-2] - Request: ```json { "jsonrpc": "2.0", "id": 1, "method": "tron_getBalance", "params": { "address": "TLyqzVGLV1srkB7dToTAEqgDSfPtXRJZYH" } } ``` - Response: ```json { "jsonrpc": "2.0", "result": 1000000000, "id": 1 } ``` ## Additional Resources [#additional-resources] For more information about Tron RPC methods and implementation details, please refer to the [official Tron documentation](https://developers.tron.network/). # How to Control Which Apps Can Connect to Your Users’ Wallets (/wallets/custodians/app-access-control) As a wallet provider or a custodian, you may want to restrict access to certain dapps to maintain control over which applications can connect to your users’ wallets. This can be useful for a variety of reasons, such as to prevent users from using certain apps that are not compliant with your policies or to simply block certain apps from connecting to your users' wallets. Using the Wallet SDK, you can block apps from connecting to your users' wallets by rejecting session requests from certain apps. ## Prerequisites [#prerequisites] - Please ensure you have integrated Wallet SDK into your wallet. - Please ensure that you have obtained and configured the project ID from the [WalletConnect Dashboard](https://dashboard.walletconnect.com). ## Maintaining a Blocklist of Apps [#maintaining-a-blocklist-of-apps] Wallet SDK allows you to identify malicious apps using [Verify API](/wallets/features/verify). However, as a wallet, you will need to build your own logic for the UI and UX of blocking certain apps. If there are specific apps that you want to block (not flagged as malicious by Verify API), you will need to maintain a blocklist of apps by storing the app's metadata in a database or a file. ## Inspecting Session Requests [#inspecting-session-requests] When receiving `onSessionProposal` events, check the dapp's metadata (name, URL, description) from `proposal.proposer.metadata`. After this, you can reject unwanted connections by calling `rejectSession()` for apps you want to block. For example: ```javascript walletKit.on('session_proposal', (event) => { const dappUrl = event.params.proposer.metadata.url; // Your blocklist logic if (isBlocked(dappUrl)) { walletKit.rejectSession({ id: event.id, reason: getSdkError('USER_REJECTED') }); return; } // Otherwise show approval UI }); ``` ## Conclusion [#conclusion] By following the steps above, you can block apps from connecting to your users' wallets by rejecting session requests from certain apps. # Extended WalletConnect Sessions Request for Apps (/wallets/custodians/app-extended-sessions) This guide will walk you through how an app developer can customize the session request expiry in WalletConnect using the **`expiry`** parameter. ## Extended Session Expiry - what does it mean? [#extended-session-expiry---what-does-it-mean] When an app sends a request through WalletConnect (for example, a signature request), it stays “active” until the expiry time is reached. If the wallet does not respond before the expiry, the request automatically fails with a timeout. By default, the expiry is short, i.e., 5 minutes. Extending the session expiry time allows the wallet and app to keep the request open longer, **up to 7 days**. This is useful for cases like off-hours approvals, delayed custody flows, or multi-party signing. ### What do apps need to do? [#what-do-apps-need-to-do] An app must: - Keep track of outstanding requests and handle delayed responses. - Have a UI that tolerates waiting for a response as long as the expiry is configured. Extended durations may not be suitable for **time-bounded actions** (e.g., swaps with quotes, flash opportunities) where blockchain state changes invalidate the request. Hence an app must align **WalletConnect expiry** with any **contract-level expiry** to avoid mismatched timing. ### Limits [#limits] - **Minimum:** 300 seconds (5 min) - **Maximum:** 604,800 seconds (7 days) ## How can I extend the session request expiry as an app? [#how-can-i-extend-the-session-request-expiry-as-an-app] Developers can define how long a WalletConnect session request remains active by using the **`expiry`** parameter in the session request payload. ### Parameter [#parameter] `expiry`: Optional field to set session expiry time. Must be in seconds. ### Implementation [#implementation] Below are the examples of how to implement the `expiry` parameter in the session request payload for different providers. ```javascript tab="Sign Client" const result = await signClient.request({ topic: 'xyz', request: { method: 'personal_sign', params: [ '0xdeadbeef', '0x000000000000000000000000000000000000dead' ] }, chainId: 'eip155:1', expiry: 600 // <-- add this for 10 minutes expiry in seconds }); ``` ```javascript tab="Universal Provider" const result = await universalProvider.request( { method: "personal_sign", params: ["0xdeadbeef", "0x000000000000000000000000000000000000dead"], }, "eip155:1", 600, // <-- add this for 10 minutes expiry in seconds ); ``` ```javascript tab="Ethereum Provider" await ethereumProvider.request( { method: "personal_sign", params: ["0xdeadbeef", "0x000000000000000000000000000000000000dead"], }, 600, // <-- add this for 10 minutes expiry in seconds ); ``` **Apps should store pending request IDs in local storage to handle delayed responses, app reload or crash scenarios.** # How to Control Which Smart Contracts Your Users Can Interact With (/wallets/custodians/contract-access-control) As a wallet provider or custodian, you may want to limit which smart contracts your users can interact with to maintain tighter control over onchain activity. This can be useful for enforcing compliance requirements, reducing exposure to malicious or unverified contracts, or simply restricting access to certain protocols that don’t align with your policies. Using the Wallet SDK, you can inspect and filter contract interaction requests to block or approve transactions based on your own criteria, such as contract addresses, function signatures, or network-specific rules. ## Prerequisites [#prerequisites] - Please ensure you have integrated Wallet SDK into your wallet. - Please ensure that you have obtained and configured the project ID from the [WalletConnect Dashboard](https://dashboard.walletconnect.com). ## Managing Smart Contract Access [#managing-smart-contract-access] Wallet SDK does not provide a built-in way to create and manage smart contract allowlists for access control. However, you can use the Wallet SDK to inspect the `session_proposal` and `session_request` payloads and review it to approve or reject the proposal before a session is established and/or a transaction is signed respectively. ### Inspecting Session Proposals [#inspecting-session-proposals] When a Web3 app is trying to establish a session or connect to your wallet, it will send a `session_proposal` payload to your wallet as shown below. After this, as a wallet, you can do the following: 1. Check `verifyContext.origin` and `validation` to confirm the dapp is trusted. 2. Approve or reject the proposal before the session is created. ```json { "id": 1685471520923476, "topic": "proposal_topic", "params": { "requiredNamespaces": { "eip155": { "chains": ["eip155:1"], "methods": ["eth_sendTransaction", "personal_sign"], "events": ["chainChanged", "accountsChanged"] } }, "proposer": { "metadata": { "name": "Aave", "description": "Aave App", "url": "https://app.aave.com", "icons": ["https://aave.com/icon.png"] } }, "verifyContext": { "origin": "https://app.aave.com", "validation": "VALID", "verifyUrl": "https://verify.walletconnect.com/record/abc123" } } } ``` ### Inspecting Session Requests [#inspecting-session-requests] After a session is approved, Web3 apps may request to sign a transaction or a message. As a wallet, you will receive a JSON-RPC request from the Web3 app as shown below. Inside the request payload, you will find the contract address (`to: 0xContractAddress`) that is being interacted with and the function that is being called. ```json { "id": 1685471630000123, "topic": "session_topic", "params": { "chainId": "eip155:1", "request": { "method": "eth_sendTransaction", "params": [ { "from": "0xCustodianSubAccount", "to": "0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32", "data": "0xa9059cbb0000000000000000000000000F1b5...", "value": "0x0" } ] }, "verifyContext": { "origin": "https://app.aave.com", "validation": "VALID" } } } ``` ### Enforcing Smart Contract Allowlists [#enforcing-smart-contract-allowlists] As a wallet or custodian, you would need to code your own logic to enforce the smart contract allowlists. Please refer to the example implementation below that works for all EVM chains. ```javascript const ALLOWED_CONTRACTS = { "eip155:1": [ "0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32", // Lido "0x7Be8076f4EA4A4AD08075C2508e481d6C946D12b" // OpenSea ] }; function handleRequest(payload) { const chain = payload.params.chainId; const request = payload.params.request; if (request.method === "eth_sendTransaction") { const tx = request.params[0]; if (!tx.to) { throw new Error("Contract creation transactions are not allowed."); } const contract = tx.to.toLowerCase(); const allowed = (ALLOWED_CONTRACTS[chain] || []).map(a => a.toLowerCase()); if (!allowed.includes(contract)) { throw new Error(`Blocked transaction to unapproved contract: ${contract}`); } else { // Forward to signing flow signAndBroadcast(tx); } } } // Example placeholder for your signing logic function signAndBroadcast(tx) { console.log("Signing and broadcasting transaction:", tx); } ``` ## Conclusion [#conclusion] By following the steps above, you can block your users from interacting with certain smart contracts from certain apps. # Extended WalletConnect Sessions Request (/wallets/custodians/extended-sessions) This guide will walk you through how a wallet developer can customize the session request expiry in WalletConnect using the **`expiry`** parameter. ## Extended Session Expiry - what does it mean? [#extended-session-expiry---what-does-it-mean] When an app sends a request through WalletConnect (for example, a signature request), it stays “active” until the expiry time is reached. If the wallet does not respond before the expiry, the request automatically fails with a timeout. By default, the expiry is short, i.e., 5 minutes. Extending the session expiry time allows the wallet and app to keep the request open longer, **up to 7 days**. This is useful for cases like off-hours approvals, delayed custody flows, or multi-party signing. ### What do wallets need to do? [#what-do-wallets-need-to-do] A wallet must: - Maintain pending state until expiry or completion. - Gracefully discard expired requests. - Verify user intent remains valid after long delays. ### Limits [#limits] - **Minimum:** 300 seconds (5 min) - **Maximum:** 604,800 seconds (7 days) ## How can I extend the session request expiry as a wallet? [#how-can-i-extend-the-session-request-expiry-as-a-wallet] Wallets must correctly interpret and enforce the expiry. - Parse `expiry` in seconds from incoming request metadata. - Keep pending requests active until they’re resolved or the expiry time elapses. - Notify the user of pending and expired requests. - If the expiry has passed, return an error response (`code: 4100`, “Request expired”). - Optional UX: display countdown timers or “expires in X hours”. Please refer to the [Best Practices](/wallets/more/best-practices#session-request-expiry) section to learn how you can implement this in your code. # WalletConnect for Custodians and Institutions (/wallets/custodians/overview) **WalletConnect** enables custodians and institutions to offer curated, policy-enforced access to decentralized finance (DeFi) through a secure, modular SDK. Integrating WalletConnect and the Wallet SDK provides **institutional-grade control** while maintaining **interoperability** across thousands of dapps. Custodians can enforce granular permissions, from domain and contract verification to policy-based transaction controls, all while retaining full custody of client assets. ## Why WalletConnect? [#why-walletconnect] WalletConnect provides the **largest and most established gateway to DeFi**, designed for scale and institutional reliability. ### $400 Billion Total Network Volume [#400-billion-total-network-volume] Total Network Volume (TNV) is the total value of all transactions routed through the WalletConnect network in a given time (annually, in this case). So this represents how much money actually flows through the WalletConnect. WalletConnect has long been the quiet backbone of Web3 and not "just a QR code". It’s the invisible glue that connects users, dApps, and wallets, and now the scale finally shows it. Chart comparing the WalletConnect Total Network Volume of 400 billion dollars with major payment providers ### Fully Chain-Agnostic [#fully-chain-agnostic] WalletConnect supports 300+ EVM chains, Bitcoin, Solana, and 70+ other networks. Any network with a CAIP-25 namespace is supported. ### Available on 70,000+ dApps [#available-on-70000-dapps] WalletConnect is available on 70,000+ dApps, making it the most widely used wallet connection protocol in the world. ### Available on 500+ wallets [#available-on-500-wallets] WalletConnect is available on 500+ wallets, making it the most robust and user-friendly. You can find the list of wallets [here](https://walletguide.walletconnect.network/). # Chain Abstraction (/wallets/features/chain-abstraction) Chain Abstraction allows users to spend stablecoins across different networks seamlessly. This solution provides wallet developers with a toolkit to integrate cross-chain functionality using WalletKit. 💡 Support for Chain Abstraction is currently in early access phase. ## How it works [#how-it-works] When an application sends a `wallet_sendTransaction` request for an ERC-20 transfer (such as USDC), the wallet checks for available tokens across all supported networks. If the user has sufficient funds on any supported network, they can complete the transaction instantly, regardless of which network holds their tokens. For example, consider a scenario where an app requests a transfer of 225 USDC on the Base Network. Even if the user doesn't have USDC on Base, their wallet can automatically source the funds from other networks, making the experience seamless for both the user and the application. 💡 Make sure you have enough gas fees in other networks from which bridging will happen. For example, in given scenario, you need to have enough gas fees on OP Mainnet and Arbitrum. The diagram below shows how the wallet, WalletKit and RPC work together when a transfer needs funds from another network. ![Sequence diagram of the chain abstraction flow between the user, app, wallet, WalletKit and RPC](/images/chain-abstraction-sequence.png) ## Get Started [#get-started] } href="/wallets/android/chain-abstraction"> Get started with WalletKit in Android. } href="/wallets/ios/chain-abstraction"> Get started with WalletKit in iOS. } href="/wallets/flutter/chain-abstraction"> Get started with WalletKit in Flutter. } href="/wallets/react-native/chain-abstraction"> Get started with WalletKit in React Native. } href="/wallets/web/chain-abstraction"> Get started with WalletKit in Web. ## FAQ [#faq] ### What are the available networks for Chain Abstraction? [#what-are-the-available-networks-for-chain-abstraction] Chain Abstraction is available on the following networks: - Base - Arbitrum - OP Mainnet - Solana ### What are the supported tokens and networks? [#what-are-the-supported-tokens-and-networks] Chain Abstraction supports the following tokens across different networks: | Network | Assets | |-----------|-----------------| | Optimism | USDC, USDT, ETH | | Arbitrum | USDC, USDT, ETH | | Base | USDC, USDS, ETH | | Solana | USDC | ### What are the limitations? [#what-are-the-limitations] We currently support 1:1 transfers i.e. sourcing funds from one address to another. Make sure that you're transferring minimum 0.6$ worth of tokens and have enough gas to pay bridging fees. # Link Mode (/wallets/features/link-mode) WalletKit Link Mode is a low latency mechanism for transporting One-Click Auth requests and session requests over Universal Links, reducing the need for a WebSocket connection with the Relay. This significantly enhances the user experience when connecting native dApps to native wallets by reducing the latency associated with network connections, especially when the user has an unstable internet connection.
Link Mode in action
## When and How can Link Mode help? [#when-and-how-can-link-mode-help] Let's assume that a user is trying to connect their wallet to a native (mobile) dApp while commuting on a train with spotty internet. Now, if the user wants to sign a message on the dApp using their mobile wallet and the dApp relies on typical WebSocket connections to relay the session request. Due to unstable connectivity, the connection drops or lags, causing the wallet to not receive the sign message request promptly. **Using Link Mode, the dApp sends a Universal Link directly to the wallet app.** Since this doesn’t rely on maintaining a WebSocket session, the wallet receives the connection or signature request instantly and reliably, even in weak network conditions. ## Get Started [#get-started] } href="/wallets/android/link-mode"> Get started with Link Mode in WalletKit - Android. } href="/wallets/ios/link-mode"> Get started with Link Mode in WalletKit - iOS. } href="/wallets/flutter/link-mode"> Get started with Link Mode in WalletKit - Flutter. } href="/wallets/react-native/link-mode"> Get started with Link Mode in WalletKit - React Native. # One-Click Auth (/wallets/features/one-click-auth) Enable your users to connect to web3 through a single tap with One-Click Auth, improving connectivity speeds and creating all-around better UX and friction-free user journeys. With one-tap multi-chain and multi-account signing, let users authenticate multiple chains and accounts simultaneously. ## Get Started [#get-started] } href="/wallets/web/one-click-auth"> Get started with WalletKit in Web. } href="/wallets/android/one-click-auth"> Get started with WalletKit in Android. } href="/wallets/ios/one-click-auth"> Get started with WalletKit in iOS. } href="/wallets/react-native/one-click-auth"> Get started with WalletKit in React Native. } href="/wallets/flutter/one-click-auth"> Get started with WalletKit in Flutter. # Verify API (/wallets/features/verify) App Verification is a first-of-its-kind layered security solution that enables wallets to help users protect themselves from phishing attacks, with robust architecture enabling wallets to support users in better identifying the veracity of a domain they are attempting to connect to.
![Wallet connection requests showing the Verify states domain match, unverified, mismatch and threat](/images/mintlify/verify-banner.png)
Verify API Userflow
## Security providers [#security-providers] Verify API combines WalletConnect's domain registry with threat intelligence from leading web3 security providers. If any of them flags the domain behind a session proposal or session request as malicious, the `verifyContext` of that request is returned with `isScam` set to `true`. Real-time detection of malicious contracts, transactions and web3 threats. Crypto-native anti-phishing intelligence, including scam domain detection and takedowns. Real-time monitoring of malicious dapps, wallet drainers and phishing domains. ## Get Started [#get-started] } href="/wallets/android/verify"> Get started with WalletKit in Android. } href="/wallets/ios/verify"> Get started with WalletKit in iOS. } href="/wallets/flutter/verify"> Get started with WalletKit in Flutter. } href="/wallets/react-native/verify"> Get started with WalletKit in React Native. } href="/wallets/web/verify"> Get started with WalletKit in Web. } href="/wallets/c-sharp/verify"> Get started with WalletKit in .NET. # Chain Abstraction (/wallets/flutter/chain-abstraction) ## Methods [#methods] The following methods from Wallet SDK are used in implementing chain abstraction. 💡 Chain abstraction is currently in the early access phase ### Prepare [#prepare] This method is used to check if chain abstraction is needed. If it is, it will return a `PrepareDetailedResponseSuccessCompat` object with the necessary transactions and funding information. If it is not, it will return a `PrepareResponseNotRequiredCompat` object with the original transaction. ```swift Future prepare({ required String chainId, required String from, required CallCompat call, Currency? localCurrency, }); ``` ### Execute [#execute] This method is used to execute the chain abstraction operation. The method will handle broadcasting all transactions in the correct order and monitor the cross-chain transfer process. It returns an `ExecuteDetails` object with the transaction status and results. ```swift Future execute({ required UiFieldsCompat uiFields, required List routeTxnSigs, required String initialTxnSig, }) ``` ## Usage [#usage] When sending a transaction, first check if chain abstraction is needed using the `prepare` method. Call the `execute` method to broadcast the routing and initial transactions and wait for it to be completed. If the operation is successful, you need to broadcast the initial transaction and await the transaction hash and receipt. If the operation is not successful, send a JsonRpcError to the dapp and display the error to the user. ```swift final response = await _walletKit.prepare( chainId: chainId, // selected chain id from: from, // sender address call: CallCompat( to: to, // contract address input: input, // calldata ), ); response.when( success: (PrepareDetailedResponseSuccessCompat deatailResponse) { deatailResponse.when( available: (UiFieldsCompat uiFieldsCompat) { // If the route is available, present a CA transaction UX flow and sign hashes when approved final TxnDetailsCompat initial = uiFieldsCompat.initial; final List route = uiFieldsCompat.route; final String initialSignature = signHashMethod(initial.transactionHashToSign); final List routeSignatures = route.map((route) { final String rSignature = signHashMethod(route.transactionHashToSign); return rSignature; }).toList(); await _walletKit.execute( uiFields: uiFields, initialTxnSig: initialSignature, routeTxnSigs: routeSignatures, ); }, notRequired: (PrepareResponseNotRequiredCompat notRequired) { // user does not need to move funds from other chains // proceeds as normal transaction with notRequired.initialTransaction }, ); }, error: (PrepareResponseError prepareError) { // Show an error // contains prepareError.error as BridgingError and could be either: // noRoutesAvailable, insufficientFunds, insufficientGasFunds }, ); ``` ### Implementation during Session Request [#implementation-during-session-request] If you are looking to trigger Chain Abstraction during a eth_sendTransaction Session Request you should do it inside the session request handler as explained in [Responding to Session requests](./usage#responding-to-session-requests) section. ```swift Future _ethSendTransactionHandler(String topic, dynamic params) async { final SessionRequest pendingRequest = _walletKit.pendingRequests.getAll().last; final int requestId = pendingRequest.id; final String chainId = pendingRequest.chainId; final transaction = (params as List).first as Map; // Intercept to check if Chain Abstraction is required if (transaction.containsKey('input') || transaction.containsKey('data')) { final inputData = transaction.containsKey('input') ?? transaction.containsKey('data'); final response = await _walletKit.prepare( chainId: chainId, from: transaction['from'], call: CallCompat( to: transaction['to'], input: inputData, ), ); response.when( success: (PrepareDetailedResponseSuccessCompat deatailResponse) { deatailResponse.when( available: (UiFieldsCompat uiFieldsCompat) { // Only if the route is available, present a Chain Abstraction approval modal // and proceed with execute() method if (approved) { final TxnDetailsCompat initial = uiFieldsCompat.initial; final List route = uiFieldsCompat.route; final String initialSignature = signHashMethod(initial.transactionHashToSign); final List routeSignatures = route.map((route) { final String rSignature = signHashMethod(route.transactionHashToSign); return rSignature; }).toList(); final executeResponse = await _walletKit.execute( uiFields: uiFields, initialTxnSig: initialSignature, routeTxnSigs: routeSignatures, ); // Respond to the session request. Flow shouldn't end here as the transaction was processed return await _walletKit.respondSessionRequest( topic: topic, response: JsonRpcResponse( id: requestId, jsonrpc: '2.0', result: executeResponse.initialTxnReceipt, ), ); } }, // If deatailResponse is not `available` type // then let the flow to continue to regular send transacrion ); }, ); } // display a prompt for the user to approve or reject the request // if approved if (approved) { final signedTx = await sendTransaction(transaction, int.parse(chainId)); // respond to requester await _walletKit.respondSessionRequest( topic: topic, response: JsonRpcResponse( id: requestId, jsonrpc: '2.0', result: signedTx, ), ); } // if rejected return _walletKit.respondSessionRequest( topic: topic, response: JsonRpcResponse( id: id, jsonrpc: '2.0', error: const JsonRpcError(code: 5001, message: 'User rejected method'), ), ); } ``` For example, check out implementation of chain abstraction in [sample wallet](https://github.com/reown-com/reown_flutter/blob/develop/packages/reown_walletkit/example/lib/dependencies/chain_services/evm_service.dart) with Flutter. ### Token Balance [#token-balance] You can use this method to query the token balance of the given address ```swift Future erc20TokenBalance({ required String chainId, // chain id required String token, // token address required String owner, // user address }) ``` ## Android [#android] If you didn't do it already, in your android (project's) build.gradle file add support for Jitpack: ``` allprojects { repositories { google() mavenCentral() maven { url 'https://jitpack.io' } // <- add jipack url } } ``` It shouldn't happen but if you encounter issues with minification, add the below rules to your application: ``` -keepattributes *Annotation* -keep class com.sun.jna.** { *; } -keepclassmembers class com.sun.jna.** { native ; *; } -keep class uniffi.** { *; } # Preserve all public and protected fields and methods -keepclassmembers class ** { public *; protected *; } -dontwarn uniffi.** -dontwarn com.sun.jna.** ``` ## Testing [#testing] Best way to test Chain Abstraction is to use our Sample wallet. - [Sample Wallet for iOS](https://testflight.apple.com/join/Uv0XoBuD) - [Sample Wallet for Android](https://appdistribution.firebase.dev/i/2b8b3dce9e2831cd) You can also use the [AppKit laboratory](https://lab.reown.com/appkit/?name=wagmi) and try sending [USDC/USDT](/wallets/features/chain-abstraction#what-are-the-supported-tokens-and-networks) with any chain abstraction-supported wallet. # Analytics (/wallets/flutter/cloud/analytics) # Explorer Submission (/wallets/flutter/cloud/explorer-submission) # Relay (/wallets/flutter/cloud/relay) # Wallet Call API (/wallets/flutter/eip5792) WalletConnect supports [EIP-5792](https://eips.ethereum.org/EIPS/eip-5792#atomicbatch-capability), which defines new JSON-RPC methods that enable apps to ask a wallet to process a batch of onchain write calls and to check on the status of those calls. Applications can specify that these onchain calls be executed taking advantage of specific capabilities previously expressed by the wallet; an additional, a novel wallet RPC is defined to enable apps to query the wallet for those capabilities. - `wallet_sendCalls`: Requests that a wallet submits a batch of calls. - `wallet_getCallsStatus`: Returns the status of a call batch that was sent via wallet_sendCalls. - `wallet_showCallsStatus`: Requests that a wallet shows information about a given call bundle that was sent with wallet_sendCalls. - `wallet_getCapabilities`: This RPC allows an application to request capabilities from a wallet (e.g. batch transactions, paymaster communication). ## Usage [#usage] ## Capabilities in CAIP-25 Connection Requests [#capabilities-in-caip-25-connection-requests] CAIP-25 defines how capabilities can be expressed in wallet-to-dapp connections. These capabilities control how methods like `wallet_sendCalls` behave. ### Session Properties [#session-properties] In a connection request, dapps can request capabilities via `sessionProperties`. These can be universal (across all chains) or chain-specific: ```json "sessionProperties": { "expiry": "2022-12-24T17:07:31+00:00", "caip154": { "supported": "true" }, "flow-control": { "loose": [], "strict": [], "exoticThirdThing": [] }, "atomic": { "status": "supported" } } ``` ### Scoped Properties [#scoped-properties] For chain-specific capabilities, dapps use `scopedProperties`: ```json "scopedProperties": { "eip155:8453": { "paymasterService": { "supported": true }, "sessionKeys": { "supported": true } }, "eip155:84532": { "auxiliaryFunds": { "supported": true } } } ``` ### Wallet Response [#wallet-response] A wallet's response should indicate which capabilities it actually supports, following EIP-5792 and CAIP-25: ```json "sessionProperties": { "expiry": "2022-12-24T17:07:31+00:00", "caip154": { "supported": "true" }, "flow-control": { "loose": ["halt", "continue"], "strict": ["continue"] }, "atomic": { "status": "ready" } }, "scopedProperties": { "eip155:1": { "atomic": { "status": "supported" } }, "eip155:137": { "atomic": { "status": "unsupported" } }, "eip155:84532": { "eip155:83532:0x0910e12C68d02B561a34569E1367c9AAb42bd810": { "auxiliaryFunds": { "supported": false }, "atomic": { "status": "supported" } } } } ``` - Capabilities shared across all address in a namespace can be expressed at top-level - Address-specific capabilities can include exceptions to scope-wide capabilities ### Atomic Capability [#atomic-capability] According to EIP-5792, the `atomic` capability specifies how the wallet will execute batches of transactions. It has three possible values: - `supported` - The wallet will execute calls atomically and contiguously - `ready` - The wallet can upgrade to support atomic execution pending user approval - `unsupported` - The wallet provides no atomicity guarantees This capability is expressed per chain and is crucial for determining how `wallet_sendCalls` with `atomicRequired: true` will be handled. ### Example [#example] The `wallet_getCapabilities` method is used to request information about what capabilities a wallet supports. Following EIP-5792, here's how it should be implemented: #### Request [#request] ```json { "id": 1, "jsonrpc": "2.0", "method": "wallet_getCapabilities", "params": ["0xd46e8dd67c5d32be8058bb8eb970870f07244567", ["0x2105", "0x14A34"]] } ``` #### Response [#response] The wallet should return a response following EIP-5792, where capabilities are organized by chain ID: ```json { "id": 1, "jsonrpc": "2.0", "result": { "0x2105": { "atomic": { "status": "supported" } }, "0x14A34": { "atomic": { "status": "unsupported" } } } } ``` ### Implementation [#implementation] When implementing `wallet_sendCalls`, wallets must follow these requirements: #### Connection Approval [#connection-approval] - Only approve this method during the connection approval flow if your wallet can implement it correctly - Define the `atomic` capability per chain/account in the CAIP-25 response #### Request Format [#request-format] ```json { "id": 12345, "version": "2.0", "method": "wc_sessionRequest", "params": { "chainId": "caip-2-chain-id", "request": { "method": "wallet_sendCalls", "params": { "from": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "chainId": "0x01", "atomicRequired": true, "calls": [ { "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "value": "0x9184e72a", "data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675" }, { "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "value": "0x182183", "data": "0xfbadbaf01" } ] } } } } ``` #### Core Implementation Requirements [#core-implementation-requirements] - Execute calls in the exact order specified in the request - Do not wait for any calls to be finalized before completing the batch - If the user rejects the request, do not send any calls #### Atomic Execution Behavior [#atomic-execution-behavior] When `atomicRequired` is `true`: - Execute all calls atomically (either all succeed or none have any effect) - Execute all calls contiguously (no other transactions between batch calls) - If your wallet can upgrade from `ready` to `supported` atomicity, do so before executing When `atomicRequired` is `false`: - You may execute calls sequentially without atomicity guarantees - You may execute atomically if your wallet supports it - You may upgrade to `supported` atomicity and execute atomically #### Response Enrichment [#response-enrichment] To enhance the user experience and eliminate the need for app switching, wallets can enrich the wallet_sendCalls response with caip2 id and transactionHash to let the Universal Provider resolve the transaction hash. ```json { "id": "...", "capabilities": { "caip345": { "caip2": "eip155:1", "transactionHashes": ["..."], } } } ``` ### Example [#example-1] To enhance the user experience and eliminate the need for app switching, wallets can enrich the wallet_sendCalls response with caip2 id and transactionHash to let the Universal Provider resolve the transaction hash. To implement this functionality, the response for wallet_sendCalls should be enriched with capabilities: ```json { "id": "...", "capabilities": { "caip345": { "caip2": "eip155:1", "transactionHashes": ["..."], } } } ``` Specify the `scopedProperties` when approving a session: ```json "scopedProperties": { "eip155": { "walletService": [{ "url": "", "methods": ["wallet_getCallsStatus"] }] } } ``` ### Response Format [#response-format] The response format for `wallet_getCallsStatus` varies based on the execution method: #### For Atomic Execution [#for-atomic-execution] ```json { "receipts": [/* single receipt or array of receipts */], "atomic": true } ``` #### For Non-Atomic Execution [#for-non-atomic-execution] ```json { "receipts": [/* array of receipts for all transactions */], "atomic": false } ``` For non-atomic execution, include all transactions in the receipts array, even those that were included on-chain but eventually reverted. ## References [#references] - EIP-5792: https://eips.ethereum.org/EIPS/eip-5792#atomicbatch-capability - CAIP-25 namespaces: https://github.com/ChainAgnostic/namespaces/blob/main/eip155/caip25.md # Installation (/wallets/flutter/installation) - Add `reown_walletkit` as dependency in your `pubspec.yaml` and run `flutter pub get` (check out the [latest version](https://pub.dev/packages/reown_walletkit/install)) - Or simply run `flutter pub add reown_walletkit` If you are on **Android** add jitpack support to your android (project's) build.gradle file ``` allprojects { repositories { google() mavenCentral() maven { url 'https://jitpack.io' } // <- add jipack url } } ``` If you are on **MacOS** add the following to your `DebugProfile.entitlements` and `Release.entitlements` files to connect to the WebSocket server. ```xml com.apple.security.network.client ``` ## Next Steps [#next-steps] Now that you've installed Wallet SDK SDK, you're ready to start integrating it. The next section will walk you through the process of setting up your project to use the SDK. # Link Mode (/wallets/flutter/link-mode) WalletKit Link Mode is a low latency mechanism for transporting [One-Click Auth](/wallets/flutter/one-click-auth) requests and session requests over Universal Links, reducing the need for a WebSocket connection with the Relay. This significantly enhances the user experience when connecting native dApps to native wallets by reducing the latency associated with network connections, especially when the user has an unstable internet connection. By enabling it, the wallet and dapp will communicate through declared Universal Links on iOS and/or App Links on Android **even without an internet connection.** Make sure that [One-Click Auth](/wallets/flutter/one-click-auth) is implemented before enabling Link Mode. ### How to enable it: [#how-to-enable-it] 1. Add a Universal Link for your wallet in the **Explorer** tab of your [**Cloud project configuration**](https://dashboard.walletconnect.com/sign-in), under the **Mobile Linking** section 2. Configure your `PairingMetadata`'s `redirect:` object with that Universal Link 3. Set the `linkMode` property to `true`: ```javascript final _walletKit = ReownWalletKit( core: ReownCore( projectId: '{YOUR_PROJECT_ID}', ), metadata: PairingMetadata( name: 'Example Wallet', description: 'Example wallet description', url: 'https://example.com/', icons: ['https://example.com/logo.png'], redirect: Redirect( native: 'examplewallet://', universal: 'https://example.com/wallet', linkMode: true, ), ), ); ``` Once everything is properly configured, and the user interacts with a Link Mode-supporting dApp, your wallet will receive requests through it. In Flutter, there are several plugins that can help you integrate Universal/App Links. However, regardless of which one you choose, it is crucial that, when capturing an incoming link, you pass it to WalletKit so it can process the request. ```javascript void _onLinkCaptured(String link) async { await _walletKit.dispatchEnvelope(link); } ``` ### Platform specifics: [#platform-specifics] 1. Ensure that you handle incoming Universal Links in the appropriate methods of `AppDelegate` or `SceneDelegate`. 2. Ensure that you have enabled the Associated Domains Capability in your XCode project and that your Universal Link is properly configured. _(Depending on the previous states of your Provisioning Profiles it may be necessary to update or create new ones)_ ```xml com.apple.developer.associated-domains applinks:your_wallet_universal_link.com ``` 3. Update/Create your domain's `.well-known/apple-app-site-association` file accordingly. For more information on how to configure universal links for your app, refer to the [Apple Documentation](https://developer.apple.com/documentation/xcode/allowing-apps-and-websites-to-link-to-your-content?language=swift).
For a debugging guide, visit the [Debugging Universal Links](https://developer.apple.com/documentation/technotes/tn3155-debugging-universal-links) page.
You can check our Flutter's Wallet SDK sample [AppDelegate file](https://github.com/reown-com/reown_flutter/blob/master/packages/reown_walletkit/example/ios/Runner/AppDelegate.swift) as a reference.
1. Ensure that you handle incoming App Links in your Activity's `onCreate` method and in `onNewIntent` callback. 2. Ensure that your App Link is properly configured in your app's `AndroidManifest.xml` file with the `autoVerify` set to `true`: ```xml ``` 3. Update/Create your domains's `.well-known/assetlinks.json` file accordingly For more information on how to configure app links for your app, refer to the [Android Documentation](https://developer.android.com/training/app-links/verify-android-applinks).
For enabling links to app content check [this](https://developer.android.com/training/app-links/deep-linking) documentation page.
For more information on how to interact with other apps using intents, see [Android Intent Documentation](https://developer.android.com/training/basics/intents). You can check our Flutter's Wallet SDK sample [MainActivity file](https://github.com/reown-com/reown_flutter/blob/master/packages/reown_walletkit/example/android/app/src/main/kotlin/com/example/wallet/MainActivity.kt) as a reference.
# Mobile Linking (/wallets/flutter/mobile-linking) This feature is only relevant to native platforms. ## Usage [#usage] Mobile Linking allows your wallet to automatically redirect back to the Dapp allowing for less user interactions and hence a better UX for your users. ### Establishing Communication Between Mobile Wallets and Apps [#establishing-communication-between-mobile-wallets-and-apps] When integrating a wallet with a mobile application, it's essential to understand how they communicate. The process involves two main steps: 1. **QR Code Handshake:** The mobile app (Dapp) generates a unique URI (Uniform Resource Identifier) and displays it as a QR code. This URI acts like a secret handshake. When the user scans the QR code using their wallet app, they establish a connection. It's like saying, "Hey, let's chat!" 2. **Deep Links and Universal Links:** The URI from the QR code allows the wallet app to create a [deep link](https://support.google.com/google-ads/answer/10023042?hl=en#:~:text=Deep%20links%20send%20mobile%20device,%2C%20Shopping%2C%20and%20Display%20campaigns.) or [universal link](https://developer.apple.com/ios/universal-links/). These links work on both Android and iOS. They enable seamless communication between the wallet and the app. **Developers should prefer Deep Linking over Universal Linking.** Universal Linking may redirect the user to a browser, which might not provide the intended user experience. Deep Linking ensures the user is taken directly to the app. ### Key Behavior to Address [#key-behavior-to-address] In some scenarios, wallets use redirect metadata provided in session proposals to open applications. This can cause unintended behavior, such as: Redirecting to the wrong app when multiple apps share the same redirect metadata (e.g., a desktop and mobile version of the same Dapp). Opening an unrelated application if a QR code is scanned on a different device than where the wallet is installed. #### Recommended Approach [#recommended-approach] To avoid this behavior, wallets should: - **Restrict Redirect Metadata to Deep Link Use Cases**: Redirect metadata should only be used when the session proposal is initiated through a deep link. QR code scans should not trigger app redirects using session proposal metadata. The connection and sign request flows are similar across platforms. ### Connection Flow [#connection-flow] - **Dapp Prompts User:** The Dapp asks the user to connect. - **User Chooses Wallet:** The user selects a wallet from a list of compatible wallets. - **Redirect to Wallet:** The user is redirected to their chosen wallet. - **Wallet Approval:** The wallet prompts the user to approve or reject the session (similar to granting permission). - **Return to Dapp:** - **Manual Return:** The wallet asks the user to manually return to the Dapp. - **Automatic Return:** Alternatively, the wallet automatically takes the user back to the Dapp. - **User Reunites with Dapp:** After all the interactions, the user ends up back in the Dapp. ![Mobile linking flow where the dApp sends the user to the wallet to connect and back](/images/mintlify/w3w/mobileLinking-light.png) ### Sign Request Flow [#sign-request-flow] When the Dapp needs the user to sign something (like a transaction), a similar pattern occurs: - **Automatic Redirect:** The Dapp automatically sends the user to their previously chosen wallet. - **Approval Prompt:** The wallet asks the user to approve or reject the request. - **Return to Dapp:** - **Manual Return:** The wallet asks the user to manually return to the Dapp. - **Automatic Return:** Alternatively, the wallet automatically takes the user back to the Dapp. - **User Reconnects:** Eventually, the user returns to the Dapp. ![Mobile linking flow where the dApp sends the user to the wallet to sign a message](/images/mintlify/w3w/mobileLinking_sign-light.png) ## Platform preparations [#platform-preparations] In order for Dapps to be able to trigger your wallet for a connection or sign request using deep links you first need to add your custom scheme under [`CFBundleURLTypes`](https://developer.apple.com/documentation/bundleresources/information_property_list/cfbundleurltypes) key in your Info.plist file. For instance, if your Wallet's name is Example Wallet, your custom scheme would be more likely as `examplewallet://`, therefor you will add the following in your iOS's Info.plist file: ```ruby CFBundleURLTypes CFBundleTypeRole Editor CFBundleURLName $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleURLSchemes examplewallet ``` In order for Dapps to be able to trigger your wallet for a connection or sign request using deep links you first need to declare an [``](https://developer.android.com/training/app-links/deep-linking#adding-filters) in your wallet's Manifest.xml as follows: For instance, if your Wallet's name is Example Wallet, your custom scheme would be more likely as `examplewallet://`, therefor you will add the following intent filter in your Android's Manifest.xml file: ```xml ``` Since Flutter leverages on native APIs, you must follow iOS and Android steps for each native platform. **Additionally**, you would have to set FlutterDeepLinkingEnabled key to true on iOS's Info.plist file. ```xml FlutterDeepLinkingEnabled ``` More information in official documentation: https://docs.flutter.dev/ui/navigation/deep-linking Dapps developers must do the same for their own custom schemes if they want the wallet to be able to navigate back after a session approval or a sign request response ## Integration [#integration] Either you are approving a session proposal or responding to a session request, redirecting back to the Dapp is as simply as launching requester's `redirect` object in `PairingMetadata`, the same way as Dapps would call your wallet's `redirect` object on their side: A dapp would call `examplewallet://wc?uri={pairingUri}` from their side when they request to connect with your wallet, and given the fact that `examplewallet` is your registered custom scheme then your wallet will be opened. ### Redirecting back to dapp (proposer) after session approval: [#redirecting-back-to-dapp-proposer-after-session-approval] Wallet SDK exports a handy method for easy redirection back to the requester app, whether it be after a session proposal, a session authentication or a session request. ```javascript Future redirectToDapp({ required String topic, required Redirect? redirect, }) ``` After Session Proposal: ```javascript _walletKit!.onSessionProposal.subscribe(_onSessionProposal); // void _onSessionProposal(SessionProposalEvent? event) async { if (event != null) { // Process session proposal // .... // Redirect back to proposer dapp try { await _walletKit.redirectToDapp( topic: topic, redirect: event.params.proposer.metadata.redirect, ); } catch (e) { ... } } } ``` After Session Authenticate: ```javascript // If your wallet supports One-Click Auth _walletKit!.onSessionAuthRequest.subscribe(_onSessionAuthRequest); // void _onSessionAuthRequest(SessionAuthRequest? event) async { if (event != null) { // Process session authentication // .... // Redirect back to proposer dapp try { await _walletKit.redirectToDapp( topic: topic, redirect: event.params.proposer.metadata.redirect, ); } catch (e) { ... } } } ``` A dapp would call `examplewallet://` (or even better `session.peer?.metadata.redirect?.native` object) from their side when they request to sign a transaction, and given the fact that `session.peer?.metadata.redirect?.native` contains your registered custom scheme (`examplewallet://`) then your wallet will be opened. **Redirecting back to dapp (proposer) after responding to a sign request:** ```javascript // Your registered request handler for the given requested method will be triggered Future personalSignRequestHandler(String topic, dynamic parameters) async { // Process signing requests // ... // With the given topic with retrieve the current session data final session = _walletKit.sessions.get(topic); // And we get the peer metadata to trigger dapp's redirect value try { await _walletKit.redirectToDapp( topic: topic, redirect: session!.peer.metadata.redirect, ); } catch (e) { ... } } ``` `launchUrlString()` from [url_launcher](https://pub.dev/packages/url_launcher) official package was used as an example to explain the mechanism, you can choose whatever other package you would like. # One-click Auth (/wallets/flutter/one-click-auth) ## Introduction [#introduction] This section outlines an innovative protocol method that facilitates the initiation of a Sign session and the authentication of a wallet through a [Sign-In with Ethereum](https://eips.ethereum.org/EIPS/eip-4361) (SIWE) message, enhanced by [ReCaps](https://eips.ethereum.org/EIPS/eip-5573) (ReCap Capabilities). This enhancement not only offers immediate authentication for dApps, paving the way for prompt user logins, but also integrates informed consent for authorization. Through this mechanism, dApps can request the delegation of specific capabilities to perform actions on behalf of the wallet user. These capabilities, encapsulated within SIWE messages as ReCap URIs, detail the scope of actions authorized by the user in an explicit and human-readable form. By incorporating ReCaps, this method extends the utility of SIWE messages, allowing dApps to combine authentication with a nuanced authorization model. This model specifies the actions a dApp is authorized to execute on the user's behalf, enhancing security and user autonomy by providing clear consent for each delegated capability. As a result, dApps can utilize these consent-backed messages to perform predetermined actions, significantly enriching the interaction between dApps, wallets, and users within the Ethereum ecosystem. ![Regular connect and sign flow compared with the one-click authenticated sessions flow](/images/mintlify/w3w/authenticatedSessions-light.png) ## Handling Authentication Requests [#handling-authentication-requests] To handle incoming authentication requests, subscribe to the `onSessionAuthRequest` event. This will notify you of any authentication requests that need to be processed, allowing you to either approve or reject them based on your application logic. ```javascript // subscribe to onSessionAuthRequest with a handler _walletKit!.onSessionAuthRequest.subscribe(_onSessionAuthRequest); // void _onSessionAuthRequest(SessionAuthRequest? args) { if (args != null) { // Process the authentication request here. // Steps include: // 1. Populate the authentication payload with the supported chains and methods // 2. Format the authentication message using the payload and the user's account // 3. Present the authentication message to the user // 4. Sign the authentication message(s) to create a verifiable authentication object(s) // 5. Approve the authentication request with the authentication object(s) } } ``` ## Authentication Objects/Payloads [#authentication-objectspayloads] ```javascript final supportedChains = ['eip155:1', 'eip155:10', 'eip155:137']; final supportedMethods = ['personal_sign', 'eth_sendTransaction']; final SessionAuthPayload authPayload = AuthSignature.populateAuthPayload( authPayload: args.authPayload, chains: supportedChains, methods: supportedMethods, ); final cacaoRequestPayload = CacaoRequestPayload.fromSessionAuthPayload( newAuthPayload, ); // Prepare the user's address in CAIP10(https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-10.md) format final iss = 'eip155:1:0x59e2f66C0E96803206B6486cDb39029abAE834c0'; // Now you can use the authPayload to format the authentication message final message = _walletKit!.formatAuthMessage( iss: iss, cacaoPayload: cacaoRequestPayload, ); // Present the authentication message to the user ... ``` ## Approving Authentication Requests [#approving-authentication-requests] 1. The recommended approach for secure authentication across multiple chains involves signing a SIWE (Sign-In with Ethereum) message for each chain and account. However, at a minimum, one SIWE message must be signed to establish a session. It is possible to create a session for multiple chains with just one issued authentication object. 2. Sometimes a dapp may want to only authenticate the user without creating a session, not every approval will result with a new session. ```javascript // Approach 1 // Sign the authentication message(s) to create a verifiable authentication object(s) final credentials = EthPrivateKey.fromHex('$privateKey'); final signature = credentials.signPersonalMessageToUint8List( Uint8List.fromList(message.codeUnits), ); final hexSignature = bytesToHex(signature, include0x: true); // Build the authentication object(s) final cacao = AuthSignature.buildAuthObject( requestPayload: cacaoRequestPayload, signature: CacaoSignature( t: CacaoSignature.EIP191, s: hexSignature, ), iss: iss, ); // Approve await _walletKit!.approveSessionAuthenticate( id: args.id, auths: [cacao], ); // Approach 2 // Note that you can also sign multiple messages for every requested chain/address pair final List cacaos = []; for (var chain in newAuthPayload.chains) { final message = _walletKit!.formatAuthMessage( iss: iss, cacaoPayload: cacaoRequestPayload, ); final credentials = EthPrivateKey.fromHex('$privateKey'); final signature = credentials.signPersonalMessageToUint8List( Uint8List.fromList(message.codeUnits), ); final hexSignature = bytesToHex(signature, include0x: true); final cacao = AuthSignature.buildAuthObject( requestPayload: cacaoRequestPayload, signature: CacaoSignature( t: CacaoSignature.EIP191, s: hexSignature, ), iss: iss, ); cacaos.add(cacao) } // Approve await _walletKit!.approveSessionAuthenticate( id: args.id, auths: cacaos, ); ``` ## Rejecting Authentication Requests [#rejecting-authentication-requests] If the authentication request cannot be approved or if the user chooses to reject it, use the rejectSession method. ```javascript await _walletKit!.rejectSessionAuthenticate( id: args.id, reason: Errors.getSdkError(Errors.USER_REJECTED_AUTH).toSignError(), ); ``` ## Testing One-click Auth [#testing-one-click-auth] You can use [AppKit Lab](https://lab.reown.com/appkit/?name=siwx-ethers) to test and verify that your wallet supports One-click Auth properly. # Usage (/wallets/flutter/usage) This section provides instructions on how to initialize the WalletKit client, approve sessions with supported namespaces, and respond to session requests, enabling easy integration of Web3 wallets with dapps through a simple and intuitive interface. ## Content [#content] Links to sections on this page. Some sections are platform specific and are only visible when the platform is selected. To view a summary of useful platform specific topics, check out **Extra (Platform Specific)** under this section. **[Initialization](#initialization)**: Creating a new ReownWalletKit instance and initializing it with a projectId from [WalletConnect Dashboard](https://dashboard.walletconnect.com). **Session**: Connection between a dapp and a wallet. - [Namespace Builder](#namespace-builder): Namespace Builder is a helper utility that greatly reduces the complexity of parsing the required and optional namespaces. It accepts as parameters a session proposal along with your user's chains/methods/events/accounts and returns a ready-to-use object - [Session Approval](#session-approval): Approving a session sent from a dapp - [Session Rejection](#session-rejection): Rejecting a session sent from a dapp - [Responding to Session Requests](#responding-to-session-requests): Responding to session requests sent from a dapp - [Updating a Session](#updating-a-session): Updating a session sent between a dapp and wallet - [Extending a Session](#extending-a-session): Extending a session between a dapp and wallet - [Session Disconnect](#session-disconnect): Disconnecting a session between a dapp and wallet - [Formatted Errors](#formatted-errors): A list of useful error objects to be used ## Initialization [#initialization] To create an instance of ReownWalletKit, you need to pass in the `core` and `metadata` parameters. ```javascript final _walletKit = ReownWalletKit( core: ReownCore( projectId: '{YOUR_PROJECT_ID}', ), metadata: PairingMetadata( name: 'Example Wallet', description: 'Example wallet description', url: 'https://example.com/', icons: ['https://example.com/logo.png'], redirect: Redirect( native: 'examplewallet://', universal: 'https://reown.com/examplewallet', ), ), ); ``` ## Session [#session] A session is a connection between a dapp and a wallet. It is established when a user approves a session proposal from a dapp. A session is active until the user disconnects from the dapp or the session expires. ### Namespace Builder [#namespace-builder] On flutter you don't need to worry about Namespace Builder as Flutter SDK would handle that for you and generate a namespace object with the supported ones for you to approve. All you have to do is make sure you register... 1. **wallet's accounts** with `_walletKit.registerAccount()` for accounts you want events and methods to be enabled on. This is essential if you want to properly form a session object between your wallet and the requester dapp. 2. **request handlers** with `_walletKit.registerRequestHandler()` for methods you want to support on your wallet. Optional but **highly recommended** if you want to seamlessly create a session object, as we will see in the coming section. 3. **events emitters** with `_walletKit.registerEventEmitter()` for events you want to support on your wallet. Optional but recommended if you plan to send events such as `chainChanged` and `accountsChanged`. And you'll have to do this **for every chain** you want to support on your wallet. ```dart // Quick example: List supportedChains = ['eip155:1', 'eip155:10', ...]; List walletAddresses = ['0x1234......']; List supportedEvents = ['chainChanged', 'accountsChanged', ...]; Map get _methodHandlers => { 'personal_sign': personalSignHandler, 'eth_sendTransaction': ethSendTransactionHandler, }; for (final chainId in supportedChains) { for (var address in walletAddresses) { _walletKit!.registerAccount( chainId: chainId, // CAIP-2 format chain id accountAddress: address, // 0x.... address ); } for (var handler in _methodHandlers.entries) { _walletKit.registerRequestHandler( chainId: chainId, method: handler.key, handler: handler.value, ); } for (final event in supportedEvents) { _walletKit.registerEventEmitter( chainId: chainId, event: event, ); } } ``` When a dApp propose a session, with declared namespaces, your wallet will be able to approve an **already generated set of namespaces** based on your registered accounts, methods and events. You can access this object in **SessionProposalEvent** during `onSessionProposal` event by querying `event.params.generatedNamespaces`. (See [Session Approval](#session-approval) below) You can choose **not to use** `registerRequestHandler` to configure your supported methods and rather define them during session approval (See [Session Approval](#session-approval) below) By not using `registerRequestHandler` your methods requests are going to be sent through `onSessionRequest` event subscription. If you do choose to use `registerRequestHandler` **(highly recommended)** then `onSessionRequest` event subscription is not going to be called. Flutter SDK provides a handy `MethodsConstants` and `EventsConstants` for already defined set of required and optional values. ### EVM methods & events [#evm-methods--events] In @walletconnect/ethereum-provider, (our abstracted EVM SDK for apps) we support by default the following Ethereum methods and events: ```ts { //... methods: [ "eth_accounts", "eth_requestAccounts", "eth_sendRawTransaction", "eth_sign", "eth_signTransaction", "eth_signTypedData", "eth_signTypedData_v3", "eth_signTypedData_v4", "eth_sendTransaction", "personal_sign", "wallet_switchEthereumChain", "wallet_addEthereumChain", "wallet_getPermissions", "wallet_requestPermissions", "wallet_registerOnboarding", "wallet_watchAsset", "wallet_scanQRCode", "wallet_sendCalls", "wallet_getCallsStatus", "wallet_showCallsStatus", "wallet_getCapabilities", ], events: [ "chainChanged", "accountsChanged", "message", "disconnect", "connect", ] } ``` ### Session Approval [#session-approval] As mentioned before, the `SessionProposalEvent` is emitted when a dapp initiates a new session with your wallet. The event object will include the information about the dapp and requested namespaces. The wallet should display a prompt for the user to approve or reject the session. To approve a session, subscribe to `onSessionProposal` event and call `approveSession()` passing in the `event.id` and the namespaces object. ```javascript _walletKit.onSessionProposal.subscribe((SessionProposalEvent? event) { // display a prompt for the user to approve or reject the session // .... // If approved _walletKit.approveSession( id: event.id, namespaces: event.params.generatedNamespaces ?? {}, ); }); ``` As mentioned before, `namespaces:` should be either `event.params.generatedNamespaces!` if you decided to use `registerRequestHandler` method to configure your supported methods or a `Map` object defined by yourself if you decided **not** to use `registerRequestHandler` method #### Pairing [#pairing] The `pair` method initiates a pairing process with a dapp using the given `uri` (QR code from the dapps). To learn more about pairing, checkout out the [docs](https://specs.walletconnect.com/2.0/specs/clients/core/pairing/). Scan the QR code and parse the URI, and pair with the dapp. Upon the first pairing, you will immediately receive `onSessionProposal` and `onAuthRequest` events. ```javascript Uri uri = Uri.parse(scannedUriString); await _walletKit.pair(uri: uri); ``` ### Session Rejection [#session-rejection] To reject the request, pass in an error code and reason according to [protocol specs](https://specs.walletconnect.com/2.0/specs/clients/sign/error-codes). See also [Formatted Errors](#formatted-errors) section. To reject a session: ```javascript _walletKit.onSessionProposal.subscribe((SessionProposalEvent? event) async { // display a prompt for the user to approve or reject the session // .... // If rejected await _walletKit.rejectSession( id: event.id, reason: Errors.getSdkError(Errors.USER_REJECTED).toSignError(), ); }); ``` ### Responding to Session requests [#responding-to-session-requests] To handle a session request, such as `personal_sign`, you have two ways as explained before, and they are mutually exclusive, so, either you use onSessionRequest event subscription or your methods handlers configured with `registerRequestHandler`. 1. The **recommended one** is to register a request handler for the methods and chains you want to support. So let's say your wallet supports `eip155:1` and `eip155:137`. This would translate to: ```javascript final supportedChains = ['eip155:1', 'eip155:137']; Map supportedMethods = { 'personal_sign': _personalSignHandler, 'eth_sendTransaction': _ethSendTransactionHandler, }; // Register your handlers as stated in Namespace Builder section for (var chainId in supportedChains) { for (var method in supportedMethods.entries) { _walletKit.registerRequestHandler( chainId: chainId, method: method.key, handler: method.value, ); } } Future _personalSignHandler(String topic, dynamic params) async { final SessionRequest pendingRequest = _walletKit.pendingRequests.getAll().last; final int requestId = pendingRequest.id; // message should arrive encoded final decoded = hex.decode(params.first.substring(2)); final message = utf8.decode(decoded); // display a prompt for the user to approve or reject the request // if approved if (approved) { // Your code to sign the message here final signature = await signMessage(message); return _walletKit.respondSessionRequest( topic: topic, response: JsonRpcResponse( id: requestId, jsonrpc: '2.0', result: signature, ), ); } // if rejected return _walletKit.respondSessionRequest( topic: topic, response: JsonRpcResponse( id: id, jsonrpc: '2.0', error: const JsonRpcError(code: 5001, message: 'User rejected method'), ), ); } Future _ethSendTransactionHandler(String topic, dynamic params) async { final SessionRequest pendingRequest = _walletKit.pendingRequests.getAll().last; final int requestId = pendingRequest.id; final String chainId = pendingRequest.chainId; final transaction = (params as List).first as Map; // display a prompt for the user to approve or reject the request // if approved if (approved) { final signedTx = await sendTransaction(transaction, int.parse(chainId)); // respond to requester await _walletKit.respondSessionRequest( topic: topic, response: JsonRpcResponse( id: requestId, jsonrpc: '2.0', result: signedTx, ), ); } // if rejected return _walletKit.respondSessionRequest( topic: topic, response: JsonRpcResponse( id: id, jsonrpc: '2.0', error: const JsonRpcError(code: 5001, message: 'User rejected method'), ), ); } ``` 2. The other way is subscribing to `onSessionRequest` events (if you didn't use `generatedNamespaces` object) and handle the request based on the method that is firing the event. ```javascript _walletKit.onSessionRequest.subscribe(_onSessionRequest); void _onSessionRequest(SessionRequestEvent? event) async { if (event != null) { final id = event.id; final topic = event.topic; final method = event.method; final chainId = event.chainId; final params = event.params as List; // message should arrive encoded final decoded = hex.decode(params.first.substring(2)); final message = utf8.decode(decoded); // display a prompt for the user to approve or reject the request // if approved if (approved) { // Your code to sign the message here final signature = ... return _walletKit.respondSessionRequest( topic: topic, response: JsonRpcResponse( id: id, jsonrpc: '2.0', result: signature, ), ); } // if rejected return _walletKit.respondSessionRequest( topic: topic, response: JsonRpcResponse( id: id, jsonrpc: '2.0', error: const JsonRpcError(code: 5001, message: 'User rejected method'), ), ); } } ``` Remember that if you have handlers registered these are going to be triggered **instead of** the `onSessionRequest` event. ### Updating a Session [#updating-a-session] If you wish to include new accounts, chains or methods in an existing session, `updateSession` allows you to do so. You need pass in the `topic` and a new `Namespaces` object that contains all of the existing namespaces as well as the new data you wish to include. After you update the session, the dapp connected to your wallet will receive a `SessionUpdate` event. ```javascript await _walletKit.updateSession(topic: 'topic', namespaces: '{}') ``` ### Extending a Session [#extending-a-session] To extend the session, call the `extendSession` method and pass in the new `topic`. The `SessionUpdate` event will be emitted from the wallet. ```javascript await _walletKit.extendSession(topic: 'topic') ``` ### Session Disconnect [#session-disconnect] To initiate a session disconnect, call the `disconnectSession` method and pass in the `topic` and a `reason`. When either the dapp or the wallet disconnects from a session, a `SessionDelete` event will be emitted. It's important to subscribe to this event so you could keep your state up-to-date. ```javascript await _walletKit.disconnectSession( topic: session.topic, reason: Errors.getSdkError(Errors.USER_DISCONNECTED).toSignError(), ); ``` Using `disconnectSession()` alone will make the pairing topic persist, i.e, it can be re-used until it expires. If you want to disconnect (remove) the pairing topic as well you would have add another call as follows: ```javascript await _walletKit.core.pairing.disconnect( topic: pairing.topic, ); ``` #### Supporting session events [#supporting-session-events] In order to support session events, such as `chainChanged` or `accountChanged`, you would have to register an event emitter for such events, for every chain you want to emit an event for (similar to request handlers). ```javascript final supportedChains = ['eip155:1', 'eip155:137']; const supportedEvents = ['chainChanged', 'accountChanged']; for (var chainId in supportedChains) { for (var event in supportedEvents) { _walletKit.registerEventEmitter( chainId: chainId, event: event, ); } } ``` And to emit an event, call `emitSessionEvent()` as follows: ```javascript await _walletKit.emitSessionEvent( topic: session.topic, chainId: 'eip155:1', event: SessionEventParams( name: 'chainChanged', data: 1, ), ); ``` For a better understanding please check out the [example wallet](https://github.com/reown-com/reown_flutter/tree/master/packages/reown_walletkit/example/lib) and, in particular, the [EVMService](https://github.com/reown-com/reown_flutter/blob/master/packages/reown_walletkit/example/lib/dependencies/chain_services/evm_service.dart) inside of it. ### Formatted Errors [#formatted-errors] Our SDK exports a variety of ready-made error objects for you to use in the different situations. Most commonly used are... ```javascript // When user rejects session proposal or method request. final userRejectedError = Errors.getSdkError(Errors.USER_REJECTED).toSignError(); // When the request coming to your wallet can not be unparsed final malformedRequest = Errors.getSdkError(Errors.MALFORMED_REQUEST_PARAMS).toSignError(); // When user disconnects the session final userDisconnected = Errors.getSdkError(Errors.USER_DISCONNECTED).toSignError(); // When dapp request an unsupported method to your wallet final unsupportedMethods = Errors.getSdkError(Errors.UNSUPPORTED_METHODS).toSignError(); ``` But you can check the full list of [available errors here](https://github.com/reown-com/reown_flutter/blob/master/packages/reown_core/lib/utils/errors.dart) # Verify API (/wallets/flutter/verify) Verify API is a security-focused feature that allows wallets to notify end-users when they may be connecting to a suspicious or malicious domain, helping to prevent phishing attacks across the industry. Once a wallet knows whether an end-user is on uniswap.com or eviluniswap.com, it can help them to detect potentially harmful connections through Verify's combined offering of WalletConnect's domain registry. When a user initiates a connection with an application, Verify API enables wallets to present their users with four key states that can help them determine whether the domain they’re about to connect to might be malicious. These are:
![Wallet connection requests showing the Verify states domain match, unverified, mismatch and threat](/images/mintlify/verify-banner.png)
Verify Banner
## Disclaimer [#disclaimer] Verify API helps wallets detect suspicious or malicious domains, but it may not catch every threat. Use it as one more layer of protection alongside your wallet's other security measures. ## Domain risk detection [#domain-risk-detection] The Verify security system will discriminate session proposals & session requests with distinct validations that can be either `VALID`, `INVALID` or `UNKNOWN`. - Domain match: The domain linked to this request has been verified as this application's domain. - This interface appears when the domain a user is attempting to connect to has been ‘verified’ in our domain registry as the registered domain of the application the user is trying to connect to, and the domain has not returned as suspicious from either of the security tools we work with. The `verifyContext` included in the request will have a validation of `VALID`. - Unverified: The domain sending the request cannot be verified. - This interface appears when the domain a user is attempting to connect to has not been verified in our domain registry, but the domain has not returned as suspicious from either of the security tools we work with. The `verifyContext` included in the request will have a validation of `UNKNOWN`. - Mismatch: The application's domain doesn't match the sender of this request. - This interface appears when the domain a user is attempting to connect to has been flagged as a different domain to the one this application has verified in our domain registry, but the domain has not returned as suspicious from either of the security tools we work with. The `verifyContext` included in the request will have a validation of `INVALID` - Threat: This domain is flagged as malicious and potentially harmful. - This interface appears when the domain a user is attempting to connect to has been flagged as malicious on one or more of the security tools we work with. The `verifyContext` included in the request will contain parameter `isScam` with value `true`. ### Reading `verifyContext` by connection type [#reading-verifycontext-by-connection-type] How your wallet should read `verifyContext` depends on how the dApp connects: - **Web dApp over QR code or deep link (relay):** This is the full Verify API, including scam checks. Show all four states: `VALID` as Domain match, `UNKNOWN` as Cannot verify, `INVALID` as Mismatch, and `isScam` as Security risk (ideally blocking or requiring the user to confirm). - **Native dApp over relay:** Native apps can't create a Verify attestation, so `UNKNOWN` is expected here. We suggest a neutral "Cannot verify" label rather than an alarming warning. - **[Link Mode](/wallets/flutter/link-mode) (native to native):** The domain check above applies, with no scam check. `INVALID` means the dApp's universal link domain doesn't match its `metadata.url`. The wallet's own Link Mode setup also needs to be complete, or the result falls back to `INVALID`. ### Implementation [#implementation] `onSessionProposal` and `onSessionAuthRequest` include a `verifyContext`. `onSessionRequest` doesn't, so read it from the matching pending request. Map it to one of the four states once, then use that state in each handler. ```dart enum VerifyState { threat, mismatch, unverified, domainMatch } VerifyState getVerifyState(VerifyContext? verifyContext) { return switch (verifyContext?.validation) { // Threat: only set over relay, since Link Mode has no scam check Validation.SCAM => VerifyState.threat, Validation.INVALID => VerifyState.mismatch, Validation.VALID => VerifyState.domainMatch, // UNKNOWN: expected for native dApps over relay. Link Mode never returns UNKNOWN _ => VerifyState.unverified, }; } // Session proposals from a web or native dApp _walletKit!.onSessionProposal.subscribe((SessionProposalEvent? args) { if (args == null) return; final state = getVerifyState(args.verifyContext); // show the state on the approval screen }); // One-click auth requests can arrive over relay or Link Mode _walletKit!.onSessionAuthRequest.subscribe((SessionAuthRequest? args) { if (args == null) return; final state = getVerifyState(args.verifyContext); final isLinkMode = args.transportType.isLinkMode; // in Link Mode, MISMATCH means the universal link domain doesn't match metadata.url }); // Session requests: read verifyContext from the pending request _walletKit!.onSessionRequest.subscribe((SessionRequestEvent? args) { if (args == null) return; final pendingRequest = _walletKit!.pendingRequests.get(args.id.toString()); final state = getVerifyState(pendingRequest?.verifyContext); final isLinkMode = args.transportType.isLinkMode; // show the state on the signing screen }); ``` Present each state like this: - `THREAT`: Block the request, or require the user to explicitly accept the risk. Check before anything else, so the user doesn't also see a Mismatch warning. - `MISMATCH`: Show a warning and proceed only if the user accepts the risk. - `UNVERIFIED`: Show a neutral "Cannot verify" label. Don't block the request, since native dApps over relay always land here. - `DOMAIN_MATCH`: Show a verified badge and proceed as normal. # WalletConnect Wallet SDK (/wallets) **Wallet SDK** is WalletConnect's modular SDK for integrating secure, multichain, policy-aligned wallet access directly into your infrastructure. Enable your wallets users to securely connect to any app, powered by the WalletConnect Network It’s designed for apps, institutions, and custodians that need full control over key management, signing, and access without compromising UX or compliance. ## Quickstart [#quickstart] } href="/wallets/android/installation"> Get started with Wallet SDK in Android. } href="/wallets/ios/installation"> Get started with Wallet SDK in iOS. } href="/wallets/react-native/installation"> Get started with Wallet SDK in React Native. } href="/wallets/flutter/installation"> Get started with Wallet SDK in Flutter. } href="/wallets/web/installation"> Get started with Wallet SDK in Web. } href="/wallets/c-sharp/installation"> Get started with Wallet SDK in .NET. ## Features [#features] ![Wallet SDK banner](/images/mintlify/walletkit.png) Some of the key features of Wallet SDK include: * **Sign API**: Allows dapps to request that the user sign a transaction or message. * **Auth API**: Allows dapps to verify wallet address ownership through a single signature request, realizing login in one action. * **Chain agnostic**: Wallet SDK is designed to work with any blockchain, so you can easily support multiple chains without having to write separate integration code. ## Use Cases [#use-cases] * Custom wallet infrastructure. * Governance flows with onchain or offchain execution. * Secure DeFi access from custody-controlled environments. * Seamless cross-chain policy enforcement. * In-app and in-wallet payments * Secure in-app signature workflows. * Access to 65,000+ onchain apps. * Chain Agnostic by design. * Fast, frictionless integration. * Transparent and open source. * Battle-tested and audit-proven security. * No dropped connections, no interruptions. # Best Practices (/wallets/ios/best-practices) The purpose of this guide is to show the best practices in regards of the WalletKit client usage. The goal is to provide the best user experience that just works in every circumstances. In order to ensure the best user experience and flawless connection flow, please make sure that WalletKit is initialized immediately after your app launch, especially if launched via a WalletConnect Deep Link. It guarantees that websocket connection is opened immediately and all requests are received by your wallet ## Pairing [#pairing] A pairing is a connection between a wallet and a dapp that has fixed permissions to only allow a dapp to propose a session through it. Dapp can propose infinite number of sessions on one pairing. Wallet must use a pair method from the WalletKit client to pair with dapp. ```swift let uri = WalletConnectURI(string: urlString) if let uri { Task { try await WalletKit.instance.pair(uri: uri) } } ``` ### Pairing State [#pairing-state] A pairing state is a primitive exposed by the WalletKit client for a wallet to indicate whether it should await a session proposal. The pairing state is `true` when a wallet scans a QR and awaits a session proposal. Once the session proposal is received by the wallet, the pairing state is changed to `false`. When `true` wallet should show a loading indicator awaiting a session proposal, when changed to `false` a proposal dialog should be displayed. ```swift WalletKit.instance.pairingStatePublisher .receive(on: DispatchQueue.main) .sink { [weak self] isPairing in self?.showPairingLoading = isPairing }.store(in: &disposeBag) ``` ### Pairing Expiry [#pairing-expiry] A pairing expiry event is triggered whenever a pairing is expired. The expiry for inactive pairing is 5 mins, whereas for active pairing is 30 days. A pairing becomes active when a session proposal is received and user successfully approves it. This event helps to know when given pairing expires and update UI accordingly. ```swift WalletKit.instance.pairingExpirationPublisher .receive(on: DispatchQueue.main) .sink { pairing in guard !pairing.active else { return } // let user know that pairing has expired }.store(in: &publishers) ``` ### Expected User flow [#expected-user-flow] ### Pairing Flow [#pairing-flow] Wallet pairing with a dApp and showing the session proposal to approve or reject ### Pairing Error [#pairing-error] Wallet showing an error when pairing with a dApp fails ### Expected Errors [#expected-errors] While pairing the following errors might occur: - No Internet connection error or pairing timeout when scanning QR with no Internet connection - User should pair again with Internet connection - Pairing expired error when scanning a QR code with expired pairing - User should refresh a QR code and scan again - Pairing with existing pairing is not allowed - User should refresh a QR code and scan again. I usually happens when user scans an already paired QR code. ## Session Proposal [#session-proposal] A session proposal is a handshake sent by a dapp and it's purpose is to define a session rules. Whenever a user wants to establish a connection between a wallet and a dapp, one should approve a session proposal. ### User Action Feedback [#user-action-feedback] Whenever user approves or rejects a session proposal, wallet should show loading indicators in a moment of the button press until Relay acknowledgement is received for any of this actions. Session Approve ```swift do { try await WalletKit.instance.approve(proposalId: proposal.id, namespaces: sessionNamespaces, sessionProperties: proposal.sessionProperties) // Update UI, remove loader } catch { // present error } ``` Session Reject ```swift do { try await WalletKit.instance.reject(proposalId: proposal.id, reason: .userRejected) // Update UI, remove loader } catch { // present error } ``` ### Session Proposal Expiry [#session-proposal-expiry] A session proposal expiry is 5 mins. It means a given proposal is stored for 5 mins in the SDK storage and user has 5 mins for approval or rejection decision. After that time the below event is emitted and proposal modal should be removed from the app's UI. ```swift WalletKit.instance.sessionProposalExpirationPublisher.sink { _ in // let user know that session proposal has expired, update UI }.store(in: &publishers) ``` ### Expected User flow [#expected-user-flow-1] ### Approve or Reject Session Proposal [#approve-or-reject-session-proposal] Wallet pairing with a dApp and showing the session proposal to approve or reject ### Error Handling [#error-handling] Wallet showing an error while approving or rejecting a session proposal ### Expected Errors [#expected-errors-1] While approving or rejecting a session proposal the following errors might occurs: - No Internet connection - It happens when a user tries to approve or reject session proposal with no Internet connection - Session proposal expired - It happens when users tries to approve or reject expired session proposal - Invalid namespaces - It happens when a validation of session namespaces fails - Timeout - It happens when Relay doesn't acknowledge session settle publish within 10s ## Session Request [#session-request] A session request represents the request sent by a dapp to a wallet. ### User Action Feedback [#user-action-feedback-1] Whenever user approves or rejects a session request, wallet should show loading indicators in a moment of the button press until Relay acknowledgement is received for any of this actions. ```swift do { try await WalletKit.instance.respond(requestId: request.id, signature: signature, from: account) // update UI -> remove the loader } catch { // present error to the user } ``` ### Session Request Expiry [#session-request-expiry] A session request expiry is defined by a dapp. It's value must be between now() + 5mins and now() + 7 days. After the session request expires the below event is emitted and session request modal should be removed from the app's UI. ```swift WalletKit.instance.requestExpirationPublisher.sink { _ in // let user know that request has expired }.store(in: &publishers) ``` ### Expected User flow [#expected-user-flow-2] ### Approve or Reject Session Proposal [#approve-or-reject-session-proposal-1] Wallet showing a dApp signing request for the user to approve or reject ### Error Handling [#error-handling-1] Wallet showing an error while responding to a session request ### Expected Errors [#expected-errors-2] While approving or rejecting a session request the following error might occur: - Invalid session - This error might happen when user approves or rejects a session request on expired session - Session request expired - This error might happen when user approves or rejects a session request that already expires - Timeout - It happens when Relay doesn't acknowledge session settle publish within 10s ## Web Socket Connection State [#web-socket-connection-state] The Web Socket connection state tracks the connection with the relay server, event is emitted whenever a connection state changes. ```swift WalletKit.instance.socketConnectionStatusPublisher .receive(on: DispatchQueue.main) .sink { status in switch status { case .connected: // ... case .disconnected: // ... } }.store(in: &publishers) ``` ### Expected User flow [#expected-user-flow-3] ### Connection State [#connection-state] ![Wallet showing a no internet connection banner when the relay connection drops](/images/mintlify/assets/connection_state.gif) # Chain Abstraction (/wallets/ios/chain-abstraction) ## Methods [#methods] The following methods from Wallet SDK are used in implementing chain abstraction. 💡 Chain abstraction is currently in the early access phase, use with careful ### Prepare [#prepare] This method is used to check if chain abstraction is needed. If it is, it will return a response with the necessary transactions. If it is not, it will return a response with the original transaction. ```swift @available(*, message: "This method is experimental. Use with caution.") public func prepare(chainId: String, from: FfiAddress, call: Call, accounts: [String], localCurrency: Currency) async throws -> PrepareDetailedResponse } ``` ### Execute [#execute] This method is used to execute the chain abstraction operation. The method will handle broadcasting all transactions in the correct order and monitor the cross-chain transfer process. It returns an `ExecuteDetails` object with the transaction status and results. ```swift @available(*, message: "This method is experimental. Use with caution.") public func execute(uiFields: UiFields, routeTxnSigs: [FfiPrimitiveSignature], initialTxnSig: FfiPrimitiveSignature) async throws -> ExecuteDetails { } ``` ## Usage [#usage] When sending a transaction, first check if chain abstraction is needed using the `prepare` method. Call the `execute` method to broadcast the routing and initial transactions and wait for it to be completed. If the operation is successful, you need to broadcast the initial transaction and await the transaction hash and receipt. If the operation is not successful, send a JsonRpcError to the dapp and display the error to the user. ```swift let routeResponseSuccess = try await WalletKit.instance.ChainAbstraction.prepare( chainId: selectedNetwork.chainId.absoluteString, from: myAccount.address, call: call, accounts: caip10Accounts, localCurrency: .usd ) switch routeResponseSuccess { case .success(let routeResponse): switch routeResponse { case .available(let UiFileds): // If the route is available, present a CA transaction flow for txnDetails in uiFields.route { let hash = txnDetails.transactionHashToSign let sig = try! signer.signHash(hash) routeTxnSigs.append(sig) } // sign initial transaction hash let initialTxHash = uiFields.initial.transactionHashToSign let initialTxnSig = try! signer.signHash(initialTxHash) let executeDetails = try await WalletKit.instance.ChainAbstraction.execute(uiFields: uiFields, routeTxnSigs: routeTxnSigs, initialTxnSig: initialTxnSig) case .notRequired: // user does not need to move funds from other chains, sign and broadcast original transaction } case .error(let routeResponseError): // Show an error } ``` For example, check out implementation of chain abstraction in [sample wallet](https://github.com/reown-com/reown-swift/blob/develop/Example/WalletApp/PresentationLayer/Wallet/CATransactionModal/CATransactionPresenter.swift) with Swift. ## Testing [#testing] Best way to test Chain Abstraction is to use [sample wallet](https://testflight.apple.com/join/09bTAryp). You can also use the [AppKit laboratory](https://lab.reown.com/appkit/?name=wagmi) and try sending any supported [tokens](/wallets/features/chain-abstraction#what-are-the-supported-tokens-and-networks) with any chain abstraction-supported wallet. # Analytics (/wallets/ios/cloud/analytics) # Explorer Submission (/wallets/ios/cloud/explorer-submission) # Relay (/wallets/ios/cloud/relay) # Wallet Call API (/wallets/ios/eip5792) WalletConnect supports [EIP-5792](https://eips.ethereum.org/EIPS/eip-5792#atomicbatch-capability), which defines new JSON-RPC methods that enable apps to ask a wallet to process a batch of onchain write calls and to check on the status of those calls. Applications can specify that these onchain calls be executed taking advantage of specific capabilities previously expressed by the wallet; an additional, a novel wallet RPC is defined to enable apps to query the wallet for those capabilities. - `wallet_sendCalls`: Requests that a wallet submits a batch of calls. - `wallet_getCallsStatus`: Returns the status of a call batch that was sent via wallet_sendCalls. - `wallet_showCallsStatus`: Requests that a wallet shows information about a given call bundle that was sent with wallet_sendCalls. - `wallet_getCapabilities`: This RPC allows an application to request capabilities from a wallet (e.g. batch transactions, paymaster communication). ## Usage [#usage] ## Capabilities in CAIP-25 Connection Requests [#capabilities-in-caip-25-connection-requests] CAIP-25 defines how capabilities can be expressed in wallet-to-dapp connections. These capabilities control how methods like `wallet_sendCalls` behave. ### Session Properties [#session-properties] In a connection request, dapps can request capabilities via `sessionProperties`. These can be universal (across all chains) or chain-specific: ```json "sessionProperties": { "expiry": "2022-12-24T17:07:31+00:00", "caip154": { "supported": "true" }, "flow-control": { "loose": [], "strict": [], "exoticThirdThing": [] }, "atomic": { "status": "supported" } } ``` ### Scoped Properties [#scoped-properties] For chain-specific capabilities, dapps use `scopedProperties`: ```json "scopedProperties": { "eip155:8453": { "paymasterService": { "supported": true }, "sessionKeys": { "supported": true } }, "eip155:84532": { "auxiliaryFunds": { "supported": true } } } ``` ### Wallet Response [#wallet-response] A wallet's response should indicate which capabilities it actually supports, following EIP-5792 and CAIP-25: ```json "sessionProperties": { "expiry": "2022-12-24T17:07:31+00:00", "caip154": { "supported": "true" }, "flow-control": { "loose": ["halt", "continue"], "strict": ["continue"] }, "atomic": { "status": "ready" } }, "scopedProperties": { "eip155:1": { "atomic": { "status": "supported" } }, "eip155:137": { "atomic": { "status": "unsupported" } }, "eip155:84532": { "eip155:83532:0x0910e12C68d02B561a34569E1367c9AAb42bd810": { "auxiliaryFunds": { "supported": false }, "atomic": { "status": "supported" } } } } ``` - Capabilities shared across all address in a namespace can be expressed at top-level - Address-specific capabilities can include exceptions to scope-wide capabilities ### Atomic Capability [#atomic-capability] According to EIP-5792, the `atomic` capability specifies how the wallet will execute batches of transactions. It has three possible values: - `supported` - The wallet will execute calls atomically and contiguously - `ready` - The wallet can upgrade to support atomic execution pending user approval - `unsupported` - The wallet provides no atomicity guarantees This capability is expressed per chain and is crucial for determining how `wallet_sendCalls` with `atomicRequired: true` will be handled. ### Example [#example] The `wallet_getCapabilities` method is used to request information about what capabilities a wallet supports. Following EIP-5792, here's how it should be implemented: #### Request [#request] ```json { "id": 1, "jsonrpc": "2.0", "method": "wallet_getCapabilities", "params": ["0xd46e8dd67c5d32be8058bb8eb970870f07244567", ["0x2105", "0x14A34"]] } ``` #### Response [#response] The wallet should return a response following EIP-5792, where capabilities are organized by chain ID: ```json { "id": 1, "jsonrpc": "2.0", "result": { "0x2105": { "atomic": { "status": "supported" } }, "0x14A34": { "atomic": { "status": "unsupported" } } } } ``` ### Implementation [#implementation] When implementing `wallet_sendCalls`, wallets must follow these requirements: #### Connection Approval [#connection-approval] - Only approve this method during the connection approval flow if your wallet can implement it correctly - Define the `atomic` capability per chain/account in the CAIP-25 response #### Request Format [#request-format] ```json { "id": 12345, "version": "2.0", "method": "wc_sessionRequest", "params": { "chainId": "caip-2-chain-id", "request": { "method": "wallet_sendCalls", "params": { "from": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "chainId": "0x01", "atomicRequired": true, "calls": [ { "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "value": "0x9184e72a", "data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675" }, { "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "value": "0x182183", "data": "0xfbadbaf01" } ] } } } } ``` #### Core Implementation Requirements [#core-implementation-requirements] - Execute calls in the exact order specified in the request - Do not wait for any calls to be finalized before completing the batch - If the user rejects the request, do not send any calls #### Atomic Execution Behavior [#atomic-execution-behavior] When `atomicRequired` is `true`: - Execute all calls atomically (either all succeed or none have any effect) - Execute all calls contiguously (no other transactions between batch calls) - If your wallet can upgrade from `ready` to `supported` atomicity, do so before executing When `atomicRequired` is `false`: - You may execute calls sequentially without atomicity guarantees - You may execute atomically if your wallet supports it - You may upgrade to `supported` atomicity and execute atomically #### Response Enrichment [#response-enrichment] To enhance the user experience and eliminate the need for app switching, wallets can enrich the wallet_sendCalls response with caip2 id and transactionHash to let the Universal Provider resolve the transaction hash. ```json { "id": "...", "capabilities": { "caip345": { "caip2": "eip155:1", "transactionHashes": ["..."], } } } ``` ### Example [#example-1] To enhance the user experience and eliminate the need for app switching, wallets can enrich the wallet_sendCalls response with caip2 id and transactionHash to let the Universal Provider resolve the transaction hash. To implement this functionality, the response for wallet_sendCalls should be enriched with capabilities: ```json { "id": "...", "capabilities": { "caip345": { "caip2": "eip155:1", "transactionHashes": ["..."], } } } ``` Specify the `scopedProperties` when approving a session: ```json "scopedProperties": { "eip155": { "walletService": [{ "url": "", "methods": ["wallet_getCallsStatus"] }] } } ``` ### Response Format [#response-format] The response format for `wallet_getCallsStatus` varies based on the execution method: #### For Atomic Execution [#for-atomic-execution] ```json { "receipts": [/* single receipt or array of receipts */], "atomic": true } ``` #### For Non-Atomic Execution [#for-non-atomic-execution] ```json { "receipts": [/* array of receipts for all transactions */], "atomic": false } ``` For non-atomic execution, include all transactions in the receipts array, even those that were included on-chain but eventually reverted. ## References [#references] - EIP-5792: https://eips.ethereum.org/EIPS/eip-5792#atomicbatch-capability - CAIP-25 namespaces: https://github.com/ChainAgnostic/namespaces/blob/main/eip155/caip25.md # Installation (/wallets/ios/installation) WalletConnect Wallet SDK is available via [Swift Package Manager](https://swift.org/package-manager/) or [Cocoapods](https://cocoapods.org/). You can add a WalletConnect SDK to your project with Swift Package Manager. In order to do that: 1. Open XCode 2. Go to File -> Add Packages 3. Paste the repo GitHub URL: https://github.com/reown-com/reown-swift 4. Tap Add Package 5. Select WalletConnect check mark **WARNING** Cocoapods support may be deprecated soon, use SPM instead. 1. Update Cocoapods spec repos. Type in terminal `pod repo update` 2. Initialize Podfile if needed with `pod init` 3. Add pod to your Podfile: ```ruby pod 'reown-swift' ``` 4. Install pods with `pod install` If you encounter any problems during package installation, you can specify the exact path to the repository ```ruby pod 'reown-swift', :git => 'https://github.com/reown-com/reown-swift.git', :tag => '1.0.0' ``` ## Next Steps [#next-steps] Now that you've installed Wallet SDK, you're ready to start integrating it. The next section will walk you through the process of setting up your project to use the SDK. # Link Mode (/wallets/ios/link-mode) Wallet SDK Link Mode is a low latency mechanism for transporting [One-Click Auth](/wallets/ios/one-click-auth) requests and session requests over Universal Links, reducing the need for a WebSocket connection with the Relay. This significantly enhances the user experience when connecting native dApps to native wallets by reducing the latency associated with network connections, especially when the user has an unstable internet connection. To support Link Mode add a universal link for your wallet in Cloud project configuration dashboard, configure your `AppMetadata.Redirect` with a valid universal link and set the `linkMode` property to `true`: Make sure that [1-Click Auth](/wallets/ios/one-click-auth) is implemented before enabling Link Mode. ```swift let metadata = AppMetadata( ... redirect: try! AppMetadata.Redirect( native: "exampleApp://", universal: "https://example.com/example_wallet", linkMode: true ) ) WalletKit.configure( metadata: metadata, ... ) ``` Once link mode and universal linking are properly configured and the user interacts with a link mode supporting dApp, your wallet will receive requests over universal linking. You must pass these requests to WalletKit so it can process them: ```swift try WalletKit.instance.dispatchEnvelope(url.absoluteString) ``` Ensure to handle incoming universal links in different methods of `AppDelegate` or `SceneDelegate`. For more information on how to configure universal links for your app, refer to the [Apple Documentation](https://developer.apple.com/documentation/xcode/allowing-apps-and-websites-to-link-to-your-content?language=objc). For a debugging guide, visit the [Debugging Universal Links](https://developer.apple.com/documentation/technotes/tn3155-debugging-universal-links) page. You can also find this [article](https://developer.apple.com/documentation/xcode/supporting-universal-links-in-your-app?language=objc) helpful. # Mobile Linking (/wallets/ios/mobile-linking) **Note** This feature is only relevant to native platforms. ## Usage [#usage] Mobile Linking allows your wallet to automatically redirect back to the Dapp allowing for less user interactions and hence a better UX for your users. ### Establishing Communication Between Mobile Wallets and Apps [#establishing-communication-between-mobile-wallets-and-apps] When integrating a wallet with a mobile application, it's essential to understand how they communicate. The process involves two main steps: 1. **QR Code Handshake:** The mobile app (Dapp) generates a unique URI (Uniform Resource Identifier) and displays it as a QR code. This URI acts like a secret handshake. When the user scans the QR code using their wallet app, they establish a connection. It's like saying, "Hey, let's chat!" 2. **Deep Links and Universal Links:** The URI from the QR code allows the wallet app to create a [deep link](https://support.google.com/google-ads/answer/10023042?hl=en#:~:text=Deep%20links%20send%20mobile%20device,%2C%20Shopping%2C%20and%20Display%20campaigns.) or [universal link](https://developer.apple.com/ios/universal-links/). These links work on both Android and iOS. They enable seamless communication between the wallet and the app. **Developers should prefer Deep Linking over Universal Linking.** Universal Linking may redirect the user to a browser, which might not provide the intended user experience. Deep Linking ensures the user is taken directly to the app. #### Recommended Approach [#recommended-approach] To avoid this behavior, wallets should: - **Restrict Redirect Metadata to Deep Link Use Cases**: Redirect metadata should only be used when the session proposal is initiated through a deep link. QR code scans should not trigger app redirects using session proposal metadata. #### Recommended Approach [#recommended-approach-1] To avoid this behavior, wallets should: Restrict Redirect Metadata to Deep Link Use Cases: Redirect metadata should only be used when the session proposal is initiated through a deep link. QR code scans should not trigger app redirects using session proposal metadata. Ensure Unique Redirect URIs for Cross-Platform Apps: Cross-platform Dapps should use distinct redirect URIs for their mobile and desktop versions to avoid conflicts. The connection and sign request flows are similar across platforms. ### Connection Flow [#connection-flow] - **Dapp Prompts User:** The Dapp asks the user to connect. - **User Chooses Wallet:** The user selects a wallet from a list of compatible wallets. - **Redirect to Wallet:** The user is redirected to their chosen wallet. - **Wallet Approval:** The wallet prompts the user to approve or reject the session (similar to granting permission). - **Return to Dapp:** - **Manual Return:** The wallet asks the user to manually return to the Dapp. - **Automatic Return:** Alternatively, the wallet automatically takes the user back to the Dapp. - **User Reunites with Dapp:** After all the interactions, the user ends up back in the Dapp. ![Mobile linking flow where the dApp sends the user to the wallet to connect and back](/images/mintlify/w3w/mobileLinking-light.png) ### Sign Request Flow [#sign-request-flow] When the Dapp needs the user to sign something (like a transaction), a similar pattern occurs: - **Automatic Redirect:** The Dapp automatically sends the user to their previously chosen wallet. - **Approval Prompt:** The wallet asks the user to approve or reject the request. - **Return to Dapp:** - **Manual Return:** The wallet asks the user to manually return to the Dapp. - **Automatic Return:** Alternatively, the wallet automatically takes the user back to the Dapp. - **User Reconnects:** Eventually, the user returns to the Dapp. ![Mobile linking flow where the dApp sends the user to the wallet to sign a message](/images/mintlify/w3w/mobileLinking_sign-light.png) ## Platform preparations [#platform-preparations] In order for Dapps to be able to trigger your wallet for a connection or sign request using deep links you first need to add your custom scheme under [`CFBundleURLTypes`](https://developer.apple.com/documentation/bundleresources/information_property_list/cfbundleurltypes) key in your Info.plist file. ```ruby CFBundleURLTypes CFBundleTypeRole Editor CFBundleURLName $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleURLSchemes examplewallet ``` Dapps developers must do the same for their own custom schemes if they want the wallet to be able to navigate back after a session approval or a sign request response ## Integration [#integration] ### iOS Wallet Support [#ios-wallet-support] iOS has some more caveats to the integration but we ensure to make it as straightforward as possible. Since its operating system is not designed to handle multiple applications subscribing to the same deep linking schema, we've designed the AppKit to list supporting wallets on our [WalletGuide](https://walletguide.walletconnect.network/) and target specific deep links or universal links for each wallet. To add your own wallet to the Explorer, login to your [WalletConnect Dashboard](https://dashboard.walletconnect.com/sign-in) account. ```bash # For deep links examplewallet://wc?uri=wc:94caa59c77dae0dd234b5818fb7292540d017b27d41f7f387ee75b22b9738c94@2?relay-protocol=irn&symKey=ce3a2c7724c03cf1769ba8b1bdedad5414cc7b920aa3fb72112b997d1916266f # For universal links https://example.wallet/wc?uri=wc:94caa59c77dae0dd234b5818fb7292540d017b27d41f7f387ee75b22b9738c94@2?relay-protocol=irn&symKey=ce3a2c7724c03cf1769ba8b1bdedad5414cc7b920aa3fb72112b997d1916266f ``` Additionally when there is a signing request triggered by the Dapp it will hit the deep link with an incomplete URI, this should be ignored and not considered valid as it's only used for automatically redirecting the users to approve or reject a signing request. ```bash # For deep links examplewallet://wc?uri=wc:00e46b69-d0cc-4b3e-b6a2-cee442f97188@2 # For universal links https://example.wallet/wc?uri=wc:00e46b69-d0cc-4b3e-b6a2-cee442f97188@2 ``` --- ### WalletConnectRouter [#walletconnectrouter] ### Overview [#overview] WalletConnectRouter simplifies navigation by automatically redirecting users back to the DApp after they've interacted with a wallet via a deep link. This eliminates the need for users to manually navigate back after approving a session or confirming a transaction. ### Key Features [#key-features] **Automatic Redirection:** By invoking WalletConnectRouter.goBack(uri: "example://")—where "example://" is the DApp's custom scheme as declared in their AppMetadata redirect field—users are seamlessly returned to the DApp. ### Important Consideration [#important-consideration] **Mandatory redirect Field:** Starting with WalletConnect SDK version 1.9.5, specifying the redirect field in the AppMetadata object is mandatory to avoid redirection issues. ### Installation and Usage [#installation-and-usage] ```swift import WalletConnectRouter try await Sign.instance.approve(proposalId: , namespaces: ) if let uri = proposal.proposer.redirect?.native { WalletConnectRouter.goBack(uri: uri) } else { // Inform the user to manually return to the DApp } ``` --- ### Limitations [#limitations] This section outlines some of the known limitations and constraints when using WalletConnect on iOS. ### Redirects on iOS 17 and Above [#redirects-on-ios-17-and-above] Automatic redirection to browser-based DApps after wallet interaction is not possible from iOS 17 onwards. Developers should adjust their app's UI to inform users about manual navigation back to the browser. For iOS versions below 17, `WalletConnectRouter.goBack(uri: uri)` facilitates automatic redirection.
![Wallet showing a connected message that tells the user to go back to the browser](/images/mintlify/ios-redirect.png)
Redirect
### iOS Universal Links Constraints [#ios-universal-links-constraints] **Developers should prefer Deep Linking over Universal Linking.** In the case of Universal Linking, the user may be redirected to the browser, which may not be the desired behavior. Deep Linking ensures that the user is redirected to the app, providing a seamless experience. When using WalletConnect on iOS and triggering a wallet interaction (e.g. when sending a transaction or signing a message), you may experience issues where the native app is not opened as expected and a browser navigation occurs instead. This issue occurs because Universal Links (app links) on iOS will only open the native app when the following rules are followed: - **The wallet interaction must be triggered by a user-initiated event,** e.g. in a click handler rather than on page load or in an asynchronous callback. - **The wallet interaction must be triggered as soon as possible within the event handler.** Any preceding asynchronous work (e.g. estimating gas, resolving an ENS name, fetching a nonce) should have already completed before the event handler fires. This may require you to design the user experience around this constraint, preventing users from initiating a wallet interaction until it's ready rather than doing the work lazily. **Note that even if your own code follows these rules, libraries you depend on may be running their own asynchronous logic before triggering a wallet interaction.** For example, [Ethers asynchronously populates transactions before sending them.](https://docs.ethers.io/v5/api/signer/#Signer-sendTransaction) Known workarounds are documented below, but if you're still experiencing these issues, you should raise them with the relevant library maintainers. ### For Ethers v5 (Legacy) [#for-ethers-v5-legacy] These are the known workarounds for avoiding app linking issues on iOS when using [Ethers v5](https://docs.ethers.io/v5). ### When sending a transaction [#when-sending-a-transaction] 1. **[`signer.sendTransaction`](https://docs.ethers.io/v5/api/signer/#Signer-sendTransaction) should be avoided in favor of [`signer.sendUncheckedTransaction`](https://docs.ethers.io/v5/api/providers/jsonrpc-provider/#JsonRpcSigner-sendUncheckedTransaction)**
 This avoids an asynchronous call to retrieve the internal block number which Ethers uses to resolve a complete [`TransactionResponse`](https://docs.ethers.io/v5/api/providers/types/#providers-TransactionResponse) object.
 Note that as a result of this optimization, `sendUncheckedTransaction` returns a mock transaction response that only contains the `hash` property and a `wait` method. All other properties are `null`. 2. **The transaction's `to` property should be a plain address rather than an ENS name**
This avoids an asynchronous call to automatically resolve ENS names during the send process.
 If you still want to support ENS name resolution, you should manually run [`provider.resolveName`](https://docs.ethers.io/v5/api/providers/provider/#Provider-ResolveName) ahead of time, storing the result before the user attempts to send a transaction. Do not resolve ENS names in the event handler. 3. **The transaction's `gasLimit` property should be set**
This avoids the asynchronous work performed in `sendTransaction` which automatically estimates the gas limit if it's missing.
 If you still want to use the same gas limit estimation logic from `sendTransaction`, you should manually run [`provider.estimateGas`](https://docs.ethers.io/v5/api/providers/provider/#Provider-estimateGas) ahead of time, storing the result before the user attempts to send the transaction. Do not estimate gas in the event handler. ### When calling a write method on a contract [#when-calling-a-write-method-on-a-contract] 1. **[`contract.METHOD_NAME`](https://docs.ethers.io/v5/api/contract/contract/#contract-functionsSend) should be avoided if favor of calling [`contract.populateTransaction.METHOD_NAME`](https://docs.ethers.io/v5/api/contract/contract/#contract-populateTransaction) ahead of time, then sending the populated transaction with [`signer.sendUncheckedTransaction`](https://docs.ethers.io/v5/api/providers/jsonrpc-provider/#JsonRpcSigner-sendUncheckedTransaction).** 2. When sending the populated transaction, you should [follow the same guidelines as regular transactions](#when-sending-a-transaction) to avoid any asynchronous logic breaking the app link navigation. Do not populate the contract transaction in the event handler. ### When signing a message [#when-signing-a-message] If the message depends on the result of an asynchronous call (e.g. retrieving a nonce when implementing [Sign-In With Ethereum](https://login.xyz)), you should do this work ahead of time, storing the result before the user attempts to sign the message. Do not perform this asynchronous work in the event handler. # One-click Auth (/wallets/ios/one-click-auth) ## Introduction [#introduction] This section outlines an innovative protocol method that facilitates the initiation of a Sign session and the authentication of a wallet through a [Sign-In with Ethereum](https://eips.ethereum.org/EIPS/eip-4361) (SIWE) message, enhanced by [ReCaps](https://eips.ethereum.org/EIPS/eip-5573) (ReCap Capabilities). This enhancement not only offers immediate authentication for dApps, paving the way for prompt user logins, but also integrates informed consent for authorization. Through this mechanism, dApps can request the delegation of specific capabilities to perform actions on behalf of the wallet user. These capabilities, encapsulated within SIWE messages as ReCap URIs, detail the scope of actions authorized by the user in an explicit and human-readable form. By incorporating ReCaps, this method extends the utility of SIWE messages, allowing dApps to combine authentication with a nuanced authorization model. This model specifies the actions a dApp is authorized to execute on the user's behalf, enhancing security and user autonomy by providing clear consent for each delegated capability. As a result, dApps can utilize these consent-backed messages to perform predetermined actions, significantly enriching the interaction between dApps, wallets, and users within the Ethereum ecosystem. ![Regular connect and sign flow compared with the one-click authenticated sessions flow](/images/mintlify/w3w/authenticatedSessions-light.png) ## Handling Authentication Requests [#handling-authentication-requests] To handle incoming authentication requests, subscribe to the authenticateRequestPublisher. This will notify you of any authentication requests that need to be processed, allowing you to either approve or reject them based on your application logic. ```swift WalletKit.instance.authenticateRequestPublisher .receive(on: DispatchQueue.main) .sink { result in // Process the authentication request here. // This involves displaying UI to the user. } .store(in: &subscriptions) // Assuming `subscriptions` is where you store your Combine subscriptions. ``` ## Authentication Objects/Payloads [#authentication-objectspayloads] To interact with authentication requests, first build authentication objects (AuthObject). These objects are crucial for approving authentication requests. This involves: - **Creating an Authentication Payload** - Generate an authentication payload that matches your application's supported chains and methods. - **Formatting Authentication Messages** - Format the authentication message using the payload and the user's account. - **Signing the Authentication Message** - Sign the formatted message to create a verifiable authentication object. Example Implementation: ```swift func buildAuthObjects(request: AuthenticationRequest, account: Account, privateKey: String) throws -> [AuthObject] { let requestedChains = Set(request.payload.chains.compactMap { Blockchain($0) }) let supportedChains: Set = [Blockchain("eip155:1")!, Blockchain("eip155:137")!, Blockchain("eip155:69")!] let commonChains = requestedChains.intersection(supportedChains) let supportedMethods = ["personal_sign", "eth_sendTransaction"] var authObjects = [AuthObject]() for chain in commonChains { let accountForChain = Account(blockchain: chain, address: account.address)! let supportedAuthPayload = try WalletKit.instance.buildAuthPayload( payload: request.payload, supportedEVMChains: Array(commonChains), supportedMethods: supportedMethods ) let formattedMessage = try WalletKit.instance.formatAuthMessage(payload: supportedAuthPayload, account: accountForChain) let signature = // Assume `signMessage` is a function you've implemented to sign messages. signMessage(message: formattedMessage, privateKey: privateKey) let authObject = try WalletKit.instance.buildSignedAuthObject( authPayload: supportedAuthPayload, signature: signature, account: accountForChain ) authObjects.append(authObject) } return authObjects } ``` ## Approving Authentication Requests [#approving-authentication-requests] **Note** 1. The recommended approach for secure authentication across multiple chains involves signing a SIWE (Sign-In with Ethereum) message for each chain and account. However, at a minimum, one SIWE message must be signed to establish a session. It is possible to create a session for multiple chains with just one issued authentication object. 2. Sometimes a dapp may want to only authenticate the user without creating a session, not every approval will result with a new session. To approve an authentication request, construct AuthObject instances for each supported blockchain, sign the authentication messages, build AuthObjects and call approveSessionAuthenticate with the request ID and the authentication objects. ```swift let session = try await WalletKit.instance.approveSessionAuthenticate(requestId: requestId, auths: authObjects) ``` ## Rejecting Authentication Requests [#rejecting-authentication-requests] If the authentication request cannot be approved or if the user chooses to reject it, use the rejectSession method. ```swift try await WalletKit.instance.rejectSession(requestId: requestId) ``` ## Testing One-click Auth [#testing-one-click-auth] You can use [AppKit Lab](https://lab.reown.com/appkit/?name=siwx-ethers) to test and verify that your wallet supports One-click Auth properly. # Resources (/wallets/ios/resources) Valuable assets for developers and users interested in integrating Wallet SDK into their applications. - [Awesome WalletConnect](https://github.com/WalletConnect/awesome-walletconnect) - Community-curated collection of WalletConnect-enabled wallets, libraries, and tools. - [AppKit Laboratory](https://lab.reown.com/) - A place to test your wallet integrations against various setups of AppKit. - [Wallet SDK Swift GitHub](https://github.com/WalletConnect/walletconnect-monorepo/tree/v2.0/packages/web3wallet) - Wallet SDK Swift GitHub repository. ### Wallet Resources [#wallet-resources] To check more in details go and visit our [Wallet SDK Swift implementation app](https://github.com/reown-com/reown-swift/tree/main/Example/WalletApp). Sample Wallet and Dapp sample apps can be found under the Example directory in [Swift's V2 repository](https://github.com/reown-com/reown-swift/tree/main/Example) If you need to test your app's integration, you can use one of our following demo dapps. **Sign** - [React dApp (with standalone client) - v2](https://github.com/WalletConnect/web-examples/tree/main/advanced/dapps/react-dapp-v2) ([Demo](https://react-app.walletconnect.com/)) ### Dapp Resources [#dapp-resources] Sample Dapp can be found under the Example directory in [Swift's V2 repository](https://github.com/reown-com/reown-swift/tree/main/Example) You can test your integration against Swift Sample Wallet that is included in the same repo or use the following JS React Wallet: - [React Wallet Ethers - v2](https://github.com/WalletConnect/web-examples/tree/main/advanced/wallets/react-wallet-v2) ([Demo](https://react-wallet.walletconnect.com/)) # Usage (/wallets/ios/usage) This section provides instructions on how to initialize the WalletKit client, approve sessions with supported namespaces, and respond to session requests, enabling easy integration of Web3 wallets with dapps through a simple and intuitive interface. ## Content [#content] Links to sections on this page. Some sections are platform specific and are only visible when the platform is selected. To view a summary of useful platform specific topics, check out **Extra (Platform Specific)** under this section. **[Initialization](#initialization)**: Creating a new WalletKit instance and initializing it with a projectId from [WalletConnect Dashboard](https://dashboard.walletconnect.com). **Session**: Connection between a dapp and a wallet. - [Namespace Builder](#namespace-builder): Namespace Builder is a helper utility that greatly reduces the complexity of parsing the required and optional namespaces. It accepts as parameters a session proposal along with your user's chains/methods/events/accounts and returns a ready-to-use object - [Session Approval](#session-approval): Approving a session sent from a dapp - [Session Rejection](#session-rejection): Rejecting a session sent from a dapp - [Responding to Session Requests](#responding-to-session-requests): Responding to session requests sent from a dapp - [Updating a Session](#updating-a-session): Updating a session sent between a dapp and wallet - [Extending a Session](#extending-a-session): Extending a session between a dapp and wallet - [Session Disconnect](#session-disconnect): Disconnecting a session between a dapp and wallet - [Register Device Token](#register-device-token) Enabling Wallet Push Notifications by registering a device token. - [Subscribe for WalletKit Publishers](#subscribe-for-walletkit-publishers) Publishers available to subscribe to for WalletKit ## Initialization [#initialization] Confirm you have configured the [Network Client](https://docs.reown.com/advanced/api/core/relay) first. Starting from WalletConnect SDK version 1.9.5, the `redirect` field in the `AppMetadata` object is mandatory. Ensure that the provided value matches your app's URL scheme to prevent redirection-related issues. Once you're done, in order to initialize a client just call a `configure` method from the WalletKit instance wrapper ```swift let telemetryEnabled = true; let metadata = AppMetadata( name: "Example Wallet", description: "Wallet description", url: "example.wallet", icons: ["https://avatars.githubusercontent.com/u/37784886"], redirect: AppMetadata.Redirect(native: "example://", universal: nil) ) WalletKit.configure( metadata: metadata, crypto: DefaultCryptoProvider(), // Used for the Push: "echo.walletconnect.com" will be used by default if not provided pushHost: "echo.walletconnect.com", // Used for the Push: "APNSEnvironment.production" will be used by default if not provided environment: .production, telemetryEnabled: telemetryEnabled ) ``` In order to allow users to receive push notifications you have to communicate with Apple Push Notification service and receive unique device token. Register that token with following method: ```swift try await WalletKit.instance.register(deviceToken: deviceToken) ``` The telemetry feature aims to enhance the reliability and observability of connection flows between decentralized applications (dApps) and wallets. It focuses solely on collecting data related to code execution and error codes, without tracking any sensitive user information such as amounts, accounts, etc. It provides a comprehensive tracing system for three key use cases: - Subscribing to a Pairing Topic - Approving a Session - Approving an Authenticated Session Each execution trace consists of: - Trace Events: Collected to verify the proper execution of code. - Error Events: Captured when errors occur during the trace, halting the execution trace. When an error event is encountered, it is stored locally within the SDK along with all preceding trace events. These stored events are then transmitted to the server whenever the SDK is initialized. Error event tracing is enabled by default. **Telemetry Enabled (telemetryEnabled = true):** - The SDK stores events and sends them to the server. **Telemetry Disabled (telemetryEnabled = false):** - The SDK stops storing new events and deletes all unsent events from local storage upon the next initialization. Important Note: Since the SDK only stores abstract trace and error data, user identification is not possible. Example of the error events: ```json [ { "eventId": "69e53f11-fd4b-4efc-8d36-1f60a9ac8207", "bundleId": "com.wallet.example", "timestamp": 1689611327943, "props": { "event": "ERROR", "type": "pairing_already_exists", "properties": { "topic": "topic1", "trace": [ "pairing_started", "pairing_uri_validation_success", "pairing_uri_not_expired", "existing_pairing", "pairing_not_expired", "pairing_not_expired" ] } } }, { "eventId": "69e53f11-fd4b-4efc-8d36-2321312fds", "bundleId": "com.wallet.example", "timestamp": 16896113234323, "props": { "event": "ERROR", "type": "session_approve_namespace_validation_failure", "properties": { "topic": "topic2", "trace": ["session_approve_started", "proposal_not_expired"] } } } ] ``` ## Session [#session] A session is a connection between a dapp and a wallet. It is established when a user approves a session proposal from a dapp. A session is active until the user disconnects from the dapp or the session expires. ### Namespace Builder [#namespace-builder] `AutoNamespaces` is a helper utility that greatly reduces the complexity of parsing the required and optional namespaces. It accepts as parameters a session proposal along with your user's chains/methods/events/accounts and returns ready-to-use `SessionNamespace` object. ```swift public static func build( sessionProposal: Session.Proposal, chains: [Blockchain], methods: [String], events: [String], accounts: [Account] ) throws -> [String: SessionNamespace] ``` Example usage ```swift do { sessionNamespaces = try AutoNamespaces.build( sessionProposal: proposal, chains: [Blockchain("eip155:1")!, Blockchain("eip155:137")!], methods: ["eth_sendTransaction", "personal_sign"], events: ["accountsChanged", "chainChanged"], accounts: [ Account(blockchain: Blockchain("eip155:1")!, address: "0xab16a96d359ec26a11e2c2b3d8f8b8942d5bfcdb")!, Account(blockchain: Blockchain("eip155:137")!, address: "0xab16a96d359ec26a11e2c2b3d8f8b8942d5bfcdb")! ] ) } catch let error as AutoNamespacesError { // reject session proposal if AutoNamespace build function threw try await reject(proposal: proposal, reason: RejectionReason(from: error)) return } // approve session with sessionNamespaces try await WalletKit.instance.approve(proposalId: proposal.id, namespaces: sessionNamespaces) ``` ### EVM methods & events [#evm-methods--events] In @walletconnect/ethereum-provider, (our abstracted EVM SDK for apps) we support by default the following Ethereum methods and events: ```ts { //... methods: [ "eth_accounts", "eth_requestAccounts", "eth_sendRawTransaction", "eth_sign", "eth_signTransaction", "eth_signTypedData", "eth_signTypedData_v3", "eth_signTypedData_v4", "eth_sendTransaction", "personal_sign", "wallet_switchEthereumChain", "wallet_addEthereumChain", "wallet_getPermissions", "wallet_requestPermissions", "wallet_registerOnboarding", "wallet_watchAsset", "wallet_scanQRCode", "wallet_sendCalls", "wallet_getCallsStatus", "wallet_showCallsStatus", "wallet_getCapabilities", ], events: [ "chainChanged", "accountsChanged", "message", "disconnect", "connect", ] } ``` ### Session Approval [#session-approval] ```swift WalletKit.instance.approve( proposalId: "proposal_id", namespaces: sessionNamespaces ) ``` When session is successfully approved `sessionsPublishers` will publish a `Session` ```swift WalletKit.instance.sessionsPublishers .receive(on: DispatchQueue.main) .sink { [weak self] _ in self?.reloadSessions() }.store(in: &publishers) ``` `Session` object represents an active session connection with a dapp. It contains dapp’s metadata (that you may want to use for displaying an active session to the user), namespaces, and expiry date. There is also a topic property that you will use for linking requests with related sessions. You can always query settled sessions from the client later with: ```swift WalletKit.instance.getSessions() ``` #### Connect Clients [#connect-clients] Your Wallet should allow users to scan a QR code generated by dapps. You are responsible for implementing it on your own. For testing, you can use our test dapp at: https://react-app.walletconnect.com/, which is v2 protocol compliant. Once you derive a URI from the QR code call `pair` method: ```swift try await WalletKit.instance.pair(uri: uri) ``` if everything goes well, you should handle following event: ```swift WalletKit.instance.sessionProposalPublisher .receive(on: DispatchQueue.main) .sink { [weak self] session in self?.verifyDapp(session.context) self?.showSessionProposal(session.proposal) }.store(in: &publishers) ``` Session proposal is a handshake sent by a dapp and it's purpose is to define a session rules. Handshake procedure is defined by [CAIP-25](https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-25.md). `Session.Proposal` object conveys set of required and optional `ProposalNamespaces` that contains blockchains methods and events. Dapp requests with methods and wallet will emit events defined in namespaces. `VerifyContext` provides a domain verification information about `Session.Proposal` and `Request`. It consists of origin of a Dapp from where the request has been sent, validation enum that says whether origin is **unknown**, **valid** or **invalid** and verify URL server. To enable or disable verification find the **Verify SDK** toggle in your project [WalletConnect Dashboard](https://dashboard.walletconnect.com). ```swift public struct VerifyContext: Equatable, Hashable { public enum ValidationStatus { case unknown case valid case invalid } public let origin: String? public let validation: ValidationStatus public let verifyUrl: String } ``` The user will either approve the session proposal (with session namespaces) or reject it. Session namespaces must at least contain requested methods, events and accounts associated with proposed blockchains. Accounts must be provided according to [CAIP10](https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-10.md) specification and be prefixed with a chain identifier. chain_id + : + account_address. You can find more on blockchain identifiers in [CAIP2](https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-2.md). Our `Account` type meets the criteria. ``` let account = Account("eip155:1:0xab16a96d359ec26a11e2c2b3d8f8b8942d5bfcdb")! ``` Accounts sent in session approval must at least match all requested blockchains. Example proposal namespaces request: ```json { "eip155": { "chains": ["eip155:137", "eip155:1"], "methods": ["eth_sign"], "events": ["accountsChanged"] }, "cosmos": { "chains": ["cosmos:cosmoshub-4"], "methods": ["cosmos_signDirect"], "events": ["someCosmosEvent"] } } ``` Example session namespaces response: ```json { "eip155": { "accounts": [ "eip155:137:0xab16a96d359ec26a11e2c2b3d8f8b8942d5bfcdb", "eip155:1:0xab16a96d359ec26a11e2c2b3d8f8b8942d5bfcdb" ], "methods": ["eth_sign"], "events": ["accountsChanged"] }, "cosmos": { "accounts": [ "cosmos:cosmoshub-4:cosmos1t2uflqwqe0fsj0shcfkrvpukewcw40yjj6hdc0" ], "methods": ["cosmos_signDirect", "personal_sign"], "events": ["someCosmosEvent", "proofFinalized"] } } ``` #### Track Sessions [#track-sessions] When your `WalletKit` instance receives requests from a peer it will publish a related event. Set a subscription to handle them. To track sessions subscribe to `sessionsPublisher` publisher ```swift WalletKit.instance.sessionsPublisher .receive(on: DispatchQueue.main) .sink { [weak self] sessions in // Reload UI }.store(in: &publishers) ``` ### Session Rejection [#session-rejection] ```swift try await WalletKit.instance.reject(requestId: request.id) ``` ### Responding to Session requests [#responding-to-session-requests] After the session is established, a dapp will request your wallet's users to sign a transaction or a message. Requests will be delivered by the following publisher. ```swift WalletKit.instance.sessionRequestPublisher .receive(on: DispatchQueue.main) .sink { [weak self] session in self?.verifyDapp(session.context) self?.showSessionRequest(session.request) }.store(in: &publishers) ``` When a wallet receives a session request, you probably want to show it to the user. It’s method will be in scope of session namespaces. And it’s params are represented by `AnyCodable` type. An expected object can be derived as follows: ```swift if sessionRequest.method == "personal_sign" { let params = try! sessionRequest.params.get([String].self) } else if method == "eth_signTypedData" { let params = try! sessionRequest.params.get([String].self) } else if method == "eth_sendTransaction" { let params = try! sessionRequest.params.get([EthereumTransaction].self) } ``` Now, your wallet (as it owns your user’s private keys) is responsible for signing the transaction. After doing it, you can send a response to a dapp. ```swift let response: AnyCodable = sign(request: sessionRequest) // Implement your signing method try await WalletKit.instance.respond(topic: request.topic, requestId: request.id, response: .response(response)) ``` ### Updating a Session [#updating-a-session] If you want to update user session's chains, accounts, methods or events you can use session update method. ```swift try await WalletKit.instance.update(topic: session.topic, namespaces: newNamespaces) ``` ### Extending a Session [#extending-a-session] By default, session lifetime is set for 7 days and after that time user's session will expire. But if you consider that a session should be extended you can call: ```swift try await WalletKit.instance.extend(topic: session.topic) ``` Above method will extend a user's session to a week. ### Session Disconnect [#session-disconnect] For good user experience your wallet should allow users to disconnect unwanted sessions. In order to terminate a session use `disconnect` method. ```swift try await WalletKit.instance.disconnect(topic: session.topic) ``` ### Subscribe for WalletKit Publishers [#subscribe-for-walletkit-publishers] The following publishers are available to subscribe: ```swift public var sessionProposalPublisher: AnyPublisher<(proposal: Session.Proposal, context: VerifyContext?), Never> public var sessionRequestPublisher: AnyPublisher<(request: Request, context: VerifyContext?), Never> public var authRequestPublisher: AnyPublisher<(request: AuthRequest, context: VerifyContext?), Never> public var sessionPublisher: AnyPublisher<[Session], Never> public var socketConnectionStatusPublisher: AnyPublisher public var sessionSettlePublisher: AnyPublisher public var sessionDeletePublisher: AnyPublisher<(String, Reason), Never> public var sessionResponsePublisher: AnyPublisher ``` ### Register Device Token [#register-device-token] To register a wallet to receive WalletConnect push notifications, call `register` method and pass the device token received from the `didRegisterForRemoteNotificationsWithDeviceToken` method in the `AppDelegate`. ```swift WalletKit.instance.register(deviceToken: deviceToken, enableEncrypted: true) ``` # Verify API (/wallets/ios/verify) Verify API is a security-focused feature that allows wallets to notify end-users when they may be connecting to a suspicious or malicious domain, helping to prevent phishing attacks across the industry. Once a wallet knows whether an end-user is on uniswap.com or eviluniswap.com, it can help them to detect potentially harmful connections through Verify's combined offering of WalletConnect's domain registry. When a user initiates a connection with an application, Verify API enables wallets to present their users with four key states that can help them determine whether the domain they’re about to connect to might be malicious. These are: ![Verify Banner](/images/mintlify/verify-banner.png) ## Disclaimer [#disclaimer] Verify API helps wallets detect suspicious or malicious domains, but it may not catch every threat. Use it as one more layer of protection alongside your wallet's other security measures. ## Domain risk detection [#domain-risk-detection] The Verify security system will discriminate session proposals & session requests with distinct validations that can be either `VALID`, `INVALID` or `UNKNOWN`. - Domain match: The domain linked to this request has been verified as this application's domain. - This interface appears when the domain a user is attempting to connect to has been ‘verified’ in our domain registry as the registered domain of the application the user is trying to connect to, and the domain has not returned as suspicious from either of the security tools we work with. The `verifyContext` included in the request will have a validation of `VALID`. - Unverified: The domain sending the request cannot be verified. - This interface appears when the domain a user is attempting to connect to has not been verified in our domain registry, but the domain has not returned as suspicious from either of the security tools we work with. The `verifyContext` included in the request will have a validation of `UNKNOWN`. - Mismatch: The application's domain doesn't match the sender of this request. - This interface appears when the domain a user is attempting to connect to has been flagged as a different domain to the one this application has verified in our domain registry, but the domain has not returned as suspicious from either of the security tools we work with. The `verifyContext` included in the request will have a validation of `INVALID` - Threat: This domain is flagged as malicious and potentially harmful. - This interface appears when the domain a user is attempting to connect to has been flagged as malicious on one or more of the security tools we work with. The `verifyContext` included in the request will contain parameter `isScam` with value `true`. ### Reading `verifyContext` by connection type [#reading-verifycontext-by-connection-type] How your wallet should read `verifyContext` depends on how the dApp connects: - **Web dApp over QR code or deep link (relay):** This is the full Verify API, including scam checks. Show all four states: `VALID` as Domain match, `UNKNOWN` as Cannot verify, `INVALID` as Mismatch, and `isScam` as Security risk (ideally blocking or requiring the user to confirm). - **Native dApp over relay:** Native apps can't create a Verify attestation, so `UNKNOWN` is expected here. We suggest a neutral "Cannot verify" label rather than an alarming warning. - **[Link Mode](/wallets/ios/link-mode) (native to native):** The domain check above applies, with no scam check. `INVALID` means the dApp's universal link domain doesn't match its `metadata.url`. The wallet's own Link Mode setup also needs to be complete, or the result falls back to `INVALID`. ### Implementation [#implementation] `sessionProposalPublisher`, `authenticateRequestPublisher` and `sessionRequestPublisher` each emit a `VerifyContext?` alongside the request: ```swift public struct VerifyContext: Equatable, Hashable, Codable { public enum ValidationStatus: Codable { case unknown case valid case invalid case scam } public let origin: String? public let validation: ValidationStatus } ``` Map it to one of the four states once, then use that state in each subscriber. ```swift enum VerifyState { case threat, mismatch, unverified, domainMatch } func verifyState(for context: VerifyContext?) -> VerifyState { switch context?.validation { case .scam: // Threat: only set over relay, since Link Mode has no scam check return .threat case .invalid: return .mismatch case .valid: return .domainMatch case .unknown, .none: // UNKNOWN: expected for native dApps over relay return .unverified } } // Session proposals from a web or native dApp WalletKit.instance.sessionProposalPublisher .receive(on: DispatchQueue.main) .sink { proposal, context in let state = verifyState(for: context) // show the state on the approval screen } .store(in: &publishers) // One-click auth requests can arrive over relay or Link Mode WalletKit.instance.authenticateRequestPublisher .receive(on: DispatchQueue.main) .sink { request, context in let state = verifyState(for: context) // in Link Mode, MISMATCH means the universal link domain doesn't match metadata.url } .store(in: &publishers) WalletKit.instance.sessionRequestPublisher .receive(on: DispatchQueue.main) .sink { request, context in let state = verifyState(for: context) // show the state on the signing screen } .store(in: &publishers) ``` Keep in mind: - WalletKit doesn't expose the transport a request arrived on. To detect Link Mode, check for `wc_ev` in the incoming universal link before passing it to `WalletKit.instance.dispatchEnvelope(_:)`, and keep track of that request's topic. - Session requests sent over Link Mode arrive with a `nil` context, so they map to `UNVERIFIED`. Present each state like this: - `THREAT`: Block the request, or require the user to explicitly accept the risk. Check before anything else, so the user doesn't also see a Mismatch warning. - `MISMATCH`: Show a warning and proceed only if the user accepts the risk. - `UNVERIFIED`: Show a neutral "Cannot verify" label. Don't block the request, since native dApps over relay always land here. - `DOMAIN_MATCH`: Show a verified badge and proceed as normal. # Best Practices for Wallets (/wallets/more/best-practices) To ensure the smoothest and most seamless experience for our users, WalletConnect is committed to working closely with wallet providers to encourage the adoption of our recommended best practices. By implementing these guidelines, we aim to optimize performance and minimize potential challenges, even in suboptimal network conditions. We are actively partnering with wallet developers to optimize performance in scenarios such as: 1. **Success and Error Messages** - Users need to know what’s going on, at all times. Too much communication is better than too little. The less users need to figure out themselves or assume what’s going on, the better. 2. **(Perceived) Latency** - A lot of factors can influence latency (or perceived latency), e.g. network conditions, position in the boot chain, waiting on the wallet to connect or complete a transaction and not knowing if or when it has done it. 3. **Old SDK Versions** - Older versions can have known and already fixed bugs, leading to unnecessary issues to users, which can be simply and quickly solved by updating to the latest SDK. To take all of the above into account and to make experience better for users, we've put together some key guidelines for wallet providers. These best practices focus on the most important areas for improving user experience. Please follow these best practices and make the experience for your users and yourself a delightful and quick one. ## Checklist Before Going Live [#checklist-before-going-live] To make sure your wallet adheres to the best practices, we recommend implementing the following checklist before going live. You can find more detailed information on each point below. 1. **Success and Error Messages** * ✅ Display clear and concise messages for all user interactions * ✅ Provide feedback for all user actions * ✅ Connection success * ✅ Connection error * ✅ Loading indicators for waiting on connection, transaction, etc. * ✅ Ensure that users are informed of the status of their connection and transactions * ✅ Implement status indicators internet availability * ✅ Make sure to provide feedback not only to users but also back to the dapp (e.g., if there's an error or a user has not enough funds to pay for gas, don't just display the info message to the user, but also send the error back to the dapp so that it can change the state accordingly) 2. **Mobile Linking** * ✅ Implement mobile linking to allow for automatic redirection between the wallet and the dapp * ✅ Use deep linking over universal linking for a better user experience * ✅ Ensure that the user is redirected back to the dapp after completing a transaction 3. **Latency** * ✅ Optimize performance to minimize latency * ✅ Latency for connection in normal conditions: under 5 seconds * ✅ Latency for connection in poor network (3G) conditions: under 15 seconds * ✅ Latency for signing in normal conditions: under 5 seconds * ✅ Latency for signing in poor network (3G) conditions: under 10 seconds 4. **Verify API** * ✅ Present users with four key states that can help them determine whether the domain they’re about to connect to might be malicious (Domain match, Unverified, Mismatch, Threat) 5. **Latest SDK Version** * ✅ Ensure that you are using the latest SDK version * ✅ Update your SDK regularly to benefit from the latest features and bug fixes * ✅ Subscribe to SDK updates to stay informed about new releases ## 1. Success and Error Messages [#1-success-and-error-messages] Users often face ambiguity in determining whether their connection or transactions were successful. They are also not guided to switching back into the dapp or automatically switched back when possible, causing unnecessary user anxiety. Additionally, wallets typically lack status indicators for connection and internet availability, leaving users in the dark.
![Wallet approving a connection request and then confirming the user is connected](/images/mintlify/assets/connection-successful.png)
An example of a successful connection message in a Rainbow wallet
### Pairing [#pairing] A pairing is a connection between a wallet and a dapp that has fixed permissions to only allow a dapp to propose a session through it. Dapp can propose infinite number of sessions on one pairing. Wallet must use a pair method from WalletKit client to pair with dapp. ```jsx const uri = 'xxx'; // pairing uri try { await walletKit.pair({ uri }); } catch (error) { // some error happens while pairing - check Expected errors section } ``` ```jsx const uri = 'xxx'; // pairing uri try { await walletKit.pair({ uri }); } catch (error) { // some error happens while pairing - check Expected errors section } ``` ```swift let uri = WalletConnectURI(string: urlString) if let uri { Task { try await WalletKit.instance.pair(uri: uri) } } ``` ```kotlin val pairingParams = Wallet.Params.Pair(pairingUri) WalletKit.pair(pairingParams, onSuccess = { //Subscribed on the pairing topic successfully. Wallet should await for a session proposal }, onError = { error -> //Some error happens while pairing - check Expected errors section } } ``` #### Pairing Expiry [#pairing-expiry] A pairing expiry event is triggered whenever a pairing is expired. The expiry for inactive pairing is 5 mins, whereas for active pairing is 30 days. A pairing becomes active when a session proposal is received and user successfully approves it. This event helps to know when given pairing expires and update UI accordingly. ```typescript core.pairing.events.on("pairing_expire", (event) => { // pairing expired before user approved/rejected a session proposal const { topic } = topic; }); ``` ```typescript core.pairing.events.on("pairing_expire", (event) => { // pairing expired before user approved/rejected a session proposal const { topic } = topic; }); ``` ```swift WalletKit.instance.pairingExpirationPublisher .receive(on: DispatchQueue.main) .sink { pairing in guard !pairing.active else { return } // let user know that pairing has expired }.store(in: &publishers) ``` ```kotlin val coreDelegate = object : CoreClient.CoreDelegate { override fun onPairingExpired(expiredPairing: Core.Model.ExpiredPairing) { // Here a pairing expiry is triggered } // ...other callbacks } CoreClient.setDelegate(coreDelegate) ``` #### Pairing messages [#pairing-messages] 1. Consider displaying a successful pairing message when pairing is successful. Before that happens, wallet should show a loading indicator. 2. Display an error message when a pairing fails. #### Expected Errors [#expected-errors] While pairing, the following errors might occur: * **No Internet connection error or pairing timeout when scanning QR with no Internet connection** * User should pair again with Internet connection * **Pairing expired error when scanning a QR code with expired pairing** * User should refresh a QR code and scan again * **Pairing with existing pairing is not allowed** * User should refresh a QR code and scan again. It usually happens when user scans an already paired QR code. ### Session Proposal [#session-proposal] A session proposal is a handshake sent by a dapp and its purpose is to define session rules. Whenever a user wants to establish a connection between a wallet and a dapp, one should approve a session proposal. Whenever user approves or rejects a session proposal, a wallet should show a loading indicator the moment the button is pressed, until Relay acknowledgement is received for any of these actions. #### Approving session [#approving-session] ```typescript try { await walletKit.approveSession(params); // update UI -> remove the loader } catch (error) { // present error to the user } ``` ```typescript try { await walletKit.approveSession(params); // update UI -> remove the loader } catch (error) { // present error to the user } ``` ```swift do { try await WalletKit.instance.approve(proposalId: proposal.id, namespaces: sessionNamespaces, sessionProperties: proposal.sessionProperties) // Update UI, remove loader } catch { // present error } ``` ```kotlin WalletKit.approveSession(approveProposal, onSuccess = { //Session approval response was sent successfully - update your UI } onError = { error -> //Error while sending session approval - update your UI }) ``` #### Rejecting session [#rejecting-session] ```typescript try { await walletKit.rejectSession(params); // update UI -> remove the loader } catch (error) { // present error to the user } ``` ```typescript try { await walletKit.rejectSession(params); // update UI -> remove the loader } catch (error) { // present error to the user } ``` ```swift do { try await WalletKit.instance.reject(proposalId: proposal.id, reason: .userRejected) // Update UI, remove loader } catch { // present error } ``` ```kotlin WalletKit.rejectSession(reject, onSuccess = { //Session rejection response was sent successfully - update your UI }, onError = { error -> //Error while sending session rejection - update your UI }) ``` #### Session proposal expiry [#session-proposal-expiry] A session proposal expiry is 5 minutes. It means a given proposal is stored for 5 minutes in the SDK storage and user has 5 minutes for the approval or rejection decision. After that time, the below event is emitted and proposal modal should be removed from the app's UI. ```typescript walletKit.on("proposal_expire", (event) => { // proposal expired and any modal displaying it should be removed const { id } = event; }); ``` ```typescript walletKit.on("proposal_expire", (event) => { // proposal expired and any modal displaying it should be removed const { id } = event; }); ``` ```swift WalletKit.instance.sessionProposalExpirationPublisher.sink { _ in // let user know that session proposal has expired, update UI }.store(in: &publishers) ``` ```kotlin val walletDelegate = object : WalletKit.WalletDelegate { override fun onProposalExpired(proposal: Wallet.Model.ExpiredProposal) { // Here this event is triggered when a proposal expires - update your UI } // ...other callbacks } WalletKit.setWalletDelegate(walletDelegate) ``` #### Session Proposal messages [#session-proposal-messages] 1. Consider displaying a successful session proposal message before redirecting back to the dapp. Before the success message is displayed, wallet should show a loading indicator. 2. Display an error message when session proposal fails. #### Expected errors [#expected-errors-1] While approving or rejecting a session proposal, the following errors might occur: * **No Internet connection** * It happens when a user tries to approve or reject a session proposal with no Internet connection * **Session proposal expired** * It happens when a user tries to approve or reject an expired session proposal * **Invalid [namespaces](https://docs.reown.com/advanced/glossary#namespaces)** * It happens when a validation of session namespaces fails * **Timeout** * It happens when Relay doesn't acknowledge session settle publish within 10s ### Session Request [#session-request] A session request represents the request sent by a dapp to a wallet. Whenever user approves or rejects a session request, a wallet should show a loading indicator the moment the button is pressed, until Relay acknowledgement is received for any of these actions. ```typescript try { await walletKit.respondSessionRequest(params); // update UI -> remove the loader } catch (error) { // present error to the user } ``` ```typescript try { await walletKit.respondSessionRequest(params); // update UI -> remove the loader } catch (error) { // present error to the user } ``` ```swift do { try await WalletKit.instance.respond(requestId: request.id, signature: signature, from: account) // update UI -> remove the loader } catch { // present error to the user } ``` ```kotlin WalletKit.respondSessionRequest(Wallet.Params.SessionRequestResponse, onSuccess = { //Session request response was sent successfully - update your UI }, onError = { error -> //Error while sending session response - update your UI }) ``` #### Session request expiry [#session-request-expiry] A session request expiry is defined by a dapp. Its value must be between `now() + 5mins` and `now() + 7 days`. After the session request expires, the below event is emitted and session request modal should be removed from the app's UI. ```typescript walletKit.on("session_request_expire", (event) => { // request expired and any modal displaying it should be removed const { id } = event; }); ``` ```typescript walletKit.on("session_request_expire", (event) => { // request expired and any modal displaying it should be removed const { id } = event; }); ``` ```swift WalletKit.instance.requestExpirationPublisher.sink { _ in // let user know that request has expired }.store(in: &publishers) ``` ```kotlin val walletDelegate = object : WalletKit.WalletDelegate { override fun onRequestExpired(request: Wallet.Model.ExpiredRequest) { // Here this event is triggered when a session request expires - update your UI } // ...other callbacks } WalletKit.setWalletDelegate(walletDelegate) ``` #### Expected errors [#expected-errors-2] While approving or rejecting a session request, the following errors might occur: * **Invalid session** * This error might happen when a user approves or rejects a session request on an expired session * **Session request expired** * This error might happen when a user approves or rejects a session request that already expired * **Timeout** * It happens when Relay doesn't acknowledge session settle publish within 10 seconds ### Connection state [#connection-state] The Web Socket connection state tracks the connection with the Relay server. An event is emitted whenever a connection state changes. ```typescript core.relayer.on("relayer_connect", () => { // connection to the relay server is established }) core.relayer.on("relayer_disconnect", () => { // connection to the relay server is lost }) ``` ```typescript core.relayer.on("relayer_connect", () => { // connection to the relay server is established }) core.relayer.on("relayer_disconnect", () => { // connection to the relay server is lost }) ``` ```swift WalletKit.instance.socketConnectionStatusPublisher .receive(on: DispatchQueue.main) .sink { status in switch status { case .connected: // ... case .disconnected: // ... } }.store(in: &publishers) ``` ```kotlin val walletDelegate = object : WalletKit.WalletDelegate { override fun onConnectionStateChange(state: Wallet.Model.ConnectionState) { // Here this event is triggered when a connection state has changed } // ...other callbacks } WalletKit.setWalletDelegate(walletDelegate) ``` #### Connection state messages [#connection-state-messages] When the connection state changes, show a message in the UI. For example, display a message when the connection is lost or re-established. ## 2. Mobile Linking [#2-mobile-linking] ### Why use Mobile Linking? [#why-use-mobile-linking] Mobile Linking uses the mobile device’s native OS to automatically redirect between the native wallet app and a native app. This results in few user actions a better UX. #### Establishing Communication Between Mobile Wallets and Apps [#establishing-communication-between-mobile-wallets-and-apps] When integrating a wallet with a mobile application, it's essential to understand how they communicate. The process involves two main steps: 1. **QR Code Handshake:** The mobile app (Dapp) generates a unique URI (Uniform Resource Identifier) and displays it as a QR code. This URI acts like a secret handshake. When the user scans the QR code or copy/pastes the URI using their wallet app, they establish a connection. It's like saying, "Hey, let's chat!" 2. **Deep Links and Universal Links:** The URI from the QR code allows the wallet app to create a [deep link](https://support.google.com/google-ads/answer/10023042) or [universal link](https://developer.apple.com/ios/universal-links/). These links work on both Android and iOS. They enable seamless communication between the wallet and the app. **Developers should prefer Deep Linking over Universal Linking.** Universal Linking may redirect the user to a browser, which might not provide the intended user experience. Deep Linking ensures the user is taken directly to the app. ### Key Behavior to Address [#key-behavior-to-address] In some scenarios, wallets use redirect metadata provided in session proposals to open applications. This can cause unintended behavior, such as: Redirecting to the wrong app when multiple apps share the same redirect metadata (e.g., a desktop and mobile version of the same Dapp). Opening an unrelated application if a QR code is scanned on a different device than where the wallet is installed. #### Recommended Approach [#recommended-approach] To avoid this behavior, wallets should: * **Restrict Redirect Metadata to Deep Link Use Cases**: Redirect metadata should only be used when the session proposal is initiated through a deep link. QR code scans should not trigger app redirects using session proposal metadata. ### Connection Flow [#connection-flow] 1. **Dapp prompts user:** The Dapp asks the user to connect. 2. **User chooses wallet:** The user selects a wallet from a list of compatible wallets. 3. **Redirect to wallet:** The user is redirected to their chosen wallet. 4. **Wallet approval:** The wallet prompts the user to approve or reject the session (similar to granting permission). 5. **Return to dapp:** * **Manual return:** The wallet asks the user to manually return to the Dapp. * **Automatic return:** Alternatively, the wallet automatically takes the user back to the Dapp. 6. **User reunites with dapp:** After all the interactions, the user ends up back in the Dapp. ![Mobile linking flow where the dApp sends the user to the wallet to connect and back](/images/mintlify/w3w/mobileLinking-light.png) ### Sign Request Flow [#sign-request-flow] When the Dapp needs the user to sign something (like a transaction), a similar pattern occurs: 1. **Automatic redirect:** The Dapp automatically sends the user to their previously chosen wallet. 2. **Approval prompt:** The wallet asks the user to approve or reject the request. 3. **Return to dapp:** * **Manual return:** The wallet asks the user to manually return to the Dapp. * **Automatic return:** Alternatively, the wallet automatically takes the user back to the Dapp. 4. **User reconnects:** Eventually, the user returns to the Dapp. ![Mobile linking flow where the dApp sends the user to the wallet to sign a message](/images/mintlify/w3w/mobileLinking_sign-light.png) ### Platform Specific Preparation [#platform-specific-preparation] Read the specific steps for iOS here: [Platform preparations](./ios/mobile-linking#platform-preparations) Read the specific steps for Android here: [Platform preparations](./android/mobile-linking#platform-preparations) Read the specific steps for Flutter here: [Platform preparations](./flutter/mobile-linking#platform-preparations) Read the specific steps for React Native here: [Platform preparations](./react-native/mobile-linking#platform-preparations) ### How to Test [#how-to-test] To experience the desired behavior, try our Sample Wallet and Dapps which use our Mobile linking best practices. These are available on all platforms. Once you have completed your integration, you can test it against our sample apps to see if it is working as expected. Download the app and and try your mobile linking integration on your device. * [Sample Wallet](https://testflight.apple.com/join/09bTAryp) - on TestFlight * [Sample DApp](https://testflight.apple.com/join/7S1GYcjC) - on TestFlight * [Sample Wallet](https://appdistribution.firebase.dev/i/6f9437a5f9bf4eec) - on Firebase - [Sample DApp](https://appdistribution.firebase.dev/i/5e4fe4b30c8a208d) - on Firebase * Sample Wallet: - [Sample Wallet for iOS](https://testflight.apple.com/join/Uv0XoBuD) - [Sample Wallet for Android](https://appdistribution.firebase.dev/i/2b8b3dce9e2831cd) - AppKit DApp: - [AppKit Dapp for iOS](https://testflight.apple.com/join/6aRJSllc) - [AppKit Dapp for Android](https://appdistribution.firebase.dev/i/2c6573f6956fa7b5) * Sample Wallet: * [Sample Wallet for Android](https://appdistribution.firebase.dev/i/e7711e780547234e) * Sample DApp: * [Sample App for iOS](https://testflight.apple.com/join/Ivd8bg7s) * [Sample App for Android](https://appdistribution.firebase.dev/i/0297fbd3de8f1e3f) ## 3. Latency [#3-latency] Our SDK’s position in the boot chain can lead to up to 15 seconds in throttled network conditions. Lack of loading indicators exacerbates the perceived latency issues, impacting user experience negatively. Additionally, users often do not receive error messages or codes when issues occur or timeouts happen. ### Target latency [#target-latency] For **connecting**, the target latency is: * **Under 5 seconds** in normal conditions * **Under 15 seconds** when throttled (3G network speed) For **signing**, the target latency is: * **Under 5 seconds** in normal conditions * **Under 10 seconds** when throttled (3G network speed) ### How to test [#how-to-test-1] To test latency under suboptimal network conditions, you can enable throttling on your mobile phone. You can simulate different network conditions to see how your app behaves in various scenarios. For example, on iOS you need to enable Developer Mode and then go to **Settings > Developer > Network Link Conditioner**. You can then select the network condition you want to simulate. For 3G, you can select **3G** from the list, for no network or timeout simulations, choose **100% Loss**. Check this article for how to simulate slow internet connection on iOS & Android, with multiple options for both platforms: [How to simulate slow internet connection on iOS & Android](https://www.browserstack.com/guide/how-to-simulate-slow-network-conditions). ## 4. Verify API [#4-verify-api] Verify API is a security-focused feature that allows wallets to notify end-users when they may be connecting to a suspicious or malicious domain, helping to prevent phishing attacks across the industry. Once a wallet knows whether an end-user is on uniswap.com or eviluniswap.com, it can help them to detect potentially harmful connections through Verify's combined offering of WalletConnect's domain registry. When a user initiates a connection with an application, Verify API enables wallets to present their users with four key states that can help them determine whether the domain they’re about to connect to might be malicious. Possible states: * Domain match * Unverified * Mismatch * Threat ![Verify States](/images/mintlify/verify-states-1.png) ![Verify States](/images/mintlify/verify-states-2.png) Verify API helps wallets detect suspicious or malicious domains, but it may not catch every threat. Use it as one more layer of protection alongside your wallet's other security measures. ### Domain risk detection[](https://docs.reown.com/walletkit/web/verify#domain-risk-detection) [#domain-risk-detection] The Verify security system will discriminate session proposals & session requests with distinct validations that can be either `VALID`, `INVALID` or `UNKNOWN`. * **Domain match:** The domain linked to this request has been verified as this application's domain. * This interface appears when the domain a user is attempting to connect to has been ‘verified’ in our domain registry as the registered domain of the application the user is trying to connect to, and the domain has not returned as suspicious from either of the security tools we work with. The `verifyContext` included in the request will have a validation of `VALID`. * **Unverified:** The domain sending the request cannot be verified. * This interface appears when the domain a user is attempting to connect to has not been verified in our domain registry, but the domain has not returned as suspicious from either of the security tools we work with. The `verifyContext` included in the request will have a validation of `UNKNOWN`. * **Mismatch:** The application's domain doesn't match the sender of this request. * This interface appears when the domain a user is attempting to connect to has been flagged as a different domain to the one this application has verified in our domain registry, but the domain has not returned as suspicious from either of the security tools we work with. The `verifyContext` included in the request will have a validation of `INVALID` * **Threat:** This domain is flagged as malicious and potentially harmful. * This interface appears when the domain a user is attempting to connect to has been flagged as malicious on one or more of the security tools we work with. The `verifyContext` included in the request will contain parameter `isScam` with value `true`. ### Verify API Implementation [#verify-api-implementation] To see how to implement Verify API for your framework, see [Verify API](./features/verify) page and select your platform to see code examples. ### How to test [#how-to-test-2] To test Verify API with a malicious domain, you can check out the [Malicious React dapp](https://malicious-app-verify-simulation.vercel.app/), created specifically for testing. This app is flagged as malicious and will have the `isScam` parameter set to `true` in the `verifyContext` of the request. You can use this app to test how your wallet behaves when connecting to a malicious domain. ### Error messages [#error-messages] ![Verify API flagged domain](/images/mintlify/assets/verify-api-flagged-domain.png) *A sample error warning when trying to connect to a malicious domain* ## 5. Latest SDK [#5-latest-sdk] Numerous features have been introduced, bugs have been identified and fixed over time, stability has improved, but many dapps and wallets continue to use older SDK versions with known issues, affecting overall reliability. Make sure you are using the latest version of the SDK for your platform * **WalletConnectSwiftV2**: [Latest release](https://github.com/reown-com/reown-swift/releases/latest/) * **WalletConnectKotlinV2**: [Latest release](https://github.com/WalletConnect/WalletConnectKotlinV2/releases/latest) * **WalletConnectFlutterV2**: [Latest release](https://github.com/WalletConnect/WalletConnectFlutterV2/releases/latest) * **AppKit for React Native**: [Latest release](https://github.com/WalletConnect/reown-react-native/releases/latest) ### Subscribe to updates [#subscribe-to-updates] To stay up to date with the latest SDK releases, you can use GitHub's native feature to subscribe to releases. This way, you will be notified whenever a new release is published. You can find the "Watch" button on the top right of the repository page. Click on it, then select "Custom" and "Releases only". You'll get a helpful ping whenever a new release is out. ![Subscribe to releases](/images/mintlify/assets/subsribe-to-release-updates.png) ## Resources [#resources] * [React Wallet](https://react-wallet.reown.com/) - for testing dapps, features, Verify API messages, etc. * [React dapp](https://react-app.reown.com/) - for testing wallets * [Malicious React dapp](https://malicious-app-verify-simulation.vercel.app/) - for testing Verify API with malicious domain # Push Notifications (/wallets/more/push-notifications) WalletConnect lets your wallet receive push notifications for incoming requests through a self-hosted push server. When a dapp sends your wallet a session proposal, a session request or an authentication request, the relay sends it to the push URL set on your project. The push server behind that URL looks up the device and sends the notification through APNs or FCM. The push URL points at a server you run. Use the [open-source push server](https://github.com/reown-com/push-server), or write your own against the push server API. ```mermaid sequenceDiagram participant W as Wallet app participant P as Your push server participant R as Relay participant N as APNs / FCM W->>P: POST /clients (client ID and device token) R->>P: POST /clients/{client_id}, signed by the relay P->>N: Notification N->>W: Notification ``` ## Run the push server [#run-the-push-server] Build the image from `slim.Dockerfile`. This is the single-tenant build: it serves one wallet app and reads its APNs and FCM credentials from environment variables. The credentials stay on your server; the dashboard stores only the push URL. | Variable | Value | | --- | --- | | `PUBLIC_URL` | The server's public address, for example `https://push.example.com`. | | `DATABASE_URL` | A Postgres database for device registrations. The server runs its own migrations on start. | | `TENANT_DATABASE_URL` | Must be set, and left empty in this build. | | `RELAY_PUBLIC_KEY` | The relay's signing key, from `https://relay.walletconnect.com/public-key`. | | `FCM_V1_CREDENTIALS` | Your Firebase service account key, as JSON. | | `APNS_TYPE`, `APNS_TOPIC` | `Token` or `Certificate`, and your app's bundle ID. | | `APNS_PKCS8_PEM`, `APNS_KEY_ID`, `APNS_TEAM_ID` | For `Token`: your `.p8` key, base64-encoded, and its key and team IDs. | | `APNS_CERTIFICATE`, `APNS_CERTIFICATE_PASSWORD` | For `Certificate`: your `.p12` certificate, base64-encoded, and its password. | Keep `VALIDATE_SIGNATURES` at its default of `true`, so the server rejects requests that the relay did not sign. ## Set the push URL [#set-the-push-url] In the [WalletConnect Dashboard](https://dashboard.walletconnect.com), open your project's **Push** page and choose **Create Push URL**. The page appears only for wallet projects. ![The Push page in the WalletConnect Dashboard, with the Create Push URL button](/images/push-url.png) Enter your `PUBLIC_URL`: - It must use HTTPS and a public domain name, not an IP address. - It can include a base path, but no query string, fragment or credentials, because the relay appends `/clients/{client_id}` to it. The relay caches project settings, so a change can take several minutes to take effect. ## Register devices [#register-devices] The relay knows each wallet only by its relay client ID, and APNs and FCM deliver only to a device token. Registering a device stores the pair on your push server, so that when the relay asks it to notify a client ID, the server knows which device token to send to. A device that is not registered gets no notifications. Don't use the SDK's push registration (`WalletKit.instance.register(deviceToken:)` on iOS, `WalletKit.registerDeviceToken` on Android, `walletKit.registerDeviceToken` in React Native) with a self-hosted server. On Android and React Native it always registers with WalletConnect's hosted server. On iOS you can change the host with `pushHost`, but the SDK sends to `/{projectId}/clients`, which the self-hosted server doesn't serve. Your app has to register with your server directly instead: ```http POST https://push.example.com/clients Content-Type: application/json { "client_id": "", "type": "fcm", "token": "", "always_raw": true } ``` - `client_id` is the ID the wallet uses on the relay: `CoreClient.Push.clientId` on Android, `Networking.interactor.getClientId()` on iOS, `walletKit.core.crypto.getClientId()` in React Native. - `type` is `apns`, `apns-sandbox` or `fcm`. - `always_raw` sets what the notification contains. It matches the SDKs' `enableEncrypted` option: - `true`: the notification carries the encrypted request as `topic`, `tag` and `message`. Your app decrypts it and shows its own text, for example the dapp's name and what it asks for. - `false`: the user sees a fixed "Signature required" alert written by the relay, and your app does not decrypt anything. Send the registration when the app starts and has a device token, and again whenever the OS issues a new token. To stop notifications, for example when the user turns them off or logs out, send `DELETE /clients/{client_id}`. ## Delivery [#delivery] The open-source push server already handles this. If you write your own, respond to each request from the relay within 30 seconds: - Return a 2xx response once the notification is handed to APNs or FCM. - Return a 5xx response only when a retry could succeed. The relay retries after a timeout, a network error or a 5xx response, and does not retry any other response. # Staying up to date (/wallets/more/updating-wallet-sdk) ## Why Should You Keep WalletKit Updated? [#why-should-you-keep-walletkit-updated] Keeping your WalletKit SDK updated to the latest version is crucial for maintaining optimal performance, security, and compatibility with the evolving Web3 ecosystem. Regular updates ensure: * **Security patches** - Protection against newly discovered vulnerabilities * **Bug fixes** - Resolution of known issues and improved stability * **New features** - Access to the latest WalletConnect protocol enhancements * **Protocol compatibility** - Seamless interaction with updated dApps and wallets * **Performance improvements** - Optimizations for better user experience ## Latest Releases by Platform [#latest-releases-by-platform] Stay current with the latest WalletKit releases for your development platform: ### Kotlin (Android) [#kotlin-android] Check the latest Kotlin releases for Android development: * [WalletConnect Kotlin Releases](https://github.com/reown-com/reown-kotlin/releases) ### Swift (iOS) [#swift-ios] Stay updated with the latest Swift releases for iOS development: * [WalletConnect Swift Releases](https://github.com/reown-com/reown-swift/releases) ### JavaScript / React Native [#javascript--react-native] Monitor JavaScript and React Native package updates: * [WalletConnect WalletKit JS Releases](https://github.com/reown-com/reown-walletkit-js/releases) ### Flutter [#flutter] Check the latest Flutter releases for Flutter development: * [WalletConnect WalletKit Flutter Releases](https://pub.dev/packages/reown_walletkit) # Upgrade from Web3Wallet to WalletKit for Android (/wallets/more/web3wallet-migration/android) ## Upgrade to WalletKit [#upgrade-to-walletkit] This upgrade guide helps developers transition from using the Web3Wallet library to the WalletKit within reown-kotlin. The guide involves updating imports, modifying class references and updating artefacts dependencies. Follow these steps to ensure a smooth migration. ### Step 1. Update the Repository Dependencies [#step-1-update-the-repository-dependencies] The Web3Wallet library has been deprecated and moved to a new repository under the reown-com organization. Update your dependencies to use WalletKit: ```swift /* highlight-delete-start */ - dependencies { - implementation(platform("com.walletconnect:android-bom:{BOM version}")) - implementation("com.walletconnect:android-core") - implementation("com.walletconnect:web3wallet") - } /* highlight-delete-end */ /* highlight-add-start */ + dependencies { + implementation(platform("com.reown:android-bom:{BOM version}")) + implementation("com.reown:android-core") + implementation("com.reown:walletkit") + } /* highlight-add-end */ ``` ### Step 2. Update Imports in Your Code [#step-2--update-imports-in-your-code] All references to Web3Wallet in your import statements should be updated to use WalletKit. ```swift /* highlight-delete-start */ - import com.walletconnect.android.* - import com.walletconnect.web3.wallet.* /* highlight-delete-end */ /* highlight-add-start */ + import com.reown.android.* + import com.reown.walletkit.* /* highlight-add-end */ ``` ### Step 3. Update Class Name [#step-3-update-class-name] The singleton instance for Web3Wallet has been replaced with WalletKit. Update all instances where Web3Wallet is used with WalletKit. ```swift /* highlight-delete-start */ - Web3Wallet.initialize(Wallet.Params.Init(core = CoreClient), onSuccess, onError) - Web3Wallet.approveSession(approveProposal, onSuccess, onError) /* highlight-delete-end */ /* highlight-add-start */ + WalletKit.initialize(Wallet.Params.Init(core = CoreClient), onSuccess, onError) + WalletKit.approveSession(approveProposal, onSuccess, onError) /* highlight-add-end */ ``` ### Step 4. Update ProGuard file rules [#step-4-update-proguard-file-rules] If you have ProGuard rules defined remember to update ```swift /* highlight-delete-start */ - -keep class com.walletconnect.web3.wallet.client.Wallet$Model { *; } - -keep class com.walletconnect.web3.wallet.client.Wallet { *; } /* highlight-delete-end */ /* highlight-add-start */ + -keep class com.reown.walletkit.client.Wallet$Model { *; } + -keep class com.reown.walletkit.client.Wallet { *; } /* highlight-add-end */ ``` ### Step 5. Test Your Changes [#step-5-test-your-changes] After updating all references to Web3Wallet to use WalletKit, thoroughly test your application to ensure that all functionalities work as expected. ## Pairing Expiry [#pairing-expiry] Currently, Dapps create a new pairing whenever the user selects the **"Connect Wallet"** button, instead of reusing existing pairings. Although pairings were not intended to be reused, they were being persisted for 30 days, causing unnecessary resource usage for both Dapps and wallet clients, including redundant socket connections. This led to an accumulation of stale pairings in wallets, resulting in degraded efficiency and increased resource consumption. To address this issue, we have introduced changes to how pairings are managed to ensure more efficient connection handling. Pairings were never intended to be listed in the wallet, and wallets should only display active sessions to users. ## WebSocket Connection Handling [#websocket-connection-handling] We've optimized the WebSocket connection management to improve performance and resource utilization. The SDK will now establish a WebSocket connection only when there's an explicit intention to send a request or subscribe to a topic. If none of these conditions are met, the WebSocket connection will remain closed by default. ### What's Changed? [#whats-changed] Previous Behavior: The SDK automatically initiated a WebSocket connection upon startup, regardless of active sessions or pending actions. New Behavior: The SDK delays establishing a WebSocket connection until it's necessary based on the app's activities. ### Why This Change? [#why-this-change] This adjustment reduces unnecessary network traffic and conserves device resources, leading to better performance and battery life, especially important for mobile applications. ### Impact on Your Application [#impact-on-your-application] Disconnected State on Launch: Apps without active sessions at launch will start with the WebSocket in a disconnected state. UI Elements Depending on WebSocket: Buttons or features that rely on an active WebSocket connection may not function until the connection is established. ### Steps for Migration [#steps-for-migration] Wallets are no longer expected to handle pairing-related methods. If your wallet has been listing pairings, please replace this with listing active sessions instead. # Upgrade from Web3Wallet to WalletKit for Flutter (/wallets/more/web3wallet-migration/flutter) ## Upgrade to WalletKit [#upgrade-to-walletkit] This document outlines the steps to migrate from the old `walletconnect_flutter_v2` package to the new `reown_walletkit` packages in your Flutter project. ### Step 1. Replace the corresponding dependency [#step-1-replace-the-corresponding-dependency] Remove `walletconnect_flutter_v2` dependency from pubspec.yaml and add `reown_walletkit`: ```dart /* highlight-delete-start */ walletconnect_flutter_v2: ^X.Y.Z /* highlight-delete-end */ /* highlight-add-start */ reown_walletkit: ^1.0.0 /* highlight-add-end */ ``` Run `flutter clean && flutter pub get` after replacing the packages Then replace the imports... ```dart /* highlight-delete-start */ import 'package:walletconnect_flutter_v2/walletconnect_flutter_v2.dart'; /* highlight-delete-end */ /* highlight-add-start */ import 'package:reown_walletkit/reown_walletkit.dart'; /* highlight-add-end */ ``` ### Step 2. Update main classes [#step-2-update-main-classes] | Old | New | | --- | --- | | `Web3Wallet` | `ReownWalletKit` | | `Core` | `ReownCore` | ### Step 3. Update error definitions [#step-3-update-error-definitions] ```tsx /* highlight-delete-start */ Errors.getSdkError(Errors.USER_REJECTED); /* highlight-delete-end */ /* highlight-add-start */ Errors.getSdkError(Errors.USER_REJECTED).toSignError(); /* highlight-add-end */ ``` ### Step 5. Update any exception type [#step-5-update-any-exception-type] | Old | New | | --- | --- | | `WalletConnectError` | `ReownSignError` | ### Final notes [#final-notes] - Ensure that you have updated all relevant configurations and imports in your project to reflect the changes from Web3Wallet to WalletKit. - Test your application thoroughly to ensure that the migration has been successful and that all functionality is working as expected. - Check our [WalletKit example for Flutter](https://github.com/reown-com/reown_flutter/tree/master/packages/reown_walletkit/example/) to compare with your implementation in case you are having issues # Upgrade from Web3Wallet to WalletKit for iOS (/wallets/more/web3wallet-migration/ios) ## Upgrade to WalletKit [#upgrade-to-walletkit] This upgrade guide helps developers transition from using the Web3Wallet library to the WalletKit within reown-swift. The guide involves updating import statements, modifying instance references, changing configuration methods, and updating repository URLs for CocoaPods and Swift Package Manager (SPM). ### Step 1. Update the Repository URL [#step-1-update-the-repository-url] The Web3Wallet library has been moved to a new repository under the reown-com organization. If you are using Swift Package Manager (SPM) to manage dependencies, update your Package.swift file to point to the new repository: ```swift /* highlight-delete-start */ - .package(url: "https://github.com/WalletConnect/WalletConnectSwiftV2", from: "1.0.0"), /* highlight-delete-end */ /* highlight-add-start */ + .package(url: "https://github.com/reown-com/reown-swift", from: "1.0.0"), /* highlight-add-end */ ``` ### Step 2. Update Imports in Your Code [#step-2-update-imports-in-your-code] All references to Web3Wallet in your import statements should be updated to use WalletKit. ```swift /* highlight-delete-start */ - import Web3Wallet /* highlight-delete-end */ /* highlight-add-start */ + import WalletKit /* highlight-add-end */ ``` ### Step 3. Update Instance Access and Method Calls [#step-3-update-instance-access-and-method-calls] The singleton instance access for Web3Wallet has been replaced with WalletKit. Update all instances where Web3Wallet.instance is used to WalletKit.instance. ```swift /* highlight-delete-start */ - Web3Wallet.instance.authRequestPublisher.sink { (id, result) in - // Your code here - } /* highlight-delete-end */ /* highlight-add-start */ + WalletKit.instance.authRequestPublisher.sink { (id, result) in + // Your code here + } /* highlight-add-end */ ``` ### Step 4. Update Configuration Method [#step-4-update-configuration-method] The configure method has been updated to reflect the new branding. Replace calls to Web3Wallet.configure with WalletKit.configure. ```swift /* highlight-delete-start */ - Web3Wallet.configure( - ... - ) /* highlight-delete-end */ /* highlight-add-start */ + WalletKit.configure( + ... + ) /* highlight-add-end */ ``` ### Step 5. Update CocoaPods Podspec [#step-5-update-cocoapods-podspec] If you are using CocoaPods to manage dependencies, update your Podfile to use the new library name. ```swift /* highlight-delete-start */ - pod 'Web3Wallet', '~> 1.0' /* highlight-delete-end */ /* highlight-add-start */ + pod 'WalletKit', '~> 1.0' /* highlight-add-end */ ``` ### Step 6. Test Your Changes [#step-6-test-your-changes] After updating all references to Web3Wallet to use WalletKit, thoroughly test your application to ensure that all functionalities work as expected. ## Pairing Expiry [#pairing-expiry] Currently, Dapps create a new pairing whenever the user selects the **"Connect Wallet"** button, instead of reusing existing pairings. Although pairings were not intended to be reused, they were being persisted for 30 days, causing unnecessary resource usage for both Dapps and wallet clients, including redundant socket connections. This led to an accumulation of stale pairings in wallets, resulting in degraded efficiency and increased resource consumption. To address this issue, we have introduced changes to how pairings are managed to ensure more efficient connection handling. Pairings were never intended to be listed in the wallet, and wallets should only display active sessions to users. ## WebSocket Connection Handling [#websocket-connection-handling] We've optimized the WebSocket connection management to improve performance and resource utilization. The SDK will now establish a WebSocket connection only when there's an explicit intention to send a request or subscribe to a topic. If none of these conditions are met, the WebSocket connection will remain closed by default. ### What's Changed? [#whats-changed] Previous Behavior: The SDK automatically initiated a WebSocket connection upon startup, regardless of active sessions or pending actions. New Behavior: The SDK delays establishing a WebSocket connection until it's necessary based on the app's activities. ### Why This Change? [#why-this-change] This adjustment reduces unnecessary network traffic and conserves device resources, leading to better performance and battery life, especially important for mobile applications. ### Impact on Your Application [#impact-on-your-application] Disconnected State on Launch: Apps without active sessions at launch will start with the WebSocket in a disconnected state. UI Elements Depending on WebSocket: Buttons or features that rely on an active WebSocket connection may not function until the connection is established. ### Steps for Migration [#steps-for-migration] Wallets are no longer expected to handle pairing-related methods. If your wallet has been listing pairings, please replace this with listing active sessions instead. # Upgrade from Web3Wallet to Reown WalletKit (/wallets/more/web3wallet-migration/quickstart) ## Upgrade Platform list [#upgrade-platform-list] } href="/wallets/more/web3wallet-migration/web"> Upgrade to WalletKit in Web. } href="/wallets/more/web3wallet-migration/react-native"> Upgrade to WalletKit in React Native. } href="/wallets/more/web3wallet-migration/flutter"> Upgrade to WalletKit in Flutter. } href="/wallets/more/web3wallet-migration/android"> Upgrade to WalletKit in Android. } href="/wallets/more/web3wallet-migration/ios"> Migrate to WalletKit in iOS. } href="/wallets/more/web3wallet-migration/unity"> Upgrade to WalletKit in .NET. # Upgrade from Web3Wallet to WalletKit for React Native (/wallets/more/web3wallet-migration/react-native) ## Upgrade to WalletKit [#upgrade-to-walletkit] This document outlines the steps to migrate from the old `@walletconnect/web3wallet` package to the new `@reown/walletkit` packages in your project. ### Step 1. Update your package.json [#step-1-update-your-packagejson] Replace your existing `@walletconnect/web3wallet` dependency with `@reown/walletkit`: ```json /* highlight-delete-start */ "@walletconnect/web3wallet": "^x.y.z" /* highlight-delete-end */ /* highlight-add-start */ "@reown/walletkit": "^1.0.0" /* highlight-add-end */ ``` ### Step 2. Install `@reown/walletkit` [#step-2-install-reownwalletkit] Run `npm install` (or your preferred package manager command) to install the new package. ### Step 3. Update your imports [#step-3-update-your-imports] Replace the imports in your project: ```javascript /* highlight-delete-start */ import { Web3Wallet } from "@walletconnect/web3wallet"; /* highlight-delete-end */ /* highlight-add-start */ import { WalletKit } from "@reown/walletkit"; /* highlight-add-end */ ``` and your initialization to use the new package: ```javascript /* highlight-delete-start */ await Web3Wallet.init() /* highlight-delete-end */ /* highlight-add-start */ await WalletKit.init() /* highlight-add-end */ ``` If you're using additional imports from `@walletconnect/web3wallet`, you can replace them with their corresponding version from `@reown/walletkit` such as: ```javascript /* highlight-delete-start */ import { IWeb3Wallet } from "@walletconnect/web3wallet"; /* highlight-delete-end */ /* highlight-add-start */ import { IWalletKit } from "@reown/walletkit"; /* highlight-add-end */ ``` ## You're all set! [#youre-all-set] ### Final Notes [#final-notes] + public API documentation can be found [here](/wallets/web/usage) + `auth_request` is deprecated in favor of `session_authenticate`. Docs can be found [here](/wallets/web/one-click-auth) # Upgrade from Web3Wallet to WalletKit for .NET (/wallets/more/web3wallet-migration/unity) ## Upgrade to WalletKit [#upgrade-to-walletkit] This document outlines the steps to migrate from the old `WalletConnect.Web3Wallet` package to the new `Reown.WalletKit` package in your .NET project. ### Step 1. Replace the corresponding dependency in your project file [#step-1-replace-the-corresponding-dependency-in-your-project-file] ```xml /* highlight-delete-start */ /* highlight-delete-end */ /* highlight-add-start */ /* highlight-add-end */ ``` Alternatively, you can use the .NET CLI: ```bash # Remove the old package dotnet remove package WalletConnect.Web3Wallet # Add the new package dotnet add package Reown.WalletKit ``` ### Step 2. Update references to the namespaces [#step-2-update-references-to-the-namespaces] | Old | New | | --- | --- | | `WalletConnectSharp.Web3Wallet` | `Reown.WalletKit` | | `WalletConnectSharp.Sign` | `Reown.Sign` | | `WalletConnectSharp.Core` | `Reown.Core` | | `WalletConnectSharp.Storage` | `Reown.Core.Storage` | | `WalletConnectSharp.Crypto` | `Reown.Core.Crypto` | | `WalletConnectSharp.Network` | `Reown.Core.Network` | ### Step 3. Update references to the classes [#step-3-update-references-to-the-classes] | Old | New | | --- | --- | | `WalletConnectCore` | `CoreClient` | | `WalletConnectSignClient` | `SignClient` | | `Web3WalletClient` | `WalletKitClient` | | `WCLogger` | `ReownLogger` | ### Final notes [#final-notes] - Ensure that you have updated all relevant configurations and imports in your project to reflect the changes from Web3Wallet to WalletKit. - Test your application thoroughly to ensure that the migration has been successful and that all functionality is working as expected. # Upgrade from Web3Wallet to WalletKit for Web (/wallets/more/web3wallet-migration/web) ## Upgrade to WalletKit [#upgrade-to-walletkit] This document outlines the steps to migrate from the old `@walletconnect/web3wallet` package to the new `@reown/walletkit` packages in your project. ### Step 1. Update your package.json [#step-1-update-your-packagejson] Replace your existing `@walletconnect/web3wallet` dependency with `@reown/walletkit`: ```json /* highlight-delete-start */ "@walletconnect/web3wallet": "^x.y.z" /* highlight-delete-end */ /* highlight-add-start */ "@reown/walletkit": "^1.0.0" /* highlight-add-end */ ``` ### Step 2. Install `@reown/walletkit` [#step-2-install-reownwalletkit] Run `npm install` (or your preferred package manager command) to install the new package. ### Step 3. Update your imports [#step-3-update-your-imports] Replace the imports in your project: ```javascript /* highlight-delete-start */ import { Web3Wallet } from "@walletconnect/web3wallet"; /* highlight-delete-end */ /* highlight-add-start */ import { WalletKit } from "@reown/walletkit"; /* highlight-add-end */ ``` and your initialization to use the new package: ```javascript /* highlight-delete-start */ await Web3Wallet.init() /* highlight-delete-end */ /* highlight-add-start */ await WalletKit.init() /* highlight-add-end */ ``` If you're using additional imports from `@walletconnect/web3wallet`, you can replace them with their corresponding version from `@reown/walletkit` such as: ```javascript /* highlight-delete-start */ import { IWeb3Wallet } from "@walletconnect/web3wallet"; /* highlight-delete-end */ /* highlight-add-start */ import { IWalletKit } from "@reown/walletkit"; /* highlight-add-end */ ``` ## You're all set! [#youre-all-set] ### Final Notes [#final-notes] + public API documentation can be found [here](/wallets/web/usage) + `auth_request` is deprecated in favor of `session_authenticate`. Docs can be found [here](/wallets/web/one-click-auth) # Best Practices (/wallets/react-native/best-practices) The purpose of this guide is to show the best practices in regards of the WalletKit client usage. The goal is to provide the best user experience that just works in every circumstances. In order to ensure the best user experience and flawless connection flow, please make sure that WalletKit is initialized immediately after your app launch, especially if launched via a WalletConnect Deep Link. It guarantees that websocket connection is opened immediately and all requests are received by your wallet ## Pairing [#pairing] A pairing is a connection between a wallet and a dapp that has fixed permissions to only allow a dapp to propose a session through it. Dapp can propose infinite number of sessions on one pairing. Wallet must use a pair method from the WalletKit client to pair with dapp. ```typescript const uri = 'xxx'; // pairing uri try { await walletKit.pair({ uri }); } catch (error) { // some error happens while pairing - check Expected errors section } ``` ### Pairing Expiry [#pairing-expiry] A pairing expiry event is triggered whenever a pairing is expired. The expiry for inactive pairing is 5 mins, whereas for active pairing is 30 days. A pairing becomes active when a session proposal is received and user successfully approves it. This event helps to know when given pairing expires and update UI accordingly. ```typescript core.pairing.events.on("pairing_expire", (event) => { // pairing expired before user approved/rejected a session proposal const { topic } = topic; }); ``` ### Expected User flow [#expected-user-flow] ### Pairing Flow [#pairing-flow] Wallet pairing with a dApp and showing the session proposal to approve or reject ### Pairing Error [#pairing-error] Wallet showing an error when pairing with a dApp fails ### Expected Errors [#expected-errors] While pairing the following errors might occur: - No Internet connection error or pairing timeout when scanning QR with no Internet connection - User should pair again with Internet connection - Pairing expired error when scanning a QR code with expired pairing - User should refresh a QR code and scan again - Pairing with existing pairing is not allowed - User should refresh a QR code and scan again. I usually happens when user scans an already paired QR code. ## Session Proposal [#session-proposal] A session proposal is a handshake sent by a dapp and it's purpose is to define a session rules. Whenever a user wants to establish a connection between a wallet and a dapp, one should approve a session proposal. ### User Action Feedback [#user-action-feedback] Whenever user approves or rejects a session proposal, wallet should show loading indicators in a moment of the button press until Relay acknowledgement is received for any of this actions. Approving session ```typescript try { await walletKit.approveSession(params); // update UI -> remove the loader } catch (error) { // present error to the user } ``` Rejecting session ```typescript try { await walletKit.rejectSession(params); // update UI -> remove the loader } catch (error) { // present error to the user } ``` ### Session Proposal Expiry [#session-proposal-expiry] A session proposal expiry is 5 mins. It means a given proposal is stored for 5 mins in the SDK storage and user has 5 mins for approval or rejection decision. After that time the below event is emitted and proposal modal should be removed from the app's UI. ```typescript walletKit.on("proposal_expire", (event) => { // proposal expired and any modal displaying it should be removed const { id } = event; }); ``` ### Expected User flow [#expected-user-flow-1] ### Approve or Reject Session Proposal [#approve-or-reject-session-proposal] Wallet pairing with a dApp and showing the session proposal to approve or reject ### Error Handling [#error-handling] Wallet showing an error while approving or rejecting a session proposal ### Expected Errors [#expected-errors-1] While approving or rejecting a session proposal the following errors might occurs: - No Internet connection - It happens when a user tries to approve or reject session proposal with no Internet connection - Session proposal expired - It happens when users tries to approve or reject expired session proposal - Invalid namespaces - It happens when a validation of session namespaces fails - Timeout - It happens when Relay doesn't acknowledge session settle publish within 10s ## Session Request [#session-request] A session request represents the request sent by a dapp to a wallet. ### User Action Feedback [#user-action-feedback-1] Whenever user approves or rejects a session request, wallet should show loading indicators in a moment of the button press until Relay acknowledgement is received for any of this actions. ```typescript try { await walletKit.respondSessionRequest(params); // update UI -> remove the loader } catch (error) { // present error to the user } ``` ### Session Request Expiry [#session-request-expiry] A session request expiry is defined by a dapp. It's value must be between now() + 5mins and now() + 7 days. After the session request expires the below event is emitted and session request modal should be removed from the app's UI. ```typescript walletKit.on("session_request_expire", (event) => { // request expired and any modal displaying it should be removed const { id } = event; }); ``` ### Expected User flow [#expected-user-flow-2] ### Approve or Reject Session Proposal [#approve-or-reject-session-proposal-1] Wallet showing a dApp signing request for the user to approve or reject ### Error Handling [#error-handling-1] Wallet showing an error while responding to a session request ### Expected Errors [#expected-errors-2] While approving or rejecting a session request the following error might occur: - Invalid session - This error might happen when user approves or rejects a session request on expired session - Session request expired - This error might happen when user approves or rejects a session request that already expires - Timeout - It happens when Relay doesn't acknowledge session settle publish within 10s ## Web Socket Connection State [#web-socket-connection-state] The Web Socket connection state tracks the connection with the relay server, event is emitted whenever a connection state changes. ```typescript core.relayer.on("relayer_connect", () => { // connection to the relay server is established }) core.relayer.on("relayer_disconnect", () => { // connection to the relay server is lost }) ``` ### Expected User flow [#expected-user-flow-3] ### Connection State [#connection-state] ![Wallet showing a no internet connection banner when the relay connection drops](/images/mintlify/assets/connection_state.gif) # Chain Abstraction (/wallets/react-native/chain-abstraction) ## Methods [#methods] The following methods from Wallet SDK are used in implementing chain abstraction. 💡 Chain abstraction is currently in the early access phase. Make sure you are using canary version of `@reown/walletkit` and `@walletconnect/react-native-compat` Following are the methods from WalletKit that you will use in implementing chain abstraction. ### Prepare [#prepare] This method checks if a transaction requires additional bridging transactions beforehand. ```typescript public abstract prepare(params: { transaction: ChainAbstractionTypes.PartialTransaction; }): ChainAbstractionTypes.PrepareResponse; ``` ### Execute [#execute] Helper method used to broadcast the bridging and initial transactions and wait for them to be completed. ```typescript public abstract execute(params: { orchestrationId: ChainAbstractionTypes.OrchestrationId; bridgeSignedTransactions: ChainAbstractionTypes.SignedTransaction[]; initialSignedTransaction: ChainAbstractionTypes.SignedTransaction; }): ChainAbstractionTypes.ExecuteResult; ``` ## Usage [#usage] When sending a transaction, first check if chain abstraction is needed using the `prepare` method. If it is needed, you must sign all the fulfillment transactions and use the `execute` method. Here's a complete example: ```typescript // Check if chain abstraction is needed const result = await walletKit.chainAbstraction.prepare({ transaction: { from: transaction.from as `0x${string}`, to: transaction.to as `0x${string}`, // @ts-ignore - cater for both input or data input: transaction.input || (transaction.data as `0x${string}`), chainId: chainId, }, }); // Handle the prepare result if ('success' in result) { if ('notRequired' in result.success) { // No bridging required, proceed with normal transaction console.log('no routing required'); } else if ('available' in result.success) { const available = result.success.available; // Sign all bridge transactions and initial transaction const bridgeTxs = available.route.map(tx => tx.transactionHashToSign); const signedBridgeTxs = bridgeTxs.map(tx => wallet.signAny(tx)); const signedInitialTx = wallet.signAny(available.initial.transactionHashToSign); // Execute the chain abstraction const result = await walletKit.chainAbstraction.execute({ bridgeSignedTransactions: signedBridgeTxs, initialSignedTransaction: signedInitialTx, orchestrationId: available.routeResponse.orchestrationId, }); } } ``` For example, check out implementation of chain abstraction in [sample wallet](https://github.com/reown-com/react-native-examples/tree/main/wallets/rn_cli_wallet) with React Native CLI. ## Testing [#testing] To test Chain Abstraction, you can use the [AppKit laboratory](https://lab.reown.com/appkit/?name=wagmi) and try sending any supported [tokens](/wallets/features/chain-abstraction#what-are-the-supported-tokens-and-networks) with any chain abstraction supported wallet. You can also use this [sample wallet](https://appdistribution.firebase.dev/i/076a3bc9669d3bee) for testing. # Analytics (/wallets/react-native/cloud/analytics) # Explorer Submission (/wallets/react-native/cloud/explorer-submission) # Relay (/wallets/react-native/cloud/relay) # Wallet Call API (/wallets/react-native/eip5792) WalletConnect supports [EIP-5792](https://eips.ethereum.org/EIPS/eip-5792#atomicbatch-capability), which defines new JSON-RPC methods that enable apps to ask a wallet to process a batch of onchain write calls and to check on the status of those calls. Applications can specify that these onchain calls be executed taking advantage of specific capabilities previously expressed by the wallet; an additional, a novel wallet RPC is defined to enable apps to query the wallet for those capabilities. - `wallet_sendCalls`: Requests that a wallet submits a batch of calls. - `wallet_getCallsStatus`: Returns the status of a call batch that was sent via wallet_sendCalls. - `wallet_showCallsStatus`: Requests that a wallet shows information about a given call bundle that was sent with wallet_sendCalls. - `wallet_getCapabilities`: This RPC allows an application to request capabilities from a wallet (e.g. batch transactions, paymaster communication). ## Usage [#usage] ## Capabilities in CAIP-25 Connection Requests [#capabilities-in-caip-25-connection-requests] CAIP-25 defines how capabilities can be expressed in wallet-to-dapp connections. These capabilities control how methods like `wallet_sendCalls` behave. ### Session Properties [#session-properties] In a connection request, dapps can request capabilities via `sessionProperties`. These can be universal (across all chains) or chain-specific: ```json "sessionProperties": { "expiry": "2022-12-24T17:07:31+00:00", "caip154": { "supported": "true" }, "flow-control": { "loose": [], "strict": [], "exoticThirdThing": [] }, "atomic": { "status": "supported" } } ``` ### Scoped Properties [#scoped-properties] For chain-specific capabilities, dapps use `scopedProperties`: ```json "scopedProperties": { "eip155:8453": { "paymasterService": { "supported": true }, "sessionKeys": { "supported": true } }, "eip155:84532": { "auxiliaryFunds": { "supported": true } } } ``` ### Wallet Response [#wallet-response] A wallet's response should indicate which capabilities it actually supports, following EIP-5792 and CAIP-25: ```json "sessionProperties": { "expiry": "2022-12-24T17:07:31+00:00", "caip154": { "supported": "true" }, "flow-control": { "loose": ["halt", "continue"], "strict": ["continue"] }, "atomic": { "status": "ready" } }, "scopedProperties": { "eip155:1": { "atomic": { "status": "supported" } }, "eip155:137": { "atomic": { "status": "unsupported" } }, "eip155:84532": { "eip155:83532:0x0910e12C68d02B561a34569E1367c9AAb42bd810": { "auxiliaryFunds": { "supported": false }, "atomic": { "status": "supported" } } } } ``` - Capabilities shared across all address in a namespace can be expressed at top-level - Address-specific capabilities can include exceptions to scope-wide capabilities ### Atomic Capability [#atomic-capability] According to EIP-5792, the `atomic` capability specifies how the wallet will execute batches of transactions. It has three possible values: - `supported` - The wallet will execute calls atomically and contiguously - `ready` - The wallet can upgrade to support atomic execution pending user approval - `unsupported` - The wallet provides no atomicity guarantees This capability is expressed per chain and is crucial for determining how `wallet_sendCalls` with `atomicRequired: true` will be handled. ### Example [#example] The `wallet_getCapabilities` method is used to request information about what capabilities a wallet supports. Following EIP-5792, here's how it should be implemented: #### Request [#request] ```json { "id": 1, "jsonrpc": "2.0", "method": "wallet_getCapabilities", "params": ["0xd46e8dd67c5d32be8058bb8eb970870f07244567", ["0x2105", "0x14A34"]] } ``` #### Response [#response] The wallet should return a response following EIP-5792, where capabilities are organized by chain ID: ```json { "id": 1, "jsonrpc": "2.0", "result": { "0x2105": { "atomic": { "status": "supported" } }, "0x14A34": { "atomic": { "status": "unsupported" } } } } ``` ### Implementation [#implementation] When implementing `wallet_sendCalls`, wallets must follow these requirements: #### Connection Approval [#connection-approval] - Only approve this method during the connection approval flow if your wallet can implement it correctly - Define the `atomic` capability per chain/account in the CAIP-25 response #### Request Format [#request-format] ```json { "id": 12345, "version": "2.0", "method": "wc_sessionRequest", "params": { "chainId": "caip-2-chain-id", "request": { "method": "wallet_sendCalls", "params": { "from": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "chainId": "0x01", "atomicRequired": true, "calls": [ { "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "value": "0x9184e72a", "data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675" }, { "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "value": "0x182183", "data": "0xfbadbaf01" } ] } } } } ``` #### Core Implementation Requirements [#core-implementation-requirements] - Execute calls in the exact order specified in the request - Do not wait for any calls to be finalized before completing the batch - If the user rejects the request, do not send any calls #### Atomic Execution Behavior [#atomic-execution-behavior] When `atomicRequired` is `true`: - Execute all calls atomically (either all succeed or none have any effect) - Execute all calls contiguously (no other transactions between batch calls) - If your wallet can upgrade from `ready` to `supported` atomicity, do so before executing When `atomicRequired` is `false`: - You may execute calls sequentially without atomicity guarantees - You may execute atomically if your wallet supports it - You may upgrade to `supported` atomicity and execute atomically #### Response Enrichment [#response-enrichment] To enhance the user experience and eliminate the need for app switching, wallets can enrich the wallet_sendCalls response with caip2 id and transactionHash to let the Universal Provider resolve the transaction hash. ```json { "id": "...", "capabilities": { "caip345": { "caip2": "eip155:1", "transactionHashes": ["..."], } } } ``` ### Example [#example-1] To enhance the user experience and eliminate the need for app switching, wallets can enrich the wallet_sendCalls response with caip2 id and transactionHash to let the Universal Provider resolve the transaction hash. To implement this functionality, the response for wallet_sendCalls should be enriched with capabilities: ```json { "id": "...", "capabilities": { "caip345": { "caip2": "eip155:1", "transactionHashes": ["..."], } } } ``` Specify the `scopedProperties` when approving a session: ```json "scopedProperties": { "eip155": { "walletService": [{ "url": "", "methods": ["wallet_getCallsStatus"] }] } } ``` ### Response Format [#response-format] The response format for `wallet_getCallsStatus` varies based on the execution method: #### For Atomic Execution [#for-atomic-execution] ```json { "receipts": [/* single receipt or array of receipts */], "atomic": true } ``` #### For Non-Atomic Execution [#for-non-atomic-execution] ```json { "receipts": [/* array of receipts for all transactions */], "atomic": false } ``` For non-atomic execution, include all transactions in the receipts array, even those that were included on-chain but eventually reverted. ## References [#references] - EIP-5792: https://eips.ethereum.org/EIPS/eip-5792#atomicbatch-capability - CAIP-25 namespaces: https://github.com/ChainAgnostic/namespaces/blob/main/eip155/caip25.md # Installation (/wallets/react-native/installation) Install the WalletKit package. ```sh yarn add @reown/walletkit @walletconnect/react-native-compat ``` Additionally add these extra packages to help with async storage, polyfills and the instance of ethers. ```sh yarn add @react-native-async-storage/async-storage @react-native-community/netinfo react-native-get-random-values fast-text-encoding ``` ```sh npx expo install expo-application ``` For those using Typescript, we recommend adding these dev dependencies: ```sh yarn add @walletconnect/jsonrpc-types --dev ``` ## Next Steps [#next-steps] Now that you've installed Wallet SDK, you're ready to start integrating it. The next section will walk you through the process of setting up your project to use the SDK. # Link Mode (/wallets/react-native/link-mode) Wallet SDK Link Mode is a low latency mechanism for transporting [One-Click Auth](/wallets/react-native/one-click-auth) requests and session requests over Universal Links, reducing the need for a WebSocket connection with the Relay. This significantly enhances the user experience when connecting native dApps to native wallets by reducing the latency associated with network connections, especially when the user has an unstable internet connection. Make sure that [One-Click Auth](/wallets/react-native/one-click-auth) is implemented before enabling Link Mode. ### How to enable it: [#how-to-enable-it] To support Link Mode add a universal link for your wallet in Cloud project configuration [dashboard](https://dashboard.walletconnect.com/sign-in), configure your Metadata with a valid universal link and set the `linkMode` property to `true`: ```ts const walletKit = await WalletKit.init({ core, metadata: { name: "Demo React Native Wallet", description: "Demo RN Wallet to interface with Dapps", url: "www.reown.com/walletkit", icons: ["https://your_wallet_icon.png"], redirect: { native: "yourwalletscheme://", universal: "https://example.com/example_wallet", linkMode: true, }, }, }); ``` ### Platform specifics: [#platform-specifics] To enable universal links for your app, refer to [React Native Documentation](https://reactnative.dev/docs/linking?syntax=ios#enabling-deep-links).
After following the steps provided in the official guide: 1. Ensure that you handle incoming Universal Links in the your `AppDelegate.mm` file. ```swift #import // Enable deeplinks - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary *)options { return [RCTLinkingManager application:application openURL:url options:options]; } // Enable Universal Links - (BOOL)application:(UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity restorationHandler:(nonnull void (^)(NSArray> * _Nullable))restorationHandler { return [RCTLinkingManager application:application continueUserActivity:userActivity restorationHandler:restorationHandler]; } ``` 2. Open your project in XCode and go to `Settings/Signing & Capabilities/Associated Domains` to add the new domain. After this, `your_project.entitlement` should look like this: ```xml com.apple.developer.associated-domains applinks:example.com ``` 3. Update/Create your domain's `.well-known/apple-app-site-association` file accordingly. For more information about supporting universal links, visit the [Supporting associated domains](https://developer.apple.com/documentation/xcode/supporting-associated-domains?language=objc) page For a debugging guide, visit the [Debugging Universal Links](https://developer.apple.com/documentation/technotes/tn3155-debugging-universal-links) page.
Android Studio provides a tool to configure Universal Links easily, you can read the guide in [Android Documentation](https://developer.android.com/studio/write/app-link-indexing) After following the steps provided in the guide: 1. Ensure that your Universal Link is properly configured in your app's `AndroidManifest.xml` file with the `autoVerify` set to `true`. It should look similar to this: ```xml ``` 2. Update/Create your domains's `.well-known/assetlinks.json` file accordingly For more information on how to configure universal links for your app, refer to [Android Documentation](https://developer.android.com/studio/write/app-link-indexing).
For testing the configured universal link to app content check [this](https://developer.android.com/training/app-links/deep-linking#testing-filters) documentation page.
Once everything is properly configured, and the user interacts with a Link Mode-supporting dApp, your wallet will receive requests through it. # Mobile Linking (/wallets/react-native/mobile-linking) This feature is only relevant to native platforms. ## Usage [#usage] Mobile Linking allows your wallet to automatically redirect back to the Dapp allowing for less user interactions and hence a better UX for your users. ### Establishing Communication Between Mobile Wallets and Apps [#establishing-communication-between-mobile-wallets-and-apps] When integrating a wallet with a mobile application, it's essential to understand how they communicate. The process involves two main steps: 1. **QR Code Handshake:** The mobile app (Dapp) generates a unique URI (Uniform Resource Identifier) and displays it as a QR code. This URI acts like a secret handshake. When the user scans the QR code using their wallet app, they establish a connection. It's like saying, "Hey, let's chat!" 2. **Deep Links and Universal Links:** The URI from the QR code allows the wallet app to create a [deep link](https://support.google.com/google-ads/answer/10023042?hl=en#:~:text=Deep%20links%20send%20mobile%20device,%2C%20Shopping%2C%20and%20Display%20campaigns.) or [universal link](https://developer.apple.com/ios/universal-links/). These links work on both Android and iOS. They enable seamless communication between the wallet and the app. **Developers should prefer Deep Linking over Universal Linking.** Universal Linking may redirect the user to a browser, which might not provide the intended user experience. Deep Linking ensures the user is taken directly to the app. ### Key Behavior to Address [#key-behavior-to-address] In some scenarios, wallets use redirect metadata provided in session proposals to open applications. This can cause unintended behavior, such as: Redirecting to the wrong app when multiple apps share the same redirect metadata (e.g., a desktop and mobile version of the same Dapp). Opening an unrelated application if a QR code is scanned on a different device than where the wallet is installed. #### Recommended Approach [#recommended-approach] To avoid this behavior, wallets should: - **Restrict Redirect Metadata to Deep Link Use Cases**: Redirect metadata should only be used when the session proposal is initiated through a deep link. QR code scans should not trigger app redirects using session proposal metadata. The connection and sign request flows are similar across platforms. ### Connection Flow [#connection-flow] - **Dapp Prompts User:** The Dapp asks the user to connect. - **User Chooses Wallet:** The user selects a wallet from a list of compatible wallets. - **Redirect to Wallet:** The user is redirected to their chosen wallet. - **Wallet Approval:** The wallet prompts the user to approve or reject the session (similar to granting permission). - **Return to Dapp:** - **Manual Return:** The wallet asks the user to manually return to the Dapp. - **Automatic Return:** Alternatively, the wallet automatically takes the user back to the Dapp. - **User Reunites with Dapp:** After all the interactions, the user ends up back in the Dapp. Mobile Linking Connect Flow Mobile Linking Connect Flow ### Sign Request Flow [#sign-request-flow] When the Dapp needs the user to sign something (like a transaction), a similar pattern occurs: - **Automatic Redirect:** The Dapp automatically sends the user to their previously chosen wallet. - **Approval Prompt:** The wallet asks the user to approve or reject the request. - **Return to Dapp:** - **Manual Return:** The wallet asks the user to manually return to the Dapp. - **Automatic Return:** Alternatively, the wallet automatically takes the user back to the Dapp. - **User Reconnects:** Eventually, the user returns to the Dapp. Mobile Linking Connect Flow Mobile Linking Connect Flow ## Platform preparations [#platform-preparations] Since React Native leverages on native APIs, you must follow iOS and Android steps for each native platform More information in official documentation: https://reactnative.dev/docs/linking?syntax=android#enabling-deep-links Dapps developers must do the same for their own custom schemes if they want the wallet to be able to navigate back after a session approval or a sign request response ## Integration [#integration] In order to redirect to the Dapp, you'll need to use `Linking` from `react-native` and call `openURL()` method with the Dapp scheme that comes in the proposal metadata. ```js import { Linking } from "react-native"; async function onApprove(proposal, namespaces) { const session = await walletKit.approveSession({ id: proposal.id, namespaces, }); const dappScheme = session.peer.metadata.redirect?.native; if (dappScheme) { Linking.openURL(dappScheme); } else { // Inform the user to manually return to the DApp } } ``` # One-click Auth (/wallets/react-native/one-click-auth) ## Introduction [#introduction] This section outlines an innovative protocol method that facilitates the initiation of a Sign session and the authentication of a wallet through a [Sign-In with Ethereum](https://eips.ethereum.org/EIPS/eip-4361) (SIWE) message, enhanced by [ReCaps](https://eips.ethereum.org/EIPS/eip-5573) (ReCap Capabilities). This enhancement not only offers immediate authentication for dApps, paving the way for prompt user logins, but also integrates informed consent for authorization. Through this mechanism, dApps can request the delegation of specific capabilities to perform actions on behalf of the wallet user. These capabilities, encapsulated within SIWE messages as ReCap URIs, detail the scope of actions authorized by the user in an explicit and human-readable form. By incorporating ReCaps, this method extends the utility of SIWE messages, allowing dApps to combine authentication with a nuanced authorization model. This model specifies the actions a dApp is authorized to execute on the user's behalf, enhancing security and user autonomy by providing clear consent for each delegated capability. As a result, dApps can utilize these consent-backed messages to perform predetermined actions, significantly enriching the interaction between dApps, wallets, and users within the Ethereum ecosystem. Mobile Linking Connect Flow Mobile Linking Connect Flow ## Handling Authentication Requests [#handling-authentication-requests] To handle incoming authentication requests, subscribe to the `session_authenticate` event. This will notify you of any authentication requests that need to be processed, allowing you to either approve or reject them based on your application logic. ```typescript walletKit.on("session_authenticate", async (payload) => { // Process the authentication request here. // Steps include: // 1. Populate the authentication payload with the supported chains and methods // 2. Format the authentication message using the payload and the user's account // 3. Present the authentication message to the user // 4. Sign the authentication message(s) to create a verifiable authentication object(s) // 5. Approve the authentication request with the authentication object(s) }); ``` ## Authentication Payload [#authentication-payload] ```typescript import { populateAuthPayload } from "@walletconnect/utils"; // EVM chains that your wallet supports const supportedChains = ["eip155:1", "eip155:2", 'eip155:137']; // EVM methods that your wallet supports const supportedMethods = ["personal_sign", "eth_sendTransaction", "eth_signTypedData"]; // Populate the authentication payload with the supported chains and methods const authPayload = populateAuthPayload({ authPayload: payload.params.authPayload, chains: supportedChains, methods: supportedMethods, }); // Prepare the user's address in CAIP10(https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-10.md) format const iss = `eip155:1:0x0Df6d2a56F90e8592B4FfEd587dB3D5F5ED9d6ef`; // Now you can use the authPayload to format the authentication message const message = walletKit.formatAuthMessage({ request: authPayload, iss }); // Present the authentication message to the user ... ``` ## Approving Authentication Requests [#approving-authentication-requests] 1. The recommended approach for secure authentication across multiple chains involves signing a SIWE (Sign-In with Ethereum) message for each chain and account. However, at a minimum, one SIWE message must be signed to establish a session. It is possible to create a session for multiple chains with just one issued authentication object. 2. Sometimes a dapp may want to only authenticate the user without creating a session, not every approval will result with a new session. ```typescript // Approach 1 // Sign the authentication message(s) to create a verifiable authentication object(s) const signature = await cryptoWallet.signMessage(message, privateKey); // Build the authentication object(s) const auth = buildAuthObject( authPayload, { t: "eip191", s: signature, }, iss ); // Approve await walletKit.approveSessionAuthenticate({ id: payload.id, auths: [auth], }); // Approach 2 // Note that you can also sign multiple messages for every requested chain/address pair const auths = []; authPayload.chains.forEach(async (chain) => { const message = walletKit.formatAuthMessage({ request: authPayload, iss: `${chain}:${cryptoWallet.address}`, }); const signature = await cryptoWallet.signMessage(message); const auth = buildAuthObject( authPayload, { t: "eip191", // signature type s: signature, }, `${chain}:${cryptoWallet.address}` ); auths.push(auth); }); // Approve await walletKit.approveSessionAuthenticate({ id: payload.id, auths, }); ``` ## Rejecting Authentication Requests [#rejecting-authentication-requests] If the authentication request cannot be approved or if the user chooses to reject it, use the rejectSession method. ```typescript import { getSdkError } from "@walletconnect/utils"; await walletKit.rejectSessionAuthenticate({ id: payload.id, reason: getSdkError("USER_REJECTED"), // or choose a different reason if applicable }); ``` ## Testing One-click Auth [#testing-one-click-auth] You can use [AppKit Labs](https://lab.reown.com/appkit/?name=siwx-ethers) to test and verify that your wallet supports One-click Auth properly. # Resources (/wallets/react-native/resources) Valuable assets for developers and users interested in integrating Wallet SDK into their applications. - [Awesome WalletConnect](https://github.com/WalletConnect/awesome-walletconnect) - Community-curated collection of WalletConnect-enabled wallets, libraries, and tools. - [AppKit Laboratory](https://lab.reown.com/) - A place to test your wallet integrations against various setups of AppKit. - [Wallet SDK React Native GitHub](https://github.com/WalletConnect/walletconnect-monorepo/tree/v2.0/packages/web3wallet) - Wallet SDK React Native GitHub repository. ### Wallet Resources [#wallet-resources] [Wallet SDK](https://medium.com/walletconnect/simplifying-integration-for-wallet-developers-with-the-new-web3wallet-sdk-8706b69e149c) simplifies the integration process for wallet developers by combining our Sign and Auth APIs. Please note that only V2 [WCURIs](https://specs.walletconnect.com/2.0/specs/clients/core/pairing/pairing-uri) will work with this SDK, as V1 is being deprecated by June 28th, 2023. #### Expo [#expo] Experimental: For Expo, we have an unofficial npx starter command. `newWallet` represents the name of your project. ```bash npx create-wc-wallet-expo@latest newWallet ``` This downloads an Expo template with Wallet SDK installed. More information available in this [tutorial](https://medium.com/walletconnect/how-to-build-a-wallet-in-react-native-with-the-web3wallet-sdk-b6f57bf02f9a) ### Dapp Resources [#dapp-resources] If you need to test your app's integration, you can use one of our following demo wallets and/or dapps. **Sign** - [React dApp (with standalone client) - v2](https://github.com/WalletConnect/web-examples/tree/main/advanced/dapps/react-dapp-v2) ([Demo](https://react-app.walletconnect.com/)) # Usage (/wallets/react-native/usage) This section provides instructions on how to initialize the WalletKit client, approve sessions with supported namespaces, and respond to session requests, enabling easy integration of Web3 wallets with dapps through a simple and intuitive interface. ## Cloud Configuration [#cloud-configuration] Create a new project on WalletConnect Dashboard at https://dashboard.walletconnect.com and obtain a new project ID. ## Initialization [#initialization] `@walletconnect/react-native-compat` must be installed and imported before any `@reown/*` dependencies for proper React Native polyfills. ```ts import "@walletconnect/react-native-compat"; // Other imports ``` Create a new instance from `Core` and initialize it with your `projectId`. Next, create a WalletKit instance by calling `init` on `WalletKit`. Passing in the options object containing metadata about the app. The `pair` function will help us pair between the dapp and wallet and will be used shortly. ```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 React Native Wallet", description: "Demo RN Wallet to interface with Dapps", url: "www.walletconnect.com", icons: ["https://your_wallet_icon.png"], redirect: { native: "yourwalletscheme://", }, }, }); ``` ### Core Instance Sharing [#core-instance-sharing] Starting from newer versions of WalletKit, Core instances are shared globally by default to optimize resource usage. This means that multiple Core instances with the same configuration will reuse the same underlying Core. **For parallel testing scenarios** where you need isolated Core instances, you have two options: #### Option 1: Use customStoragePrefix [#option-1-use-customstorageprefix] ```javascript const core = new Core({ projectId: process.env.PROJECT_ID, customStoragePrefix: `test-${Date.now()}`, // Unique prefix for each test }); ``` Don't use randomly generated `customStoragePrefix` in production - this will cause the client to create new storage each time it is initialized. The client will not be able to persist/read existing data and all existing sessions will be lost after each reload. #### Option 2: Disable global Core sharing [#option-2-disable-global-core-sharing] ```javascript // Set environment variable before initializing Core process.env.DISABLE_GLOBAL_CORE = "true"; const core = new Core({ projectId: process.env.PROJECT_ID, }); ``` The global Core sharing behavior was introduced to prevent resource waste when multiple SDK instances are created. If you're running parallel tests and experiencing cross-test interference, use one of the solutions above to ensure proper test isolation. ## Session [#session] A session is a connection between a dapp and a wallet. It is established when a user approves a session proposal from a dapp. A session is active until the user disconnects from the dapp or the session expires. ### Namespace Builder [#namespace-builder] With WalletKit (and @walletconnect/utils) we've published a helper utility that greatly reduces the complexity of parsing the `required` and `optional` namespaces. It accepts as parameters a `session proposal` along with your user's `chains/methods/events/accounts` and returns ready-to-use `namespaces` object. ```javascript // util params { proposal: ProposalTypes.Struct; // the proposal received by `.on("session_proposal")` supportedNamespaces: Record< // your Wallet's supported namespaces string, // the supported namespace key e.g. eip155 { chains: string[]; // your supported chains in CAIP-2 format e.g. ["eip155:1", "eip155:2", ...] methods: string[]; // your supported methods e.g. ["personal_sign", "eth_sendTransaction"] events: string[]; // your supported events e.g. ["chainChanged", "accountsChanged"] accounts: string[] // your user's accounts in CAIP-10 format e.g. ["eip155:1:0x453d506b1543dcA64f57Ce6e7Bb048466e85e228"] } >; }; ``` Example usage ```javascript // import the builder util import { WalletKit, WalletKitTypes } from '@reown/walletkit' import { buildApprovedNamespaces, getSdkError } from '@walletconnect/utils' async function onSessionProposal({ id, params }: WalletKitTypes.SessionProposal){ try{ // ------- namespaces builder util ------------ // const approvedNamespaces = buildApprovedNamespaces({ proposal: params, supportedNamespaces: { eip155: { chains: ['eip155:1', 'eip155:137'], methods: ['eth_sendTransaction', 'personal_sign'], events: ['accountsChanged', 'chainChanged'], accounts: [ 'eip155:1:0xab16a96d359ec26a11e2c2b3d8f8b8942d5bfcdb', 'eip155:137:0xab16a96d359ec26a11e2c2b3d8f8b8942d5bfcdb' ] } } }) // ------- end namespaces builder util ------------ // const session = await walletKit.approveSession({ id, namespaces: approvedNamespaces }) }catch(error){ // use the error.message to show toast/info-box letting the user know that the connection attempt was unsuccessful .... await walletKit.rejectSession({ id: proposal.id, reason: getSdkError("USER_REJECTED") }) } } walletKit.on('session_proposal', onSessionProposal) ``` If your wallet supports multiple namespaces e.g. `eip155`,`cosmos` & `near` Your `supportedNamespaces` should look like the following example. ```javascript // ------- namespaces builder util ------------ // const approvedNamespaces = buildApprovedNamespaces({ proposal: params, supportedNamespaces: { eip155: {...}, cosmos: {...}, near: {...} }, }); // ------- end namespaces builder util ------------ // ``` ### Get Active Sessions [#get-active-sessions] You can get the wallet active sessions using the `getActiveSessions` function. ```js const activeSessions = walletKit.getActiveSessions(); ``` ### EVM methods & events [#evm-methods--events] In @walletconnect/ethereum-provider, (our abstracted EVM SDK for apps) we support by default the following Ethereum methods and events: ```ts { //... methods: [ "eth_accounts", "eth_requestAccounts", "eth_sendRawTransaction", "eth_sign", "eth_signTransaction", "eth_signTypedData", "eth_signTypedData_v3", "eth_signTypedData_v4", "eth_sendTransaction", "personal_sign", "wallet_switchEthereumChain", "wallet_addEthereumChain", "wallet_getPermissions", "wallet_requestPermissions", "wallet_registerOnboarding", "wallet_watchAsset", "wallet_scanQRCode", "wallet_sendCalls", "wallet_getCallsStatus", "wallet_showCallsStatus", "wallet_getCapabilities", ], events: [ "chainChanged", "accountsChanged", "message", "disconnect", "connect", ] } ``` ### Session Approval [#session-approval] In order to connect with a dapp, you will need to receive a WalletConnect URI (WCURI) and this will talk to our protocol to facilitate a pairing session. Therefore, you will need a test dapp in order to communicate with the wallet. We recommend testing with our [React V2 Dapp](https://react-app.walletconnect.com/) as this is the most up-to-date development site. In order to capture the WCURI, recommend having some sort of state management you will pass through a `TextInput` or QRcode instance. The `session_proposal` event is emitted when a dapp initiates a new session with a user's wallet. The event will include a `proposal` object with information about the dapp and requested permissions. The wallet should display a prompt for the user to approve or reject the session. If approved, call `approveSession` and pass in the `proposal.id` and requested `namespaces`. The `pair` method initiates a WalletConnect pairing process with a dapp using the given `uri` (QR code from the dapps). To learn more about pairing, checkout out the [docs](https://specs.walletconnect.com/2.0/specs/clients/core/pairing/). ```javascript import { getSdkError } from "@walletconnect/utils"; // Approval: Using this listener for sessionProposal, you can accept the session walletKit.on("session_proposal", async (proposal) => { const session = await walletKit.approveSession({ id: proposal.id, namespaces, }); }); // Call this after WCURI is received await walletKit.pair({ uri: wcuri }); ``` ### Session Rejection [#session-rejection] You can use the `getSDKError` function, which is available in the `@walletconnect/utils` for the rejection function [library](https://github.com/WalletConnect/walletconnect-monorepo/tree/v2.0/packages/utils). ```javascript import { getSdkError } from "@walletconnect/utils"; // Reject: Using this listener for sessionProposal, you can reject the session walletKit.on("session_proposal", async (proposal) => { await walletKit.rejectSession({ id: proposal.id, reason: getSdkError("USER_REJECTED_METHODS"), }); }); ``` ### Responding to Session requests [#responding-to-session-requests]
![Sample dApp connected to a wallet, listing accounts and signing methods for each chain](/images/mintlify/assets/SessionRequestExample.png)
session-request-example
The `session_request` event is triggered by a dapp when it needs the wallet to perform a specific action, such as signing a transaction. The event contains a `topic` and a `request` object, which will vary depending on the action requested. To respond to the request, the wallet can access the `topic` and `request` object by destructuring them from the event payload. To see a list of possible `request` and `response` objects, refer to the relevant JSON-RPC Methods for [Ethereum](https://docs.reown.com/advanced/multichain/rpc-reference/ethereum-rpc), [Solana](https://docs.reown.com/advanced/multichain/rpc-reference/solana-rpc), [Cosmos](https://docs.reown.com/advanced/multichain/rpc-reference/cosmos-rpc), or [Stellar](https://docs.reown.com/advanced/multichain/rpc-reference/stellar-rpc). As an example, if the dapp requests a `personal_sign` method, the wallet can extract the `params` array from the `request` object. The first item in the array is the hex version of the message to be signed, which can be converted to UTF-8 and assigned to a `message` variable. The second item in `params` is the user's wallet address. To sign the message, the wallet can use the `wallet.signMessage` method and pass in the message. The signed message, along with the `id` from the event payload, can then be used to create a `response` object, which can be passed into `respondSessionRequest`. The wallet then signs the message. `signedMessage`, along with the `id` from the event payload, can then be used to create a `response` object, which can be passed into `respondSessionRequest`. ```javascript walletKit.on("session_request", async (event) => { const { topic, params, id } = event; const { request } = params; const requestParamsMessage = request.params[0]; // convert `requestParamsMessage` by using a method like hexToUtf8 const message = hexToUtf8(requestParamsMessage); // sign the message const signedMessage = await wallet.signMessage(message); const response = { id, result: signedMessage, jsonrpc: "2.0" }; await walletKit.respondSessionRequest({ topic, response }); }); ``` To reject a session request, the response should be similar to this. ```javascript const response = { id, jsonrpc: "2.0", error: { code: 5000, message: "User rejected.", }, }; ``` ### Updating a Session [#updating-a-session] The `session_update` event is emitted from the wallet when the session is updated by calling `updateSession`. To update a session, pass in the [topic](https://docs.reown.com/advanced/glossary#topics) and the new namespace. ```javascript await walletKit.updateSession({ topic, namespaces: newNs }); ``` ### Extending a Session [#extending-a-session] To extend the session, call the `extendSession` method and pass in the new `topic`. The `session_update` event will be emitted from the wallet. ```javascript await walletKit.extendSession({ topic }); ``` ### Session Disconnect [#session-disconnect] When either the dapp or the wallet disconnects from a session, a `session_delete` event will be emitted. It's important to subscribe to this event so you could keep your state up-to-date. To initiate a session disconnect, call the `disconnectSession` method and pass in the `topic` and `reason`. You can use the `getSDKError` utility function, which is available in the `@walletconnect/utils` [library](https://github.com/WalletConnect/walletconnect-monorepo/tree/v2.0/packages/utils). ```javascript await walletKit.disconnectSession({ topic, reason: getSdkError("USER_DISCONNECTED"), }); ``` ### Emitting Session Events [#emitting-session-events] To emit session events, call the `emitSessionEvent` and pass in the params. If you wish to switch to chain/account that is not approved (missing from `session.namespaces`) you will have to update the session first. In the following example, the wallet will emit `session_event` that will instruct the dapp to switch the active accounts. ```javascript await walletKit.emitSessionEvent({ topic, event: { name: "accountsChanged", data: ["0xab16a96D359eC26a11e2C2b3d8f8B8942d5Bfcdb"], }, chainId: "eip155:1", }); ``` In the following example, the wallet will emit `session_event` when the wallet switches chains. ```javascript await walletKit.emitSessionEvent({ topic, event: { name: "chainChanged", data: 1, }, chainId: "eip155:1", }); ``` # Verify API (/wallets/react-native/verify) Verify API is a security-focused feature that allows wallets to notify end-users when they may be connecting to a suspicious or malicious domain, helping to prevent phishing attacks across the industry. Once a wallet knows whether an end-user is on uniswap.com or eviluniswap.com, it can help them to detect potentially harmful connections through Verify's combined offering of WalletConnect's domain registry. When a user initiates a connection with an application, Verify API enables wallets to present their users with four key states that can help them determine whether the domain they’re about to connect to might be malicious. These are:
![Wallet connection requests showing the Verify states domain match, unverified, mismatch and threat](/images/mintlify/verify-banner.png)
Verify Banner
## Disclaimer [#disclaimer] Verify API helps wallets detect suspicious or malicious domains, but it may not catch every threat. Use it as one more layer of protection alongside your wallet's other security measures. ## Domain risk detection [#domain-risk-detection] The Verify security system will discriminate session proposals & session requests with distinct validations that can be either `VALID`, `INVALID` or `UNKNOWN`. - Domain match: The domain linked to this request has been verified as this application's domain. - This interface appears when the domain a user is attempting to connect to has been ‘verified’ in our domain registry as the registered domain of the application the user is trying to connect to, and the domain has not returned as suspicious from either of the security tools we work with. The `verifyContext` included in the request will have a validation of `VALID`. - Unverified: The domain sending the request cannot be verified. - This interface appears when the domain a user is attempting to connect to has not been verified in our domain registry, but the domain has not returned as suspicious from either of the security tools we work with. The `verifyContext` included in the request will have a validation of `UNKNOWN`. - Mismatch: The application's domain doesn't match the sender of this request. - This interface appears when the domain a user is attempting to connect to has been flagged as a different domain to the one this application has verified in our domain registry, but the domain has not returned as suspicious from either of the security tools we work with. The `verifyContext` included in the request will have a validation of `INVALID` - Threat: This domain is flagged as malicious and potentially harmful. - This interface appears when the domain a user is attempting to connect to has been flagged as malicious on one or more of the security tools we work with. The `verifyContext` included in the request will contain parameter `isScam` with value `true`. ### Reading `verifyContext` by connection type [#reading-verifycontext-by-connection-type] How your wallet should read `verifyContext` depends on how the dApp connects: - **Web dApp over QR code or deep link (relay):** This is the full Verify API, including scam checks. Show all four states: `VALID` as Domain match, `UNKNOWN` as Cannot verify, `INVALID` as Mismatch, and `isScam` as Security risk (ideally blocking or requiring the user to confirm). - **Native dApp over relay:** Native apps can't create a Verify attestation, so `UNKNOWN` is expected here. We suggest a neutral "Cannot verify" label rather than an alarming warning. - **[Link Mode](/wallets/react-native/link-mode) (native to native):** The domain check above applies, with no scam check. `INVALID` means the dApp's universal link domain doesn't match its `metadata.url`. The wallet's own Link Mode setup also needs to be complete, or the result falls back to `INVALID`. ### Implementation [#implementation] Every `session_proposal`, `session_authenticate` and `session_request` event includes a `verifyContext`. Map it to one of the four states once, then use that state in each handler. ```javascript function getVerifyState(verifyContext) { const { validation, isScam } = verifyContext.verified // Threat: only set over relay, since Link Mode has no scam check if (isScam) return "THREAT" switch (validation) { case "VALID": return "DOMAIN_MATCH" case "INVALID": return "MISMATCH" default: // UNKNOWN: expected for native dApps over relay. Link Mode never returns UNKNOWN return "UNVERIFIED" } } // Session proposals always arrive over relay, from a web or native dApp walletKit.on("session_proposal", async (proposal) => { const state = getVerifyState(proposal.verifyContext) // show the state on the approval screen }) // One-click auth requests can arrive over relay or Link Mode walletKit.on("session_authenticate", async (payload) => { const state = getVerifyState(payload.verifyContext) const isLinkMode = payload.transportType === "link_mode" // in Link Mode, MISMATCH means the universal link domain doesn't match metadata.url }) // Session requests: read the transport from the session they belong to walletKit.on("session_request", async (request) => { const state = getVerifyState(request.verifyContext) const { transportType } = walletKit.getActiveSessions()[request.topic] // show the state on the signing screen }) ``` Present each state like this: - `THREAT`: Block the request, or require the user to explicitly accept the risk. Check before anything else, so the user doesn't also see a Mismatch warning. - `MISMATCH`: Show a warning and proceed only if the user accepts the risk. - `UNVERIFIED`: Show a neutral "Cannot verify" label. Don't block the request, since native dApps over relay always land here. - `DOMAIN_MATCH`: Show a verified badge and proceed as normal. For live demo examples of the intended Verify API flows, check out our demo apps: - [Demo Web Wallet](https://react-wallet.walletconnect.com) - [Demo React Native Wallet](https://github.com/WalletConnect/react-native-examples/tree/main/wallets/rn_cli_wallet) - [Demo App](https://react-app.walletconnect.com/) - you can toggle between the verify states by clicking on the `gear` & selecting the decided Validation before connecting to the wallet - [Demo Malicious App](https://malicious-app-verify-simulation.vercel.app/) - this app is flagged as malicious and will have the `isScam` parameter set to `true` in the `verifyContext` of the request # WalletConnect Certified (/wallets/walletguide/certified) WalletConnect Certified is a program to improve onchain connectivity together with the wallet ecosystem. It recognizes wallets that meet the highest standards for reliability, usability, security, and interoperability on the WalletConnect Network. To date, 32 wallets have been certified. Find them all on [WalletGuide](https://walletguide.walletconnect.network/?badge_type=certified). ## Why get certified [#why-get-certified] Certified wallets benefit from: - **Trust and visibility** — a WalletConnect Certified badge, shown when users open the connection modal to access an app, a listing on WalletGuide, and co-marketing opportunities with the WalletConnect brand. - **Higher rank in the wallet list** — certified wallets appear before non-certified wallets in the wallet list shown when users connect via WalletConnect. - **Improved analytics** — data on how a wallet's users are connecting via the WalletConnect Network, in a dedicated dashboard for certified wallets. - **New revenue streams** — access to rewards and incentives, including $WCT token rewards, interchange fees, and revenue-generating programs exclusive to certified wallets. ## How the program works [#how-the-program-works] The program runs in seasons, each with its own theme and progressively higher requirements. Each season builds on the last: certification requires meeting the criteria for every season up to the current one. | Season | Theme | Status | | --- | --- | --- | | Season 1 (2024) | "It just works" — foundational reliability | Complete | | Season 2 (2025) | UX excellence | Complete | | Season 3 (2026) | Payments | Open (Jan 21, 2026 – end of 2026) | Requirements are set by WalletConnect in collaboration with the [WalletConnect Council](https://walletconnect.com/blog/the-walletconnect-council), which represents leading projects across the ecosystem. The Season 2 requirements, for example, came out of a workshop with wallets at WalletCon II in Bangkok. ## Eligibility [#eligibility] Certification is high-touch and collaborative, so only a limited number of wallets are certified per season. To be eligible, a wallet must meet at least one of the following: 1. **Top 40 wallet** by number of WalletConnect connections. 2. **Demonstrated growth potential** — a credible path to becoming top 40. 3. **High transaction volume** — for example, institutional-grade wallets. Not sure a wallet qualifies? [Reach out](https://share.hsforms.com/1Q12irNdNRo2HJe3Jl1OJiAnxw6s) to evaluate eligibility. ## Criteria by season [#criteria-by-season] ### Season 1 — "It just works" [#season-1--it-just-works] The foundation: connecting a wallet to apps through WalletConnect works reliably, every time. Wallets integrate the WalletKit SDK and prove that connecting, switching chains and accounts, disconnecting, and handling errors all work smoothly and fast — even on poor networks. ### Season 2 — UX excellence [#season-2--ux-excellence] Fewer clicks, better experience. Wallets make connecting and approving as simple as possible — Link Mode, One-Click Auth, a clean connect screen — and support the key RPC methods of every chain they offer (EVM, Solana, Bitcoin), so users can do everything an app asks of them. ### Season 3 — Payments [#season-3--payments] Wallets become a way to pay. Through WalletConnect Pay, users scan a merchant QR code in-store or check out online and approve the payment in one click, and the wallet earns interchange-like revenue on every transaction. Wallets integrate native WalletConnect Pay and confirm the fallback payment flow works for users who haven't updated yet. Certification requires meeting the criteria of all seasons. Every test case, with steps and expected results, is in the detailed QA sheet: [WalletConnect Certified QA Template](https://docs.google.com/spreadsheets/d/1sGZnBilocXfSQKSFlDSkB_G3OUMNr0x_41JD-Qc-UuY/copy). ## How to apply [#how-to-apply] ### Check eligibility [#check-eligibility] Confirm the wallet meets one of the eligibility criteria above. ### Meet the requirements [#meet-the-requirements] Complete the SDK integration and work through the [WalletConnect Certified QA Template](https://docs.google.com/spreadsheets/d/1sGZnBilocXfSQKSFlDSkB_G3OUMNr0x_41JD-Qc-UuY/copy) to validate the integration before submitting. ### Submit for review [#submit-for-review] When you're sure you meet the eligibility criteria and requirements, [apply via the form](https://share.hsforms.com/1Q12irNdNRo2HJe3Jl1OJiAnxw6s). ### Get listed and rewarded [#get-listed-and-rewarded] Once approved, the wallet appears on [WalletGuide](https://walletguide.walletconnect.network/) and becomes eligible for all Certified benefits. ## How we review [#how-we-review] Certification is a guided process, not a one-shot submission: - The WalletConnect team walks the wallet team through testing and validation once submitted. - Each criterion is tested across the relevant flows — for Season 3, that means both QR scanning methods (the wallet's built-in scanner and the device's default camera), on both in-store and online checkout where applicable. - Wallet teams share QA builds of their app with WalletConnect for verification against the season's test cases. - Flows across certified wallets are tested on an ongoing basis, and any issues found are flagged — certification is maintained, not just awarded. # Supported Chains (/wallets/walletguide/chain-list) ## Overview [#overview] This page provides a list of chains on the [WalletGuide](https://walletguide.walletconnect.network/). WalletGuide is a tool that allows users to discover wallets and dapps that support their preferred blockchain. On this page, you can: - Filter chains by Mainnet / Testnet - Search for chains by name - Click on a chain to copy its Chain ID # Explorer API (/wallets/walletguide/explorer-api) The Cloud Explorer API currently offers the following functionality: - [Listings](#listings) - Allows for fetching of wallets listed in the [WalletGuide](https://walletguide.walletconnect.network/). - [Logos](#logos) - Provides logo assets in different sizes for a given Cloud explorer entry. ### Listings [#listings] By default listings endpoints return all data for provided type. You can use following query params to return paginated data or search for a specific listing by its name: | Param | Required? | Description | | ----------- | --------- | ------------------------------------------------------------------------------------------------------------------------ | | projectId | Required | Your WalletConnect Dashboard Project ID (from [dashboard.walletconnect.com](https://dashboard.walletconnect.com/)) | | entries | | Specifies how many entries will be returned (must be used together with page param) | | page | | Specifies current page (must be used with entries param) | | search | | Returns listings whose name matches provided search query | | ids | | Returns listings whose id matches provided ids (e.g. `&ids=LISTING_ID1,LISTING_ID2`) | | chains | | Returns listings that support at least one of the provided chains
(e.g. `?chains=eip155:1,eip155:137`) | | platforms | | Returns listings that support at least one of the provided platforms
(e.g. `?platforms=ios,android,mac,injected`) | | sdks | | Returns listings that support at least one of the provided Reown SDKs
(e.g. `?sdks=sign_v1,sign_v2,auth_v1`) | | standards | | Returns listings that support at least one of the provided standards
(e.g. `?standards=eip-712,eip-3085`) | | ~~version~~ | | Deprecated - replaced by `sdks` param. Specifies supported Sign version (1 or 2) | #### `GET /v3/wallets` [#get-v3wallets] Returns a JSON object containing all wallets listed in the cloud explorer. Examples: - `GET https://explorer-api.walletconnect.com/v3/wallets?projectId=YOUR_PROJECT_ID&entries=5&page=1` (will return the first 5 wallets from the first page) - `GET https://explorer-api.walletconnect.com/v3/wallets?projectId=YOUR_PROJECT_ID&platforms=injected` (will only return injected wallets) #### `GET /v3/all` [#get-v3all] Returns a JSON object containing all entries listed in the public cloud explorer. Examples: - `GET https://explorer-api.walletconnect.com/v3/all?projectId=YOUR_PROJECT_ID&entries=5&page=1` #### `GET /v3/all?projectId=YOUR_PROJECT_ID&ids=LISTING_ID1,LISTING_ID2` [#get-v3allprojectidyour_project_ididslisting_id1listing_id2] Returns a JSON object containing the entry listings by ID, which can be useful for allowlisting purposes.
You can find and copy listing ids from our [WalletGuide](https://walletguide.walletconnect.network/) Examples: - `GET https://explorer-api.walletconnect.com/v3/all?projectId=YOUR_PROJECT_ID&ids=be49f0a78d6ea1beed3804c3a6b62ea71f568d58d9df8097f3d61c7c9baf273d,4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0` ### Logos [#logos] #### Path Parameters [#path-parameters] | Param | Description | | ----- | ---------------------------------------------------------------------------------------- | | size | Determines resolution of returned image can be one of: `sm`, `md` or `lg` | | id | Corresponds to a Cloud Explorer entry's `image_id` field as returned by the Listings API | #### Query Parameters [#query-parameters] | Param | Required? | Description | | --------- | --------- | ------------------------------------------------------------------------------------------------------ | | projectId | Required | Your WalletConnect Dashboard Project ID (from [dashboard.walletconnect.com](https://dashboard.walletconnect.com/)) | #### `GET /v3/logo/:size/:image_id` [#get-v3logosizeimage_id] Returns the image source of the logo for `image_id` sized according `size`. Examples: - `GET https://explorer-api.walletconnect.com/v3/logo/md/32a77b79-ffe8-42c3-61a7-3e02e019ca00?projectId=YOUR_PROJECT_ID` # Chain Onboarding (/wallets/walletguide/submit-chain) The WalletConnect protocol is multi-chain by design. By using the [CAIP-25 standard](https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-25.md), WalletConnect aims to provide a standardized process for onboarding new chains into our ecosystem. To get started, follow the following steps. ## Register Chain with the Explorer [#register-chain-with-the-explorer] **Registering a chain with the Explorer does not impact or improve the ability for wallets and dapps to support your chain.** It is simply a way for users to discover wallets and dapps that support your chain by: - Browsing the [Chains List](./chain-list) - Filtering results programmatically via the [Explorer API](/wallets/walletguide/explorer-api) **It is still up to wallets and dapps to provide concrete support for your chain once it is listed as part of the Explorer.** If you don't see your chain listed in this [list](./chain-list), fill out the application form linked on our [chains and foundations landing page](https://walletconnect.com/solutions/chains-and-foundations) to get the process started. Once your chain is added to this list, wallets & dapps will be able to indicate support for your chain via [WalletConnect Dashboard](https://dashboard.walletconnect.com). ## CASA [#casa] To register a chain, you must know both its native representation (the chainID used with that kind of blockchain) _and_ its Chain Agnostic Standards Alliance representation, which can be found reading the relevant CAIP-2 profiles on the [CASA Namespaces Project Docs](https://namespaces.chainagnostic.org/). If no such profile yet exists, you can collaborate with an expert in the respective chain's tooling and submit a [namespaces PR](https://github.com/ChainAgnostic/namespaces/?tab=readme-ov-file#namespaces) to add one. ## Add RPC Methods [#add-rpc-methods] Integrate RPC method support into the example wallets and dapp. **Example Wallet** - [Demo](https://react-wallet.walletconnect.com/) - [GitHub](https://github.com/WalletConnect/web-examples/tree/main/advanced/wallets/react-walletkit) **Example Dapp** - [Demo](https://react-app.walletconnect.com/) - [GitHub](https://github.com/WalletConnect/web-examples/tree/main/advanced/dapps/react-dapp-v2) ## Promote [#promote] For a chain to benefit users, its prominent wallets and dApps must be registered in the Explorer. Encourage them to join the API, allowing users to view the wallets as options when connecting to a dApp. ## Wagmi & Viem [#wagmi--viem] If the chain you are registering is EVM compliant, we highly recommend you to integrate it with [Viem](https://viem.sh/docs/clients/chains.html), an ethereum library used by Wagmi and Reown. To accomplish this you will need to open a GitHub Pull Request in the Viem repository. - [Viem GitHub Repository](https://github.com/wagmi-dev/viem/tree/main/src/chains/definitions) # WalletGuide Submission (/wallets/walletguide/submit-wallet) Submitting a project to the WalletConnect Dashboard Explorer is recommended but optional. You can still use WalletConnect services without submitting your project. However, doing so ensures that your project is listed under [WalletGuide](https://walletguide.walletconnect.network/?utm_source=walletconnect-docs&utm_medium=cloud&utm_campaign=github) and [Cloud Explorer API](./explorer.md). ## Creating a New Project [#creating-a-new-project] First, open the WalletConnect Dashboard by navigating to [dashboard.walletconnect.com](https://dashboard.walletconnect.com/?utm_source=blog&utm_medium=devrel&utm_campaign=conversion) and signing in. If you don’t have an account yet, please create one before proceeding. - Once you're logged in, navigate to your team view and click the **"+ Project"** button. ![Projects page in the WalletConnect Dashboard with the + Project button](/images/cloud/1.png) - Select **"Wallet"**, enter a project name, and click **"Add"**. ![Add a project dialog in the WalletConnect Dashboard with WalletKit selected](/images/cloud/2.png) ## Project Details [#project-details] - From the project Dashboard, click on the **"WalletGuide"** tab in the top navigation. ![Project dashboard in the WalletConnect Dashboard with the WalletGuide tool highlighted](/images/cloud/3.png) - Click **"Start submission"** to begin the submission wizard. ![WalletGuide tab in the WalletConnect Dashboard with the Publish button](/images/cloud/4.png) ## Project Submission [#project-submission] The submission is a multi-step wizard. Follow each step to complete your listing: ### Step 1 — Describe your project [#step-1--describe-your-project] Fill in your wallet's basic details: - **Name** — This will appear in WalletGuide and other SDKs using the WalletConnect API - **Link** — The homepage URL of your project - **Description** — A short description of your wallet - **Logo** — Upload your wallet's logo Click **"Continue"** to proceed. ![WalletGuide submission wizard Submit your listing step with test instructions](/images/cloud/5.png) ### Step 2 — Add wallet types [#step-2--add-wallet-types] Select the wallet types that apply to your project and provide the required links for each: - Mobile Wallet - Desktop Wallet - Web Wallet - Browser Extension Click **"+ Add"** next to each applicable type to add its details. Click **"Continue"** when done. ![Add wallet types step listing mobile, desktop, web and browser extension wallets](/images/cloud/6.png) ![Add wallet types step confirming the mobile wallet was added](/images/cloud/7.png) ### Step 3 — Add chains [#step-3--add-chains] Select all chains your project supports. You can search by name or browse by ecosystem (EVM, Solana, Cosmos, etc.). Toggle **"My wallet supports custom chains"** if applicable. Click **"Continue"** when done. ![Add chains step with chain search and EVM, Solana and Cosmos groups](/images/cloud/8.png) ### Step 4 — Submit your listing [#step-4--submit-your-listing] Add **Test instructions** to help the review team validate your WalletConnect integration. Clear test instructions help accelerate the review process. Click **"Submit"** to send your listing for review. ![Submit your listing step with the test instructions field and Submit button](/images/cloud/9.png) ## Review Timeline [#review-timeline] After submitting, your listing will go through a QA review to verify your WalletConnect integration is working correctly. - **Initial review** takes **7–10 business days** on average. You can track the status in the **WalletGuide** tab of your project — it will show as **"In Review"** while pending. - **Once approved**, changes take approximately **24 hours** to go live on the production WalletGuide page. If your submission is not accepted, the reason will be noted in the WalletGuide tab and in the notification email. You can make the necessary changes and resubmit at any time. ## How do we test wallets? [#how-do-we-test-wallets] In order to offer a great user experience in our APIs and SDKs every Cloud submission goes through a QA process to make sure that the integration of the WalletConnect protocol is working correctly. The following list details our QA flow and how to reproduce it: | Test Case | Steps | Expected Results | |-----------------------------------------------|-------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------| | **Set Up** | 1. Download the wallet
2. Install the wallet app
3. Sign up for an account
4. Create one or more accounts | 1. N/A
2. The app is installed
3. I have an account
4. I have one or more accounts | | **Connect to dapp via web browser** | 1. Open the Reown connection page [lab.reown.com](https://lab.reown.com/) from a PC
2. Press "Connect Wallet" and select Reown.
3. Open the wallet app and scan QR code.
4. Accept the connection request. | 1. The app is set up correctly
2. A modal with wallet options appears
3. A QR code is shown and scanned
4. Connection established, wallet data displayed on site | | **Connect to dapp via mobile browser (Deep-link)** | 1. Open [lab.reown.com](https://lab.reown.com/) on mobile.
2. Select a default option (e.g., Wagmi for EVM chains), click "Custom Wallet," enter wallet name and deep link, then add it. Press "Connect Wallet" and select the new wallet.
3. Accept connection request in the wallet app. | 1. N/A
2. A form appears to enter wallet data, new wallet option is visible.
3. User is redirected to the wallet app, sees a connection request, and successfully connects. On Android, user is redirected back to the website. | | **Switch chains - dapp side** | 1. After connecting, click the modal button (top right of website).
2. Click the first button in the modal to switch chains.
3. Select a chain, close the modal, and press "Send Transaction." | 1. Modal with account info appears.
2. A new view with supported chains appears.
3. The transaction request in the wallet shows the correct chain. | | **Switch Chains - wallet side (if supported)** | 1. Check if wallet supports chain switching. If so, switch to a different chain. | 1. The chain change is reflected on the website. The first card displays the current chain ID. | | **Accounts Switching - wallet side** | 1. Switch accounts in the wallet app. | 1. The account switch is reflected in the modal’s account view on the website. | | **Disconnect a wallet** | 1. Press "Disconnect" in the Wallet App (if available).
2. Alternatively, press "Disconnect" from the dApp. | 1. The session disappears from both the dApp and Wallet App.
2. The session disappears from both the dApp and Wallet App. | | **Verify API** | 1. Open [malicious-app-verify-simulation.vercel.app](https://malicious-app-verify-simulation.vercel.app/).
2. Select a wallet-supported chain, press "Connect."
3. Scan the QR code with the wallet. | 1. N/A
2. A QR code modal appears.
3. The wallet flags the site as malicious. | ### Chain Specific [#chain-specific] The following test cases only apply for wallets supporting a particular set of chains. | Test Case | Steps | Expected Results | |-------------------------------------|-----------------------------------------------------------------------|----------------------------------------------------------------------| | **Supporting personal_sign** | 1. Connect the wallet.
2. Press the “Sign Message” button.
3. Accept the signature request on the wallet. | 1. N/A
2. A modal should popup on the wallet app requesting a signature.
3. Once accepted and signed, the hash should show up on the website. | | **Supporting eth_signTypedData_v4** | 1. Connect the wallet.
2. Press the “Sign Typed Data” button.
3. Accept the signature request on the wallet. | 1. N/A
2. A modal should popup on the wallet app requesting a signature.
3. Once accepted and signed, the hash should show up on the website. | | **Supporting eth_sendTransaction** | 1. Connect the wallet.
2. Press the “Send Transaction” button. | 1. N/A
2. A modal should popup on the wallet app requesting a signature. |
| Test Case | Steps | Expected Results | |-------------------------------------|------------------------------------------------------------------------------------------------|----------------------------------------------------------------------| | **Supporting solana_signMessage** | 1. Connect the wallet to [lab.reown.com/appkit/?name=solana](https://lab.reown.com/appkit/?name=solana).
2. Press the "Sign Message" button.
3. Accept the signature request on the wallet. | 1. N/A.
2. A modal should pop up on the wallet app requesting a signature.
3. Once accepted and signed, the hash should show up on the website. | | **Supporting solana_signTransaction** | 1. Connect the wallet to [lab.reown.com/appkit/?name=solana](https://lab.reown.com/appkit/?name=solana).
2. Press the "Sign Transaction" button.
3. Accept the signature request on the wallet. | 1. N/A.
2. A modal should pop up on the wallet app requesting a signature.
3. Once accepted and signed, the hash should show up on the website. | | **Supporting v0 Transactions** | 1. Connect the wallet to [lab.reown.com/appkit/?name=solana](https://lab.reown.com/appkit/?name=solana).
2. Press the "Sign Versioned Transaction" button.
3. Accept the signature request on the wallet. | 1. N/A.
2. A modal should pop up on the wallet app requesting a signature.
3. Once accepted and signed, the hash should show up on the website. |
## FAQ [#faq] You should set the EIP-6963 RDNS (Reverse Domain Name System) value of your wallet. This value uniquely identifies your wallet and allows us to properly detect and discover it when it is installed in the user's browser. In the context of a browser extension, the reverse domain (RDNS): - Serves as a unique identifier for your wallet - Enables wallet discovery via the EIP-6963 standard - Allows our system to detect when your wallet extension is installed Without the correct RDNS value, your wallet may not be discoverable. ## What's Next? [#whats-next] Now depending on whether or not your submission met all parameters, you will receive an email from the WalletConnect team with the status of your submission. The **WalletGuide** tab of your project will also reflect the current status. ![WalletGuide tab showing a submitted wallet listing with In Review status](/images/cloud/11.png) If your submission was not accepted, you can make the necessary changes and resubmit your project for review. The reason for rejection will be mentioned in the email and in the WalletGuide tab of your project. In case of any questions, feel free to ask on [Github Discussions](https://github.com/orgs/WalletConnect/discussions/categories/explorer-support) # Wallets (/wallets/walletguide/wallet-list) ## Overview [#overview] This page provides a list of wallets on the [WalletGuide](https://walletguide.walletconnect.network/). WalletGuide is a tool that allows users to discover wallets and all the information like WalletId, networks, supported devices, and official links. On this page, you can: - Search for wallets by name - Click on a wallet to copy the WalletId # Best Practices (/wallets/web/best-practices) The purpose of this guide is to show the best practices in regards of the WalletKit client usage. The goal is to provide the best user experience that just works in every circumstances. In order to ensure the best user experience and flawless connection flow, please make sure that WalletKit is initialized immediately after your app launch, especially if launched via a WalletConnect Deep Link. It guarantees that websocket connection is opened immediately and all requests are received by your wallet ## Pairing [#pairing] A pairing is a connection between a wallet and a dapp that has fixed permissions to only allow a dapp to propose a session through it. Dapp can propose infinite number of sessions on one pairing. Wallet must use a pair method from WalletKit client to pair with dapp. ```typescript const uri = 'xxx'; // pairing uri try { await walletKit.pair({ uri }); } catch (error) { // some error happens while pairing - check Expected errors section } ``` ### Pairing Expiry [#pairing-expiry] A pairing expiry event is triggered whenever a pairing is expired. The expiry for inactive pairing is 5 mins, whereas for active pairing is 30 days. A pairing becomes active when a session proposal is received and user successfully approves it. This event helps to know when given pairing expires and update UI accordingly. ```typescript core.pairing.events.on("pairing_expire", (event) => { // pairing expired before user approved/rejected a session proposal const { topic } = topic; }); ``` ### Expected User flow [#expected-user-flow] ### Pairing Flow [#pairing-flow] Wallet pairing with a dApp and showing the session proposal to approve or reject ### Pairing Error [#pairing-error] Wallet showing an error when pairing with a dApp fails ### Expected Errors [#expected-errors] While pairing the following errors might occur: - No Internet connection error or pairing timeout when scanning QR with no Internet connection - User should pair again with Internet connection - Pairing expired error when scanning a QR code with expired pairing - User should refresh a QR code and scan again - Pairing with existing pairing is not allowed - User should refresh a QR code and scan again. I usually happens when user scans an already paired QR code. ## Session Proposal [#session-proposal] A session proposal is a handshake sent by a dapp and it's purpose is to define a session rules. Whenever a user wants to establish a connection between a wallet and a dapp, one should approve a session proposal. ### User Action Feedback [#user-action-feedback] Whenever user approves or rejects a session proposal, wallet should show loading indicators in a moment of the button press until Relay acknowledgement is received for any of this actions. Approving session ```typescript try { await walletKit.approveSession(params); // update UI -> remove the loader } catch (error) { // present error to the user } ``` Rejecting session ```typescript try { await walletKit.rejectSession(params); // update UI -> remove the loader } catch (error) { // present error to the user } ``` ### Session Proposal Expiry [#session-proposal-expiry] A session proposal expiry is 5 mins. It means a given proposal is stored for 5 mins in the SDK storage and user has 5 mins for approval or rejection decision. After that time the below event is emitted and proposal modal should be removed from the app's UI. ```typescript walletKit.on("proposal_expire", (event) => { // proposal expired and any modal displaying it should be removed const { id } = event; }); ``` ### Expected User flow [#expected-user-flow-1] ### Approve or Reject Session Proposal [#approve-or-reject-session-proposal] Wallet pairing with a dApp and showing the session proposal to approve or reject ### Error Handling [#error-handling] Wallet showing an error while approving or rejecting a session proposal ### Expected Errors [#expected-errors-1] While approving or rejecting a session proposal the following errors might occurs: - No Internet connection - It happens when a user tries to approve or reject session proposal with no Internet connection - Session proposal expired - It happens when users tries to approve or reject expired session proposal - Invalid namespaces - It happens when a validation of session namespaces fails - Timeout - It happens when Relay doesn't acknowledge session settle publish within 10s ## Session Request [#session-request] A session request represents the request sent by a dapp to a wallet. ### User Action Feedback [#user-action-feedback-1] Whenever user approves or rejects a session request, wallet should show loading indicators in a moment of the button press until Relay acknowledgement is received for any of this actions. ```typescript try { await walletKit.respondSessionRequest(params); // update UI -> remove the loader } catch (error) { // present error to the user } ``` ### Session Request Expiry [#session-request-expiry] A session request expiry is defined by a dapp. It's value must be between now() + 5mins and now() + 7 days. After the session request expires the below event is emitted and session request modal should be removed from the app's UI. ```typescript walletKit.on("session_request_expire", (event) => { // request expired and any modal displaying it should be removed const { id } = event; }); ``` ### Expected User flow [#expected-user-flow-2] ### Approve or Reject Session Proposal [#approve-or-reject-session-proposal-1] Wallet showing a dApp signing request for the user to approve or reject ### Error Handling [#error-handling-1] Wallet showing an error while responding to a session request ### Expected Errors [#expected-errors-2] While approving or rejecting a session request the following error might occur: - Invalid session - This error might happen when user approves or rejects a session request on expired session - Session request expired - This error might happen when user approves or rejects a session request that already expires - Timeout - It happens when Relay doesn't acknowledge session settle publish within 10s ## Web Socket Connection State [#web-socket-connection-state] The Web Socket connection state tracks the connection with the relay server, event is emitted whenever a connection state changes. ```typescript core.relayer.on("relayer_connect", () => { // connection to the relay server is established }) core.relayer.on("relayer_disconnect", () => { // connection to the relay server is lost }) ``` ### Expected User flow [#expected-user-flow-3] ### Connection State [#connection-state] ![Wallet showing a no internet connection banner when the relay connection drops](/images/mintlify/assets/connection_state.gif) # Chain Abstraction (/wallets/web/chain-abstraction) ## Methods [#methods] Make sure you are using canary version of `@reown/walletkit`. Following are the methods from WalletKit that you will use in implementing chain abstraction. ### Prepare [#prepare] This method checks if a transaction requires additional bridging transactions beforehand. ```typescript public abstract prepare(params: { transaction: ChainAbstractionTypes.PartialTransaction; }): ChainAbstractionTypes.PrepareResponse; ``` ### Execute [#execute] Helper method used to broadcast the bridging and initial transactions and wait for them to be completed. ```typescript public abstract execute(params: { orchestrationId: ChainAbstractionTypes.OrchestrationId; bridgeSignedTransactions: ChainAbstractionTypes.SignedTransaction[]; initialSignedTransaction: ChainAbstractionTypes.SignedTransaction; }): ChainAbstractionTypes.ExecuteResult; ``` ## Usage [#usage] When sending a transaction, first check if chain abstraction is needed using the `prepare` method. If it is needed, you must sign all the fulfillment transactions and use the `execute` method. Here's a complete example: ```typescript // Check if chain abstraction is needed const result = await walletKit.chainAbstraction.prepare({ transaction: { from: transaction.from as `0x${string}`, to: transaction.to as `0x${string}`, // @ts-ignore - cater for both input or data input: transaction.input || (transaction.data as `0x${string}`), chainId: chainId, }, }); // Handle the prepare result if ('success' in result) { if ('notRequired' in result.success) { // No bridging required, proceed with normal transaction console.log('no routing required'); } else if ('available' in result.success) { const available = result.success.available; // Sign all bridge transactions and initial transaction const bridgeTxs = available.route.map(tx => tx.transactionHashToSign); const signedBridgeTxs = bridgeTxs.map(tx => wallet.signAny(tx)); const signedInitialTx = wallet.signAny(available.initial.transactionHashToSign); // Execute the chain abstraction const result = await walletKit.chainAbstraction.execute({ bridgeSignedTransactions: signedBridgeTxs, initialSignedTransaction: signedInitialTx, orchestrationId: available.routeResponse.orchestrationId, }); } } ``` For example, check out implementation of chain abstraction in [sample wallet](https://github.com/reown-com/web-examples/tree/main/advanced/wallets/react-wallet-v2) built with React. ## Testing [#testing] To test Chain Abstraction, you can use the [AppKit laboratory](https://lab.reown.com/appkit/?name=wagmi) and try sending [USDC/USDT](/wallets/features/chain-abstraction#what-are-the-supported-tokens-and-networks) with any chain abstraction supported wallet. You can also use this [sample wallet](https://react-wallet.walletconnect.com) for testing. # Analytics (/wallets/web/cloud/analytics) # Explorer Submission (/wallets/web/cloud/explorer-submission) # Relay (/wallets/web/cloud/relay) # Wallet Call API (/wallets/web/eip5792) WalletConnect supports [EIP-5792](https://eips.ethereum.org/EIPS/eip-5792#atomicbatch-capability), which defines new JSON-RPC methods that enable apps to ask a wallet to process a batch of onchain write calls and to check on the status of those calls. Applications can specify that these onchain calls be executed taking advantage of specific capabilities previously expressed by the wallet; an additional, a novel wallet RPC is defined to enable apps to query the wallet for those capabilities. - `wallet_sendCalls`: Requests that a wallet submits a batch of calls. - `wallet_getCallsStatus`: Returns the status of a call batch that was sent via wallet_sendCalls. - `wallet_showCallsStatus`: Requests that a wallet shows information about a given call bundle that was sent with wallet_sendCalls. - `wallet_getCapabilities`: This RPC allows an application to request capabilities from a wallet (e.g. batch transactions, paymaster communication). ## Usage [#usage] ## Capabilities in CAIP-25 Connection Requests [#capabilities-in-caip-25-connection-requests] CAIP-25 defines how capabilities can be expressed in wallet-to-dapp connections. These capabilities control how methods like `wallet_sendCalls` behave. ### Session Properties [#session-properties] In a connection request, dapps can request capabilities via `sessionProperties`. These can be universal (across all chains) or chain-specific: ```json "sessionProperties": { "expiry": "2022-12-24T17:07:31+00:00", "caip154": { "supported": "true" }, "flow-control": { "loose": [], "strict": [], "exoticThirdThing": [] }, "atomic": { "status": "supported" } } ``` ### Scoped Properties [#scoped-properties] For chain-specific capabilities, dapps use `scopedProperties`: ```json "scopedProperties": { "eip155:8453": { "paymasterService": { "supported": true }, "sessionKeys": { "supported": true } }, "eip155:84532": { "auxiliaryFunds": { "supported": true } } } ``` ### Wallet Response [#wallet-response] A wallet's response should indicate which capabilities it actually supports, following EIP-5792 and CAIP-25: ```json "sessionProperties": { "expiry": "2022-12-24T17:07:31+00:00", "caip154": { "supported": "true" }, "flow-control": { "loose": ["halt", "continue"], "strict": ["continue"] }, "atomic": { "status": "ready" } }, "scopedProperties": { "eip155:1": { "atomic": { "status": "supported" } }, "eip155:137": { "atomic": { "status": "unsupported" } }, "eip155:84532": { "eip155:83532:0x0910e12C68d02B561a34569E1367c9AAb42bd810": { "auxiliaryFunds": { "supported": false }, "atomic": { "status": "supported" } } } } ``` - Capabilities shared across all address in a namespace can be expressed at top-level - Address-specific capabilities can include exceptions to scope-wide capabilities ### Atomic Capability [#atomic-capability] According to EIP-5792, the `atomic` capability specifies how the wallet will execute batches of transactions. It has three possible values: - `supported` - The wallet will execute calls atomically and contiguously - `ready` - The wallet can upgrade to support atomic execution pending user approval - `unsupported` - The wallet provides no atomicity guarantees This capability is expressed per chain and is crucial for determining how `wallet_sendCalls` with `atomicRequired: true` will be handled. ### Example [#example] The `wallet_getCapabilities` method is used to request information about what capabilities a wallet supports. Following EIP-5792, here's how it should be implemented: #### Request [#request] ```json { "id": 1, "jsonrpc": "2.0", "method": "wallet_getCapabilities", "params": ["0xd46e8dd67c5d32be8058bb8eb970870f07244567", ["0x2105", "0x14A34"]] } ``` #### Response [#response] The wallet should return a response following EIP-5792, where capabilities are organized by chain ID: ```json { "id": 1, "jsonrpc": "2.0", "result": { "0x2105": { "atomic": { "status": "supported" } }, "0x14A34": { "atomic": { "status": "unsupported" } } } } ``` ### Implementation [#implementation] When implementing `wallet_sendCalls`, wallets must follow these requirements: #### Connection Approval [#connection-approval] - Only approve this method during the connection approval flow if your wallet can implement it correctly - Define the `atomic` capability per chain/account in the CAIP-25 response #### Request Format [#request-format] ```json { "id": 12345, "version": "2.0", "method": "wc_sessionRequest", "params": { "chainId": "caip-2-chain-id", "request": { "method": "wallet_sendCalls", "params": { "from": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "chainId": "0x01", "atomicRequired": true, "calls": [ { "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "value": "0x9184e72a", "data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675" }, { "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "value": "0x182183", "data": "0xfbadbaf01" } ] } } } } ``` #### Core Implementation Requirements [#core-implementation-requirements] - Execute calls in the exact order specified in the request - Do not wait for any calls to be finalized before completing the batch - If the user rejects the request, do not send any calls #### Atomic Execution Behavior [#atomic-execution-behavior] When `atomicRequired` is `true`: - Execute all calls atomically (either all succeed or none have any effect) - Execute all calls contiguously (no other transactions between batch calls) - If your wallet can upgrade from `ready` to `supported` atomicity, do so before executing When `atomicRequired` is `false`: - You may execute calls sequentially without atomicity guarantees - You may execute atomically if your wallet supports it - You may upgrade to `supported` atomicity and execute atomically #### Response Enrichment [#response-enrichment] To enhance the user experience and eliminate the need for app switching, wallets can enrich the wallet_sendCalls response with caip2 id and transactionHash to let the Universal Provider resolve the transaction hash. ```json { "id": "...", "capabilities": { "caip345": { "caip2": "eip155:1", "transactionHashes": ["..."], } } } ``` ### Example [#example-1] To enhance the user experience and eliminate the need for app switching, wallets can enrich the wallet_sendCalls response with caip2 id and transactionHash to let the Universal Provider resolve the transaction hash. To implement this functionality, the response for wallet_sendCalls should be enriched with capabilities: ```json { "id": "...", "capabilities": { "caip345": { "caip2": "eip155:1", "transactionHashes": ["..."], } } } ``` Specify the `scopedProperties` when approving a session: ```json "scopedProperties": { "eip155": { "walletService": [{ "url": "", "methods": ["wallet_getCallsStatus"] }] } } ``` ### Response Format [#response-format] The response format for `wallet_getCallsStatus` varies based on the execution method: #### For Atomic Execution [#for-atomic-execution] ```json { "receipts": [/* single receipt or array of receipts */], "atomic": true } ``` #### For Non-Atomic Execution [#for-non-atomic-execution] ```json { "receipts": [/* array of receipts for all transactions */], "atomic": false } ``` For non-atomic execution, include all transactions in the receipts array, even those that were included on-chain but eventually reverted. ## References [#references] - EIP-5792: https://eips.ethereum.org/EIPS/eip-5792#atomicbatch-capability - CAIP-25 namespaces: https://github.com/ChainAgnostic/namespaces/blob/main/eip155/caip25.md # Installation (/wallets/web/installation) Install Wallet SDK using npm or yarn. ```bash tab="npm" npm install @reown/walletkit @walletconnect/utils @walletconnect/core ``` ```bash tab="Yarn" yarn add @reown/walletkit @walletconnect/utils @walletconnect/core ``` ```bash tab="Bun" bun add @reown/walletkit @walletconnect/utils @walletconnect/core ``` ```bash tab="pnpm" pnpm add @reown/walletkit @walletconnect/utils @walletconnect/core ``` ## Next Steps [#next-steps] Now that you've installed WalletKit, you're ready to start integrating it. The next section will walk you through the process of setting up your project to use the SDK. # One-click Auth / SIWS (/wallets/web/one-click-auth-siws) ## Introduction [#introduction] This section outlines an innovative protocol method that facilitates the initiation of a Sign session and the authentication of a wallet through a [Sign-In with Solana](https://github.com/phantom/sign-in-with-solana) (SIWS) message, enhanced by [ReCaps](https://eips.ethereum.org/EIPS/eip-5573) (ReCap Capabilities). This enhancement not only offers immediate authentication for dApps, paving the way for prompt user logins, but also integrates informed consent for authorization. Through this mechanism, dApps can request the delegation of specific capabilities to perform actions on behalf of the wallet user. These capabilities, encapsulated within SIWS messages as ReCap URIs, detail the scope of actions authorized by the user in an explicit and human-readable form. By incorporating ReCaps, this method extends the utility of SIWS messages, allowing dApps to combine authentication with a nuanced authorization model. This model specifies the actions a dApp is authorized to execute on the user's behalf, enhancing security and user autonomy by providing clear consent for each delegated capability. As a result, dApps can utilize these consent-backed messages to perform predetermined actions, significantly enriching the interaction between dApps, wallets, and users within the Solana ecosystem. ## Handling Authentication Requests [#handling-authentication-requests] To handle incoming authentication requests, subscribe to the `session_authenticate` event. This will notify you of any authentication requests that need to be processed, allowing you to either approve or reject them based on your application logic. ```typescript walletKit.on("session_authenticate", async (payload) => { // Process the authentication request here. // Steps include: // 1. Populate the authentication payload with the supported chains and methods // 2. Format the authentication message using the payload and the user's account // 3. Present the authentication message to the user // 4. Sign the authentication message(s) to create a verifiable authentication object(s) // 5. Approve the authentication request with the authentication object(s) }); ``` ## Authentication Objects/Payloads [#authentication-objectspayloads] ```typescript import { populateAuthPayload } from "@walletconnect/utils"; // Solana chains that your wallet supports const supportedChains = [ "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp", "solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ" ] // Solana methods that your wallet supports const supportedMethods = ["solana_signMessage", "solana_signTransaction"]; // Populate the authentication payload with the supported chains and methods const authPayload = populateAuthPayload({ authPayload: payload.params.authPayload, chains: supportedChains, methods: supportedMethods, }); // Prepare the user's address in CAIP10(https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-10.md) format const iss = `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp:8nJ694gNrHx76L2eyJzQw7JBGRoW8Fdtrxf588pEqyYh`; // Now you can use the authPayload to format the authentication message const message = walletKit.formatAuthMessage({ request: authPayload, iss }); // Present the authentication message to the user ... ``` ## Approving Authentication Requests [#approving-authentication-requests] 1. The recommended approach for secure authentication across multiple chains involves signing a SIWS (Sign-In with Solana) message for each chain and account. However, at a minimum, one SIWS message must be signed to establish a session. It is possible to create a session for multiple chains with just one issued authentication object. 2. Sometimes a dapp may want to only authenticate the user without creating a session, not every approval will result with a new session. ```typescript // Approach 1 // Sign the authentication message(s) to create a verifiable authentication object(s) const signature = await cryptoWallet.signMessage(message, privateKey); // Build the authentication object(s) const auth = buildAuthObject( authPayload, { t: "caip122", s: signature, }, iss ); // Approve await walletKit.approveSessionAuthenticate({ id: payload.id, auths: [auth], }); // Approach 2 // Note that you can also sign multiple messages for every requested chain/address pair const auths = []; authPayload.chains.forEach(async (chain) => { const message = walletKit.formatAuthMessage({ request: authPayload, iss: `${chain}:${cryptoWallet.address}`, }); const signature = await cryptoWallet.signMessage(message); const auth = buildAuthObject( authPayload, { t: "caip122", // signature type s: signature, }, `${chain}:${cryptoWallet.address}` ); auths.push(auth); }); // Approve await walletKit.approveSessionAuthenticate({ id: payload.id, auths, }); ``` ## Rejecting Authentication Requests [#rejecting-authentication-requests] If the authentication request cannot be approved or if the user chooses to reject it, use the rejectSession method. ```typescript import { getSdkError } from "@walletconnect/utils"; await walletKit.rejectSessionAuthenticate({ id: payload.id, reason: getSdkError("USER_REJECTED"), // or choose a different reason if applicable }); ``` ## Testing One-click Auth [#testing-one-click-auth] You can use [AppKit Labs](https://lab.reown.com/appkit/?name=siwx-solana) to test and verify that your wallet supports One-click Auth properly. # One-click Auth (/wallets/web/one-click-auth) ## Introduction [#introduction] This section outlines an innovative protocol method that facilitates the initiation of a Sign session and the authentication of a wallet through a [Sign-In with Ethereum](https://eips.ethereum.org/EIPS/eip-4361) (SIWE) message, enhanced by [ReCaps](https://eips.ethereum.org/EIPS/eip-5573) (ReCap Capabilities). This enhancement not only offers immediate authentication for dApps, paving the way for prompt user logins, but also integrates informed consent for authorization. Through this mechanism, dApps can request the delegation of specific capabilities to perform actions on behalf of the wallet user. These capabilities, encapsulated within SIWE messages as ReCap URIs, detail the scope of actions authorized by the user in an explicit and human-readable form. By incorporating ReCaps, this method extends the utility of SIWE messages, allowing dApps to combine authentication with a nuanced authorization model. This model specifies the actions a dApp is authorized to execute on the user's behalf, enhancing security and user autonomy by providing clear consent for each delegated capability. As a result, dApps can utilize these consent-backed messages to perform predetermined actions, significantly enriching the interaction between dApps, wallets, and users within the Ethereum ecosystem. ![Regular connect and sign flow compared with the one-click authenticated sessions flow](/images/authenticatedSessions-light.png) ## Handling Authentication Requests [#handling-authentication-requests] To handle incoming authentication requests, subscribe to the `session_authenticate` event. This will notify you of any authentication requests that need to be processed, allowing you to either approve or reject them based on your application logic. ```typescript walletKit.on("session_authenticate", async (payload) => { // Process the authentication request here. // Steps include: // 1. Populate the authentication payload with the supported chains and methods // 2. Format the authentication message using the payload and the user's account // 3. Present the authentication message to the user // 4. Sign the authentication message(s) to create a verifiable authentication object(s) // 5. Approve the authentication request with the authentication object(s) }); ``` ## Authentication Objects/Payloads [#authentication-objectspayloads] ```typescript import { populateAuthPayload } from "@walletconnect/utils"; // EVM chains that your wallet supports const supportedChains = ["eip155:1", "eip155:2", 'eip155:137']; // EVM methods that your wallet supports const supportedMethods = ["personal_sign", "eth_sendTransaction", "eth_signTypedData"]; // Populate the authentication payload with the supported chains and methods const authPayload = populateAuthPayload({ authPayload: payload.params.authPayload, chains: supportedChains, methods: supportedMethods, }); // Prepare the user's address in CAIP10(https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-10.md) format const iss = `eip155:1:0x0Df6d2a56F90e8592B4FfEd587dB3D5F5ED9d6ef`; // Now you can use the authPayload to format the authentication message const message = walletKit.formatAuthMessage({ request: authPayload, iss }); // Present the authentication message to the user ... ``` ## Approving Authentication Requests [#approving-authentication-requests] **Note** 1. The recommended approach for secure authentication across multiple chains involves signing a SIWE (Sign-In with Ethereum) message for each chain and account. However, at a minimum, one SIWE message must be signed to establish a session. It is possible to create a session for multiple chains with just one issued authentication object. 2. Sometimes a dapp may want to only authenticate the user without creating a session, not every approval will result with a new session. ```typescript // Approach 1 // Sign the authentication message(s) to create a verifiable authentication object(s) const signature = await cryptoWallet.signMessage(message, privateKey); // Build the authentication object(s) const auth = buildAuthObject( authPayload, { t: "eip191", s: signature, }, iss ); // Approve await walletKit.approveSessionAuthenticate({ id: payload.id, auths: [auth], }); // Approach 2 // Note that you can also sign multiple messages for every requested chain/address pair const auths = []; authPayload.chains.forEach(async (chain) => { const message = walletKit.formatAuthMessage({ request: authPayload, iss: `${chain}:${cryptoWallet.address}`, }); const signature = await cryptoWallet.signMessage(message); const auth = buildAuthObject( authPayload, { t: "eip191", // signature type s: signature, }, `${chain}:${cryptoWallet.address}` ); auths.push(auth); }); // Approve await walletKit.approveSessionAuthenticate({ id: payload.id, auths, }); ``` ## Rejecting Authentication Requests [#rejecting-authentication-requests] If the authentication request cannot be approved or if the user chooses to reject it, use the rejectSession method. ```typescript import { getSdkError } from "@walletconnect/utils"; await walletKit.rejectSessionAuthenticate({ id: payload.id, reason: getSdkError("USER_REJECTED"), // or choose a different reason if applicable }); ``` ## Testing One-click Auth [#testing-one-click-auth] You can use [AppKit Lab](https://lab.reown.com/appkit/?name=siwx-ethers) to test and verify that your wallet supports One-click Auth properly. # Resources (/wallets/web/resources) Valuable assets for developers and users interested in integrating Wallet SDK into their applications. - [Awesome WalletConnect](https://github.com/WalletConnect/awesome-walletconnect) - Community-curated collection of WalletConnect-enabled wallets, libraries, and tools. - [AppKit Laboratory](https://lab.reown.com/) - A place to test your wallet integrations against various setups of AppKit. - [Wallet SDK JavaScript GitHub](https://github.com/reown-com/reown-walletkit-js) - Wallet SDK JavaScript GitHub repository. ### Wallet Resources [#wallet-resources] We have a set of official examples in our [web-examples](https://github.com/WalletConnect/web-examples) repository to help you get started. **Wallet SDK** This wallet can be used with any dapp using Sign v2 or Auth. - [React Wallet SDK](https://github.com/reown-com/web-examples/tree/main/advanced/wallets/react-wallet-v2) ([Demo](https://react-wallet.walletconnect.com)) **Sign** - [React Wallet Ethers - v2](https://github.com/reown-com/web-examples/tree/main/advanced/wallets/react-wallet-auth) ([Demo](https://react-auth-wallet.walletconnect.com/)) ### Dapp Resources [#dapp-resources] If you need to test your app's integration, you can use one of our following demo wallets and/or dapps. **Sign** - [React dApp (with standalone client) - v2](https://github.com/WalletConnect/web-examples/tree/main/advanced/dapps/react-dapp-v2) ([Demo](https://react-app.reown.com/)) # Usage (/wallets/web/usage) ## Overview [#overview] WalletConnect makes distributing your Web wallet (such as Safe, Abstract Global Wallet, and many more) much faster. By integrating the Wallet SDK, your web wallet will be able to connect to any dApp that supports WalletConnect and will be available in the list of wallets on both WalletConnect, Reown AppKit, and others.
Web Wallet in Reown AppKit Web Wallet in WalletConnect
Web Wallet in Reown AppKit & WalletButtons
Additionally, you don't need to build SDKs in native languages such as Swift, Kotlin, Flutter, Unity, or React Native. This means your wallet can be available not just for web dApps, but also for native dApps, all from a single codebase. This section provides instructions on how to initialize the WalletKit client, approve sessions with supported namespaces, and respond to session requests, enabling easy integration of Web3 wallets with dApps through a simple and intuitive interface. ## User Experience [#user-experience] ### Default Integration [#default-integration] This integration automatically opens a new web wallet tab when a user clicks "Connect" in a dApp. The wallet handles the WalletConnect URI automatically, meaning users don't need to manually copy and paste the URI. This provides a seamless, one-click connection experience.
### QR Code Integration [#qr-code-integration] This integration only handles the session proposal and approval via the WalletConnect QR code. The user will need to manually copy and paste the WalletConnect URI into the wallet.
## Cloud Configuration [#cloud-configuration] Create a new project on WalletConnect Dashboard at https://dashboard.walletconnect.com and obtain a new project ID. ## Initialization [#initialization] Create a new instance from Core and initialize it with a projectId created from installation. Next, create WalletKit instance by calling init on walletKit. Passing in the options object containing metadata about the app and an optional relay URL. Make sure you initialize `walletKit` globally and use the same instance for all your sessions. For React-based apps, you can initialize it in the root component and export it to use in other components. ```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: "https://reown.com/walletkit", icons: [], }, }); ``` ### Core Instance Sharing [#core-instance-sharing] Starting from newer versions of WalletKit, Core instances are shared globally by default to optimize resource usage. This means that multiple Core instances with the same configuration will reuse the same underlying Core. **For parallel testing scenarios** where you need isolated Core instances, you have two options: #### Option 1: Use customStoragePrefix [#option-1-use-customstorageprefix] ```javascript const core = new Core({ projectId: process.env.PROJECT_ID, customStoragePrefix: `test-${Date.now()}`, // Unique prefix for each test }); ``` Don't use randomly generated `customStoragePrefix` in production - this will cause the client to create new storage each time it is initialized. The client will not be able to persist/read existing data and all existing sessions will be lost after each reload. #### Option 2: Disable global Core sharing [#option-2-disable-global-core-sharing] ```javascript // Set environment variable before initializing Core process.env.DISABLE_GLOBAL_CORE = "true"; const core = new Core({ projectId: process.env.PROJECT_ID, }); ``` The global Core sharing behavior was introduced to prevent resource waste when multiple SDK instances are created. If you're running parallel tests and experiencing cross-test interference, use one of the solutions above to ensure proper test isolation. ## Session [#session] A session is a connection between a dapp and a wallet. It is established when a user approves a session proposal from a dapp. A session is active until the user disconnects from the dapp or the session expires. ### Handling Session Proposals [#handling-session-proposals] You can connect your web wallet to a dApp in three ways: 1. Retrieve the WC URI from the dApp via query parameters 2. Implement a scanner to read the WC URI from a WalletConnect QR code 3. Allow users to manually enter the WC URI in an input field When opening the wallet directly from the dApp, the `WC_URI` will be in the following format in the query parameters: ``` {YOUR_WALLET_URL}/wc?uri={WC_URI} ``` We recommend closing the web wallet tab after the user approves the request and redirecting back to the dApp. For web requests, redirect to the original browser tab, and for mobile requests, redirect to the native mobile dApp. To test your web wallet connection flow, use our [Appkit Laboratory](https://lab.reown.com/) by adding a custom wallet with your web wallet URL. ### Handling Session Requests [#handling-session-requests] When a dApp sends a session request to your wallet, the request will be available in the following format in the query parameters: ``` {YOUR_WALLET_URL}/wc?requestId={requestId}&sessionTopic={session.Topic} ``` This format allows your wallet to identify both the specific request and the session it belongs to. To test your web wallet connection flow, use our [Appkit Laboratory](https://lab.reown.com/) by adding a custom wallet with your web wallet URL. ### Handling Redirects [#handling-redirects] When handling redirects after session approval or request completion, you should: 1. For web dApps: * Redirect back to the original browser tab using `window.opener.location.href` * Close the current wallet tab using `window.close()` 2. For native dApps: * Check the peer metadata for a `redirect` URL in the session proposal * If available, use deep linking to redirect to the native app * If no redirect URL is found, display a "Return to App" message to the user Example implementation: ```javascript function handleRedirect(session) { // Check if this is a native app const isNativeApp = session.peer.metadata.redirect !== undefined; if (isNativeApp) { // Redirect to native app if URL is available if (session.peer.metadata.redirect) { window.location.href = session.peer.metadata.redirect; } else { // Show "Return to App" message showReturnToAppMessage(); } } else { // For web dApps, redirect back to original tab if (window.opener) { window.opener.location.href = session.peer.metadata.url; window.close(); } } } ``` ### Namespace Builder [#namespace-builder] With WalletKit (and @walletconnect/utils) we've published a helper utility that greatly reduces the complexity of parsing the `required` and `optional` namespaces. It accepts as parameters a `session proposal` along with your user's `chains/methods/events/accounts` and returns ready-to-use `namespaces` object. ```javascript // util params { proposal: ProposalTypes.Struct; // the proposal received by `.on("session_proposal")` supportedNamespaces: Record< // your Wallet's supported namespaces string, // the supported namespace key e.g. eip155 { chains: string[]; // your supported chains in CAIP-2 format e.g. ["eip155:1", "eip155:2", ...] methods: string[]; // your supported methods e.g. ["personal_sign", "eth_sendTransaction"] events: string[]; // your supported events e.g. ["chainChanged", "accountsChanged"] accounts: string[] // your user's accounts in CAIP-10 format e.g. ["eip155:1:0x453d506b1543dcA64f57Ce6e7Bb048466e85e228"] } >; }; ``` Example usage ```javascript // import the builder util import { WalletKit, WalletKitTypes } from '@reown/walletkit' import { buildApprovedNamespaces, getSdkError } from '@walletconnect/utils' async function onSessionProposal({ id, params }: WalletKitTypes.SessionProposal){ try{ // ------- namespaces builder util ------------ // const approvedNamespaces = buildApprovedNamespaces({ proposal: params, supportedNamespaces: { eip155: { chains: ['eip155:1', 'eip155:137'], methods: ['eth_sendTransaction', 'personal_sign'], events: ['accountsChanged', 'chainChanged'], accounts: [ 'eip155:1:0xab16a96d359ec26a11e2c2b3d8f8b8942d5bfcdb', 'eip155:137:0xab16a96d359ec26a11e2c2b3d8f8b8942d5bfcdb' ] } } }) // ------- end namespaces builder util ------------ // const session = await walletKit.approveSession({ id, namespaces: approvedNamespaces }) }catch(error){ // use the error.message to show toast/info-box letting the user know that the connection attempt was unsuccessful .... await walletKit.rejectSession({ id: proposal.id, reason: getSdkError("USER_REJECTED") }) } } walletKit.on('session_proposal', onSessionProposal) ``` If your wallet supports multiple namespaces e.g. `eip155`,`cosmos` & `near` Your `supportedNamespaces` should look like the following example. ```javascript // ------- namespaces builder util ------------ // const approvedNamespaces = buildApprovedNamespaces({ proposal: params, supportedNamespaces: { eip155: {...}, cosmos: {...}, near: {...} }, }); // ------- end namespaces builder util ------------ // ``` ### Get Active Sessions [#get-active-sessions] You can get the wallet active sessions using the `getActiveSessions` function. ```js const activeSessions = walletKit.getActiveSessions(); ``` ### EVM methods & events [#evm-methods--events] In @walletconnect/ethereum-provider, (our abstracted EVM SDK for apps) we support by default the following Ethereum methods and events: ```ts { //... methods: [ "eth_accounts", "eth_requestAccounts", "eth_sendRawTransaction", "eth_sign", "eth_signTransaction", "eth_signTypedData", "eth_signTypedData_v3", "eth_signTypedData_v4", "eth_sendTransaction", "personal_sign", "wallet_switchEthereumChain", "wallet_addEthereumChain", "wallet_getPermissions", "wallet_requestPermissions", "wallet_registerOnboarding", "wallet_watchAsset", "wallet_scanQRCode", "wallet_sendCalls", "wallet_getCallsStatus", "wallet_showCallsStatus", "wallet_getCapabilities", ], events: [ "chainChanged", "accountsChanged", "message", "disconnect", "connect", ] } ``` ### Session Approval [#session-approval] The `session_proposal` event is emitted when a dapp initiates a new session with a user's wallet. The event will include a `proposal` object with information about the dapp and requested permissions. The wallet should display a prompt for the user to approve or reject the session. If approved, call `approveSession` and pass in the `proposal.id` and requested `namespaces`. The `pair` method initiates a WalletConnect pairing process with a dapp using the given `uri` (QR code from the dapps). To learn more about pairing, checkout out the [docs](https://docs.reown.com/advanced/api/core/pairing). ```javascript walletKit.on( "session_proposal", async (proposal: WalletKitTypes.SessionProposal) => { const session = await walletKit.approveSession({ id: proposal.id, namespaces, }); } ); await walletKit.pair({ uri }); ``` ### 🛠️ Usage examples [#️-usage-examples] * [in a demo wallet app](https://github.com/reown-com/web-examples/blob/main/advanced/wallets/react-wallet-v2/src/views/SessionProposalModal.tsx#L264) * [in integration tests](https://github.com/reown-com/reown-walletkit-js/blob/main/packages/walletkit/test/sign.spec.ts#L55) ### ⚠️ Expected Errors [#️-expected-errors] * `No matching key. proposal id doesn't exist: 1` This rejection means the SDK can't find a record with the given `proposal.id` - in this example `1`. This can happen when the proposal has expired (by default 5 minutes) or if you attempt to respond to a proposal that has already been approved/rejected. If you are seeing this error, please make sure that you are calling `approveSession` with the correct `proposal.id` that is available within the proposal payload. * `Error: Missing or invalid. approve(), namespaces should be an object with data` This error means that the `namespaces` parameter passed to `approveSession` is either missing or invalid. Please check that you are passing a valid `namespaces` object that satisfies all required properties. * `Non conforming namespaces. approve() namespaces don't satisfy required namespaces.` This error indicates that some value(s) in your `namespaces` object do not satisfy the required namespaces requested by the dapp. To provide additional guidance, the message might include info about the exact property that is missing or invalid e.g. `Required: eip155:1 Approved: eip155:137`. Please check [CAIP-25](https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-25.md) to familiarize yourself with the standard and it's nuances. Additionally, we highly recommend you to use our `namespace` builder utility that would greatly simplify the process of parsing & building a valid `namespaces` object. ### Session Rejection [#session-rejection] In the event you want to reject the session proposal, call the `rejectSession` method. The `getSDKError` function comes from the `@walletconnect/utils` [library](https://github.com/WalletConnect/walletconnect-monorepo/tree/v2.0/packages/utils). ```javascript walletKit.on( "session_proposal", async (proposal: WalletKitTypes.SessionProposal) => { await walletKit.rejectSession({ id: proposal.id, reason: getSdkError("USER_REJECTED_METHODS"), }); } ); ``` ### 🛠️ Usage examples [#️-usage-examples-1] * [in a demo wallet app](https://github.com/WalletConnect/web-examples/blob/a50c8eb5a10666f25911713c5358e78f1ca576d6/advanced/wallets/react-wallet-v2/src/views/SessionProposalModal.tsx#L287) * [in integration tests](https://github.com/reown-com/reown-walletkit-js/blob/main/packages/walletkit/test/sign.spec.ts#L79) ### ⚠️ Expected Errors [#️-expected-errors-1] * `No matching key. proposal id doesn't exist: 1` This rejection means the SDK can't find a record with the given `proposal.id` - in this example `1`. This can happen when the proposal has expired (by default 5 minutes) or if you attempt to respond to a proposal that has already been approved/rejected. If you are seeing this error, please make sure that you are calling `rejectSession` with the correct `proposal.id` that is available within the proposal payload. * `Error: Missing or invalid. reject() reason:` This rejection means the `reason` parameter passed to `rejectSession` is either missing or invalid. We recommend using the `getSDKError` function from the `@walletconnect/utils` library that will populate & format the parameter for you. ### Responding to Session requests [#responding-to-session-requests] The `session_request` event is emitted when the SDK received a request from the peer and it needs the wallet to perform a specific action, such as signing a transaction. The event contains a `topic` and a `request` object, which will vary depending on the action requested. To respond to the request, you can access the `topic` and `request` object by destructuring them from the event payload. To see a list of possible `request` and `response` objects, refer to the relevant JSON-RPC Methods for [Ethereum](https://docs.reown.com/advanced/multichain/rpc-reference/ethereum-rpc), [Solana](https://docs.reown.com/advanced/multichain/rpc-reference/solana-rpc), [Cosmos](https://docs.reown.com/advanced/multichain/rpc-reference/cosmos-rpc), or [Stellar](https://docs.reown.com/advanced/multichain/rpc-reference/stellar-rpc). As an example, if the dapp requests a `personal_sign` method, you can extract the `params` array from the `request` object. The first item in the array is the hex version of the message to be signed, which can be converted to UTF-8 and assigned to a `message` variable. The second item in `params` is the user's wallet address. To sign the message, you can use your wallet's `signMessage` method and pass in the message. The signed message, along with the `id` from the event payload, can then be used to create a `response` object, which can be passed into `respondSessionRequest`. ```javascript walletKit.on( "session_request", async (event: WalletKitTypes.SessionRequest) => { const { topic, params, id } = event; const { request } = params; const requestParamsMessage = request.params[0]; // convert `requestParamsMessage` by using a method like hexToUtf8 const message = hexToUtf8(requestParamsMessage); // sign the message const signedMessage = await wallet.signMessage(message); const response = { id, result: signedMessage, jsonrpc: "2.0" }; await walletKit.respondSessionRequest({ topic, response }); } ); ``` To reject a session request, the response should be similar to this. ```javascript const response = { id, jsonrpc: "2.0", error: { code: 5000, message: "User rejected.", }, }; ``` ### 🛠️ Usage examples [#️-usage-examples-2] * [in a demo wallet app](https://github.com/WalletConnect/web-examples/blob/a50c8eb5a10666f25911713c5358e78f1ca576d6/advanced/wallets/react-wallet-v2/src/views/SessionSignModal.tsx#L36) * [in integration tests](https://github.com/reown-com/reown-walletkit-js/blob/main/packages/walletkit/test/sign.spec.ts#L165) ### ⚠️ Expected Errors [#️-expected-errors-2] * `Error: No matching key. session topic doesn't exist: 'xyz...'` This rejection means the SDK can't find a session with the given `topic` - in this example `xyz...`. This can happen when the session has been disconnected by either the wallet or the dapp while the session request was being processed or if a session with such topic doesn't exist. If you are seeing this error, please make sure that you are using a correct topic that is available within the request payload. * `Error: Missing or invalid. respond() response:` This rejection means the `response` parameter passed to `respondSessionRequest` is either missing or invalid. The response should be a valid [JSON-RPC 2.0](https://www.jsonrpc.org/specification) response object. We recommend you to use our `formatJsonRpcResult` utility from `"@walletconnect/jsonrpc-utils"` that will format the response for you. Example usage: `id` argument being the request id from the request payload. ```javascript import { formatJsonRpcResult } from "@walletconnect/jsonrpc-utils"; const signature = await cryptoWallet.signTransaction(signTransaction); const response = await walletKit.respondSessionRequest({ topic: session.topic, response: formatJsonRpcResult(id, signature), }); ``` ### Updating a Session [#updating-a-session] If you wish to include new accounts or chains or methods in an existing session, `updateSession` allows you to do so. You need pass in the `topic` and a new `Namespaces` object that contains all of the existing namespaces as well as the new data you wish to include. After you update the session, the other peer will receive a `session_update` event. An example adding a new account to an existing session: ```javascript const namespaces = session.namespaces; const accounts = [ "eip155:1:0xab16a96d359ec26a11e2c2b3d8f8b8942d5bfcdb", "eip155:1:0x1234567890123456789012345678901234567890", ]; const updatedNamespaces = { ...namespaces, eip155: { ...namespaces.eip155, accounts, }, }; const { acknowledged } = await walletKit.updateSession({ topic: session.topic, namespaces: updatedNamespaces, }); // If you wish to be notified when the dapp acknowledges the update. // note that if the dapp is offline `acknowledged` will not resolve until it comes back online await acknowledged(); ``` An example adding a new chain to an existing session: ```javascript const namespaces = session.namespaces; const chains = ["eip155:1", "eip155:137"]; const accounts = [ "eip155:1:0xab16a96d359ec26a11e2c2b3d8f8b8942d5bfcdb", "eip155:137:0x1234567890123456789012345678901234567890", ]; const updatedNamespaces = { ...namespaces, eip155: { ...namespaces.eip155, accounts, chains, }, }; await walletKit.updateSession({ topic: session.topic, namespaces: updatedNamespaces, }); ``` ### 🛠️ Usage examples [#️-usage-examples-3] * [in a demo wallet app](https://github.com/WalletConnect/web-examples/blob/a50c8eb5a10666f25911713c5358e78f1ca576d6/advanced/wallets/react-wallet-v2/src/pages/session.tsx#L77) * [in integration tests](https://github.com/reown-com/reown-walletkit-js/blob/main/packages/walletkit/test/sign.spec.ts#L98) ### ⚠️ Expected Errors [#️-expected-errors-3] Note that all `namespaces` validation applies and you still have to satisfy the required namespaces requested by the dapp. * `Error: No matching key. session topic doesn't exist: 'xyz...'` This rejection means the SDK can't find a session with the given `topic` - in this example `xyz...`. This can happen when the session you're trying to update has already been disconnected by either the wallet or the dapp or if a session with such topic doesn't exist. If you are seeing this error, please make sure that you are using a correct topic of an active session. * `Error: Missing or invalid. update(), namespaces should be an object with data` This error means that the `namespaces` parameter passed to `updateSession` is either missing or invalid. Please check that you are passing a valid `namespaces` object that satisfies all required properties. * `Non conforming namespaces. update() namespaces don't satisfy required namespaces.` This error indicates that some value(s) in your `namespaces` object do not satisfy the required namespaces requested by the dapp. To provide additional guidance, the message might include info about the exact property that is missing or invalid e.g. `Required: eip155:1 Approved: eip155:137`. Please check [CAIP-25](https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-25.md) to familiarize yourself with the standard and it's nuances. Additionally, we highly recommend you to use our `namespace` builder utility that would greatly simplify the process of parsing & building a valid `namespaces` object. ### Extending a Session [#extending-a-session] Sessions have a default expiry of 7 days. To extend a session by an additional 7 days, call `.extendSession` method and pass in the `topic` of the session you wish to extend. ```javascript const { acknowledged } = await walletKit.extendSession({ topic }); // if you wish to be notified when the dapp acks the extend // note that if the dapp is offline `acknowledged` will not resolve until it comes back online await acknowledged(); ``` ### 🛠️ Usage examples [#️-usage-examples-4] * [in integration tests](https://github.com/reown-com/reown-walletkit-js/blob/main/packages/walletkit/test/sign.spec.ts#L130) ### ⚠️ Expected Errors [#️-expected-errors-4] * `Error: No matching key. session topic doesn't exist: 'xyz...'` This rejection means the SDK can't find a session with the given `topic` - in this example `xyz...`. This can happen when the session you're trying to update has already been disconnected by either the wallet or the dapp or if a session with such topic doesn't exist. If you are seeing this error, please make sure that you are using a correct topic of an active session. ### Session Disconnect [#session-disconnect] To initiate disconnect from a session(think session delete), call `.disconnectSession` by passing a `topic` & `reason` for the disconnect. The other peer will receive a `session_delete` and be notified that the session has been disconnected. **Note** It's important that you're subscribed to the `session_delete` event as well, to be notified when the other peer initiates a disconnect. We recommend using the `getSDKError` utility function, that will provide ready-to-use `reason` payloads and is available in the `@walletconnect/utils` [library](https://github.com/WalletConnect/walletconnect-monorepo/tree/v2.0/packages/utils). ```javascript await walletKit.disconnectSession({ topic, reason: getSdkError("USER_DISCONNECTED"), }); ``` ### 🛠️ Usage examples [#️-usage-examples-5] * [in integration tests](https://github.com/reown-com/reown-walletkit-js/blob/main/packages/walletkit/test/sign.spec.ts#L222) ### ⚠️ Expected Errors [#️-expected-errors-5] * `Error: No matching key. session topic doesn't exist: 'xyz...'` This rejection means the SDK can't find a session with the given `topic` - in this example `xyz...`. This can happen when the session you're trying to update has already been disconnected by either the wallet or the dapp or if a session with such topic doesn't exist. If you are seeing this error, please make sure that you are using a correct topic of an active session. ### Emitting Session Events [#emitting-session-events] To emit session events, call the `emitSessionEvent` and pass in the params. If you wish to switch to chain/account that is not approved (missing from `session.namespaces`) you will have to update the session first. In the following example, the wallet will emit `session_event` that will instruct the dapp to switch the active accounts. ```javascript await walletKit.emitSessionEvent({ topic, event: { name: "accountsChanged", data: ["0xab16a96D359eC26a11e2C2b3d8f8B8942d5Bfcdb"], }, chainId: "eip155:1", }); ``` In the following example, the wallet will emit `session_event` when the wallet switches chains. ```javascript await walletKit.emitSessionEvent({ topic, event: { name: "chainChanged", data: 1, }, chainId: "eip155:1", }); ``` # Verify API (/wallets/web/verify) Verify API is a security-focused feature that allows wallets to notify end-users when they may be connecting to a suspicious or malicious domain, helping to prevent phishing attacks across the industry. Once a wallet knows whether an end-user is on uniswap.com or eviluniswap.com, it can help them to detect potentially harmful connections through Verify's combined offering of WalletConnect's domain registry. When a user initiates a connection with an application, Verify API enables wallets to present their users with four key states that can help them determine whether the domain they’re about to connect to might be malicious. These are: ![Verify Banner](/images/mintlify/verify-banner.png) ## Disclaimer [#disclaimer] Verify API helps wallets detect suspicious or malicious domains, but it may not catch every threat. Use it as one more layer of protection alongside your wallet's other security measures. ## Domain risk detection [#domain-risk-detection] The Verify security system will discriminate session proposals & session requests with distinct validations that can be either `VALID`, `INVALID` or `UNKNOWN`. - Domain match: The domain linked to this request has been verified as this application's domain. - This interface appears when the domain a user is attempting to connect to has been ‘verified’ in our domain registry as the registered domain of the application the user is trying to connect to, and the domain has not returned as suspicious from either of the security tools we work with. The `verifyContext` included in the request will have a validation of `VALID`. - Unverified: The domain sending the request cannot be verified. - This interface appears when the domain a user is attempting to connect to has not been verified in our domain registry, but the domain has not returned as suspicious from either of the security tools we work with. The `verifyContext` included in the request will have a validation of `UNKNOWN`. - Mismatch: The application's domain doesn't match the sender of this request. - This interface appears when the domain a user is attempting to connect to has been flagged as a different domain to the one this application has verified in our domain registry, but the domain has not returned as suspicious from either of the security tools we work with. The `verifyContext` included in the request will have a validation of `INVALID` - Threat: This domain is flagged as malicious and potentially harmful. - This interface appears when the domain a user is attempting to connect to has been flagged as malicious on one or more of the security tools we work with. The `verifyContext` included in the request will contain parameter `isScam` with value `true`. ### Reading `verifyContext` by connection type [#reading-verifycontext-by-connection-type] How your wallet should read `verifyContext` depends on how the dApp connects: - **Web dApp over QR code or deep link (relay):** This is the full Verify API, including scam checks. Show all four states: `VALID` as Domain match, `UNKNOWN` as Cannot verify, `INVALID` as Mismatch, and `isScam` as Security risk (ideally blocking or requiring the user to confirm). - **Native dApp over relay:** Native apps can't create a Verify attestation, so `UNKNOWN` is expected here. We suggest a neutral "Cannot verify" label rather than an alarming warning. - **[Link Mode](/wallets/features/link-mode) (native to native):** The domain check above applies, with no scam check. `INVALID` means the dApp's universal link domain doesn't match its `metadata.url`. The wallet's own Link Mode setup also needs to be complete, or the result falls back to `INVALID`. ### Implementation [#implementation] Every `session_proposal`, `session_authenticate` and `session_request` event includes a `verifyContext`. Map it to one of the four states once, then use that state in each handler. ```javascript function getVerifyState(verifyContext) { const { validation, isScam } = verifyContext.verified // Threat: only set over relay, since Link Mode has no scam check if (isScam) return "THREAT" switch (validation) { case "VALID": return "DOMAIN_MATCH" case "INVALID": return "MISMATCH" default: // UNKNOWN: expected for native dApps over relay. Link Mode never returns UNKNOWN return "UNVERIFIED" } } // Session proposals always arrive over relay, from a web or native dApp walletKit.on("session_proposal", async (proposal) => { const state = getVerifyState(proposal.verifyContext) // show the state on the approval screen }) // One-click auth requests can arrive over relay or Link Mode walletKit.on("session_authenticate", async (payload) => { const state = getVerifyState(payload.verifyContext) const isLinkMode = payload.transportType === "link_mode" // in Link Mode, MISMATCH means the universal link domain doesn't match metadata.url }) // Session requests: read the transport from the session they belong to walletKit.on("session_request", async (request) => { const state = getVerifyState(request.verifyContext) const { transportType } = walletKit.getActiveSessions()[request.topic] // show the state on the signing screen }) ``` Present each state like this: - `THREAT`: Block the request, or require the user to explicitly accept the risk. Check before anything else, so the user doesn't also see a Mismatch warning. - `MISMATCH`: Show a warning and proceed only if the user accepts the risk. - `UNVERIFIED`: Show a neutral "Cannot verify" label. Don't block the request, since native dApps over relay always land here. - `DOMAIN_MATCH`: Show a verified badge and proceed as normal. For live demo examples of the intended Verify API flows, check out our demo apps: - [Demo Wallet](https://react-wallet.walletconnect.com) - [Demo App](https://react-app.walletconnect.com/) - you can toggle between the verify states by clicking on the `gear` & selecting the decided Validation before connecting to the wallet - [Demo Malicious App](https://malicious-app-verify-simulation.vercel.app/) - this app is flagged as malicious and will have the `isScam` parameter set to `true` in the `verifyContext` of the request