kybr 0.2.2

Unofficial Rust client for the KyberSwap API (kybr)
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
//! HTTP client for the `KyberSwap` Aggregator API

use crate::error::{self, Error, Result};
use crate::types::{
    BuildRouteData, BuildRouteRequest, BuildRouteResponse, Chain, RouteData, RouteRequest,
    RouteSummary, RoutesResponse, SwapData, SwapRequest, SwapResponse,
};
use crate::{default_config, Config};
use yldfi_common::api::BaseClient;

/// Client for the `KyberSwap` Aggregator API
#[derive(Debug, Clone)]
pub struct Client {
    base: BaseClient,
    client_id: Option<String>,
}

impl Client {
    /// Create a new client with default configuration
    pub fn new() -> Result<Self> {
        Self::with_config(default_config())
    }

    /// Create a new client with custom configuration
    pub fn with_config(config: Config) -> Result<Self> {
        let base = BaseClient::new(config)?;
        Ok(Self {
            base,
            client_id: None,
        })
    }

    /// Identify the integration with an `X-Client-Id` header
    ///
    /// `KyberSwap` uses the client id for attribution and rate limiting.
    #[must_use]
    pub fn with_client_id(mut self, client_id: impl Into<String>) -> Self {
        self.client_id = Some(client_id.into());
        self
    }

    /// Get the configured `X-Client-Id`, if any
    #[must_use]
    pub fn client_id(&self) -> Option<&str> {
        self.client_id.as_deref()
    }

    /// Request headers: `X-Api-Key` (not `Authorization`) when an API key is
    /// configured, plus `X-Client-Id` when set
    fn build_headers(&self) -> reqwest::header::HeaderMap {
        let mut headers = reqwest::header::HeaderMap::new();
        if let Some(key) = self.config().get_api_key() {
            if let Ok(value) = reqwest::header::HeaderValue::from_str(key) {
                headers.insert("X-Api-Key", value);
            }
        }
        if let Some(ref id) = self.client_id {
            if let Ok(value) = reqwest::header::HeaderValue::from_str(id) {
                headers.insert(
                    reqwest::header::HeaderName::from_static("x-client-id"),
                    value,
                );
            }
        }
        headers
    }

    /// Get the underlying base client
    #[must_use]
    pub fn base(&self) -> &BaseClient {
        &self.base
    }

    /// Get the configuration
    #[must_use]
    pub fn config(&self) -> &Config {
        self.base.config()
    }

    /// Get swap routes (V1 API)
    ///
    /// # Example
    ///
    /// ```no_run
    /// use kybr::{Client, Chain, RouteRequest};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), kybr::Error> {
    ///     let client = Client::new()?;
    ///
    ///     let request = RouteRequest::new(
    ///         "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
    ///         "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
    ///         "1000000000000000000",
    ///     );
    ///
    ///     let routes = client.get_routes(Chain::Ethereum, &request).await?;
    ///     println!("Output: {}", routes.amount_out);
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_routes(&self, chain: Chain, request: &RouteRequest) -> Result<RouteSummary> {
        let data = self.get_route_data(chain, request).await?;
        data.summary()
            .map_err(|e| error::invalid_param(format!("unexpected routeSummary shape: {e}")))
    }

    /// Get full route data including router address
    pub async fn get_route_data(&self, chain: Chain, request: &RouteRequest) -> Result<RouteData> {
        let query_params = request.to_query_params();
        let path = format!("/{}/api/v1/routes", chain.as_str());

        let response: RoutesResponse = self
            .base
            .get_with_headers(&path, &query_params, self.build_headers())
            .await?;

        if response.code != 0 {
            return Err(Error::api(response.code as u16, response.message));
        }

        response.data.ok_or_else(error::no_route_found)
    }

    /// Build a route for execution (get transaction data)
    ///
    /// After getting routes, call this to get the transaction data.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use kybr::{Client, Chain, RouteRequest, BuildRouteRequest};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), kybr::Error> {
    ///     let client = Client::new()?;
    ///
    ///     // First get routes
    ///     let request = RouteRequest::new(
    ///         "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
    ///         "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
    ///         "1000000000000000000",
    ///     );
    ///     let route_data = client.get_route_data(Chain::Ethereum, &request).await?;
    ///
    ///     // Then build the route to get tx data (summary passed through unmodified)
    ///     let build_request = BuildRouteRequest {
    ///         route_summary: route_data.route_summary,
    ///         sender: "0xYourAddress".to_string(),
    ///         recipient: "0xYourAddress".to_string(),
    ///         slippage_tolerance_bps: Some(50), // 0.5%
    ///         deadline: None,
    ///         enable_permit: None,
    ///     };
    ///
    ///     let tx_data = client.build_route(Chain::Ethereum, &build_request).await?;
    ///     println!("Router: {}", tx_data.router_address);
    ///     println!("Data: {}", tx_data.data);
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn build_route(
        &self,
        chain: Chain,
        request: &BuildRouteRequest,
    ) -> Result<BuildRouteData> {
        let path = format!("/{}/api/v1/route/build", chain.as_str());
        let response: BuildRouteResponse = self
            .base
            .post_json_with_headers(&path, request, self.build_headers())
            .await?;

        if response.code != 0 {
            return Err(Error::api(response.code as u16, response.message));
        }

        response.data.ok_or_else(error::no_route_found)
    }

