jito-client 0.1.4

A Rust client for interacting with the Solana Jito network, supporting rate limiting, multi-IP usage, and broadcasting requests to multiple endpoints.
Documentation
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
use anyhow::{Context, anyhow};
use base64::prelude::*;
use load_balancer::{LoadBalancer, interval::IntervalLoadBalancer};
use reqwest::{Client, ClientBuilder, Response};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::{net::IpAddr, sync::Arc, time::Duration};

pub use load_balancer;
pub use load_balancer::get_if_addrs;
pub use load_balancer::ip::{get_ip_list, get_ipv4_list, get_ipv6_list};
pub use reqwest;
pub use reqwest::Proxy;
pub use reqwest::header::HeaderMap;
pub use serde_json;

/// Builder for configuring and creating a `JitoClient`.
pub struct JitoClientBuilder {
    url: Vec<String>,
    broadcast: bool,
    interval: Duration,
    timeout: Option<Duration>,
    proxy: Option<Proxy>,
    headers: Option<HeaderMap>,
    ip: Vec<IpAddr>,
}

impl JitoClientBuilder {
    /// Creates a new `JitoClientBuilder` with default settings.
    pub fn new() -> Self {
        Self {
            url: vec!["https://mainnet.block-engine.jito.wtf".to_string()],
            broadcast: false,
            interval: Duration::ZERO,
            timeout: None,
            proxy: None,
            headers: None,
            ip: Vec::new(),
        }
    }

    /// Sets the target URLs for the client.
    pub fn url<T: IntoIterator<Item = impl AsRef<str>>>(mut self, url: T) -> Self {
        self.url = url.into_iter().map(|v| v.as_ref().to_string()).collect();
        self
    }

    /// Sets the interval duration between requests (0 = unlimited)
    /// For example, 5 requests per second = 200 ms interval.
    pub fn interval(mut self, interval: Duration) -> Self {
        self.interval = interval;
        self
    }

    /// Sets the local IP addresses to bind outgoing requests to.
    pub fn ip(mut self, ip: Vec<IpAddr>) -> Self {
        self.ip = ip;
        self
    }

    /// Broadcast each request to all configured URLs.
    pub fn broadcast(mut self, broadcast: bool) -> Self {
        self.broadcast = broadcast;
        self
    }

    /// Sets a timeout duration for requests.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Sets a proxy for the client.
    pub fn proxy(mut self, proxy: Proxy) -> Self {
        self.proxy = Some(proxy);
        self
    }

    /// Sets headers for the client.
    pub fn headers(mut self, headers: HeaderMap) -> Self {
        self.headers = Some(headers);
        self
    }

    /// Builds the `JitoClient` with the configured options.
    pub fn build(self) -> anyhow::Result<JitoClient> {
        let default_ip = self.ip.is_empty();

        let inner = if self.broadcast {
            let mut entries = Vec::new();

            if default_ip {
                let mut cb = ClientBuilder::new();

                if let Some(v) = self.timeout {
                    cb = cb.timeout(v);
                }

                if let Some(v) = self.proxy {
                    cb = cb.proxy(v);
                }

                if let Some(v) = self.headers {
                    cb = cb.default_headers(v);
                }

                entries.push((self.interval, Arc::new((self.url.clone(), cb.build()?))));
            } else {
                for ip in &self.ip {
                    let mut cb = ClientBuilder::new();

                    if let Some(v) = self.timeout {
                        cb = cb.timeout(v);
                    }

                    if let Some(v) = self.proxy.clone() {
                        cb = cb.proxy(v);
                    }

                    if let Some(v) = self.headers.clone() {
                        cb = cb.default_headers(v);
                    }

                    cb = cb.local_address(*ip);

                    entries.push((self.interval, Arc::new((self.url.clone(), cb.build()?))));
                }
            }

            JitoClientRef {
                broadcast: true,
                lb: IntervalLoadBalancer::new(entries),
            }
        } else {
            let mut entries = Vec::new();

            if default_ip {
                for url in &self.url {
                    let mut cb = ClientBuilder::new();

                    if let Some(v) = self.timeout {
                        cb = cb.timeout(v);
                    }

                    if let Some(v) = self.proxy.clone() {
                        cb = cb.proxy(v);
                    }

                    if let Some(v) = self.headers.clone() {
                        cb = cb.default_headers(v);
                    }

                    entries.push((self.interval, Arc::new((vec![url.clone()], cb.build()?))));
                }
            } else {
                for url in &self.url {
                    for ip in &self.ip {
                        let mut cb = ClientBuilder::new();

                        if let Some(v) = self.timeout {
                            cb = cb.timeout(v);
                        }

                        if let Some(v) = self.proxy.clone() {
                            cb = cb.proxy(v);
                        }

                        if let Some(v) = self.headers.clone() {
                            cb = cb.default_headers(v);
                        }

                        cb = cb.local_address(*ip);

                        entries.push((self.interval, Arc::new((vec![url.clone()], cb.build()?))));
                    }
                }
            }

            JitoClientRef {
                broadcast: false,
                lb: IntervalLoadBalancer::new(entries),
            }
        };

        Ok(JitoClient {
            inner: inner.into(),
        })
    }
}

