ledger module provides types for retrieving information about the current ledger, including sequence numbers, timestamps, and network identifiers.
Overview
Access ledger information throughenv.ledger() in your contracts. The ledger provides metadata about the blockchain state at the time of execution.
Types
Ledger
Retrieves information about the current ledger.env.ledger() in contract code.
Functions
sequence
Returns the sequence number of the current ledger.timestamp
Returns the Unix timestamp when the ledger was closed.network_id
Returns the network identifier.- Public Network:
SHA256("Public Global Stellar Network ; September 2015") - Test Network:
SHA256("Test SDF Network ; September 2015")
protocol_version (deprecated)
Returns the protocol version of the ledger.max_live_until_ledger (hidden)
Returns the maximum ledger sequence number that data can live until.Examples
Time-based Logic
Sequence-based Logic
Network Detection
Test Utilities
When thetestutils feature is enabled, additional functions are available for controlling ledger state in tests:
set
Sets complete ledger info.set_sequence_number
Sets the ledger sequence number.set_timestamp
Sets the ledger timestamp.set_network_id
Sets the network ID.set_protocol_version
Sets the protocol version.set_base_reserve
Sets the base reserve.set_min_temp_entry_ttl
Sets the minimum temporary entry TTL.set_min_persistent_entry_ttl
Sets the minimum persistent entry TTL.set_max_entry_ttl
Sets the maximum entry TTL.get
Gets the current ledger info.with_mut
Modifies ledger info using a closure.Test Example
LedgerInfo
Complete ledger information structure (available withtestutils):
Best Practices
- Use timestamps for real-world time: Use
timestamp()when working with real-world deadlines - Use sequence for block-based logic: Use
sequence()for logic tied to blockchain progression - Cache ledger values: If using multiple times, cache the value to save computation
- Test time-based logic: Use testutils to thoroughly test time-dependent behavior
- Handle time drift: Remember that timestamps may not be perfectly accurate
See Also
- Env - For accessing ledger functions
- Bytes - For byte arrays and fixed-size BytesN
- Ledger Headers - Stellar documentation on ledger headers