    /// Find the best route and encode its transaction in one call
    /// (`GET /{chain}/api/v1/swap`)
    ///
    /// Combines [`get_route_data`](Self::get_route_data) and
    /// [`build_route`](Self::build_route) into one round trip. `KyberSwap`
    /// restricts it to partners (identify with
    /// [`with_client_id`](Self::with_client_id)) because, unlike the legacy
    /// `/route/encode`, it includes RFQ liquidity.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use kybr::{Client, Chain, SwapRequest};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), kybr::Error> {
    ///     let client = Client::new()?.with_client_id("my-app");
    ///
    ///     let request = SwapRequest::new(
    ///         "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
    ///         "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
    ///         "1000000000000000000",
    ///     )
    ///     .with_sender("0xYourAddress")
    ///     .with_recipient("0xYourAddress")
    ///     .with_slippage_bps(50);
    ///
    ///     let swap = client.get_swap(Chain::Ethereum, &request).await?;
    ///     println!("Send to {}: {}", swap.router_address, swap.data);
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_swap(&self, chain: Chain, request: &SwapRequest) -> Result<SwapData> {
        let path = format!("/{}/api/v1/swap", chain.as_str());
        let response: SwapResponse = self
            .base
            .get_with_headers(&path, &request.to_query_params(), self.build_headers())
            .await?;

        if response.code != 0 {
            return Err(Error::api(
                response.code as u16,
                response.message.unwrap_or_default(),
            ));
        }

        response.data.ok_or_else(error::no_route_found)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_client_creation() {
        let client = Client::new();
        assert!(client.is_ok());
    }

    #[test]
    fn test_chain_parsing() {
        assert_eq!(Chain::try_from_str("ethereum"), Some(Chain::Ethereum));
        assert_eq!(Chain::try_from_str("arbitrum"), Some(Chain::Arbitrum));
        assert_eq!(Chain::try_from_str("unknown"), None);
    }

    #[test]
    fn test_route_request_builder() {
        let request = RouteRequest::new("0xTokenIn", "0xTokenOut", "1000000000000000000")
            .with_recipient("0xRecipient");

        assert_eq!(request.to, Some("0xRecipient".to_string()));
    }

    #[test]
    fn test_route_request_query_params() {
        let request = RouteRequest::new("0xTokenIn", "0xTokenOut", "1000")
            .with_included_sources("uniswap,curve")
            .with_excluded_sources("balancer")
            .with_gas_include(true)
            .with_save_gas(true);
        let params = request.to_query_params();
        let get = |k: &str| {
            params
                .iter()
                .find(|(key, _)| *key == k)
                .map(|(_, v)| v.as_str())
        };
        assert_eq!(get("tokenIn"), Some("0xTokenIn"));
        assert_eq!(get("includedSources"), Some("uniswap,curve"));
        assert_eq!(get("excludedSources"), Some("balancer"));
        assert_eq!(get("gasInclude"), Some("true"));
        assert_eq!(get("saveGas"), Some("true"));
        // Slippage is a build/swap parameter, not a routes parameter
        assert_eq!(get("slippageTolerance"), None);
        assert_eq!(get("includeDexs"), None);
    }

    #[test]
    fn test_route_summary_price_impact_from_usd() {
        let summary: crate::types::RouteSummary = serde_json::from_value(serde_json::json!({
            "tokenIn": "0x1111111111111111111111111111111111111111",
            "tokenOut": "0x2222222222222222222222222222222222222222",
            "amountIn": "1000",
            "amountInUsd": "100",
            "amountOut": "990",
            "amountOutUsd": "99",
            "gas": "100000",
            "gasPrice": "1",
            "gasUsd": "0.1",
            "l1FeeUsd": "0",
            "checksum": "1",
            "timestamp": 1,
            "route": []
        }))
        .unwrap();
        let impact = summary.price_impact_percent().unwrap();
        assert!((impact - 1.0).abs() < 1e-9);
        let json = serde_json::to_value(&summary).unwrap();
        assert!(json.get("priceImpact").is_none());
        assert!(json.get("amountOutMin").is_none());
    }

    #[test]
    fn test_client_id_header() {
        let client = Client::new().unwrap();
        assert!(client.build_headers().get("x-client-id").is_none());

        let client = client.with_client_id("example-app");
        assert_eq!(client.client_id(), Some("example-app"));
        assert_eq!(
            client.build_headers().get("x-client-id").unwrap(),
            "example-app"
        );
    }

    /// A one-shot HTTP server on localhost that answers 200 with `body` and
    /// hands back the request head it received
    fn serve_once(body: String) -> (String, std::sync::mpsc::Receiver<String>) {
        use std::io::{Read, Write};
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            if let Ok((mut stream, _)) = listener.accept() {
                let mut buf = [0u8; 8192];
                let n = stream.read(&mut buf).unwrap_or(0);
                let _ = tx.send(String::from_utf8_lossy(&buf[..n]).into_owned());
                let _ = write!(
                    stream,
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                    body.len(),
                    body
                );
            }
        });
        (format!("http://{addr}"), rx)
    }

    fn swap_body(code: i32) -> String {
        serde_json::json!({
            "code": code,
            "message": if code == 0 { "successfully" } else { "route not found" },
            "data": if code == 0 { serde_json::json!({
                "routeSummary": {
                    "tokenIn": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
                    "amountIn": "1000000000000000000",
                    "amountInUsd": "2691.83",
                    "tokenOut": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
                    "amountOut": "2694223548",
                    "amountOutUsd": "2688.29",
                    "gas": "697210",
                    "gasPrice": "105254963",
                    "gasUsd": "0.19",
                    "l1FeeUsd": "0",
                    "route": [[{"pool": "0xe6ff", "tokenIn": "0xc02a", "tokenOut": "0xa0b8",
                        "swapAmount": "1", "amountOut": "2", "exchange": "uniswapv3",
                        "poolType": "uniswapv3", "poolExtra": null, "extra": null}]],
                    "routeID": "e30c6d4c",
                    "checksum": "4239051851851966504",
                    "timestamp": 1_790_368_014
                },
                "routerAddress": "0x6131B5fae19EA4f9D964eAc0408E4408b66337b5",
                "amountIn": "1000000000000000000",
                "amountOut": "2694223548",
                "gas": "330498",
                "gasUsd": "0.09",
                "data": "0xe21fd0e9",
                "transactionValue": "0"
            }) } else { serde_json::Value::Null },
            "requestId": "req-1"
        })
        .to_string()
    }

    #[tokio::test]
    async fn test_get_swap() {
        let (url, request_head) = serve_once(swap_body(0));
        let client = Client::with_config(Config::new(url))
            .unwrap()
            .with_client_id("example-app");
        let request = SwapRequest::new(
            "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
            "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
            "1000000000000000000",
        )
        .with_sender("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045")
        .with_recipient("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045")
        .with_slippage_bps(50);
        let swap = client.get_swap(Chain::Base, &request).await.unwrap();
        assert_eq!(
            swap.router_address,
            "0x6131B5fae19EA4f9D964eAc0408E4408b66337b5"
        );
        assert_eq!(swap.data, "0xe21fd0e9");
        assert_eq!(swap.transaction_value.as_deref(), Some("0"));
        assert_eq!(swap.route_summary.amount_out, "2694223548");

        let head = request_head.recv().unwrap().to_lowercase();
        let request_line = head.lines().next().unwrap();
        assert!(
            request_line.starts_with("get /base/api/v1/swap?tokenin=0xc02a"),
            "{request_line}"
        );
        assert!(
            request_line.contains("&slippagetolerance=50"),
            "{request_line}"
        );
        assert!(head.contains("x-client-id: example-app"), "{head}");
    }

    #[tokio::test]
    async fn test_get_swap_error_code() {
        let (url, _) = serve_once(swap_body(4008));
        let client = Client::with_config(Config::new(url)).unwrap();
        let request = SwapRequest::new("0xa", "0xb", "1");
        let err = client
            .get_swap(Chain::Ethereum, &request)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("route not found"), "{err}");
    }

    #[test]
    fn test_swap_request_query_params() {
        let request = SwapRequest::new("0xa", "0xb", "1")
            .with_fee("currency_in", "10", true, "0xf")
            .with_exclude_rfq_sources(true)
            .with_deadline(1_800_000_000);
        let params = request.to_query_params();
        let get = |k: &str| {
            params
                .iter()
                .find(|(key, _)| *key == k)
                .map(|(_, v)| v.as_str())
        };
        assert_eq!(get("amountIn"), Some("1"));
        assert_eq!(get("chargeFeeBy"), Some("currency_in"));
        assert_eq!(get("feeAmount"), Some("10"));
        assert_eq!(get("isInBps"), Some("true"));
        assert_eq!(get("feeReceiver"), Some("0xf"));
        assert_eq!(get("excludeRFQSources"), Some("true"));
        assert_eq!(get("deadline"), Some("1800000000"));
        assert_eq!(get("sender"), None);
        assert_eq!(get("slippageTolerance"), None);
    }

    #[test]
    fn test_default_config() {
        let config = crate::default_config();
        assert_eq!(config.base_url, crate::DEFAULT_BASE_URL);

        let client = Client::with_config(crate::gateway_config("k")).unwrap();
        assert_eq!(client.config().base_url, crate::GATEWAY_BASE_URL);
        assert_eq!(client.build_headers().get("X-Api-Key").unwrap(), "k");
        assert!(client.build_headers().get("authorization").is_none());
    }
}