struct JitoClientRef {
    broadcast: bool,
    lb: IntervalLoadBalancer<Arc<(Vec<String>, Client)>>,
}

/// Jito client for sending transactions and bundles.
#[derive(Clone)]
pub struct JitoClient {
    inner: Arc<JitoClientRef>,
}

impl JitoClient {
    /// Creates a new client with default settings.
    pub fn new() -> Self {
        JitoClientBuilder::new().build().unwrap()
    }

    /// Sends a raw request.
    pub async fn raw_send(&mut self, body: &serde_json::Value) -> anyhow::Result<Response> {
        let (ref url, ref client) = *self.inner.lb.alloc().await;

        if self.inner.broadcast {
            Ok(
                futures::future::select_ok(url.iter().map(|v| client.post(v).json(body).send()))
                    .await?
                    .0,
            )
        } else {
            Ok(client.post(&url[0]).json(body).send().await?)
        }
    }

    /// Sends a raw request, use base_url + api_url.
    pub async fn raw_send_api(
        &mut self,
        api_url: impl AsRef<str>,
        body: &serde_json::Value,
    ) -> anyhow::Result<Response> {
        let (ref url, ref client) = *self.inner.lb.alloc().await;

        if self.inner.broadcast {
            Ok(futures::future::select_ok(url.iter().map(|v| {
                client
                    .post(&format!("{}{}", v, api_url.as_ref()))
                    .json(body)
                    .send()
            }))
            .await?
            .0)
        } else {
            Ok(client
                .post(&format!("{}{}", url[0], api_url.as_ref()))
                .json(body)
                .send()
                .await?)
        }
    }

    /// Sends a single transaction and returns the HTTP response.
    pub async fn send_transaction(&self, tx: impl Serialize) -> anyhow::Result<Response> {
        let data = BASE64_STANDARD.encode(bincode::serialize(&tx)?);
        let body = json!({
            "id": 1,
            "jsonrpc": "2.0",
            "method": "sendTransaction",
            "params": [
                data, { "encoding": "base64" }
            ]
        });

        let (ref url, ref client) = *self.inner.lb.alloc().await;

        if self.inner.broadcast {
            Ok(futures::future::select_ok(url.iter().map(|v| {
                client
                    .post(&format!("{}/api/v1/transactions", v))
                    .query(&["bundleOnly", "true"])
                    .json(&body)
                    .send()
            }))
            .await?
            .0)
        } else {
            Ok(client
                .post(&format!("{}/api/v1/transactions", url[0]))
                .query(&["bundleOnly", "true"])
                .json(&body)
                .send()
                .await?)
        }
    }

    /// Sends a transaction and returns the bundle ID from the response headers.
    pub async fn send_transaction_bid(&self, tx: impl Serialize) -> anyhow::Result<String> {
        Ok(self
            .send_transaction(tx)
            .await?
            .error_for_status()?
            .headers()
            .get("x-bundle-id")
            .ok_or_else(|| anyhow!("missing `x-bundle-id` header"))?
            .to_str()
            .map_err(|v| anyhow!("invalid `x-bundle-id` header: {}", v))?
            .to_string())
    }

