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
use std::time::Duration;
use reqwest::{Client, Method, Response, StatusCode};
use serde::{Serialize, de::DeserializeOwned};
use crate::{
config::Config,
error::KobeApiError,
types::{
bam_epoch_metrics::BamEpochMetricsResponse, bam_validators::BamValidatorsResponse,
coinbase_balance::CoinbaseBalanceResponse, *,
},
};
/// Main client for interacting with Jito APIs
#[derive(Debug, Clone)]
pub struct KobeClient {
client: Client,
config: Config,
}
impl KobeClient {
/// Create a new Jito API client with the given configuration
pub fn new(config: Config) -> Self {
let client = Client::builder()
.timeout(config.timeout)
.user_agent(&config.user_agent)
.build()
.expect("Failed to build HTTP client");
Self { client, config }
}
/// Create a client with mainnet defaults
pub fn mainnet() -> Self {
Self::new(Config::mainnet())
}
/// Create a client with testnet defaults
pub fn testnet() -> Self {
Self::new(Config::testnet())
}
/// Get the base URL
pub fn base_url(&self) -> &str {
&self.config.base_url
}
/// Make a GET request
async fn get<T: DeserializeOwned>(
&self,
endpoint: &str,
query: &str,
) -> Result<T, KobeApiError> {
let url = format!(
"{}/api/{}{}{}",
self.config.base_url,
crate::API_VERSION,
endpoint,
query
);
self.request(Method::GET, &url, None::<&()>).await
}
/// Make a POST request
async fn post<B: Serialize, T: DeserializeOwned>(
&self,
endpoint: &str,
body: Option<&B>,
) -> Result<T, KobeApiError> {
let url = format!(
"{}/api/{}{}",
self.config.base_url,
crate::API_VERSION,
endpoint
);
self.request(Method::POST, &url, body).await
}
/// Make an HTTP request with optional retry logic
async fn request<B: Serialize, T: DeserializeOwned>(
&self,
method: Method,
url: &str,
body: Option<&B>,
) -> Result<T, KobeApiError> {
let mut retries = 0;
let max_retries = if self.config.retry_enabled {
self.config.max_retries
} else {
0
};
loop {
let mut request = self.client.request(method.clone(), url);
if let Some(body) = body {
request = request.json(body);
}
let response = request.send().await?;
match self.handle_response(response).await {
Ok(data) => return Ok(data),
Err(e) => {
if retries >= max_retries || !self.should_retry(&e) {
return Err(e);
}
retries += 1;
// Exponential backoff
let delay = Duration::from_millis(100 * 2u64.pow(retries));
tokio::time::sleep(delay).await;
}
}
}
}
/// Handle HTTP response
async fn handle_response<T: DeserializeOwned>(
&self,
response: Response,
) -> Result<T, KobeApiError> {
let status = response.status();
if status.is_success() {
response.json::<T>().await.map_err(Into::into)
} else {
let status_code = status.as_u16();
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
match status {
StatusCode::NOT_FOUND => Err(KobeApiError::NotFound(error_text)),
StatusCode::TOO_MANY_REQUESTS => Err(KobeApiError::RateLimitExceeded),
StatusCode::REQUEST_TIMEOUT => Err(KobeApiError::Timeout),
_ => Err(KobeApiError::api_error(status_code, error_text)),
}
}
}
/// Determine if an error should trigger a retry
fn should_retry(&self, error: &KobeApiError) -> bool {
matches!(error, KobeApiError::Timeout | KobeApiError::HttpError(_))
}
/// Get staker rewards
///
/// Retrieves individual claimable MEV and priority fee rewards from the tip distribution merkle trees.
///
/// # Arguments
///
/// * `limit` - Optional limit on the number of results (default: API default)
///
/// # Example
///
/// ```no_run
/// # use kobe_client::client::KobeClient;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = KobeClient::mainnet();
/// let rewards = client.get_staker_rewards(Some(10)).await?;
/// # Ok(())
/// # }
/// ```
pub async fn get_staker_rewards(
&self,
limit: Option<u32>,
) -> Result<StakerRewardsResponse, KobeApiError> {
let query = if let Some(limit) = limit {
format!("?limit={}", limit)
} else {
String::new()
};
self.get("/staker_rewards", &query).await
}
/// Get staker rewards with full query parameters
pub async fn get_staker_rewards_with_params(
&self,
params: &QueryParams,
) -> Result<StakerRewardsResponse, KobeApiError> {
self.get("/staker_rewards", ¶ms.to_query_string()).await
}
/// Get validator rewards for a specific epoch
///
/// Retrieves aggregated MEV and priority fee rewards data per validator.
///
/// # Arguments
///
/// * `epoch` - Epoch number (optional, defaults to latest)
/// * `limit` - Optional limit on the number of results
pub async fn get_validator_rewards(
&self,
epoch: Option<u64>,
limit: Option<u32>,
) -> Result<ValidatorRewardsResponse, KobeApiError> {
let mut params = Vec::new();
if let Some(epoch) = epoch {
params.push(format!("epoch={}", epoch));
}
if let Some(limit) = limit {
params.push(format!("limit={}", limit));
}
let query = if params.is_empty() {
String::new()
} else {
format!("?{}", params.join("&"))
};
self.get("/validator_rewards", &query).await
}
/// Get all validators for a given epoch
///
/// Returns validator state for a given epoch (defaults to latest).
///
/// # Arguments
///
/// * `epoch` - Optional epoch number (defaults to latest)
pub async fn get_validators(
&self,
epoch: Option<u64>,
) -> Result<ValidatorsResponse, KobeApiError> {
if let Some(epoch) = epoch {
self.post("/validators", Some(&EpochRequest { epoch }))
.await
} else {
self.post::<EpochRequest, _>("/validators", None).await
}
}
/// Get JitoSOL stake pool validators for a given epoch
///
/// Returns only validators that are actively part of the JitoSOL validator set.
pub async fn get_jitosol_validators(
&self,
epoch: Option<u64>,
) -> Result<ValidatorsResponse, KobeApiError> {
if let Some(epoch) = epoch {
self.post("/jitosol_validators", Some(&EpochRequest { epoch }))
.await
} else {
self.post::<EpochRequest, _>("/jitosol_validators", None)
.await
}
}
/// Get historical data for a single validator
///
/// Returns historical reward data for a validator, sorted by epoch (descending).
///
/// # Arguments
///
/// * `vote_account` - The validator's vote account public key
pub async fn get_validator_info_by_vote_account(
&self,
vote_account: &str,
) -> Result<Vec<ValidatorByVoteAccount>, KobeApiError> {
self.get(&format!("/validators/{}", vote_account), "").await
}
/// Get MEV rewards network statistics for an epoch
///
/// Returns network-level statistics including total MEV, stake weight, and reward per lamport.
///
/// # Arguments
///
/// * `epoch` - Optional epoch number (defaults to latest)
pub async fn get_mev_rewards(&self, epoch: Option<u64>) -> Result<MevRewards, KobeApiError> {
if let Some(epoch) = epoch {
self.post("/mev_rewards", Some(&EpochRequest { epoch }))
.await
} else {
// GET request for latest epoch
self.get("/mev_rewards", "").await
}
}
/// Get daily MEV rewards
///
/// Returns aggregated MEV rewards per calendar day.
pub async fn get_daily_mev_rewards(&self) -> Result<Vec<DailyMevRewards>, KobeApiError> {
self.get("/daily_mev_rewards", "").await
}
/// Get Jito stake over time
///
/// Returns a map of epoch to percentage of all Solana stake delegated to Jito-running validators.
pub async fn get_jito_stake_over_time(&self) -> Result<JitoStakeOverTime, KobeApiError> {
self.get("/jito_stake_over_time", "").await
}
/// Get MEV commission average over time
///
/// Returns stake-weighted average MEV commission along with other metrics.
pub async fn get_mev_commission_average_over_time(
&self,
) -> Result<MevCommissionAverageOverTime, KobeApiError> {
self.get("/mev_commission_average_over_time", "").await
}
/// Get JitoSOL to SOL exchange ratio over time
///
/// # Arguments
///
/// * `start` - Start datetime for the range
/// * `end` - End datetime for the range
pub async fn get_jitosol_sol_ratio(
&self,
start: chrono::DateTime<chrono::Utc>,
end: chrono::DateTime<chrono::Utc>,
) -> Result<JitoSolRatio, KobeApiError> {
let request = RangeRequest {
range_filter: RangeFilter { start, end },
};
self.post("/jitosol_sol_ratio", Some(&request)).await
}
/// Get stake pool statistics
///
/// Returns stake pool analytics including TVL, APY, validator count, supply metrics,
/// and aggregated MEV rewards over time.
pub async fn get_stake_pool_stats(
&self,
request: Option<&StakePoolStatsRequest>,
) -> Result<StakePoolStats, KobeApiError> {
if let Some(req) = request {
self.post("/stake_pool_stats", Some(req)).await
} else {
// GET request for default (last 7 days)
self.get("/stake_pool_stats", "").await
}
}
/// Get the current epoch from the latest MEV rewards data
pub async fn get_current_epoch(&self) -> Result<u64, KobeApiError> {
let mev_rewards = self.get_mev_rewards(None).await?;
Ok(mev_rewards.epoch)
}
/// Get all validators currently running Jito
pub async fn get_jito_validators(&self) -> Result<Vec<ValidatorInfo>, KobeApiError> {
let response: ValidatorsResponse = self.get("/validators", "").await?;
Ok(response
.validators
.into_iter()
.filter(|v| v.running_jito)
.collect())
}
// Get validators sorted by MEV rewards
// pub async fn get_validators_by_mev_rewards(
// &self,
// epoch: Option<u64>,
// limit: usize,
// ) -> Result<Vec<ValidatorInfo>, KobeApiError> {
// let mut response = self.get_validators(epoch).await?;
// response
// .validators
// .sort_by(|a, b| b.mev_rewards.cmp(&a.mev_rewards));
// Ok(response.validators.into_iter().take(limit).collect())
// }
/// Get validators sorted by active stake
pub async fn get_validators_by_stake(
&self,
epoch: Option<u64>,
limit: usize,
) -> Result<Vec<ValidatorInfo>, KobeApiError> {
let mut response = self.get_validators(epoch).await?;
response
.validators
.sort_by_key(|b| std::cmp::Reverse(b.active_stake));
Ok(response.validators.into_iter().take(limit).collect())
}
/// Check if a validator is running Jito
pub async fn is_validator_running_jito(
&self,
vote_account: &str,
) -> Result<bool, KobeApiError> {
let response = self.get_validators(None).await?;
Ok(response
.validators
.iter()
.find(|v| v.vote_account == vote_account)
.map(|v| v.running_jito)
.unwrap_or(false))
}
// Get validator MEV commission
// pub async fn get_validator_mev_commission(
// &self,
// vote_account: &str,
// ) -> Result<Option<u16>, KobeApiError> {
// let response = self.get_validators(None).await?;
// Ok(response
// .validators
// .iter()
// .find(|v| v.vote_account == vote_account)
// .map(|v| v.mev_commission_bps))
// }
/// Calculate total MEV rewards for a time period
pub async fn calculate_total_mev_rewards(
&self,
start_epoch: u64,
end_epoch: u64,
) -> Result<u64, KobeApiError> {
let mut total = 0u64;
for epoch in start_epoch..=end_epoch {
if let Ok(mev_rewards) = self.get_mev_rewards(Some(epoch)).await {
total = total.saturating_add(mev_rewards.total_network_mev_lamports);
}
}
Ok(total)
}
/// Get BAM Delegation Blacklist
///
/// Returns bam delegation blacklist
pub async fn get_bam_delegation_blacklist(
&self,
) -> Result<Vec<BamDelegationBlacklistEntry>, KobeApiError> {
self.get("/bam_delegation_blacklist", "").await
}
/// Get BAM Epoch Metrics
///
/// Returns bam epoch metrics
pub async fn get_bam_epoch_metrics(
&self,
epoch: u64,
) -> Result<BamEpochMetricsResponse, KobeApiError> {
let query = format!("?epoch={epoch}");
self.get("/bam_epoch_metrics", &query).await
}
/// Get BAM Validators
///
/// Returns bam validators
pub async fn get_bam_validators(
&self,
epoch: u64,
) -> Result<BamValidatorsResponse, KobeApiError> {
let query = format!("?epoch={epoch}");
self.get("/bam_validators", &query).await
}
/// Get Coinbase Balance
///
/// Returns coinbase balance
pub async fn get_coinbase_balance(
&self,
epoch: u64,
) -> Result<CoinbaseBalanceResponse, KobeApiError> {
let query = format!("?epoch={epoch}");
self.get("/coinbase_balance", &query).await
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use crate::{client_builder::KobeApiClientBuilder, types::QueryParams};
use super::Config;
#[test]
fn test_config_builder() {
let config = Config::mainnet()
.with_timeout(Duration::from_secs(60))
.with_user_agent("test-agent")
.with_retry(false);
assert_eq!(config.timeout, Duration::from_secs(60));
assert_eq!(config.user_agent, "test-agent");
assert!(!config.retry_enabled);
}
#[test]
fn test_query_params() {
let params = QueryParams::default().limit(10).offset(20).epoch(600);
let query = params.to_query_string();
assert!(query.contains("limit=10"));
assert!(query.contains("offset=20"));
assert!(query.contains("epoch=600"));
}
#[test]
fn test_client_builder() {
let client = KobeApiClientBuilder::new()
.timeout(Duration::from_secs(45))
.retry(true)
.max_retries(5)
.build();
assert_eq!(client.config.timeout, Duration::from_secs(45));
assert!(client.config.retry_enabled);
assert_eq!(client.config.max_retries, 5);
}
}