0
# Data Models and Types
1
2
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.
3
4
## Capabilities
5
6
### Core Model Classes
7
8
Base classes and fundamental data structures used throughout the XRPL ecosystem.
9
10
```python { .api }
11
from xrpl.models import Response, AuthAccount, Path, PathStep, XChainBridge
12
13
class Response:
14
"""Base response object for all XRPL requests."""
15
16
def __init__(self, result: dict, status: str = None):
17
self.result = result
18
self.status = status
19
20
def is_successful(self) -> bool:
21
"""Check if the response indicates success."""
22
23
class AuthAccount:
24
"""Authentication account model for cross-chain operations."""
25
26
account: str
27
28
class Path:
29
"""Payment path model representing a sequence of currency exchanges."""
30
31
def __init__(self, path_steps: list[PathStep]):
32
self.path_steps = path_steps
33
34
class PathStep:
35
"""Individual step in a payment path."""
36
37
account: str = None
38
currency: str = None
39
issuer: str = None
40
41
class XChainBridge:
42
"""Cross-chain bridge identifier."""
43
44
issuing_chain_door: str
45
issuing_chain_issue: dict
46
locking_chain_door: str
47
locking_chain_issue: dict
48
```
49
50
### Amount Types
51
52
Type-safe representations of value amounts in different currencies and formats.
53
54
```python { .api }
55
from xrpl.models.amounts import (
56
Amount, IssuedCurrencyAmount, MPTAmount, ClawbackAmount,
57
is_xrp, is_issued_currency, is_mpt, get_amount_value
58
)
59
from typing import Union
60
61
# Union type for all amount formats
62
Amount = Union[str, IssuedCurrencyAmount, MPTAmount]
63
64
class IssuedCurrencyAmount:
65
"""Amount denomination in issued currency (not XRP)."""
66
67
def __init__(self, currency: str, value: str, issuer: str):
68
self.currency = currency # 3-char ISO code or 40-char hex
69
self.value = value # Decimal string
70
self.issuer = issuer # Issuing account address
71
72
class MPTAmount:
73
"""Amount denomination in Multi-Purpose Token."""
74
75
def __init__(self, mpt_id: str, value: str):
76
self.mpt_id = mpt_id # 48-character hex MPT identifier
77
self.value = value # Decimal string amount
78
79
class ClawbackAmount:
80
"""Amount for clawback operations."""
81
82
def __init__(self, currency: str, value: str, issuer: str):
83
self.currency = currency
84
self.value = value
85
self.issuer = issuer
86
87
# Utility functions
88
def is_xrp(amount: Amount) -> bool:
89
"""Check if amount represents XRP (string format)."""
90
91
def is_issued_currency(amount: Amount) -> bool:
92
"""Check if amount is an issued currency."""
93
94
def is_mpt(amount: Amount) -> bool:
95
"""Check if amount is a Multi-Purpose Token."""
96
97
def get_amount_value(amount: Amount) -> str:
98
"""Extract the numeric value from any amount type."""
99
```
100
101
### Currency Types
102
103
Representations of different currency types supported by XRPL.
104
105
```python { .api }
106
from xrpl.models.currencies import Currency, XRP, IssuedCurrency, MPTCurrency
107
108
class Currency:
109
"""Base currency class."""
110
pass
111
112
class XRP(Currency):
113
"""XRP native currency."""
114
115
def __init__(self):
116
pass
117
118
def to_dict(self) -> dict:
119
return "XRP"
120
121
class IssuedCurrency(Currency):
122
"""Non-XRP currency issued by a specific account."""
123
124
def __init__(self, currency: str, issuer: str):
125
self.currency = currency # ISO code or hex string
126
self.issuer = issuer # Issuing account address
127
128
class MPTCurrency(Currency):
129
"""Multi-Purpose Token currency."""
130
131
def __init__(self, mpt_id: str):
132
self.mpt_id = mpt_id # 48-character hex identifier
133
```
134
135
### Transaction Models
136
137
Complete transaction type definitions covering all XRPL transaction types.
138
139
```python { .api }
140
from xrpl.models.transactions import (
141
Transaction, Memo, Signer, TransactionMetadata,
142
Payment, OfferCreate, OfferCancel, TrustSet,
143
AccountSet, AccountDelete, SetRegularKey,
144
NFTokenMint, NFTokenBurn, NFTokenCreateOffer, NFTokenAcceptOffer,
145
EscrowCreate, EscrowFinish, EscrowCancel,
146
PaymentChannelCreate, PaymentChannelFund, PaymentChannelClaim,
147
CheckCreate, CheckCash, CheckCancel,
148
TicketCreate, SignerListSet
149
)
150
151
class Transaction:
152
"""Base transaction class with common fields."""
153
154
def __init__(
155
self,
156
account: str,
157
transaction_type: str,
158
fee: str = None,
159
sequence: int = None,
160
account_txn_id: str = None,
161
last_ledger_sequence: int = None,
162
memos: list[Memo] = None,
163
signers: list[Signer] = None,
164
source_tag: int = None,
165
signing_pub_key: str = None,
166
txn_signature: str = None
167
):
168
self.account = account
169
self.transaction_type = transaction_type
170
self.fee = fee
171
self.sequence = sequence
172
# ... other fields
173
174
class Memo:
175
"""Transaction memo for attaching data."""
176
177
def __init__(self, memo_data: str = None, memo_format: str = None, memo_type: str = None):
178
self.memo_data = memo_data
179
self.memo_format = memo_format
180
self.memo_type = memo_type
181
182
class Signer:
183
"""Transaction signer for multisign operations."""
184
185
def __init__(self, account: str, txn_signature: str, signing_pub_key: str):
186
self.account = account
187
self.txn_signature = txn_signature
188
self.signing_pub_key = signing_pub_key
189
190
# Major transaction types
191
class Payment(Transaction):
192
"""Send value from one account to another."""
193
194
def __init__(
195
self,
196
account: str,
197
destination: str,
198
amount: Amount,
199
destination_tag: int = None,
200
invoice_id: str = None,
201
paths: list[Path] = None,
202
send_max: Amount = None,
203
deliver_min: Amount = None,
204
**kwargs
205
):
206
super().__init__(account, "Payment", **kwargs)
207
self.destination = destination
208
self.amount = amount
209
# ... other fields
210
211
class OfferCreate(Transaction):
212
"""Create currency exchange offer."""
213
214
def __init__(
215
self,
216
account: str,
217
taker_gets: Amount,
218
taker_pays: Amount,
219
expiration: int = None,
220
offer_sequence: int = None,
221
**kwargs
222
):
223
super().__init__(account, "OfferCreate", **kwargs)
224
self.taker_gets = taker_gets
225
self.taker_pays = taker_pays
226
# ... other fields
227
228
class TrustSet(Transaction):
229
"""Create or modify a trust line."""
230
231
def __init__(
232
self,
233
account: str,
234
limit_amount: IssuedCurrencyAmount,
235
quality_in: int = None,
236
quality_out: int = None,
237
**kwargs
238
):
239
super().__init__(account, "TrustSet", **kwargs)
240
self.limit_amount = limit_amount
241
# ... other fields
242
```
243
244
### Request Models
245
246
Models for all types of requests that can be sent to XRPL nodes.
247
248
```python { .api }
249
from xrpl.models.requests import (
250
Request, GenericRequest,
251
AccountInfo, AccountTx, AccountLines, AccountChannels,
252
Ledger, LedgerEntry, LedgerData,
253
Tx, Submit, Sign, Ping,
254
BookOffers, PathFind, Fee, ServerInfo
255
)
256
257
class Request:
258
"""Base request class."""
259
260
def __init__(self, method: str, **kwargs):
261
self.method = method
262
# Set other parameters from kwargs
263
264
class AccountInfo(Request):
265
"""Get account information and settings."""
266
267
def __init__(
268
self,
269
account: str,
270
ledger_hash: str = None,
271
ledger_index: str = "validated",
272
queue: bool = None,
273
signer_lists: bool = None,
274
strict: bool = None
275
):
276
super().__init__("account_info")
277
self.account = account
278
self.ledger_index = ledger_index
279
# ... other fields
280
281
class AccountTx(Request):
282
"""Get transaction history for an account."""
283
284
def __init__(
285
self,
286
account: str,
287
ledger_index_min: int = None,
288
ledger_index_max: int = None,
289
binary: bool = None,
290
forward: bool = None,
291
limit: int = None,
292
marker: dict = None
293
):
294
super().__init__("account_tx")
295
self.account = account
296
# ... other fields
297
298
class Ledger(Request):
299
"""Get ledger information."""
300
301
def __init__(
302
self,
303
ledger_hash: str = None,
304
ledger_index: Union[str, int] = "validated",
305
accounts: bool = None,
306
full: bool = None,
307
transactions: bool = None,
308
expand: bool = None,
309
owner_funds: bool = None
310
):
311
super().__init__("ledger")
312
self.ledger_index = ledger_index
313
# ... other fields
314
315
class BookOffers(Request):
316
"""Get currency exchange order book offers."""
317
318
def __init__(
319
self,
320
taker_gets: Currency,
321
taker_pays: Currency,
322
taker: str = None,
323
ledger_hash: str = None,
324
ledger_index: str = "validated",
325
limit: int = None,
326
marker: dict = None
327
):
328
super().__init__("book_offers")
329
self.taker_gets = taker_gets
330
self.taker_pays = taker_pays
331
# ... other fields
332
```
333
334
### Transaction Flags and Enums
335
336
Flag constants and enumerations for transaction options.
337
338
```python { .api }
339
from xrpl.models.transactions.flags import (
340
TransactionFlag, PaymentFlag, OfferCreateFlag, TrustSetFlag,
341
AccountSetFlag, NFTokenMintFlag, NFTokenCreateOfferFlag
342
)
343
344
class TransactionFlag(int, Enum):
345
"""Base transaction flags."""
346
FULLY_CANONICAL_SIG = 0x80000000
347
348
class PaymentFlag(TransactionFlag):
349
"""Payment transaction specific flags."""
350
PARTIAL_PAYMENTS = 0x00020000
351
LIMIT_PARTIAL_PAYMENTS = 0x00040000
352
353
class OfferCreateFlag(TransactionFlag):
354
"""OfferCreate transaction flags."""
355
PASSIVE = 0x00010000
356
IMMEDIATE_OR_CANCEL = 0x00040000
357
FILL_OR_KILL = 0x00080000
358
SELL = 0x00100000
359
360
class TrustSetFlag(TransactionFlag):
361
"""TrustSet transaction flags."""
362
SET_F_RIPPLE = 0x00020000
363
CLEAR_F_RIPPLE = 0x00000000
364
SET_NO_RIPPLE = 0x00040000
365
CLEAR_NO_RIPPLE = 0x00000000
366
SET_FREEZE = 0x00100000
367
CLEAR_FREEZE = 0x00000000
368
369
class AccountSetFlag(TransactionFlag):
370
"""AccountSet transaction flags."""
371
REQUIRE_DEST_TAG = 0x00000001
372
OPTIONAL_DEST_TAG = 0x00000002
373
REQUIRE_AUTH = 0x00000004
374
OPTIONAL_AUTH = 0x00000008
375
DISALLOW_XRP = 0x00000010
376
ALLOW_XRP = 0x00000020
377
```
378
379
## Usage Examples
380
381
### Working with Amounts
382
383
```python
384
from xrpl.models.amounts import IssuedCurrencyAmount, is_xrp, get_amount_value
385
386
# XRP amount (in drops)
387
xrp_amount = "1000000" # 1 XRP
388
print(f"Is XRP: {is_xrp(xrp_amount)}")
389
print(f"Value: {get_amount_value(xrp_amount)} drops")
390
391
# Issued currency amount
392
usd_amount = IssuedCurrencyAmount(
393
currency="USD",
394
value="100.50",
395
issuer="rIssuerAddress..."
396
)
397
print(f"Is issued currency: {is_issued_currency(usd_amount)}")
398
print(f"Value: {get_amount_value(usd_amount)} {usd_amount.currency}")
399
400
# Working with different amount types
401
def format_amount(amount):
402
"""Format amount for display."""
403
if is_xrp(amount):
404
drops = int(amount)
405
return f"{drops / 1_000_000:.6f} XRP ({drops} drops)"
406
elif is_issued_currency(amount):
407
return f"{amount.value} {amount.currency}"
408
elif is_mpt(amount):
409
return f"{amount.value} MPT({amount.mpt_id[:8]}...)"
410
else:
411
return str(amount)
412
413
print(format_amount(xrp_amount))
414
print(format_amount(usd_amount))
415
```
416
417
### Creating Transactions
418
419
```python
420
from xrpl.models.transactions import Payment, OfferCreate, TrustSet, Memo
421
from xrpl.models.amounts import IssuedCurrencyAmount
422
from xrpl.models.currencies import IssuedCurrency
423
424
# Simple XRP payment
425
payment = Payment(
426
account="rSender...",
427
destination="rReceiver...",
428
amount="1000000", # 1 XRP in drops
429
destination_tag=12345,
430
memos=[
431
Memo(
432
memo_data="48656c6c6f", # "Hello" in hex
433
memo_type="74657874" # "text" in hex
434
)
435
]
436
)
437
438
# Issued currency payment
439
usd_payment = Payment(
440
account="rSender...",
441
destination="rReceiver...",
442
amount=IssuedCurrencyAmount(
443
currency="USD",
444
value="50.25",
445
issuer="rIssuer..."
446
)
447
)
448
449
# Currency exchange offer
450
offer = OfferCreate(
451
account="rTrader...",
452
taker_gets="1000000", # Want 1 XRP
453
taker_pays=IssuedCurrencyAmount(
454
currency="USD",
455
value="0.50",
456
issuer="rIssuer..."
457
),
458
flags=OfferCreateFlag.SELL
459
)
460
461
# Trust line creation
462
trust_line = TrustSet(
463
account="rAccount...",
464
limit_amount=IssuedCurrencyAmount(
465
currency="USD",
466
value="1000",
467
issuer="rIssuer..."
468
),
469
flags=TrustSetFlag.SET_NO_RIPPLE
470
)
471
472
print(f"Payment: {payment.to_dict()}")
473
print(f"Offer: {offer.to_dict()}")
474
```
475
476
### Making Requests
477
478
```python
479
from xrpl.clients import JsonRpcClient
480
from xrpl.models.requests import (
481
AccountInfo, AccountTx, Ledger, BookOffers,
482
PathFind, Fee, ServerInfo
483
)
484
from xrpl.models.currencies import XRP, IssuedCurrency
485
486
client = JsonRpcClient("https://s.altnet.rippletest.net:51234")
487
488
# Account information
489
account_info = AccountInfo(
490
account="rN7n7otQDd6FczFgLdSqtcsAUxDkw6fzRH",
491
ledger_index="validated",
492
signer_lists=True
493
)
494
response = client.request(account_info)
495
print(f"Account data: {response.result}")
496
497
# Transaction history
498
account_tx = AccountTx(
499
account="rN7n7otQDd6FczFgLdSqtcsAUxDkw6fzRH",
500
limit=10,
501
forward=False
502
)
503
tx_response = client.request(account_tx)
504
print(f"Recent transactions: {len(tx_response.result['transactions'])}")
505
506
# Order book data
507
book_offers = BookOffers(
508
taker_gets=XRP(),
509
taker_pays=IssuedCurrency("USD", "rIssuer..."),
510
limit=20
511
)
512
book_response = client.request(book_offers)
513
print(f"Order book offers: {len(book_response.result['offers'])}")
514
515
# Current fees
516
fee_request = Fee()
517
fee_response = client.request(fee_request)
518
print(f"Base fee: {fee_response.result['drops']['base_fee']} drops")
519
520
# Server information
521
server_info = ServerInfo()
522
server_response = client.request(server_info)
523
print(f"Server version: {server_response.result['info']['build_version']}")
524
```
525
526
### Validating and Converting Data
527
528
```python
529
from xrpl.models.transactions import Payment
530
from xrpl.models.amounts import IssuedCurrencyAmount, is_xrp
531
from xrpl.models.utils import require_kwargs_on_init
532
533
# Model validation happens automatically
534
try:
535
# This will raise validation error - missing required fields
536
invalid_payment = Payment(account="rSender...")
537
except Exception as e:
538
print(f"Validation error: {e}")
539
540
# Valid payment
541
valid_payment = Payment(
542
account="rSender...",
543
destination="rReceiver...",
544
amount="1000000"
545
)
546
547
# Convert to dictionary (for JSON serialization)
548
payment_dict = valid_payment.to_dict()
549
print(f"Serialized: {payment_dict}")
550
551
# Create from dictionary
552
reconstructed = Payment.from_dict(payment_dict)
553
print(f"Reconstructed: {reconstructed.account}")
554
555
# Amount validation and conversion
556
def validate_amount(amount):
557
"""Validate and normalize amount."""
558
if is_xrp(amount):
559
# Ensure it's a valid drops amount
560
drops = int(amount)
561
if drops < 0:
562
raise ValueError("XRP amount cannot be negative")
563
if drops > 10**17: # Max XRP supply in drops
564
raise ValueError("XRP amount exceeds maximum supply")
565
return str(drops)
566
else:
567
# Validate issued currency amount
568
if not hasattr(amount, 'currency') or not hasattr(amount, 'value'):
569
raise ValueError("Invalid issued currency amount")
570
return amount
571
572
# Usage
573
valid_xrp = validate_amount("1000000")
574
valid_usd = validate_amount(IssuedCurrencyAmount("USD", "100", "rIssuer..."))
575
print(f"Validated amounts: {valid_xrp}, {valid_usd.value} {valid_usd.currency}")
576
```
577
578
## Exceptions
579
580
```python { .api }
581
class XRPLModelException(XRPLException):
582
"""Exception for model validation errors and data structure issues."""
583
```
584
585
## Model Inheritance Hierarchy
586
587
```python { .api }
588
# Transaction hierarchy
589
Transaction (base)
590
├── Payment
591
├── OfferCreate, OfferCancel
592
├── TrustSet
593
├── AccountSet, AccountDelete, SetRegularKey
594
├── EscrowCreate, EscrowFinish, EscrowCancel
595
├── PaymentChannelCreate, PaymentChannelFund, PaymentChannelClaim
596
├── CheckCreate, CheckCash, CheckCancel
597
├── NFTokenMint, NFTokenBurn, NFTokenCreateOffer, NFTokenAcceptOffer
598
├── AMMCreate, AMMDeposit, AMMWithdraw, AMMBid, AMMVote
599
└── ... (50+ transaction types)
600
601
# Request hierarchy
602
Request (base)
603
├── AccountInfo, AccountTx, AccountLines, AccountChannels
604
├── Ledger, LedgerEntry, LedgerData
605
├── Tx, TransactionEntry
606
├── Submit, Sign, SignFor, SubmitMultisigned
607
├── BookOffers, PathFind, RipplePathFind
608
├── Fee, ServerInfo, ServerState
609
└── ... (30+ request types)
610
611
# Amount hierarchy
612
Amount = Union[str, IssuedCurrencyAmount, MPTAmount]
613
├── str (XRP in drops)
614
├── IssuedCurrencyAmount (non-XRP currencies)
615
└── MPTAmount (Multi-Purpose Tokens)
616
617
# Currency hierarchy
618
Currency (base)
619
├── XRP (native currency)
620
├── IssuedCurrency (traditional issued currencies)
621
└── MPTCurrency (Multi-Purpose Tokens)
622
```