    /// Sends a transaction without `bundleOnly` flag.
    pub async fn send_transaction_no_bundle_only(
        &self,
        tx: impl Serialize,
    ) -> anyhow::Result<Response> {
        let data = BASE64_STANDARD.encode(bincode::serialize(&tx)?);
        let body = json!({
            "id": 1,
            "jsonrpc": "2.0",
            "method": "sendTransaction",
            "params": [
                data, { "encoding": "base64" }
            ]
        });

        let (ref url, ref client) = *self.inner.lb.alloc().await;

        if self.inner.broadcast {
            Ok(futures::future::select_ok(url.iter().map(|v| {
                client
                    .post(&format!("{}/api/v1/transactions", v))
                    .json(&body)
                    .send()
            }))
            .await?
            .0)
        } else {
            Ok(client
                .post(&format!("{}/api/v1/transactions", url[0]))
                .json(&body)
                .send()
                .await?)
        }
    }

    /// Sends multiple transactions as a bundle.
    pub async fn send_bundle<T: IntoIterator<Item = impl Serialize>>(
        &self,
        tx: T,
    ) -> anyhow::Result<Response> {
        let data = tx
            .into_iter()
            .map(|tx| {
                Ok(BASE64_STANDARD.encode(
                    bincode::serialize(&tx)
                        .map_err(|v| anyhow::anyhow!("failed to serialize tx: {}", v))?,
                ))
            })
            .collect::<anyhow::Result<Vec<_>>>()?;

        let body = json!({
            "id": 1,
            "jsonrpc": "2.0",
            "method": "sendBundle",
            "params": [ data, { "encoding": "base64" } ]
        });

        let (ref url, ref client) = *self.inner.lb.alloc().await;

        if self.inner.broadcast {
            Ok(futures::future::select_ok(url.iter().map(|v| {
                client
                    .post(&format!("{}/api/v1/bundles", v))
                    .json(&body)
                    .send()
            }))
            .await?
            .0)
        } else {
            Ok(client
                .post(&format!("{}/api/v1/bundles", url[0]))
                .json(&body)
                .send()
                .await?)
        }
    }

    /// Sends a bundle and returns its bundle ID from the JSON response.
    pub async fn send_bundle_bid<T: IntoIterator<Item = impl Serialize>>(
        &self,
        tx: T,
    ) -> anyhow::Result<String> {
        self.send_bundle(tx)
            .await?
            .error_for_status()?
            .json::<serde_json::Value>()
            .await?["result"]
            .as_str()
            .map(|v| v.to_string())
            .ok_or_else(|| anyhow::anyhow!("missing bundle result"))
    }

    /// Sends a single transaction and returns the HTTP response, with lazy serialization.
    pub async fn send_transaction_lazy<T>(
        &self,
        tx: impl Future<Output = anyhow::Result<T>>,
    ) -> anyhow::Result<Response>
    where
        T: Serialize,
    {
        let (ref url, ref client) = *self.inner.lb.alloc().await;

        let data = BASE64_STANDARD.encode(bincode::serialize(&tx.await?)?);

        let body = json!({
            "id": 1,
            "jsonrpc": "2.0",
            "method": "sendTransaction",
            "params": [
                data, { "encoding": "base64" }
            ]
        });

        if self.inner.broadcast {
            Ok(futures::future::select_ok(url.iter().map(|v| {
                client
                    .post(&format!("{}/api/v1/transactions", v))
                    .query(&["bundleOnly", "true"])
                    .json(&body)
                    .send()
            }))
            .await?
            .0)
        } else {
            Ok(client
                .post(&format!("{}/api/v1/transactions", url[0]))
                .query(&["bundleOnly", "true"])
                .json(&body)
                .send()
                .await?)
        }
    }

    /// Sends a transaction and returns the bundle ID from the response headers, with lazy serialization.
    pub async fn send_transaction_bid_lazy<T>(
        &self,
        tx: impl Future<Output = anyhow::Result<T>>,
    ) -> anyhow::Result<String>
    where
        T: Serialize,
    {
        Ok(self
            .send_transaction_lazy(tx)
            .await?
            .error_for_status()?
            .headers()
            .get("x-bundle-id")
            .ok_or_else(|| anyhow!("missing `x-bundle-id` header"))?
            .to_str()
            .map_err(|v| anyhow!("invalid `x-bundle-id` header: {}", v))?
            .to_string())
    }

