A complete Python library for interacting with the XRP Ledger blockchain, providing transaction creation, account management, and comprehensive XRPL protocol support
Comprehensive type-safe models for transactions, requests, amounts, currencies, and all XRPL data structures. The models module provides the complete type system for working with XRPL data in a structured, validated way.
Base classes and fundamental data structures used throughout the XRPL ecosystem.
from xrpl.models import Response, AuthAccount, Path, PathStep, XChainBridge
class Response:
"""Base response object for all XRPL requests."""
def __init__(self, result: dict, status: str = None):
self.result = result
self.status = status
def is_successful(self) -> bool:
"""Check if the response indicates success."""
class AuthAccount:
"""Authentication account model for cross-chain operations."""
account: str
class Path:
"""Payment path model representing a sequence of currency exchanges."""
def __init__(self, path_steps: list[PathStep]):
self.path_steps = path_steps
class PathStep:
"""Individual step in a payment path."""
account: str = None
currency: str = None
issuer: str = None
class XChainBridge:
"""Cross-chain bridge identifier."""
issuing_chain_door: str
issuing_chain_issue: dict
locking_chain_door: str
locking_chain_issue: dictType-safe representations of value amounts in different currencies and formats.
from xrpl.models.amounts import (
Amount, IssuedCurrencyAmount, MPTAmount, ClawbackAmount,
is_xrp, is_issued_currency, is_mpt, get_amount_value
)
from typing import Union
# Union type for all amount formats
Amount = Union[str, IssuedCurrencyAmount, MPTAmount]
class IssuedCurrencyAmount:
"""Amount denomination in issued currency (not XRP)."""
def __init__(self, currency: str, value: str, issuer: str):
self.currency = currency # 3-char ISO code or 40-char hex
self.value = value # Decimal string
self.issuer = issuer # Issuing account address
class MPTAmount:
"""Amount denomination in Multi-Purpose Token."""
def __init__(self, mpt_id: str, value: str):
self.mpt_id = mpt_id # 48-character hex MPT identifier
self.value = value # Decimal string amount
class ClawbackAmount:
"""Amount for clawback operations."""
def __init__(self, currency: str, value: str, issuer: str):
self.currency = currency
self.value = value
self.issuer = issuer
# Utility functions
def is_xrp(amount: Amount) -> bool:
"""Check if amount represents XRP (string format)."""
def is_issued_currency(amount: Amount) -> bool:
"""Check if amount is an issued currency."""
def is_mpt(amount: Amount) -> bool:
"""Check if amount is a Multi-Purpose Token."""
def get_amount_value(amount: Amount) -> str:
"""Extract the numeric value from any amount type."""Representations of different currency types supported by XRPL.
from xrpl.models.currencies import Currency, XRP, IssuedCurrency, MPTCurrency
class Currency:
"""Base currency class."""
pass
class XRP(Currency):
"""XRP native currency."""
def __init__(self):
pass
def to_dict(self) -> dict:
return "XRP"
class IssuedCurrency(Currency):
"""Non-XRP currency issued by a specific account."""
def __init__(self, currency: str, issuer: str):
self.currency = currency # ISO code or hex string
self.issuer = issuer # Issuing account address
class MPTCurrency(Currency):
"""Multi-Purpose Token currency."""
def __init__(self, mpt_id: str):
self.mpt_id = mpt_id # 48-character hex identifierComplete transaction type definitions covering all XRPL transaction types.
from xrpl.models.transactions import (
Transaction, Memo, Signer, TransactionMetadata,
Payment, OfferCreate, OfferCancel, TrustSet,
AccountSet, AccountDelete, SetRegularKey,
NFTokenMint, NFTokenBurn, NFTokenCreateOffer, NFTokenAcceptOffer,
EscrowCreate, EscrowFinish, EscrowCancel,
PaymentChannelCreate, PaymentChannelFund, PaymentChannelClaim,
CheckCreate, CheckCash, CheckCancel,
TicketCreate, SignerListSet
)
class Transaction:
"""Base transaction class with common fields."""
def __init__(
self,
account: str,
transaction_type: str,
fee: str = None,
sequence: int = None,
account_txn_id: str = None,
last_ledger_sequence: int = None,
memos: list[Memo] = None,
signers: list[Signer] = None,
source_tag: int = None,
signing_pub_key: str = None,
txn_signature: str = None
):
self.account = account
self.transaction_type = transaction_type
self.fee = fee
self.sequence = sequence
# ... other fields
class Memo:
"""Transaction memo for attaching data."""
def __init__(self, memo_data: str = None, memo_format: str = None, memo_type: str = None):
self.memo_data = memo_data
self.memo_format = memo_format
self.memo_type = memo_type
class Signer:
"""Transaction signer for multisign operations."""
def __init__(self, account: str, txn_signature: str, signing_pub_key: str):
self.account = account
self.txn_signature = txn_signature
self.signing_pub_key = signing_pub_key
# Major transaction types
class Payment(Transaction):
"""Send value from one account to another."""
def __init__(
self,
account: str,
destination: str,
amount: Amount,
destination_tag: int = None,
invoice_id: str = None,
paths: list[Path] = None,
send_max: Amount = None,
deliver_min: Amount = None,
**kwargs
):
super().__init__(account, "Payment", **kwargs)
self.destination = destination
self.amount = amount
# ... other fields
class OfferCreate(Transaction):
"""Create currency exchange offer."""
def __init__(
self,
account: str,
taker_gets: Amount,
taker_pays: Amount,
expiration: int = None,
offer_sequence: int = None,
**kwargs
):
super().__init__(account, "OfferCreate", **kwargs)
self.taker_gets = taker_gets
self.taker_pays = taker_pays
# ... other fields
class TrustSet(Transaction):
"""Create or modify a trust line."""
def __init__(
self,
account: str,
limit_amount: IssuedCurrencyAmount,
quality_in: int = None,
quality_out: int = None,
**kwargs
):
super().__init__(account, "TrustSet", **kwargs)
self.limit_amount = limit_amount
# ... other fieldsModels for all types of requests that can be sent to XRPL nodes.
from xrpl.models.requests import (
Request, GenericRequest,
AccountInfo, AccountTx, AccountLines, AccountChannels,
Ledger, LedgerEntry, LedgerData,
Tx, Submit, Sign, Ping,
BookOffers, PathFind, Fee, ServerInfo
)
class Request:
"""Base request class."""
def __init__(self, method: str, **kwargs):
self.method = method
# Set other parameters from kwargs
class AccountInfo(Request):
"""Get account information and settings."""
def __init__(
self,
account: str,
ledger_hash: str = None,
ledger_index: str = "validated",
queue: bool = None,
signer_lists: bool = None,
strict: bool = None
):
super().__init__("account_info")
self.account = account
self.ledger_index = ledger_index
# ... other fields
class AccountTx(Request):
"""Get transaction history for an account."""
def __init__(
self,
account: str,
ledger_index_min: int = None,
ledger_index_max: int = None,
binary: bool = None,
forward: bool = None,
limit: int = None,
marker: dict = None
):
super().__init__("account_tx")
self.account = account
# ... other fields
class Ledger(Request):
"""Get ledger information."""
def __init__(
self,
ledger_hash: str = None,
ledger_index: Union[str, int] = "validated",
accounts: bool = None,
full: bool = None,
transactions: bool = None,
expand: bool = None,
owner_funds: bool = None
):
super().__init__("ledger")
self.ledger_index = ledger_index
# ... other fields
class BookOffers(Request):
"""Get currency exchange order book offers."""
def __init__(
self,
taker_gets: Currency,
taker_pays: Currency,
taker: str = None,
ledger_hash: str = None,
ledger_index: str = "validated",
limit: int = None,
marker: dict = None
):
super().__init__("book_offers")
self.taker_gets = taker_gets
self.taker_pays = taker_pays
# ... other fieldsFlag constants and enumerations for transaction options.
from xrpl.models.transactions.flags import (
TransactionFlag, PaymentFlag, OfferCreateFlag, TrustSetFlag,
AccountSetFlag, NFTokenMintFlag, NFTokenCreateOfferFlag
)
class TransactionFlag(int, Enum):
"""Base transaction flags."""
FULLY_CANONICAL_SIG = 0x80000000
class PaymentFlag(TransactionFlag):
"""Payment transaction specific flags."""
PARTIAL_PAYMENTS = 0x00020000
LIMIT_PARTIAL_PAYMENTS = 0x00040000
class OfferCreateFlag(TransactionFlag):
"""OfferCreate transaction flags."""
PASSIVE = 0x00010000
IMMEDIATE_OR_CANCEL = 0x00040000
FILL_OR_KILL = 0x00080000
SELL = 0x00100000
class TrustSetFlag(TransactionFlag):
"""TrustSet transaction flags."""
SET_F_RIPPLE = 0x00020000
CLEAR_F_RIPPLE = 0x00000000
SET_NO_RIPPLE = 0x00040000
CLEAR_NO_RIPPLE = 0x00000000
SET_FREEZE = 0x00100000
CLEAR_FREEZE = 0x00000000
class AccountSetFlag(TransactionFlag):
"""AccountSet transaction flags."""
REQUIRE_DEST_TAG = 0x00000001
OPTIONAL_DEST_TAG = 0x00000002
REQUIRE_AUTH = 0x00000004
OPTIONAL_AUTH = 0x00000008
DISALLOW_XRP = 0x00000010
ALLOW_XRP = 0x00000020from xrpl.models.amounts import IssuedCurrencyAmount, is_xrp, get_amount_value
# XRP amount (in drops)
xrp_amount = "1000000" # 1 XRP
print(f"Is XRP: {is_xrp(xrp_amount)}")
print(f"Value: {get_amount_value(xrp_amount)} drops")
# Issued currency amount
usd_amount = IssuedCurrencyAmount(
currency="USD",
value="100.50",
issuer="rIssuerAddress..."
)
print(f"Is issued currency: {is_issued_currency(usd_amount)}")
print(f"Value: {get_amount_value(usd_amount)} {usd_amount.currency}")
# Working with different amount types
def format_amount(amount):
"""Format amount for display."""
if is_xrp(amount):
drops = int(amount)
return f"{drops / 1_000_000:.6f} XRP ({drops} drops)"
elif is_issued_currency(amount):
return f"{amount.value} {amount.currency}"
elif is_mpt(amount):
return f"{amount.value} MPT({amount.mpt_id[:8]}...)"
else:
return str(amount)
print(format_amount(xrp_amount))
print(format_amount(usd_amount))from xrpl.models.transactions import Payment, OfferCreate, TrustSet, Memo
from xrpl.models.amounts import IssuedCurrencyAmount
from xrpl.models.currencies import IssuedCurrency
# Simple XRP payment
payment = Payment(
account="rSender...",
destination="rReceiver...",
amount="1000000", # 1 XRP in drops
destination_tag=12345,
memos=[
Memo(
memo_data="48656c6c6f", # "Hello" in hex
memo_type="74657874" # "text" in hex
)
]
)
# Issued currency payment
usd_payment = Payment(
account="rSender...",
destination="rReceiver...",
amount=IssuedCurrencyAmount(
currency="USD",
value="50.25",
issuer="rIssuer..."
)
)
# Currency exchange offer
offer = OfferCreate(
account="rTrader...",
taker_gets="1000000", # Want 1 XRP
taker_pays=IssuedCurrencyAmount(
currency="USD",
value="0.50",
issuer="rIssuer..."
),
flags=OfferCreateFlag.SELL
)
# Trust line creation
trust_line = TrustSet(
account="rAccount...",
limit_amount=IssuedCurrencyAmount(
currency="USD",
value="1000",
issuer="rIssuer..."
),
flags=TrustSetFlag.SET_NO_RIPPLE
)
print(f"Payment: {payment.to_dict()}")
print(f"Offer: {offer.to_dict()}")from xrpl.clients import JsonRpcClient
from xrpl.models.requests import (
AccountInfo, AccountTx, Ledger, BookOffers,
PathFind, Fee, ServerInfo
)
from xrpl.models.currencies import XRP, IssuedCurrency
client = JsonRpcClient("https://s.altnet.rippletest.net:51234")
# Account information
account_info = AccountInfo(
account="rN7n7otQDd6FczFgLdSqtcsAUxDkw6fzRH",
ledger_index="validated",
signer_lists=True
)
response = client.request(account_info)
print(f"Account data: {response.result}")
# Transaction history
account_tx = AccountTx(
account="rN7n7otQDd6FczFgLdSqtcsAUxDkw6fzRH",
limit=10,
forward=False
)
tx_response = client.request(account_tx)
print(f"Recent transactions: {len(tx_response.result['transactions'])}")
# Order book data
book_offers = BookOffers(
taker_gets=XRP(),
taker_pays=IssuedCurrency("USD", "rIssuer..."),
limit=20
)
book_response = client.request(book_offers)
print(f"Order book offers: {len(book_response.result['offers'])}")
# Current fees
fee_request = Fee()
fee_response = client.request(fee_request)
print(f"Base fee: {fee_response.result['drops']['base_fee']} drops")
# Server information
server_info = ServerInfo()
server_response = client.request(server_info)
print(f"Server version: {server_response.result['info']['build_version']}")from xrpl.models.transactions import Payment
from xrpl.models.amounts import IssuedCurrencyAmount, is_xrp
from xrpl.models.utils import require_kwargs_on_init
# Model validation happens automatically
try:
# This will raise validation error - missing required fields
invalid_payment = Payment(account="rSender...")
except Exception as e:
print(f"Validation error: {e}")
# Valid payment
valid_payment = Payment(
account="rSender...",
destination="rReceiver...",
amount="1000000"
)
# Convert to dictionary (for JSON serialization)
payment_dict = valid_payment.to_dict()
print(f"Serialized: {payment_dict}")
# Create from dictionary
reconstructed = Payment.from_dict(payment_dict)
print(f"Reconstructed: {reconstructed.account}")
# Amount validation and conversion
def validate_amount(amount):
"""Validate and normalize amount."""
if is_xrp(amount):
# Ensure it's a valid drops amount
drops = int(amount)
if drops < 0:
raise ValueError("XRP amount cannot be negative")
if drops > 10**17: # Max XRP supply in drops
raise ValueError("XRP amount exceeds maximum supply")
return str(drops)
else:
# Validate issued currency amount
if not hasattr(amount, 'currency') or not hasattr(amount, 'value'):
raise ValueError("Invalid issued currency amount")
return amount
# Usage
valid_xrp = validate_amount("1000000")
valid_usd = validate_amount(IssuedCurrencyAmount("USD", "100", "rIssuer..."))
print(f"Validated amounts: {valid_xrp}, {valid_usd.value} {valid_usd.currency}")class XRPLModelException(XRPLException):
"""Exception for model validation errors and data structure issues."""# Transaction hierarchy
Transaction (base)
├── Payment
├── OfferCreate, OfferCancel
├── TrustSet
├── AccountSet, AccountDelete, SetRegularKey
├── EscrowCreate, EscrowFinish, EscrowCancel
├── PaymentChannelCreate, PaymentChannelFund, PaymentChannelClaim
├── CheckCreate, CheckCash, CheckCancel
├── NFTokenMint, NFTokenBurn, NFTokenCreateOffer, NFTokenAcceptOffer
├── AMMCreate, AMMDeposit, AMMWithdraw, AMMBid, AMMVote
└── ... (50+ transaction types)
# Request hierarchy
Request (base)
├── AccountInfo, AccountTx, AccountLines, AccountChannels
├── Ledger, LedgerEntry, LedgerData
├── Tx, TransactionEntry
├── Submit, Sign, SignFor, SubmitMultisigned
├── BookOffers, PathFind, RipplePathFind
├── Fee, ServerInfo, ServerState
└── ... (30+ request types)
# Amount hierarchy
Amount = Union[str, IssuedCurrencyAmount, MPTAmount]
├── str (XRP in drops)
├── IssuedCurrencyAmount (non-XRP currencies)
└── MPTAmount (Multi-Purpose Tokens)
# Currency hierarchy
Currency (base)
├── XRP (native currency)
├── IssuedCurrency (traditional issued currencies)
└── MPTCurrency (Multi-Purpose Tokens)Install with Tessl CLI
npx tessl i tessl/pypi-xrpl-py