QueryTrait provides a standardized interface for querying blockchain state. It’s used throughout SnarkVM to enable both synchronous and asynchronous state access.
QueryTrait Interface
The query trait defines methods for accessing current state and historical data.Async Variant
When theasync feature is enabled, async methods are also available:
Query Methods
Current State Root
Returns the current state root of the blockchain.State Path for Commitment
Returns a Merkle path proving a commitment is included in the state.commitment- The record commitment to prove
StatePath<N>- Merkle path from commitment to state root
- Proving record ownership in SNARKs
- Verifying a record exists on-chain
- Generating inclusion proofs for light clients
State Paths for Multiple Commitments
Returns Merkle paths for multiple commitments in a single query.commitments- Slice of commitments to prove
Vec<StatePath<N>>- State paths in the same order as inputs
get_state_path_for_commitment repeatedly, as it can batch database lookups.
Example:
Current Block Height
Returns the height of the latest block in the ledger.u32- The current block height (genesis is 0)
StatePath
AStatePath is a Merkle path proving a commitment is included in the blockchain state.
Verification
Implementing QueryTrait
You can implementQueryTrait for custom types to enable querying.
Example: Ledger Implementation
Example: BlockStore Implementation
Query Wrapper
For testing and development, theQuery type wraps a BlockStore to implement QueryTrait.
Usage in Transaction Creation
TheQueryTrait is commonly used when creating transactions to provide state access to the VM.
- Get state paths for input records
- Verify records are unspent
- Access the current block height for transaction validation
Async Query Operations
When theasync feature is enabled, you can use async query methods:
Example: Complete Query Workflow
Performance Tips
Batch Queries
Always use batch query methods when querying multiple items:Cache Current State
If you need the state root or height multiple times, cache it:Use Async for I/O-Bound Operations
If performing many queries, async methods can improve throughput:Next Steps
- Ledger Overview - Main ledger operations
- Block Types - Block and transaction structures
- Storage - Persistent storage layer