Development

What is xrpl-py (Python library)?

Last updated:

xrpl-py is the official Python library for XRP Ledger development, maintained by Ripple. It provides a comprehensive, Pythonic interface for interacting with XRPL, making it ideal for backend services, data analysis, trading bots, automation scripts, and machine learning applications.

Installation and Setup

Install xrpl-py using pip:

```bash pip install xrpl-py ```

For development with additional tools:

```bash pip install xrpl-py[dev] ```

Requirements: Python 3.7 or higher. The library has minimal dependencies and is compatible with major Python frameworks like Django, Flask, and FastAPI.

Core Components

The library is organized into several modules. The clients module provides JsonRpcClient for HTTP connections and WebsocketClient for real-time subscriptions. The wallet module handles key generation, storage, and signing. The models module contains dataclasses for all transaction types and API requests. The transaction module provides high-level functions for submitting and tracking transactions. The utils module includes helper functions for unit conversion, address validation, and encoding.

Client Connections

Connect to XRPL using JSON-RPC:

```python from xrpl.clients import JsonRpcClient

# Testnet connection client = JsonRpcClient("https://s.altnet.rippletest.net:51234")

# Mainnet connection client = JsonRpcClient("https://xrplcluster.com")

# Check connection response = client.request({ "command": "server_info" }) print(f"Ledger index: {response.result['info']['validated_ledger']['seq']}") ```

Connect using WebSocket for subscriptions:

```python from xrpl.clients import WebsocketClient import asyncio

async def main(): async with WebsocketClient("wss://s.altnet.rippletest.net:51233") as client: # Subscribe to ledger closes response = await client.request({ "command": "subscribe", "streams": ["ledger"] }) # Listen for messages async for message in client: if "ledger_index" in message: print(f"New ledger: {message['ledger_index']}")

asyncio.run(main()) ```

Wallet Management

Create and manage wallets:

```python from xrpl.wallet import Wallet

# Generate new wallet wallet = Wallet.create() print(f"Address: {wallet.address}") print(f"Public Key: {wallet.public_key}") print(f"Private Key: {wallet.private_key}") print(f"Seed: {wallet.seed}")

# Restore wallet from seed existing_wallet = Wallet.from_seed("sEdVQG9T4Bb6u7rNJxLJg6Hp8TSmN4a")

# Restore from secret (classic address) wallet_from_secret = Wallet.from_secret("shqNw4HfR5KJqe9wKNVqH8HZvqMr1") ```

Sending Transactions

Send XRP payment:

```python from xrpl.models.transactions import Payment from xrpl.transaction import submit_and_wait, safe_sign_and_autofill_transaction from xrpl.utils import xrp_to_drops from xrpl.wallet import Wallet from xrpl.clients import JsonRpcClient

client = JsonRpcClient("https://s.altnet.rippletest.net:51234") wallet = Wallet.from_seed("sEdVQG9T4Bb6u7rNJxLJg6Hp8TSmN4a")

# Create payment transaction payment = Payment( account=wallet.address, destination="rPEPPER7kfTD9w2To4CQk6UCfuHM9c6GDY", amount=xrp_to_drops(10), destination_tag=12345 )

# Submit and wait for validation try: response = submit_and_wait(payment, client, wallet) result = response.result if result["meta"]["TransactionResult"] == "tesSUCCESS": print(f"Payment successful!") print(f"Transaction hash: {result['hash']}") print(f"Ledger index: {result['ledger_index']}") else: print(f"Payment failed: {result['meta']['TransactionResult']}") except Exception as e: print(f"Error: {e}") ```

Account Information Queries

Retrieve account data:

```python from xrpl.models.requests import AccountInfo from xrpl.clients import JsonRpcClient

client = JsonRpcClient("https://s.altnet.rippletest.net:51234")

# Get account info account_info = AccountInfo( account="rN7n7otQDd6FczFgLdlqtyMVrn3qHwuSJ1", ledger_index="validated" )

response = client.request(account_info) account_data = response.result["account_data"]

print(f"Balance: {account_data['Balance']} drops") print(f"Sequence: {account_data['Sequence']}") print(f"Owner Count: {account_data['OwnerCount']}") print(f"Previous Transaction: {account_data.get('PreviousTxnID', 'N/A')}") ```

Token Issuance

Issue custom tokens:

```python from xrpl.models.transactions import TrustSet from xrpl.models.amounts import IssuedCurrencyAmount from xrpl.transaction import submit_and_wait

# Holder creates trust line trust_set = TrustSet( account=holder_wallet.address, limit_amount=IssuedCurrencyAmount( currency="USD", issuer=issuer_wallet.address, value="1000" ) )

response = submit_and_wait(trust_set, client, holder_wallet)

# Issuer sends tokens payment = Payment( account=issuer_wallet.address, destination=holder_wallet.address, amount=IssuedCurrencyAmount( currency="USD", issuer=issuer_wallet.address, value="100" ) )

response = submit_and_wait(payment, client, issuer_wallet) ```

Error Handling

Implement robust error handling:

```python from xrpl.transaction import XRPLReliableSubmissionException from xrpl.clients.exceptions import XRPLRequestFailureException

try: response = submit_and_wait(payment, client, wallet) except XRPLReliableSubmissionException as e: print(f"Transaction failed: {e}") except XRPLRequestFailureException as e: print(f"Request failed: {e}") except Exception as e: print(f"Unexpected error: {e}") ```

Utility Functions

Common utility operations:

```python from xrpl.utils import xrp_to_drops, drops_to_xrp from xrpl.core.addresscodec import is_classic_address, is_valid_xaddress from xrpl.utils import str_to_hex, hex_to_str

# Unit conversion drops = xrp_to_drops(10.5) # "10500000" xrp = drops_to_xrp("10500000") # "10.5"

# Address validation if is_classic_address("rN7n7otQDd6FczFgLdlqtyMVrn3qHwuSJ1"): print("Valid classic address")

# String encoding hex_string = str_to_hex("Hello XRPL") # For memos original = hex_to_str(hex_string) ```

Advanced Features

xrpl-py supports advanced XRPL features including Escrows, Payment Channels, Checks, NFTs (XLS-20), AMM (Automated Market Maker), Hooks (on supported networks), and Multi-signing.

Common Issues

Connection timeouts: Use try-except blocks and implement retry logic. Invalid transactions: Use the transaction validator before submitting. Account not found errors: Ensure the account is funded with at least 10 XRP reserve. Sequence number mismatches: Let the library autofill the sequence number.

xrpl-py is actively maintained with excellent documentation at xrpl-py.readthedocs.io and comprehensive examples on GitHub at XRPL-Labs/xrpl-py.

Was this helpful?

Related Questions

Go Deeper

Expand your knowledge with these related lessons

Your First XRPL Connection

45 minintermediate

Cryptographic Mechanics of XRP Escrow

Python script to track all active Ripple escrows and predict next 12 months of releases

41 minbeginner

Client Libraries Deep Dive - xrpl.js, xrpl-py, and xrpl4j

55 minintermediate

Have more questions?

Browse our complete FAQ or contact support.