What is the xrpl.js library and how do I use it?
Last updated:
xrpl.js is the official JavaScript/TypeScript SDK for interacting with the XRP Ledger, providing high-level APIs for transactions, account management, and network connectivity—making it the most popular choice for XRPL development.
## Overview
What It Is: A comprehensive NPM package that wraps XRPL's WebSocket and JSON-RPC APIs with developer-friendly JavaScript functions.
Installation: ```bash npm install xrpl # or yarn add xrpl ```
Supported Environments: Node.js (16+), browsers (via bundlers), TypeScript (full type definitions included).
Repository: https://github.com/XRPL-Labs/xrpl.js
## Core Features
Client Connection: ```javascript const { Client } = require('xrpl')
// Mainnet const client = new Client('wss://xrplcluster.com')
// Testnet const client = new Client('wss://s.altnet.rippletest.net:51233')
await client.connect() // ... use client await client.disconnect() ```
Wallet Management: ```javascript const { Wallet } = require('xrpl')
// Generate new wallet const newWallet = Wallet.generate()
// From seed const wallet = Wallet.fromSeed('sYourSecretSeed...')
// From mnemonic const wallet = Wallet.fromMnemonic('word1 word2 ... word24')
console.log(wallet.address) // rXXX... console.log(wallet.publicKey) // Public key hex console.log(wallet.privateKey) // Private key hex ```
Transactions: ```javascript const { xrpToDrops } = require('xrpl')
// Prepare payment const payment = { TransactionType: 'Payment', Account: wallet.address, Destination: 'rRecipient...', Amount: xrpToDrops('25.5'), // Converts to drops Memos: [{ Memo: { MemoData: Buffer.from('Payment for services').toString('hex') } }] }
// Auto-fill (adds Fee, Sequence, LastLedgerSequence) const prepared = await client.autofill(payment)
// Sign with wallet const signed = wallet.sign(prepared)
// Submit and wait for validation const result = await client.submitAndWait(signed.tx_blob)
if (result.result.meta.TransactionResult === 'tesSUCCESS') { console.log('Transaction successful!') } ```
Account Queries: ```javascript // Get balance const balance = await client.getXrpBalance('rAddress...')
// Account info const accountInfo = await client.request({ command: 'account_info', account: 'rAddress...', ledger_index: 'validated' })
// Transaction history const txHistory = await client.request({ command: 'account_tx', account: 'rAddress...', limit: 10 }) ```
## Common Patterns
Real-Time Payment Monitoring: ```javascript await client.request({ command: 'subscribe', accounts: ['rYourAddress...'] })
client.on('transaction', (tx) => { if (tx.transaction.TransactionType === 'Payment' && tx.transaction.Destination === 'rYourAddress...' && tx.validated) { console.log(`Received ${dropsToXrp(tx.transaction.Amount)} XRP`) } }) ```
DEX Trading: ```javascript const offer = { TransactionType: 'OfferCreate', Account: wallet.address, TakerPays: xrpToDrops('100'), // Sell 100 XRP TakerGets: { currency: 'USD', issuer: 'rIssuerAddress...', value: '50' // For 50 USD } }
const prepared = await client.autofill(offer) const signed = wallet.sign(prepared) await client.submitAndWait(signed.tx_blob) ```
Trust Lines: ```javascript const trustSet = { TransactionType: 'TrustSet', Account: wallet.address, LimitAmount: { currency: 'USD', issuer: 'rIssuerAddress...', value: '1000' // Trust up to 1000 USD } }
const prepared = await client.autofill(trustSet) const signed = wallet.sign(prepared) await client.submitAndWait(signed.tx_blob) ```
## Utility Functions
Amount Conversions: ```javascript const { xrpToDrops, dropsToXrp } = require('xrpl')
xrpToDrops('10.5') // '10500000' dropsToXrp('10500000') // '10.5' ```
Address Validation: ```javascript const { isValidAddress, isValidClassicAddress } = require('xrpl')
isValidAddress('rN7n7otQDd6FczFgLdlqtyMVrn3LZZcP3X') // true isValidClassicAddress('rN7n7otQDd6FczFgLdlqtyMVrn3LZZcP3X') // true ```
Key Derivation: ```javascript const { deriveAddress, deriveKeypair } = require('xrpl')
const keypair = deriveKeypair('sSecretSeed...') const address = deriveAddress(keypair.publicKey) ```
## Advanced Features
Path Finding (Cross-Currency Payments): ```javascript const paths = await client.request({ command: 'ripple_path_find', source_account: 'rSender...', destination_account: 'rReceiver...', destination_amount: { currency: 'EUR', issuer: 'rIssuer...', value: '100' } })
// Use paths in payment const payment = { TransactionType: 'Payment', Account: 'rSender...', Destination: 'rReceiver...', Amount: { currency: 'EUR', issuer: 'rIssuer...', value: '100' }, Paths: paths.result.alternatives[0].paths_computed } ```
Escrows: ```javascript // Create escrow (release in 24 hours) const escrowCreate = { TransactionType: 'EscrowCreate', Account: wallet.address, Destination: 'rReceiver...', Amount: xrpToDrops('100'), FinishAfter: Math.floor(Date.now() / 1000) + 86400 // Unix timestamp }
// Later: Finish escrow const escrowFinish = { TransactionType: 'EscrowFinish', Account: anyAddress, // Anyone can trigger Owner: wallet.address, OfferSequence: escrowSequenceNumber } ```
## TypeScript Support
xrpl.js includes full TypeScript definitions: ```typescript import { Client, Wallet, Payment, TrustSet } from 'xrpl'
const client: Client = new Client('wss://xrplcluster.com') const wallet: Wallet = Wallet.generate()
const payment: Payment = { TransactionType: 'Payment', Account: wallet.address, Destination: 'rReceiver...', Amount: '1000000' // TypeScript enforces correct types } ```
## Error Handling
```javascript try { const result = await client.submitAndWait(signed.tx_blob) if (result.result.meta.TransactionResult !== 'tesSUCCESS') { console.error('Transaction failed:', result.result.meta.TransactionResult) // Handle specific error codes (tecUNFUNDED_PAYMENT, etc.) } } catch (error) { if (error instanceof xrpl.RippledError) { console.error('Rippled error:', error.data) } else if (error instanceof xrpl.ValidationError) { console.error('Invalid transaction:', error.message) } else { console.error('Unknown error:', error) } } ```
## Best Practices
Connection Management: - Reuse client connections (don't create new client per request) - Implement reconnection logic for production apps - Use connection pooling for high-throughput applications
Transaction Submission: - Always use `autofill()` to set Fee, Sequence, LastLedgerSequence - Use `submitAndWait()` for critical transactions (waits for validation) - Use `submit()` for high-throughput scenarios (check later) - Implement retry logic with exponential backoff
Security: - Never log or expose wallet seeds/private keys - Use environment variables for sensitive data - Validate amounts and addresses before signing - Use testnet for development
Performance: - Batch account queries when possible - Use WebSocket subscriptions instead of polling - Cache validated ledger data (immutable) - Implement request rate limiting
## Resources
- NPM Package: https://www.npmjs.com/package/xrpl - Documentation: https://js.xrpl.org/ - GitHub: https://github.com/XRPL-Labs/xrpl.js - Examples: https://github.com/XRPL-Labs/xrpl.js/tree/main/packages/xrpl/examples
Recommendation: xrpl.js is the definitive JavaScript SDK for XRPL development, with excellent documentation, active maintenance, and comprehensive feature coverage. Use it for any JavaScript/TypeScript project interacting with XRPL.
Last updated: February 2026