Skip to main content
The 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 the async feature is enabled, async methods are also available:

Query Methods

Current State Root

Returns the current state root of the blockchain.
The state root is a Merkle root that commits to the entire blockchain state at the current block height. It’s used in SNARKs to prove statements about on-chain data. Example:

State Path for Commitment

Returns a Merkle path proving a commitment is included in the state.
Parameters:
  • commitment - The record commitment to prove
Returns:
  • StatePath<N> - Merkle path from commitment to state root
Use cases:
  • Proving record ownership in SNARKs
  • Verifying a record exists on-chain
  • Generating inclusion proofs for light clients
Example:

State Paths for Multiple Commitments

Returns Merkle paths for multiple commitments in a single query.
Parameters:
  • commitments - Slice of commitments to prove
Returns:
  • Vec<StatePath<N>> - State paths in the same order as inputs
Performance: This method is more efficient than calling 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.
Returns:
  • u32 - The current block height (genesis is 0)
Example:

StatePath

A StatePath is a Merkle path proving a commitment is included in the blockchain state.

Verification

Example:

Implementing QueryTrait

You can implement QueryTrait for custom types to enable querying.

Example: Ledger Implementation

Example: BlockStore Implementation

Query Wrapper

For testing and development, the Query type wraps a BlockStore to implement QueryTrait.

Usage in Transaction Creation

The QueryTrait is commonly used when creating transactions to provide state access to the VM.
The VM uses the query interface to:
  • Get state paths for input records
  • Verify records are unspent
  • Access the current block height for transaction validation

Async Query Operations

When the async 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