    /// Sends a transaction without `bundleOnly` flag, with lazy serialization.
    pub async fn send_transaction_no_bundle_only_lazy<T>(
        &self,
        tx: impl Future<Output = anyhow::Result<T>>,
    ) -> anyhow::Result<Response>
    where
        T: Serialize,
    {
        let (ref url, ref client) = *self.inner.lb.alloc().await;

        let data = BASE64_STANDARD.encode(bincode::serialize(&tx.await?)?);

        let body = json!({
            "id": 1,
            "jsonrpc": "2.0",
            "method": "sendTransaction",
            "params": [
                data, { "encoding": "base64" }
            ]
        });

        if self.inner.broadcast {
            Ok(futures::future::select_ok(url.iter().map(|v| {
                client
                    .post(&format!("{}/api/v1/transactions", v))
                    .json(&body)
                    .send()
            }))
            .await?
            .0)
        } else {
            Ok(client
                .post(&format!("{}/api/v1/transactions", url[0]))
                .json(&body)
                .send()
                .await?)
        }
    }

    /// Sends multiple transactions as a bundle, with lazy serialization.
    pub async fn send_bundle_lazy<T, S>(
        &self,
        tx: impl Future<Output = anyhow::Result<T>>,
    ) -> anyhow::Result<Response>
    where
        T: IntoIterator<Item = S>,
        S: Serialize,
    {
        let (ref url, ref client) = *self.inner.lb.alloc().await;

        let data = tx
            .await?
            .into_iter()
            .map(|tx| {
                Ok(BASE64_STANDARD.encode(
                    bincode::serialize(&tx)
                        .map_err(|v| anyhow::anyhow!("failed to serialize tx: {}", v))?,
                ))
            })
            .collect::<anyhow::Result<Vec<_>>>()?;

        let body = json!({
            "id": 1,
            "jsonrpc": "2.0",
            "method": "sendBundle",
            "params": [ data, { "encoding": "base64" } ]
        });

        if self.inner.broadcast {
            Ok(futures::future::select_ok(url.iter().map(|v| {
                client
                    .post(&format!("{}/api/v1/bundles", v))
                    .json(&body)
                    .send()
            }))
            .await?
            .0)
        } else {
            Ok(client
                .post(&format!("{}/api/v1/bundles", url[0]))
                .json(&body)
                .send()
                .await?)
        }
    }

    /// Sends a bundle and returns its bundle ID from the JSON response, with lazy serialization.
    pub async fn send_bundle_bid_lazy<T, S>(
        &self,
        tx: impl Future<Output = anyhow::Result<T>>,
    ) -> anyhow::Result<String>
    where
        T: IntoIterator<Item = S>,
        S: Serialize,
    {
        self.send_bundle_lazy(tx)
            .await?
            .error_for_status()?
            .json::<serde_json::Value>()
            .await?["result"]
            .as_str()
            .map(|v| v.to_string())
            .ok_or_else(|| anyhow::anyhow!("missing bundle result"))
    }

    /// Sends a single transaction and returns the HTTP response, with lazy serialization.
    #[cfg(rustc_version_1_85_0)]
    pub async fn send_transaction_lazy_fn<F, T>(&self, callback: F) -> anyhow::Result<Response>
    where
        F: AsyncFnOnce(&Vec<String>, &Client) -> anyhow::Result<T>,
        T: Serialize,
    {
        let (ref url, ref client) = *self.inner.lb.alloc().await;

        let data = BASE64_STANDARD.encode(bincode::serialize(&callback(url, client).await?)?);

        let body = json!({
            "id": 1,
            "jsonrpc": "2.0",
            "method": "sendTransaction",
            "params": [
                data, { "encoding": "base64" }
            ]
        });

        if self.inner.broadcast {
            Ok(futures::future::select_ok(url.iter().map(|v| {
                client
                    .post(&format!("{}/api/v1/transactions", v))
                    .query(&["bundleOnly", "true"])
                    .json(&body)
                    .send()
            }))
            .await?
            .0)
        } else {
            Ok(client
                .post(&format!("{}/api/v1/transactions", url[0]))
                .query(&["bundleOnly", "true"])
                .json(&body)
                .send()
                .await?)
        }
    }

    /// Sends a transaction and returns the bundle ID from the response headers, with lazy serialization.
    #[cfg(rustc_version_1_85_0)]
    pub async fn send_transaction_bid_lazy_fn<F, T>(&self, callback: F) -> anyhow::Result<String>
    where
        F: AsyncFnOnce(&Vec<String>, &Client) -> anyhow::Result<T>,
        T: Serialize,
    {
        Ok(self
            .send_transaction_lazy_fn(callback)
            .await?
            .error_for_status()?
            .headers()
            .get("x-bundle-id")
            .ok_or_else(|| anyhow!("missing `x-bundle-id` header"))?
            .to_str()
            .map_err(|v| anyhow!("invalid `x-bundle-id` header: {}", v))?
            .to_string())
    }

