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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
use crate::auth::{generate_auth_headers, HmacError};
use crate::config::Config;
use crate::endpoints::{
API_V1_FEEDS, API_V1_REPORTS, API_V1_REPORTS_BULK, API_V1_REPORTS_LATEST, API_V1_REPORTS_PAGE,
};
use crate::feed::Feed;
use chainlink_data_streams_report::feed_id::ID;
use chainlink_data_streams_report::report::Report;
use reqwest::Client as HttpClient;
use serde::Deserialize;
use serde_urlencoded;
use std::time::{SystemTime, UNIX_EPOCH};
use thiserror::Error;
/// Errors that can occur within the client.
#[derive(Error, Debug)]
pub enum ClientError {
#[error("HTTP request failed: {0}")]
HttpRequestError(#[from] reqwest::Error),
#[error("HMAC generation failed: {0}")]
HmacError(#[from] HmacError),
#[error("Invalid response format: {0}")]
InvalidResponseFormat(#[from] serde_json::Error),
#[error("API error: {0}")]
ApiError(String),
}
#[derive(Debug, Deserialize)]
struct FeedsResponse {
feeds: Vec<Feed>,
}
#[derive(Debug, Deserialize)]
pub struct ReportResponse {
pub report: Report,
}
#[derive(Debug, Deserialize)]
struct ReportsResponse {
reports: Vec<Report>,
}
pub struct Client {
config: Config,
http: HttpClient,
}
impl Client {
/// Creates a new `Client` instance using the provided `Config`.
///
/// # Arguments
///
/// * `config` - A validated `Config` instance.
///
/// # Errors
///
/// Returns an error if the HTTP client fails to initialize.
pub fn new(config: Config) -> Result<Self, ClientError> {
let http = HttpClient::builder()
.danger_accept_invalid_certs(config.insecure_skip_verify.to_bool())
.build()?;
Ok(Client { config, http })
}
/// Returns a list of available feeds.
///
/// # Endpoint:
/// ```bash
/// /api/v1/feeds
/// ```
///
/// # Type:
/// * HTTP GET
///
/// # Sample request:
/// ```bash
/// GET /api/v1/feeds
/// ```
///
/// # Error Response Codes
///
/// | Status Code | Description |
/// |-------------|-------------|
/// | **400 Bad Request** | This error is triggered when:<br>- There is any missing/malformed query argument.<br>- Required headers are missing or provided with incorrect values. |
/// | **401 Unauthorized User** | This error is triggered when:<br>- Authentication fails, typically because the HMAC signature provided by the client doesn't match the one expected by the server.<br>- A user requests access to a feed without the appropriate permission or that does not exist. |
/// | **500 Internal Server** | Indicates an unexpected condition encountered by the server, preventing it from fulfilling the request. This error typically points to issues on the server side. |
pub async fn get_feeds(&self) -> Result<Vec<Feed>, ClientError> {
let url = format!("{}{}", self.config.rest_url, API_V1_FEEDS);
let method = "GET";
let path = API_V1_FEEDS;
let body = b"";
let client_id = &self.config.api_key;
let user_secret = &self.config.api_secret;
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Error: Timestamp in the past")
.as_millis();
let headers = generate_auth_headers(method, path, body, client_id, user_secret, timestamp)?;
// Make the GET request
let response = self
.http
.get(url)
.headers(headers)
.send()
.await?
.error_for_status()
.map_err(|e| ClientError::ApiError(e.to_string()))?;
// Optionally inspect the response
if let Some(inspect_fn) = &self.config.inspect_http_response {
inspect_fn(&response);
}
let feeds_response = response.json::<FeedsResponse>().await?;
Ok(feeds_response.feeds)
}
/// Returns a single report with the latest timestamp.
///
/// # Endpoint:
/// ```bash
/// /api/v1/reports/latest
/// ```
///
/// # Type:
/// * HTTP GET
///
/// # Parameters:
/// * `feedID` - A Data Streams feed ID.
///
/// # Sample request:
/// ```bash
/// GET /api/v1/reports/latest?feedID={feedID}
/// ```
///
/// # Sample response:
/// ```json
/// {
/// "report": {
/// "feedID": "Hex encoded feedId.",
/// "validFromTimestamp": "Report's earliest applicable timestamp (in seconds).",
/// "observationsTimestamp": "Report's latest applicable timestamp (in seconds).",
/// "fullReport": "A blob containing the report context and body. Encode the fee token into the payload before passing it to the contract for verification."
/// }
/// }
/// ```
///
/// # Error Response Codes
///
/// | Status Code | Description |
/// |-------------|-------------|
/// | **400 Bad Request** | This error is triggered when:<br>- There is any missing/malformed query argument.<br>- Required headers are missing or provided with incorrect values. |
/// | **401 Unauthorized User** | This error is triggered when:<br>- Authentication fails, typically because the HMAC signature provided by the client doesn't match the one expected by the server.<br>- A user requests access to a feed without the appropriate permission or that does not exist. |
/// | **500 Internal Server** | Indicates an unexpected condition encountered by the server, preventing it from fulfilling the request. This error typically points to issues on the server side. |
pub async fn get_latest_report(&self, feed_id: ID) -> Result<ReportResponse, ClientError> {
let url = format!("{}{}", self.config.rest_url, API_V1_REPORTS_LATEST);
let feed_id = feed_id.to_hex_string();
let method = "GET";
let path = format!("{}?feedID={}", API_V1_REPORTS_LATEST, feed_id);
let body = b"";
let client_id = &self.config.api_key;
let user_secret = &self.config.api_secret;
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Error: Timestamp in the past")
.as_millis();
let headers =
generate_auth_headers(method, &path, body, client_id, user_secret, timestamp)?;
// Make the GET request
let response = self
.http
.get(url)
.query(&[("feedID", feed_id)])
.headers(headers)
.send()
.await?
.error_for_status()
.map_err(|e| ClientError::ApiError(e.to_string()))?;
// Optionally inspect the response
if let Some(inspect_fn) = &self.config.inspect_http_response {
inspect_fn(&response);
}
let report_response = response.json::<ReportResponse>().await?;
Ok(report_response)
}
/// Returns a single report at a given timestamp.
///
/// # Endpoint:
/// ```bash
/// /api/v1/reports
/// ```
///
/// # Type:
/// * HTTP GET
///
/// # Parameters:
/// * `feedID` - A Data Streams feed ID.
/// * `timestamp` - The Unix timestamp for the report (in seconds).
///
/// # Sample request:
/// ```bash
/// GET /api/v1/reports?feedID={feedID}×tamp={timestamp}
/// ```
///
/// # Sample response:
/// ```json
/// {
/// "report": {
/// "feedID": "Hex encoded feedId.",
/// "validFromTimestamp": "Report's earliest applicable timestamp (in seconds).",
/// "observationsTimestamp": "Report's latest applicable timestamp (in seconds).",
/// "fullReport": "A blob containing the report context and body. Encode the fee token into the payload before passing it to the contract for verification."
/// }
/// }
/// ```
///
/// # Error Response Codes
///
/// | Status Code | Description |
/// |-------------|-------------|
/// | **400 Bad Request** | This error is triggered when:<br>- There is any missing/malformed query argument.<br>- Required headers are missing or provided with incorrect values. |
/// | **401 Unauthorized User** | This error is triggered when:<br>- Authentication fails, typically because the HMAC signature provided by the client doesn't match the one expected by the server.<br>- A user requests access to a feed without the appropriate permission or that does not exist. |
/// | **500 Internal Server** | Indicates an unexpected condition encountered by the server, preventing it from fulfilling the request. This error typically points to issues on the server side. |
pub async fn get_report(
&self,
feed_id: ID,
timestamp: u128,
) -> Result<ReportResponse, ClientError> {
let url = format!("{}{}", self.config.rest_url, API_V1_REPORTS);
let feed_id = feed_id.to_hex_string();
let method = "GET";
let path = format!(
"{}?feedID={}×tamp={}",
API_V1_REPORTS, feed_id, timestamp
);
let body = b"";
let client_id = &self.config.api_key;
let user_secret = &self.config.api_secret;
let request_timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Error: Timestamp in the past")
.as_millis();
let headers = generate_auth_headers(
method,
&path,
body,
client_id,
user_secret,
request_timestamp,
)?;
// Make the GET request
let response = self
.http
.get(url)
.query(&[("feedID", feed_id), ("timestamp", timestamp.to_string())])
.headers(headers)
.send()
.await?
.error_for_status()
.map_err(|e| ClientError::ApiError(e.to_string()))?;
// Optionally inspect the response
if let Some(inspect_fn) = &self.config.inspect_http_response {
inspect_fn(&response);
}
let report_response = response.json::<ReportResponse>().await?;
Ok(report_response)
}
/// Returns a report for multiple FeedIDs at a given timestamp.
///
/// # Endpoint:
/// ```bash
/// /api/v1/reports/bulk
/// ```
/// # Type:
/// * HTTP GET
///
/// # Parameters:
/// * `feedIDs` - A comma-separated list of Data Streams feed IDs.
/// * `timestamp` - The Unix timestamp for the reports (in seconds).
///
/// # Sample request:
/// ```bash
/// GET /api/v1/reports/bulk?feedIDs={FeedID1},{FeedID2},...×tamp={timestamp}
/// ```
///
/// # Sample response:
/// ```json
/// {
/// "reports": [
/// {
/// "feedID": "Hex encoded feedId.",
/// "validFromTimestamp": "Report's earliest applicable timestamp (in seconds).",
/// "observationsTimestamp": "Report's latest applicable timestamp (in seconds).",
/// "fullReport": "A blob containing the report context and body. Encode the fee token into the payload before passing it to the contract for verification."
/// },
/// //...
/// ]
/// }
/// ```
///
/// # Error Response Codes
///
/// | Status Code | Description |
/// |-------------|-------------|
/// | **400 Bad Request** | This error is triggered when:<br>- There is any missing/malformed query argument.<br>- Required headers are missing or provided with incorrect values. |
/// | **401 Unauthorized User** | This error is triggered when:<br>- Authentication fails, typically because the HMAC signature provided by the client doesn't match the one expected by the server.<br>- A user requests access to a feed without the appropriate permission or that does not exist. |
/// | **500 Internal Server** | Indicates an unexpected condition encountered by the server, preventing it from fulfilling the request. This error typically points to issues on the server side. |
/// | **206 Missing Data** | Indicates that at least one feed ID data is missing from the report. E.g., you requested a report for feed IDs `<feedID1>`, `<feedID2>`, and `<feedID3>` at a given timestamp. If data for `<feedID2>` is missing from the report (not available yet at the specified timestamp), you get `[<feedID1 data>, <feedID3 data>]` and a 206 response. |
pub async fn get_reports_bulk(
&self,
feed_ids: &[ID],
timestamp: u128,
) -> Result<Vec<Report>, ClientError> {
let url = format!("{}{}", self.config.rest_url, API_V1_REPORTS_BULK);
let feed_ids: Vec<String> = feed_ids.iter().map(|id| id.to_hex_string()).collect();
let feed_ids_joined = feed_ids.join(",");
let timestamp_str = timestamp.to_string();
let query_params = &[
("feedIDs", feed_ids_joined.as_str()),
("timestamp", timestamp_str.as_str()),
];
let query_string = serde_urlencoded::to_string(query_params).unwrap();
let method = "GET";
let path = format!("{}?{}", API_V1_REPORTS_BULK, query_string);
let body = b"";
let client_id = &self.config.api_key;
let user_secret = &self.config.api_secret;
let request_timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Error: Timestamp in the past")
.as_millis();
let headers = generate_auth_headers(
method,
&path,
body,
client_id,
user_secret,
request_timestamp,
)?;
// Make the GET request
let response = self
.http
.get(url)
.query(query_params)
.headers(headers)
.send()
.await?
.error_for_status()
.map_err(|e| ClientError::ApiError(e.to_string()))?;
// Optionally inspect the response
if let Some(inspect_fn) = &self.config.inspect_http_response {
inspect_fn(&response);
}
let reports_response = response.json::<ReportsResponse>().await?;
let reports = reports_response.reports;
Ok(reports)
}
/// Returns multiple sequential reports for a single FeedID, starting at a given timestamp
///
/// # Endpoint:
/// ```bash
/// /api/v1/reports
/// ```
///
/// # Type:
/// * HTTP GET
///
/// # Parameters:
/// * `feedID` - A Data Streams feed ID.
/// * `startTimestamp` - The UNIX timestamp for the first report (in seconds).
///
/// # Sample request:
/// ```bash
/// GET /api/v1/reports/page?feedID={FeedID}&startTimestamp={StartTimestamp}
/// ```
///
/// # Sample response:
/// ```json
/// {
/// "reports": [
/// {
/// "feedID": "Hex encoded feedId.",
/// "validFromTimestamp": "Report's earliest applicable timestamp (in seconds).",
/// "observationsTimestamp": "Report's latest applicable timestamp (in seconds).",
/// "fullReport": "A blob containing the report context and body. Encode the fee token into the payload before passing it to the contract for verification."
/// },
/// //...
/// ]
/// }
/// ```
///
/// # Error Response Codes
///
/// | Status Code | Description |
/// |-------------|-------------|
/// | **400 Bad Request** | This error is triggered when:<br>- There is any missing/malformed query argument.<br>- Required headers are missing or provided with incorrect values. |
/// | **401 Unauthorized User** | This error is triggered when:<br>- Authentication fails, typically because the HMAC signature provided by the client doesn't match the one expected by the server.<br>- A user requests access to a feed without the appropriate permission or that does not exist. |
/// | **500 Internal Server** | Indicates an unexpected condition encountered by the server, preventing it from fulfilling the request. This error typically points to issues on the server side. |
pub async fn get_reports_page(
&self,
feed_id: ID,
start_timestamp: u128,
) -> Result<Vec<Report>, ClientError> {
let url = format!("{}{}", self.config.rest_url, API_V1_REPORTS_PAGE);
let feed_id = feed_id.to_hex_string();
let method = "GET";
let path = format!(
"{}?feedID={}&startTimestamp={}",
API_V1_REPORTS_PAGE, feed_id, start_timestamp
);
let body = b"";
let client_id = &self.config.api_key;
let user_secret = &self.config.api_secret;
let request_timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Error: Timestamp in the past")
.as_millis();
let headers = generate_auth_headers(
method,
&path,
body,
client_id,
user_secret,
request_timestamp,
)?;
// Make the GET request
let response = self
.http
.get(url)
.query(&[
("feedID", feed_id),
("startTimestamp", start_timestamp.to_string()),
])
.headers(headers)
.send()
.await?
.error_for_status()
.map_err(|e| ClientError::ApiError(e.to_string()))?;
// Optionally inspect the response
if let Some(inspect_fn) = &self.config.inspect_http_response {
inspect_fn(&response);
}
let reports_response = response.json::<ReportsResponse>().await?;
let reports = reports_response.reports;
Ok(reports)
}
/// Returns multiple sequential reports for a single FeedID, starting at a given timestamp
///
/// # Endpoint:
/// ```bash
/// /api/v1/reports
/// ```
///
/// # Type:
/// * HTTP GET
///
/// # Parameters:
/// * `feedID` - A Data Streams feed ID.
/// * `startTimestamp` - The UNIX timestamp for the first report (in seconds).
/// * `limit` - The number of reports to return
///
/// # Sample request:
/// ```bash
/// GET /api/v1/reports/page?feedID={FeedID}&startTimestamp={StartTimestamp}&limit={Limit}
/// ```
///
/// # Sample response:
/// ```json
/// {
/// "reports": [
/// {
/// "feedID": "Hex encoded feedId.",
/// "validFromTimestamp": "Report's earliest applicable timestamp (in seconds).",
/// "observationsTimestamp": "Report's latest applicable timestamp (in seconds).",
/// "fullReport": "A blob containing the report context and body. Encode the fee token into the payload before passing it to the contract for verification."
/// },
/// //...
/// ]
/// }
/// ```
///
/// # Error Response Codes
///
/// | Status Code | Description |
/// |-------------|-------------|
/// | **400 Bad Request** | This error is triggered when:<br>- There is any missing/malformed query argument.<br>- Required headers are missing or provided with incorrect values. |
/// | **401 Unauthorized User** | This error is triggered when:<br>- Authentication fails, typically because the HMAC signature provided by the client doesn't match the one expected by the server.<br>- A user requests access to a feed without the appropriate permission or that does not exist. |
/// | **500 Internal Server** | Indicates an unexpected condition encountered by the server, preventing it from fulfilling the request. This error typically points to issues on the server side. |
pub async fn get_reports_page_with_limit(
&self,
feed_id: ID,
start_timestamp: u128,
limit: usize,
) -> Result<Vec<Report>, ClientError> {
let url = format!("{}{}", self.config.rest_url, API_V1_REPORTS_PAGE);
let feed_id = feed_id.to_hex_string();
let method = "GET";
let path = format!(
"{}?feedID={}&startTimestamp={}&limit={}",
API_V1_REPORTS_PAGE, feed_id, start_timestamp, limit
);
let body = b"";
let client_id = &self.config.api_key;
let user_secret = &self.config.api_secret;
let request_timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Error: Timestamp in the past")
.as_millis();
let headers = generate_auth_headers(
method,
&path,
body,
client_id,
user_secret,
request_timestamp,
)?;
// Make the GET request
let response = self
.http
.get(url)
.query(&[
("feedID", feed_id),
("startTimestamp", start_timestamp.to_string()),
("limit", limit.to_string()),
])
.headers(headers)
.send()
.await?
.error_for_status()
.map_err(|e| ClientError::ApiError(e.to_string()))?;
// Optionally inspect the response
if let Some(inspect_fn) = &self.config.inspect_http_response {
inspect_fn(&response);
}
let reports_response = response.json::<ReportsResponse>().await?;
let reports = reports_response.reports;
Ok(reports)
}
}