1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use crate::query::{CollectData, ResponseData, Variables};
use anyhow::{Context, Result};
use graphql_client::{GraphQLQuery, Response};
use reqwest::{header, Client};

mod query;
#[cfg(test)]
mod test;

const TW_LOG: &str = "timegraph";

pub struct TimegraphData {
    /// collection hashId
    pub collection: String,
    /// task associated with data
    pub task_id: u64,
    /// for repeated task it's incremented on every run
    pub cycle: u64,
    /// target network block number
    pub target_block_number: u64,
    /// time-chain block number
    pub timechain_block_number: u64,
    /// TSS signature
    pub signature: [u8; 64],
    /// data to add into collection
    pub data: Vec<String>,
}

pub struct Timegraph {
    client: Client,
    url: String,
    ssk: String,
}

impl Timegraph {
    pub fn new() -> Result<Self> {
        dotenv::dotenv().ok();
        let url = std::env::var("TIMEGRAPH_GRAPHQL_URL")
            .context("Unable to get timegraph graphql url")?;
        let ssk = std::env::var("SSK").context("Unable to get timegraph ssk")?;
        let client = Client::new();
        Ok(Self { client, url, ssk })
    }

    /// Add data into collection (user must have Collector role)
    pub async fn submit_data(&self, data: TimegraphData) -> Result<()> {
        let variables = Variables {
            collection: data.collection,
            task_id: data.task_id as i64,
            task_counter: data.cycle as i64,
            block: data.target_block_number as i64,
            cycle: data.timechain_block_number as i64,
            tss: hex::encode(data.signature),
            data: data.data,
        };

        let request = CollectData::build_query(variables);
        let response = self
            .client
            .post(&self.url)
            .json(&request)
            .header(header::AUTHORIZATION, &self.ssk)
            .send()
            .await
            .map_err(|e| anyhow::anyhow!("error post to timegraph {}", e))?;
        let json = response
            .json::<Response<ResponseData>>()
            .await
            .context("Failed to parse timegraph response")?;
        let data = json.data.context(format!(
            "timegraph migrate collect status fail: No reponse {:?}",
            json.errors
        ))?;
        log::info!(
            target: TW_LOG,
            "timegraph migrate collect status: {:?}",
            data.collect.status
        );
        Ok(())
    }
}