@tomo-inc/wallet-connect-kit
v0.0.19
Published
A lightweight React SDK for integrating crypto wallet connection functionality into your applications. It provides a configurable wallet list modal and basic account operations.
Downloads
241
Readme
Wallet Connect Kit
A lightweight React SDK for integrating crypto wallet connection functionality into your applications. It provides a configurable wallet list modal and basic account operations.
Requirements
- React 18 or higher
- TypeScript 5 or higher (recommended)
Installation
Install Wallet Connect Kit using your preferred package manager:
npm install @tomo-inc/wallet-connect-kitpnpm add @tomo-inc/wallet-connect-kityarn add @tomo-inc/wallet-connect-kitDependencies
Wallet Connect Kit requires the following peer dependencies:
react >= 18react-dom >= 18wagmi >= 2.0.0(optional, if using WagmiProvider)
Quick Start
0. Prerequisites
This guide assumes you have already installed Wallet Connect Kit. If you haven't, please refer to the installation steps above.
1. Setup Provider
First, wrap your app root component with WalletConnectProvider:
// App.tsx
import React from "react";
import { WalletConnectProvider } from "@tomo-inc/wallet-connect-kit";
export default function App() {
return (
<WalletConnectProvider>
<YourApp />
</WalletConnectProvider>
);
}2. Connect Wallet
Use the useWalletConnect hook to open the wallet connection modal and manage connection state:
// ConnectButton.tsx
import React from "react";
import { useWalletConnect } from "@tomo-inc/wallet-connect-kit";
export function ConnectButton() {
const { openModal, isConnected, disconnect, isConnecting } =
useWalletConnect();
if (isConnecting) {
return <button disabled>Connecting...</button>;
}
return (
<button onClick={() => (isConnected ? disconnect() : openModal())}>
{isConnected ? "Disconnect" : "Connect Wallet"}
</button>
);
}3. Read Account Information
Use the useAccount hook to get the currently connected account information:
// AccountInfo.tsx
import React from "react";
import { useAccount } from "@tomo-inc/wallet-connect-kit";
export function AccountInfo() {
const { address, chainId, chainType, currentWallet } = useAccount();
if (!address) {
return <div>No wallet connected</div>;
}
return (
<div>
<div>Address: {address}</div>
<div>Chain ID: {chainId}</div>
<div>Chain Type: {chainType}</div>
<div>Wallet: {currentWallet?.info?.name}</div>
</div>
);
}4. Sign Message
Use the signMessage method from the useAccount hook to sign messages:
// SignMessageButton.tsx
import React from "react";
import { useAccount } from "@tomo-inc/wallet-connect-kit";
export function SignMessageButton() {
const { signMessage, address } = useAccount();
const handleSignMessage = async () => {
if (!signMessage) {
console.error("Signing functionality not available");
return;
}
try {
const signature = await signMessage({
message: "Hello Tomo Wallet",
});
console.log("Signature result:", signature);
} catch (error) {
console.error("Signing failed:", error);
}
};
if (!address) {
return null;
}
return <button onClick={handleSignMessage}>Sign Message</button>;
}5. Sign In with Wallet (SIW)
Use the signInWithWallet method to sign in with wallet and obtain an authentication token:
// SignInButton.tsx
import React from "react";
import { useAccount } from "@tomo-inc/wallet-connect-kit";
export function SignInButton() {
const { signInWithWallet, address } = useAccount();
const handleSignIn = async () => {
try {
const token = await signInWithWallet();
console.log("Authentication token:", token);
// Save token to localStorage or send to backend
} catch (error) {
console.error("Sign in failed:", error);
}
};
if (!address) {
return null;
}
return <button onClick={handleSignIn}>Sign In with Wallet</button>;
}Configuration
WalletConnectProvider accepts an optional config prop to customize the SDK's behavior.
Basic Configuration
import { WalletConnectProvider } from "@tomo-inc/wallet-connect-kit";
import type { WalletConnectKitConfig } from "@tomo-inc/wallet-connect-kit";
const config: WalletConnectKitConfig = {
// WalletConnect project ID (obtain from https://cloud.walletconnect.com)
walletConnectProjectId: "your-project-id",
// Application metadata
metadata: {
name: "My DApp",
description: "My decentralized application",
url: "https://myapp.com",
icons: ["https://myapp.com/icon.png"],
},
};
export function App() {
return (
<WalletConnectProvider config={config}>
<YourApp />
</WalletConnectProvider>
);
}Configure Supported Chains
Chains are automatically loaded by default. If you need to customize chains, use the getChains() method:
import { WalletConnectProvider, getChains } from "@tomo-inc/wallet-connect-kit";
import { useEffect, useState } from "react";
export function App() {
const [chains, setChains] = useState<
Awaited<ReturnType<typeof getChains>> | undefined
>(undefined);
useEffect(() => {
getChains().then(setChains);
}, []);
return (
<WalletConnectProvider config={{ chains }}>
<YourApp />
</WalletConnectProvider>
);
}Configure Custom Wallets
Connectors are automatically loaded by default. If you need to customize connectors, use the getConnectors() method:
import {
WalletConnectProvider,
getConnectors,
} from "@tomo-inc/wallet-connect-kit";
import { useEffect, useState } from "react";
export function App() {
const [connectors, setConnectors] = useState<
Awaited<ReturnType<typeof getConnectors>> | undefined
>(undefined);
useEffect(() => {
getConnectors().then(setConnectors);
}, []);
return (
<WalletConnectProvider config={{ connectors }}>
<YourApp />
</WalletConnectProvider>
);
}Configure Login Options
You can configure supported login methods, including basic logins (email, external wallets) and social logins (Google, X/Twitter):
import { WalletConnectProvider } from "@tomo-inc/wallet-connect-kit";
const config = {
login: {
// Basic login methods
basicLogins: ["email", "externalWallets"], // or ["email"] or ["externalWallets"]
// Social login methods
socialLogins: [
{
type: "google",
},
{
type: "x",
},
],
},
};
export function App() {
return (
<WalletConnectProvider config={config}>
<YourApp />
</WalletConnectProvider>
);
}Configure Theme
You can customize the UI theme:
import { WalletConnectProvider } from "@tomo-inc/wallet-connect-kit";
import type { ThemeConfig } from "@tomo-inc/wallet-connect-kit";
const config = {
theme: {
themes: {
light: {
colors: {
primary: {
DEFAULT: "#FE3C9C",
foreground: "#FFF",
},
background: "#FFFFFF",
foreground: "#000000",
},
},
dark: {
colors: {
primary: {
DEFAULT: "#FF5CB8",
foreground: "#FFF",
},
background: "#000000",
foreground: "#FFFFFF",
},
},
},
} as ThemeConfig,
};
export function App() {
return (
<WalletConnectProvider config={config}>
<YourApp />
</WalletConnectProvider>
);
}Complete Configuration Example
import {
WalletConnectProvider,
getChains,
getConnectors,
} from "@tomo-inc/wallet-connect-kit";
import type { WalletConnectKitConfig } from "@tomo-inc/wallet-connect-kit";
import { useEffect, useState } from "react";
export function App() {
const [chains, setChains] = useState<
Awaited<ReturnType<typeof getChains>> | undefined
>(undefined);
const [connectors, setConnectors] = useState<
Awaited<ReturnType<typeof getConnectors>> | undefined
>(undefined);
useEffect(() => {
const loadConfig = async () => {
const [loadedChains, loadedConnectors] = await Promise.all([
getChains(),
getConnectors(),
]);
setChains(loadedChains);
setConnectors(loadedConnectors);
};
loadConfig();
}, []);
const config: WalletConnectKitConfig = {
// WalletConnect configuration
walletConnectProjectId: "your-project-id",
// DApp application metadata
metadata: {
name: "My DApp",
description: "My decentralized application",
url: "https://myapp.com",
icons: ["https://myapp.com/icon.png"],
},
// Supported chains (must use getChains)
chains,
// Custom wallets (must use getConnectors)
connectors,
// Login configuration
login: {
basicLogins: ["email", "externalWallets"],
socialLogins: [{ type: "google" }, { type: "x" }],
},
// Theme configuration
theme: {
themes: {
light: {
colors: {
primary: {
DEFAULT: "#FE3C9C",
foreground: "#FFF",
},
},
},
},
},
};
if (!chains || !connectors) {
return <div>Loading configuration...</div>;
}
return (
<WalletConnectProvider config={config}>
<YourApp />
</WalletConnectProvider>
);
}API Reference
WalletConnectProvider
Main Provider component for wrapping your application.
Props:
interface WalletConnectProviderProps {
children: React.ReactNode;
config?: WalletConnectKitConfig;
}useWalletConnect
Hook for controlling the wallet connection modal and managing connection state.
Returns:
interface UseWalletConnect {
// Modal control
isOpenModal: boolean;
openModal: () => void;
closeModal: () => void;
// Connection state
isConnected: boolean;
isConnecting: boolean;
error: Error | null;
// Connection operations
connect: (variables?: ConnectVariables) => Promise<ConnectData>;
disconnect: () => Promise<void>;
}Example:
const {
isOpenModal,
openModal,
closeModal,
isConnected,
isConnecting,
connect,
disconnect,
} = useWalletConnect();useAccount
Hook for getting the currently connected account information and performing account-related operations.
Returns:
interface UseAccount {
// Account information
address: string;
balance?: string;
chainType?: ChainType;
chainId?: string;
currentWallet?: Connector | null;
currentProvider?: any;
// Operations
switchChain: (options: SwitchChainOptions) => Promise<boolean>;
signMessage?: (params: {
message: string;
nonce?: string;
}) => Promise<string | Uint8Array>;
signInWithWallet: (params?: SignInParams) => Promise<string | Uint8Array>;
}Example:
const {
address,
chainId,
chainType,
signMessage,
signInWithWallet,
switchChain,
} = useAccount();getChains
Utility function to get all available chains. Automatically fetches chains from the backend API and returns them in the config format.
Signature:
function getChains(): Promise<Partial<Record<ChainType, EvmChain[] | any[]>>>;Returns:
- A Promise that resolves to a chain configuration object containing all available chains
- Automatically includes EVM, Solana, Aptos, and Dogecoin chains
- Falls back to default chains if the API request fails
Example:
import { getChains } from "@tomo-inc/wallet-connect-kit";
import { useEffect, useState } from "react";
export function MyComponent() {
const [chains, setChains] = useState<
Awaited<ReturnType<typeof getChains>> | undefined
>(undefined);
useEffect(() => {
const loadChains = async () => {
const allChains = await getChains();
setChains(allChains);
};
loadChains();
}, []);
// Use chains in your config
const config = { chains };
}getConnectors
Utility function to get all available connectors. Automatically loads connectors from @tomo-inc/wallet-adaptor-base, including EIP6963, Wallet Standard, and WalletConnect wallets.
Signature:
function getConnectors(): Promise<WalletConfig[]>;Returns:
- A Promise that resolves to an array of all available wallet connectors
- Includes EIP6963 wallets (browser extension wallets)
- Includes Wallet Standard wallets (Solana, Aptos, etc.)
- Includes WalletConnect wallets (from WalletConnect Cloud Explorer API)
- Includes default connectors from the Tomo wallet list
Example:
import { getConnectors } from "@tomo-inc/wallet-connect-kit";
import { useEffect, useState } from "react";
export function MyComponent() {
const [connectors, setConnectors] = useState<
Awaited<ReturnType<typeof getConnectors>> | undefined
>(undefined);
useEffect(() => {
const loadConnectors = async () => {
const allConnectors = await getConnectors();
setConnectors(allConnectors);
};
loadConnectors();
}, []);
// Use connectors in your config
const config = { connectors };
}Advanced Usage
Switch Chain
Use the switchChain method from the useAccount hook to switch chains:
import { useAccount } from "@tomo-inc/wallet-connect-kit";
import type { Chain } from "@tomo-inc/wallet-connect-kit";
export function SwitchChainButton() {
const { switchChain, chainId } = useAccount();
const handleSwitchChain = async () => {
const targetChain: Chain = {
id: 137,
name: "Polygon",
nativeCurrency: {
name: "MATIC",
symbol: "MATIC",
decimals: 18,
},
rpcUrls: {
default: {
http: ["https://polygon-rpc.com"],
},
},
blockExplorers: {
default: {
name: "PolygonScan",
url: "https://polygonscan.com",
},
},
};
try {
const success = await switchChain({
chainType: "evm",
chainInfo: targetChain,
});
if (success) {
console.log("Chain switched successfully");
}
} catch (error) {
console.error("Chain switch failed:", error);
}
};
return <button onClick={handleSwitchChain}>Switch to Polygon</button>;
}Get Wallet Providers and Connectors
Use the useConnectors hook to get all available providers from the currently connected wallet, grouped by chain type.
This is useful for multi-chain wallets (for example, OKX Wallet supports EVM, Solana, Aptos, Dogecoin, etc.).
Different chain providers are usually based on different underlying protocols, for example EVM providers commonly follow the EIP-1193 standard, while Dogecoin providers may come from Unisat-compatible implementations.
import { useConnectors } from "@tomo-inc/wallet-connect-kit";
export function SignMessageExamples() {
const { connectors } = useConnectors();
if (!connectors) {
return <div>No wallet connected</div>;
}
// connectors is an object with chain types as keys
// e.g., { evm: { provider, protocol, standard }, dogecoin: { provider, protocol, standard }, ... }
const evmConnector = connectors.evm ?? null;
const dogeConnector = connectors.dogecoin ?? null;
// EVM provider usually follows EIP-1193 standard
const evmProvider = evmConnector?.provider;
// Dogecoin provider usually comes from a Unisat-compatible provider
const dogeProvider = dogeConnector?.provider;
const handleEvmSignMessage = async () => {
if (!evmProvider) return;
const accounts = await evmProvider.request({
method: "eth_requestAccounts",
});
const from = accounts[0];
const message = "Hello from EVM";
// EIP-1193 personal_sign example
const signature = await evmProvider.request({
method: "personal_sign",
params: [message, from],
});
console.log("EVM signature:", signature);
};
const handleDogeSignMessage = async () => {
if (!dogeProvider) return;
const message = "Hello from Dogecoin";
// Unisat-like Dogecoin signMessage example
// Most Unisat-compatible providers expose a signMessage method
const signature = await dogeProvider.signMessage(message);
console.log("Dogecoin signature:", signature);
};
return (
<div>
<button disabled={!evmProvider} onClick={handleEvmSignMessage}>
Sign EVM Message
</button>
<button disabled={!dogeProvider} onClick={handleDogeSignMessage}>
Sign Dogecoin Message
</button>
</div>
);
}Returns:
interface UseConnectors {
// All available providers from the current wallet, keyed by chain type
connectors: ConnectorProviders | null;
// The currently active provider for the selected chain
currentProvider: WalletProvider | null;
}Note: connectors contains all connectors supported by the current wallet. For example, if you connect OKX Wallet, connectors may include evm, dogecoin, solana, and aptos connectors. Each entry provides a provider instance that you can use directly to call chain-specific RPC methods.
Integration with Wagmi
Wallet Connect Kit can seamlessly integrate with Wagmi. If you're already using WagmiProvider, Wallet Connect Kit will automatically detect and use Wagmi's configuration:
import { WagmiProvider } from "wagmi";
import { WalletConnectProvider } from "@tomo-inc/wallet-connect-kit";
import { config } from "./wagmi-config";
export function App() {
return (
<WagmiProvider config={config}>
<WalletConnectProvider>
<YourApp />
</WalletConnectProvider>
</WagmiProvider>
);
}Error Handling
Always handle errors in connections and operations:
import { useWalletConnect, useAccount } from "@tomo-inc/wallet-connect-kit";
export function WalletComponent() {
const { error, isConnecting } = useWalletConnect();
const { signMessage } = useAccount();
const handleSign = async () => {
try {
if (!signMessage) {
throw new Error("Signing functionality not available");
}
const signature = await signMessage({ message: "Hello" });
console.log("Signing successful:", signature);
} catch (error) {
console.error("Signing failed:", error);
// Display error message to user
}
};
if (error) {
return <div>Error: {error.message}</div>;
}
if (isConnecting) {
return <div>Connecting...</div>;
}
return <button onClick={handleSign}>Sign</button>;
}Type Definitions
WalletConnectKitConfig
interface WalletConnectKitConfig {
connectors?: WalletConfig[];
chains?: Partial<Record<ChainType, EvmChain[] | any[]>>;
walletConnectProjectId?: string;
metadata?: {
name: string;
description: string;
url: string;
icons: string[];
};
theme?: ThemeConfig;
login?: UserLoginConfig;
}Chain
interface Chain {
id: number;
name: string;
nativeCurrency: {
name: string;
symbol: string;
decimals: number;
};
rpcUrls: {
default: {
http: string[];
};
};
blockExplorers?: {
default: {
name: string;
url: string;
};
};
testnet?: boolean;
}ChainType
type ChainType = "evm" | "solana" | "aptos" | "dogecoin";Exports
WalletConnectProvider- Main Provider componentuseAccount- Account information HookuseWalletConnect- Connect HookuseConnectors- Providers information Hook (get all available providers from current wallet)getChains- Utility function to configure chains (can wrap backend API chains)getConnectors- Utility function to configure connectors (from @tomo-inc/wallet-adaptor-base)- Types:
WalletConnectKitConfig,Chain,WalletConfig,UseAccount,ChainType,ModalView,ThemeConfig,UserLoginConfig
FAQ
How to get WalletConnect Project ID?
- Visit WalletConnect Cloud
- Create a new project or select an existing project
- Copy the Project ID and use it in your configuration
How to customize chains and connectors?
You can use getChains() and getConnectors() methods to customize chains and connectors:
import { getChains, getConnectors } from "@tomo-inc/wallet-connect-kit";
// Get all available chains
const chains = await getChains();
// Get all available connectors
const connectors = await getConnectors();
// Use in config
const config = { chains, connectors };The getChains() method automatically fetches chains from the backend API and includes EVM, Solana, Aptos, and Dogecoin chains. The getConnectors() method loads all available connectors including EIP6963, Wallet Standard, and WalletConnect wallets.
What chain types are supported?
Currently, EVM chains are primarily supported, along with Solana, Aptos, and Dogecoin chains.
