How do I connect to XRPL mainnet vs testnet?
Last updated:
Connecting to the appropriate XRP Ledger network is fundamental to XRPL development. The mainnet is for production applications with real XRP, while testnet provides a safe environment for development and testing with free test XRP. Understanding how to connect to each network and when to use them is essential for successful XRPL integration.
Network Overview
XRPL operates multiple networks. Mainnet is the production blockchain with real XRP where live transactions occur. This is where actual value is exchanged and all production applications operate. Testnet is a test network with free test XRP for development, exactly mirroring mainnet functionality but with no real value. Devnet is an experimental network for testing new features and amendments before they reach testnet or mainnet. AMM-Devnet is a specialized network for testing Automated Market Maker functionality.
Mainnet Connection
Mainnet endpoints are provided by multiple organizations for redundancy and reliability.
Public mainnet endpoints include: - wss://xrplcluster.com (WebSocket, load-balanced cluster) - wss://s1.ripple.com (WebSocket, Ripple's server) - wss://s2.ripple.com (WebSocket, Ripple's server) - https://xrplcluster.com (JSON-RPC) - https://s1.ripple.com:51234 (JSON-RPC)
Connecting with JavaScript (xrpl.js):
```javascript const xrpl = require('xrpl');
async function connectMainnet() { // Connect to mainnet const client = new xrpl.Client('wss://xrplcluster.com'); try { await client.connect(); console.log('Connected to XRPL Mainnet'); // Verify connection const serverInfo = await client.request({ command: 'server_info' }); console.log('Network ID:', serverInfo.result.info.network_id); // 0 for mainnet console.log('Ledger Index:', serverInfo.result.info.validated_ledger.seq); console.log('Server State:', serverInfo.result.info.server_state); // Your mainnet operations here } catch (error) { console.error('Connection error:', error); } finally { await client.disconnect(); } }
connectMainnet(); ```
Connecting with Python (xrpl-py):
```python from xrpl.clients import JsonRpcClient, WebsocketClient import asyncio
# JSON-RPC connection (synchronous) client = JsonRpcClient("https://xrplcluster.com")
response = client.request({ "command": "server_info" })
print(f"Network ID: {response.result['info']['network_id']}") print(f"Ledger: {response.result['info']['validated_ledger']['seq']}")
# WebSocket connection (asynchronous) async def connect_mainnet(): async with WebsocketClient("wss://xrplcluster.com") as client: response = await client.request({ "command": "server_info" }) print(f"Connected to mainnet: {response.result['info']['server_state']}")
asyncio.run(connect_mainnet()) ```
Testnet Connection
Testnet provides a safe environment for development with free test XRP from faucets.
Public testnet endpoints: - wss://s.altnet.rippletest.net:51233 (WebSocket) - https://s.altnet.rippletest.net:51234 (JSON-RPC)
Connecting to testnet with JavaScript:
```javascript const xrpl = require('xrpl');
async function connectTestnet() { // Connect to testnet const client = new xrpl.Client('wss://s.altnet.rippletest.net:51233'); try { await client.connect(); console.log('Connected to XRPL Testnet'); // Create and fund a test wallet const wallet = (await client.fundWallet()).wallet; console.log('Test wallet created!'); console.log('Address:', wallet.address); console.log('Seed:', wallet.seed); // Check balance const response = await client.request({ command: 'account_info', account: wallet.address, ledger_index: 'validated' }); const balance = xrpl.dropsToXrp(response.result.account_data.Balance); console.log('Balance:', balance, 'XRP'); } catch (error) { console.error('Error:', error); } finally { await client.disconnect(); } }
connectTestnet(); ```
Connecting to testnet with Python:
```python from xrpl.clients import JsonRpcClient from xrpl.wallet import generate_faucet_wallet
# Connect to testnet client = JsonRpcClient("https://s.altnet.rippletest.net:51234")
# Generate and fund test wallet test_wallet = generate_faucet_wallet(client, debug=True)
print(f"Test wallet address: {test_wallet.address}") print(f"Seed: {test_wallet.seed}")
# Verify funding from xrpl.models.requests import AccountInfo from xrpl.utils import drops_to_xrp
account_info = client.request(AccountInfo( account=test_wallet.address, ledger_index="validated" ))
balance = drops_to_xrp(account_info.result["account_data"]["Balance"]) print(f"Balance: {balance} XRP") ```
Devnet Connection
Devnet endpoints for experimental features: - wss://s.devnet.rippletest.net:51233 (WebSocket) - https://s.devnet.rippletest.net:51234 (JSON-RPC)
```javascript const client = new xrpl.Client('wss://s.devnet.rippletest.net:51233'); ```
Environment Configuration
Use environment variables to manage network configuration:
```javascript // config.js const NETWORKS = { mainnet: 'wss://xrplcluster.com', testnet: 'wss://s.altnet.rippletest.net:51233', devnet: 'wss://s.devnet.rippletest.net:51233' };
const network = process.env.XRPL_NETWORK || 'testnet'; const XRPL_ENDPOINT = NETWORKS[network];
module.exports = { XRPL_ENDPOINT, network };
// Usage const { XRPL_ENDPOINT } = require('./config'); const client = new xrpl.Client(XRPL_ENDPOINT); ```
Connection Best Practices
Implement automatic reconnection:
```javascript const xrpl = require('xrpl');
class RobustXRPLClient { constructor(url) { this.url = url; this.client = new xrpl.Client(url); this.setupEventHandlers(); } setupEventHandlers() { this.client.on('disconnected', (code) => { console.log('Disconnected, code:', code); setTimeout(() => this.reconnect(), 5000); }); this.client.on('error', (error) => { console.error('Client error:', error); }); } async connect() { await this.client.connect(); console.log('Connected to', this.url); } async reconnect() { try { await this.client.connect(); console.log('Reconnected successfully'); } catch (error) { console.error('Reconnection failed:', error); setTimeout(() => this.reconnect(), 5000); } } }
const client = new RobustXRPLClient('wss://xrplcluster.com'); ```
When to Use Each Network
Use Mainnet for production applications, real financial transactions, live trading and DEX operations, and production NFT minting.
Use Testnet for development and testing, integration testing, learning XRPL development, testing new features before mainnet deployment, and CI/CD pipelines.
Use Devnet for testing unreleased amendments, experimental feature development, and participating in early feature testing.
Common Connection Issues
WebSocket connection failures: Try alternative endpoints or use JSON-RPC as fallback. Network ID mismatches: Always verify network_id (0=mainnet, 1=testnet, 2=devnet). Timeout errors: Increase connection timeout or check firewall settings. SSL certificate errors: Ensure your environment supports modern TLS.
Network Verification
Always verify you're connected to the correct network:
```javascript async function verifyNetwork(client) { const response = await client.request({ command: 'server_info' }); const networkId = response.result.info.network_id; const networks = { 0: 'Mainnet', 1: 'Testnet', 2: 'Devnet' }; console.log('Connected to:', networks[networkId] || 'Unknown'); return networkId; } ```
Proper network selection ensures safe development practices and prevents accidental mainnet transactions during testing.