0
# Ledger Operations
1
2
Query ledger state information including current fees, ledger sequences, and network status. These functions provide essential ledger-level information for building XRPL applications.
3
4
## Capabilities
5
6
### Fee Information
7
8
Query current network fees and reserve requirements.
9
10
```python { .api }
11
from xrpl import ledger
12
13
def get_fee(client, max_fee_xrp: str = None) -> str:
14
"""
15
Get current base fee and reserve amounts from the network.
16
17
Args:
18
client: XRPL client for network communication
19
max_fee_xrp: Optional maximum fee limit in XRP
20
21
Returns:
22
Current base fee in drops as string
23
24
Raises:
25
XRPLException: If fee query fails
26
"""
27
```
28
29
### Ledger Sequence Information
30
31
Query ledger sequence numbers for timing and validation purposes.
32
33
```python { .api }
34
def get_latest_open_ledger_sequence(client) -> int:
35
"""
36
Get the latest open (not yet validated) ledger sequence number.
37
38
Args:
39
client: XRPL client for network communication
40
41
Returns:
42
Latest open ledger sequence number
43
44
Raises:
45
XRPLException: If ledger query fails
46
"""
47
48
def get_latest_validated_ledger_sequence(client) -> int:
49
"""
50
Get the latest validated ledger sequence number.
51
52
Args:
53
client: XRPL client for network communication
54
55
Returns:
56
Latest validated ledger sequence number
57
58
Raises:
59
XRPLException: If ledger query fails
60
"""
61
```
62
63
## Usage Examples
64
65
### Checking Current Network Fees
66
67
```python
68
from xrpl.clients import JsonRpcClient
69
from xrpl import ledger
70
71
# Connect to XRPL network
72
client = JsonRpcClient("https://s.altnet.rippletest.net:51234")
73
74
# Get current base fee
75
try:
76
base_fee = ledger.get_fee(client)
77
print(f"Current base fee: {base_fee} drops")
78
79
# Convert to XRP for display
80
from xrpl.utils import drops_to_xrp
81
fee_xrp = drops_to_xrp(base_fee)
82
print(f"Base fee in XRP: {fee_xrp}")
83
84
except Exception as e:
85
print(f"Failed to get fee: {e}")
86
87
# Get fee with maximum limit
88
try:
89
limited_fee = ledger.get_fee(client, max_fee_xrp="0.01")
90
print(f"Fee with limit: {limited_fee} drops")
91
except Exception as e:
92
print(f"Failed to get limited fee: {e}")
93
```
94
95
### Monitoring Ledger Progress
96
97
```python
98
from xrpl.clients import JsonRpcClient
99
from xrpl import ledger
100
import time
101
102
def monitor_ledger_progress(client, duration: int = 60):
103
"""Monitor ledger sequence progression."""
104
105
print("Monitoring ledger progress...")
106
start_time = time.time()
107
108
while time.time() - start_time < duration:
109
try:
110
# Get current ledger info
111
open_seq = ledger.get_latest_open_ledger_sequence(client)
112
validated_seq = ledger.get_latest_validated_ledger_sequence(client)
113
114
print(f"Open: {open_seq}, Validated: {validated_seq}, Gap: {open_seq - validated_seq}")
115
116
time.sleep(5) # Check every 5 seconds
117
118
except Exception as e:
119
print(f"Error monitoring ledger: {e}")
120
time.sleep(5)
121
122
# Usage
123
client = JsonRpcClient("https://s.altnet.rippletest.net:51234")
124
monitor_ledger_progress(client, duration=30)
125
```
126
127
### Transaction Timing Utilities
128
129
```python
130
from xrpl.clients import JsonRpcClient
131
from xrpl import ledger
132
133
def get_transaction_timing_info(client) -> dict:
134
"""Get timing information for transaction submission."""
135
136
try:
137
# Get current ledger sequences
138
open_seq = ledger.get_latest_open_ledger_sequence(client)
139
validated_seq = ledger.get_latest_validated_ledger_sequence(client)
140
141
# Calculate recommended LastLedgerSequence
142
# Typically set 3-10 ledgers ahead for safety
143
recommended_last_ledger = open_seq + 5
144
145
return {
146
"current_open": open_seq,
147
"current_validated": validated_seq,
148
"ledger_gap": open_seq - validated_seq,
149
"recommended_last_ledger": recommended_last_ledger,
150
"time_window_seconds": 5 * 4 # ~4 seconds per ledger
151
}
152
153
except Exception as e:
154
return {"error": str(e)}
155
156
# Usage
157
client = JsonRpcClient("https://s.altnet.rippletest.net:51234")
158
timing_info = get_transaction_timing_info(client)
159
160
if "error" not in timing_info:
161
print("Transaction Timing Info:")
162
print(f" Current open ledger: {timing_info['current_open']}")
163
print(f" Current validated ledger: {timing_info['current_validated']}")
164
print(f" Recommended LastLedgerSequence: {timing_info['recommended_last_ledger']}")
165
print(f" Estimated time window: {timing_info['time_window_seconds']} seconds")
166
else:
167
print(f"Error getting timing info: {timing_info['error']}")
168
```
169
170
### Fee Estimation for Transactions
171
172
```python
173
from xrpl.clients import JsonRpcClient
174
from xrpl import ledger
175
from xrpl.utils import xrp_to_drops
176
177
def calculate_transaction_cost(client, transaction_size_factor: float = 1.0) -> dict:
178
"""Calculate estimated transaction cost."""
179
180
try:
181
# Get base fee
182
base_fee_drops = int(ledger.get_fee(client))
183
184
# Account for transaction complexity
185
# Simple transactions use base fee, complex ones may need more
186
estimated_fee_drops = int(base_fee_drops * transaction_size_factor)
187
188
# Add some buffer for network congestion
189
recommended_fee_drops = int(estimated_fee_drops * 1.2)
190
191
return {
192
"base_fee_drops": base_fee_drops,
193
"estimated_fee_drops": estimated_fee_drops,
194
"recommended_fee_drops": recommended_fee_drops,
195
"recommended_fee_xrp": float(recommended_fee_drops / 1_000_000)
196
}
197
198
except Exception as e:
199
return {"error": str(e)}
200
201
# Usage examples
202
client = JsonRpcClient("https://s.altnet.rippletest.net:51234")
203
204
# Simple payment
205
simple_cost = calculate_transaction_cost(client, 1.0)
206
print("Simple transaction cost:", simple_cost)
207
208
# Complex transaction (e.g., with paths, multiple currencies)
209
complex_cost = calculate_transaction_cost(client, 2.0)
210
print("Complex transaction cost:", complex_cost)
211
212
# Multi-sign transaction
213
multisign_cost = calculate_transaction_cost(client, 1.5)
214
print("Multi-sign transaction cost:", multisign_cost)
215
```
216
217
### Asynchronous Ledger Operations
218
219
```python
220
import asyncio
221
from xrpl.asyncio.clients import AsyncJsonRpcClient
222
from xrpl.asyncio import ledger
223
224
async def get_ledger_info_async(client):
225
"""Get comprehensive ledger information asynchronously."""
226
227
# Run multiple queries concurrently
228
fee_task = ledger.get_fee(client)
229
open_seq_task = ledger.get_latest_open_ledger_sequence(client)
230
validated_seq_task = ledger.get_latest_validated_ledger_sequence(client)
231
232
# Wait for all to complete
233
fee, open_seq, validated_seq = await asyncio.gather(
234
fee_task, open_seq_task, validated_seq_task
235
)
236
237
return {
238
"base_fee_drops": fee,
239
"open_ledger_sequence": open_seq,
240
"validated_ledger_sequence": validated_seq,
241
"ledger_gap": open_seq - validated_seq
242
}
243
244
async def main():
245
client = AsyncJsonRpcClient("https://s.altnet.rippletest.net:51234")
246
247
try:
248
ledger_info = await get_ledger_info_async(client)
249
print("Ledger Information:")
250
for key, value in ledger_info.items():
251
print(f" {key}: {value}")
252
finally:
253
await client.close()
254
255
# Run async example
256
asyncio.run(main())
257
```
258
259
## Integration with Transaction Management
260
261
The ledger functions are commonly used with transaction operations:
262
263
```python
264
from xrpl.clients import JsonRpcClient
265
from xrpl import ledger, transaction
266
from xrpl.models.transactions import Payment
267
from xrpl.wallet import Wallet
268
269
def create_payment_with_timing(client, wallet, destination: str, amount: str):
270
"""Create payment with proper timing information."""
271
272
# Get current ledger state
273
open_seq = ledger.get_latest_open_ledger_sequence(client)
274
base_fee = ledger.get_fee(client)
275
276
# Create payment with timing info
277
payment = Payment(
278
account=wallet.address,
279
destination=destination,
280
amount=amount,
281
fee=str(int(int(base_fee) * 1.2)), # 20% buffer on fee
282
last_ledger_sequence=open_seq + 5 # 5 ledger window
283
)
284
285
print(f"Created payment with fee: {payment.fee} drops")
286
print(f"LastLedgerSequence: {payment.last_ledger_sequence}")
287
288
return payment
289
290
# Usage
291
client = JsonRpcClient("https://s.altnet.rippletest.net:51234")
292
wallet = Wallet.create() # In practice, use funded wallet
293
294
payment = create_payment_with_timing(
295
client,
296
wallet,
297
"rReceiver...",
298
"1000000"
299
)
300
```