    /// Sends a transaction without `bundleOnly` flag, with lazy serialization.
    #[cfg(rustc_version_1_85_0)]
    pub async fn send_transaction_no_bundle_only_lazy_fn<F, T>(
        &self,
        callback: F,
    ) -> anyhow::Result<Response>
    where
        F: AsyncFnOnce(&Vec<String>, &Client) -> anyhow::Result<T>,
        T: Serialize,
    {
        let (ref url, ref client) = *self.inner.lb.alloc().await;

        let data = BASE64_STANDARD.encode(bincode::serialize(&callback(url, client).await?)?);

        let body = json!({
            "id": 1,
            "jsonrpc": "2.0",
            "method": "sendTransaction",
            "params": [
                data, { "encoding": "base64" }
            ]
        });

        if self.inner.broadcast {
            Ok(futures::future::select_ok(url.iter().map(|v| {
                client
                    .post(&format!("{}/api/v1/transactions", v))
                    .json(&body)
                    .send()
            }))
            .await?
            .0)
        } else {
            Ok(client
                .post(&format!("{}/api/v1/transactions", url[0]))
                .json(&body)
                .send()
                .await?)
        }
    }

    /// Sends multiple transactions as a bundle, with lazy serialization.
    #[cfg(rustc_version_1_85_0)]
    pub async fn send_bundle_lazy_fn<F, T, S>(&self, callback: F) -> anyhow::Result<Response>
    where
        F: AsyncFnOnce(&Vec<String>, &Client) -> anyhow::Result<T>,
        T: IntoIterator<Item = S>,
        S: Serialize,
    {
        let (ref url, ref client) = *self.inner.lb.alloc().await;

        let data = callback(url, client)
            .await?
            .into_iter()
            .map(|tx| {
                Ok(BASE64_STANDARD.encode(
                    bincode::serialize(&tx)
                        .map_err(|v| anyhow::anyhow!("failed to serialize tx: {}", v))?,
                ))
            })
            .collect::<anyhow::Result<Vec<_>>>()?;

        let body = json!({
            "id": 1,
            "jsonrpc": "2.0",
            "method": "sendBundle",
            "params": [ data, { "encoding": "base64" } ]
        });

        if self.inner.broadcast {
            Ok(futures::future::select_ok(url.iter().map(|v| {
                client
                    .post(&format!("{}/api/v1/bundles", v))
                    .json(&body)
                    .send()
            }))
            .await?
            .0)
        } else {
            Ok(client
                .post(&format!("{}/api/v1/bundles", url[0]))
                .json(&body)
                .send()
                .await?)
        }
    }

    /// Sends a bundle and returns its bundle ID from the JSON response, with lazy serialization.
    #[cfg(rustc_version_1_85_0)]
    pub async fn send_bundle_bid_lazy_fn<F, T, S>(&self, callback: F) -> anyhow::Result<String>
    where
        F: AsyncFnOnce(&Vec<String>, &Client) -> anyhow::Result<T>,
        T: IntoIterator<Item = S>,
        S: Serialize,
    {
        self.send_bundle_lazy_fn(callback)
            .await?
            .error_for_status()?
            .json::<serde_json::Value>()
            .await?["result"]
            .as_str()
            .map(|v| v.to_string())
            .ok_or_else(|| anyhow::anyhow!("missing bundle result"))
    }
}

/// Represents Jito tip data.
#[derive(Debug, Clone, Deserialize)]
pub struct JitoTip {
    pub landed_tips_25th_percentile: f64,
    pub landed_tips_50th_percentile: f64,
    pub landed_tips_75th_percentile: f64,
    pub landed_tips_95th_percentile: f64,
    pub landed_tips_99th_percentile: f64,
    pub ema_landed_tips_50th_percentile: f64,
}

/// Fetches the current Jito tip from the public API.
pub async fn get_jito_tip(client: Client) -> anyhow::Result<JitoTip> {
    Ok(client
        .get("https://bundles.jito.wtf/api/v1/bundles/tip_floor")
        .send()
        .await?
        .json::<Vec<JitoTip>>()
        .await?
        .get(0)
        .context("get_jito_tip: empty response")?
        .clone())
}

