iota_light_client/
graphql.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2025 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use anyhow::{Result, anyhow};
6use iota_graphql_rpc_client::simple_client::{GraphqlQueryVariable, SimpleClient};
7use serde_json::json;
8
9use crate::config::Config;
10
11pub async fn query_last_checkpoint_of_epoch(config: &Config, epoch_id: u64) -> Result<u64> {
12    // GraphQL query to get the last checkpoint of an epoch
13    let query = r#"
14        {
15            epoch(id: $epochID) { 
16                checkpoints(last: 1) { 
17                    nodes { 
18                        sequenceNumber
19                    }
20                }
21            } 
22        }
23    "#;
24    let variables = vec![GraphqlQueryVariable {
25        name: "epochID".to_string(),
26        ty: "Int".to_string(),
27        value: json!(epoch_id),
28    }];
29    let client = SimpleClient::new(
30        config
31            .graphql_url
32            .as_ref()
33            .cloned()
34            .ok_or_else(|| anyhow!("missing graphql url"))?,
35    );
36    // Submit the query by POSTing to the GraphQL endpoint
37    let resp = client
38        .execute_to_graphql(query.to_string(), true, variables, vec![])
39        .await?;
40    anyhow::ensure!(resp.errors().is_empty(), "{:?}", resp.errors());
41
42    let data = resp.response_body().data.clone().into_json()?;
43
44    // Parse the JSON response to get the last checkpoint of the epoch
45    let checkpoint_number = data["epoch"]["checkpoints"]["nodes"][0]["sequenceNumber"]
46        .as_u64()
47        .expect("invalid sequence number");
48
49    Ok(checkpoint_number)
50}