Querying Source Chains

An agent can query their source chain for a history of the records they’ve written, including link and public and private entry data, which includes capability grants and claims. They can also query the public portion of another agent’s source chain in a zome function or validate callback.

An agent’s source chain is their record of local state changes. It’s a multi-purpose data structure, and can be interpreted in different ways, including as:

Filtering a query

Whether an agent is querying their own source chain or another agent’s, you build a query with the ChainQueryFilter struct, which has a few filter types:

After retrieving the filtered records, you can then further filter them in memory using Rust’s standard Iterator trait.

Use the builder interface

Rather than building a struct and having to specify fields you don’t need, you can use the builder interface on ChainQueryFilter:

use hdk::prelude::*;
use movies::prelude::*;

let filter_only_movie_updates = ChainQueryFilter::new()
    .entry_type(EntryType::App(UnitEntryTypes::Movie.into()))
    .action_type(ActionType::Update)
    .include_entries(true);

let filter_only_cap_grants_and_claims_newest_first = ChainQueryFilter::new()
    .entry_type(EntryType::CapGrant)
    .entry_type(EntryType::CapClaim)
    .include_entries(true)
    .descending();

let filter_first_ten_records = ChainQueryFilter::new()
    .sequence_range(ChainQueryFilterRange::ActionSeqRange(0, 9));

Use ChainQueryFilter to query a vector of actions or records

If you already have a vector of Actions or Records in memory, you can apply a ChainQueryFilter to them as if you were querying a source chain.

include hdk::prelude::*;

let actions: Vec<Action> = /* get some actions somehow */;
let movie_update_actions = filter_only_movie_updates.filter_actions(actions);

Query an agent’s own source chain

An agent can query their own source chain with the query host function, which takes a ChainQueryFilter and returns a Vec<Record> wrapped in an ExternResult.

use hdk::prelude::*;

#[hdk_extern]
pub fn get_all_movies_i_authored() -> Vec<Record> {
    query(ChainQueryFilter::new()
        .entry_type(EntryType::App(UnitEntryTypes::Movie.into()))
        .include_entries(true)
    )
}

Query another agent’s source chain for validation

There’s another source chain querying function called must_get_agent_activity, which is used in validation to check whether a contiguous region of a source chain is valid. You can find examples of this function on the Validation page.

Reference

Further reading

It looks like you are using Internet Explorer. While the basic content is available, this is no longer a supported browser by the manufacturer, and no attention is being given to having IE work well here.