/// Represents the result of querying bundle statuses.
#[derive(Debug, Deserialize)]
pub struct BundleResult {
    pub context: serde_json::Value,
    pub value: Option<Vec<BundleStatus>>,
}

#[derive(Debug, Deserialize)]
pub struct BundleStatus {
    pub bundle_id: String,
    pub transactions: Option<Vec<String>>,
    pub slot: Option<u64>,
    pub confirmation_status: Option<String>,
    pub err: Option<serde_json::Value>,
}

/// Fetches statuses of multiple bundles.
pub async fn get_bundle_statuses<T: IntoIterator<Item = impl AsRef<str>>>(
    client: Client,
    bundle: T,
) -> anyhow::Result<BundleResult> {
    #[derive(Debug, Deserialize)]
    struct RpcResponse {
        result: BundleResult,
    }

    let payload = json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "getBundleStatuses",
        "params": [bundle.into_iter().map(|v| v.as_ref().to_string()).collect::<Vec<_>>()],
    });

    Ok(client
        .post("https://mainnet.block-engine.jito.wtf/api/v1/getBundleStatuses")
        .json(&payload)
        .send()
        .await?
        .json::<RpcResponse>()
        .await?
        .result)
}

/// Represents in-flight bundle status.
#[derive(Debug, Deserialize)]
pub struct InflightBundleStatus {
    pub bundle_id: String,
    pub status: String,
    pub landed_slot: Option<u64>,
}

#[derive(Debug, Deserialize)]
pub struct InflightBundleResult {
    pub context: serde_json::Value,
    pub value: Option<Vec<InflightBundleStatus>>,
}

/// Fetches statuses of in-flight bundles.
pub async fn get_inflight_bundle_statuses<T: IntoIterator<Item = impl AsRef<str>>>(
    client: Client,
    bundle: T,
) -> anyhow::Result<InflightBundleResult> {
    #[derive(Debug, Deserialize)]
    struct InflightRpcResponse {
        result: InflightBundleResult,
    }

    let payload = json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "getInflightBundleStatuses",
        "params": [bundle.into_iter().map(|v| v.as_ref().to_string()).collect::<Vec<_>>()],
    });

    Ok(client
        .post("https://mainnet.block-engine.jito.wtf/api/v1/getInflightBundleStatuses")
        .json(&payload)
        .send()
        .await?
        .json::<InflightRpcResponse>()
        .await?
        .result)
}

pub async fn test_ip(ip: IpAddr) -> anyhow::Result<IpAddr> {
    reqwest::ClientBuilder::new()
        .timeout(Duration::from_secs(3))
        .local_address(ip)
        .build()?
        .get("https://crates.io")
        .send()
        .await?;

    Ok(ip)
}

pub async fn test_all_ip() -> Vec<anyhow::Result<IpAddr>> {
    match get_ip_list() {
        Ok(v) => futures::future::join_all(v.into_iter().map(|v| test_ip(v))).await,
        Err(_) => Vec::new(),
    }
}

pub async fn test_all_ipv4() -> Vec<anyhow::Result<IpAddr>> {
    match get_ipv4_list() {
        Ok(v) => futures::future::join_all(v.into_iter().map(|v| test_ip(v))).await,
        Err(_) => Vec::new(),
    }
}

pub async fn test_all_ipv6() -> Vec<anyhow::Result<IpAddr>> {
    match get_ipv6_list() {
        Ok(v) => futures::future::join_all(v.into_iter().map(|v| test_ip(v))).await,
        Err(_) => Vec::new(),
    }
}

pub fn serialize_tx(tx: impl Serialize) -> anyhow::Result<String> {
    Ok(BASE64_STANDARD.encode(bincode::serialize(&tx)?))
}

pub fn serialize_tx_vec<T: IntoIterator<Item = impl Serialize>>(
    tx: T,
) -> anyhow::Result<Vec<String>> {
    tx.into_iter()
        .map(|tx| {
            Ok(BASE64_STANDARD.encode(
                bincode::serialize(&tx)
                    .map_err(|v| anyhow::anyhow!("failed to serialize tx: {}", v))?,
            ))
        })
        .collect::<anyhow::Result<Vec<_>>>()
}