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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
pub mod schema;
use reqwest::{self, Client};
use std::{collections::HashMap, time::Duration};
use url::Url;

static API_BASE_URL: &str = "https://ordiscan.com/v1";

// Define the custom error type
type Result<T> = std::result::Result<T, OrdiscanError>;

#[derive(Debug, thiserror::Error)]
pub enum OrdiscanError {
  #[error("api error")]
  RequestError(#[from] reqwest::Error),
}

pub struct Ordiscan {
  client: reqwest::Client,
  api_key: String,
}

#[derive(Debug)]
pub struct GetListOfInscriptionParams<'a> {
  pub address: Option<&'a str>,
  pub content_type: Option<&'a str>,
  pub sort: Sort,
  pub after_number: Option<usize>,
  pub before_number: Option<usize>,
}

#[derive(Debug)]
pub struct GetInscriptionInfoParams<'a> {
  pub id: Option<&'a str>,
  pub number: Option<usize>,
}

#[derive(Debug)]
pub enum Sort {
  InscriptionNumberDesc,
  InscriptionNumberAsc,
}

impl Sort {
  pub fn as_str(&self) -> &'static str {
    match self {
      Sort::InscriptionNumberDesc => "inscription_number_desc", // default
      Sort::InscriptionNumberAsc => "inscription_number_asc",
    }
  }
}

impl<'a> Ordiscan {
  // create a new Ordiscan client
  pub fn new(key: String) -> reqwest::Result<Self> {
    let client = Client::builder().timeout(Duration::from_secs(10)).build()?;
    let api_key: String = key;
    Ok(Self { client, api_key })
  }

  // get inscription info
  // https://ordiscan.com/docs/api#get-inscription-info
  pub async fn get_inscription_info(
    &self,
    params: GetInscriptionInfoParams<'a>,
  ) -> Result<schema::InscriptionInfo> {
    let header = format!("Bearer {}", self.api_key);
    let mut url = Url::parse(format!("{}/inscription", API_BASE_URL).as_str()).unwrap();

    if params.id.is_none() & params.number.is_none()
      || params.id.is_some() & params.number.is_some()
    {
      panic!("please supply either id or number")
    }

    if params.id.is_some() {
      url.query_pairs_mut().append_pair("id", params.id.unwrap());
    }

    if params.number.is_some() {
      url
        .query_pairs_mut()
        .append_pair("number", params.number.unwrap().to_string().as_str());
    }

    let data = self
      .client
      .get(url.to_string())
      .header("Authorization", &header)
      .send()
      .await?
      .json::<HashMap<String, schema::InscriptionInfo>>()
      .await?;

    Ok(data.get("data").unwrap().to_owned())
  }

  // get a list of inscriptions
  // https://ordiscan.com/docs/api#get-list-of-inscriptions
  pub async fn get_list_of_inscriptions(
    &self,
    params: GetListOfInscriptionParams<'a>,
  ) -> Result<Vec<schema::InscriptionInfo>> {
    let header = format!("Bearer {}", self.api_key);
    let mut url = Url::parse(
      format!(
        "{}/inscriptions?sort={}",
        API_BASE_URL,
        params.sort.as_str()
      )
      .as_str(),
    )
    .unwrap();

    // TODO make this look better
    // dynamically create query params
    if params.address.is_some() {
      url
        .query_pairs_mut()
        .append_pair("address", params.address.unwrap());
    }
    if params.content_type.is_some() {
      url
        .query_pairs_mut()
        .append_pair("content_type", params.content_type.unwrap());
    }
    if params.after_number.is_some() {
      url.query_pairs_mut().append_pair(
        "afterNumber",
        params.after_number.unwrap().to_string().as_str(),
      );
    }
    if params.before_number.is_some() {
      url.query_pairs_mut().append_pair(
        "beforeNumber",
        params.before_number.unwrap().to_string().as_str(),
      );
    }

    // get the data
    let data = self
      .client
      .get(url.to_string())
      .header("Authorization", &header)
      .send()
      .await?
      .json::<HashMap<String, Vec<schema::InscriptionInfo>>>()
      .await?;

    Ok(data.get("data").unwrap().to_vec())
  }

  // get address activity
  // https://ordiscan.com/docs/api#get-address-activity
  pub async fn get_address_activity(&self, address: &str) -> Result<Vec<schema::AddressActivity>> {
    let api_url = format!("{}/activity?address={}", API_BASE_URL, address);
    let header = format!("Bearer {}", self.api_key);

    // get the data
    let data = self
      .client
      .get(&api_url)
      .header("Authorization", &header)
      .send()
      .await?
      .json::<HashMap<String, Vec<schema::AddressActivity>>>()
      .await?;

    Ok(data.get("data").unwrap().to_vec())
  }
}