stellar-rs 1.0.0

A Rust SDK for the Stellar network.
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
use crate::models::prelude::*;
/// Provides the `FindPaymentPathsRequest`.
///
/// # Usage
/// This module provides the `FindPaymentPathsRequest` struct, specifically designed for
/// constructing requests to find payment paths based on certain criteria. It is tailored for
/// use with the [`HorizonClient::get_find_payment_paths`](crate::horizon_client::HorizonClient::get_find_payment_paths)
/// method.
///
pub mod find_payment_paths_request;

/// Provides the `ListStrictReceivePaymentPathsRequest`.
///
/// # Usage
/// This module provides the `ListStrictReceivePaymentPathsRequest` struct, specifically designed for
/// constructing requests to list strict receive payment paths. It is tailored for
/// use with the [`HorizonClient::get_list_strict_receive_payment_paths`](crate::horizon_client::HorizonClient::get_list_strict_receive_payment_paths)
/// method.
///
pub mod list_strict_receive_payment_paths_request;

/// Provides the `ListStrictSendPaymentPathsRequest`.
///
/// # Usage
/// This module provides the `ListStrictSendPaymentPathsRequest` struct, specifically designed for
/// constructing requests to list strict send payment paths. It is tailored for
/// use with the [`HorizonClient::get_list_strict_send_payment_paths`](crate::horizon_client::HorizonClient::get_list_strict_send_payment_paths)
/// method.
///
pub mod list_strict_send_payment_paths_request;

/// Provides the response structures.
///
/// This module defines structures representing the responses from the payment path API.
/// The structures are designed to deserialize the JSON response into Rust objects, enabling
/// straightforward access to various details of payment paths.
///
/// # Usage
/// These structures are equipped with serialization capabilities to handle the JSON data from the
/// payment path server and with getter methods for easy field access.
///
pub mod response;

/// The base paths for path-related endpoints in the Horizon API.
///
/// # Usage
/// This variable is intended to be used internally by the request-building logic
/// to ensure consistent and accurate path construction for offer-related API calls.
///
pub(crate) static PATHS_PATH: &str = "paths"; // the base API path
pub(crate) static PATHS_STRICT_RECEIVE_PATH: &str = "strict-receive";
pub(crate) static PATHS_STRICT_SEND_PATH: &str = "strict-send";

/// Represents the absence of a destination asset for a payment path request.
#[derive(Default, Clone, Debug)]
pub struct NoDestinationAsset;

/// Represents a source asset for a payment path request.
#[derive(Default, Clone, Debug)]
pub struct DestinationAsset(AssetType);

/// Represents the absence of a destination amount for a payment path request.
#[derive(Default, Clone, Debug)]
pub struct NoDestinationAmount;

/// Represents the destination amount for a payment path request.
#[derive(Default, Clone, Debug)]
pub struct DestinationAmount(String);

/// Represents the absence of a source account for a payment path request.
#[derive(Default, Clone, Debug)]
pub struct NoSourceAccount;

/// Represents the source account for a payment path request.
#[derive(Default, Clone, Debug)]
pub struct SourceAccount(String);

/// Represents structure of an asset used in the vector of optional assets.
#[derive(Default, Clone, Debug)]
pub enum IssuedOrNative {
    #[default]
    Native,
    Issued(AssetData),
}

/// The `prelude` module of the `paths` module.
///
/// # Usage
/// This module serves as a convenience for users of the payment path Rust SDK, allowing for easy and
/// ergonomic import of the most commonly used items across various modules. It re-exports
/// key structs and traits from the sibling modules, simplifying access to these components
/// when using the library.
///
/// By importing the contents of `prelude`, users can conveniently access the primary
/// functionalities of the payment path-related modules without needing to import each item
/// individually.
///
/// # Contents
///
/// The `prelude` includes the following re-exports:
///
/// * From `find_payment_paths_request`: All items (e.g. `FindPaymentPathsRequest`).
/// * From `list_strict_receive_payment_paths_request`: All items (e.g. `ListStrictReceivePaymentPathsRequest`).
/// * From `list_strict_send_payment_paths_request`: All items (e.g. `ListStrictSendPaymentPathsRequest`).
/// * From `response`: All items (e.g. `PaymentPathResponse`, etc.).
///
pub mod prelude {
    pub use super::find_payment_paths_request::*;
    pub use super::list_strict_receive_payment_paths_request::*;
    pub use super::list_strict_send_payment_paths_request::*;
    pub use super::response::*;
    pub use super::{
        DestinationAmount, DestinationAsset, NoDestinationAmount, NoDestinationAsset,
        NoSourceAccount, SourceAccount,
    };
}

#[cfg(test)]
mod tests {
    use super::prelude::*;
    use super::{AssetType, IssuedOrNative};
    use crate::models::prelude::*;
    use crate::{horizon_client::HorizonClient, models::*};

    const SOURCE_ASSET_TYPE: &str = "native";
    const SOURCE_AMOUNT: &str = "100.0000000";
    const DESTINATION_ASSET_TYPE: &str = "native";
    const DESTINATION_AMOUNT: &str = "100.0000000";

    #[tokio::test]
    async fn test_find_payment_paths_request() {
        use crate::paths::PATHS_PATH;

        // Test creating and sending a request with source assets. Only the response status will be checked, as the request will not yield comparable data.
        let request = FindPaymentsPathRequest::new()
            .set_destination_asset(AssetType::Alphanumeric4(AssetData {
                asset_code: "USDC".to_string(),
                asset_issuer: "GBJJ5OCBXNZWHSJJ4YQ6ECK24MBJSZMLEMINHKGGEWUA5RU2EDMPN6MS"
                    .to_string(),
            }))
            .unwrap()
            .set_destination_amount("42".to_string())
            .unwrap()
            .set_source_account(
                "GBAC4BTW6UIJOCCUOZ7QATQPVWX6UQVH3ESQ6NEHBMCXJ3MVP4GMT77H".to_string(),
            )
            .unwrap()
            .set_destination_account(
                "GBAKINTNEGR7PO6Z6XW2S5ITT5VARNW6DZ5K4OYSLFNEA2CSMUM2UEF4".to_string(),
            )
            .unwrap();

        let expected_parameters =
            "?destination_asset_type=credit_alphanum4&destination_asset_code=USDC&destination_asset_issuer=GBJJ5OCBXNZWHSJJ4YQ6ECK24MBJSZMLEMINHKGGEWUA5RU2EDMPN6MS&destination_amount=42&destination_account=GBAKINTNEGR7PO6Z6XW2S5ITT5VARNW6DZ5K4OYSLFNEA2CSMUM2UEF4&source_account=GBAC4BTW6UIJOCCUOZ7QATQPVWX6UQVH3ESQ6NEHBMCXJ3MVP4GMT77H";

        assert_eq!(expected_parameters, request.get_query_parameters());

        let url = "base_url";
        assert_eq!(
            format!("{}/{}{}", url, PATHS_PATH, request.get_query_parameters()),
            request.build_url(url)
        );

        let horizon_client = HorizonClient::new("https://horizon-testnet.stellar.org").unwrap();

        let response = horizon_client.get_find_payment_paths(&request).await;

        assert!(response.clone().is_ok());

        // Test creating and sending a request with source account.
        let request = FindPaymentsPathRequest::new()
            .set_destination_asset(AssetType::Native)
            .unwrap()
            .set_destination_amount("100".to_string())
            .unwrap()
            .set_source_account(
                "GCDE6MVFIOYF7YZCSVA6V7MDCFTNWMIOF5PQU3DWPH27AHNX4ERY6AKS".to_string(),
            )
            .unwrap();

        let expected_parameters: &str =
            "?destination_asset_type=native&destination_amount=100&source_account=GCDE6MVFIOYF7YZCSVA6V7MDCFTNWMIOF5PQU3DWPH27AHNX4ERY6AKS";
        assert_eq!(request.get_query_parameters(), expected_parameters);

        let url = "base_url";
        assert_eq!(
            format!("{}/{}{}", url, PATHS_PATH, request.get_query_parameters()),
            request.build_url(url)
        );

        let response = horizon_client.get_find_payment_paths(&request).await;

        assert!(response.clone().is_ok());
        let binding = response.unwrap();
        let response = &binding.embedded().records()[0];
        assert_eq!(response.source_asset_type(), SOURCE_ASSET_TYPE);
        assert_eq!(response.source_amount(), SOURCE_AMOUNT);
        assert_eq!(response.destination_asset_type(), DESTINATION_ASSET_TYPE);
        assert_eq!(response.destination_amount(), DESTINATION_AMOUNT);

        // Test creating a request with an invalid source account ID.
        let request = FindPaymentsPathRequest::new()
            .set_destination_asset(AssetType::Native)
            .unwrap()
            .set_destination_amount("42".to_string())
            .unwrap()
            .set_source_account("invalid_account_id".to_string());
        assert_eq!(
            request.err().unwrap(),
            "Public key must be 56 characters long"
        );
    }

    #[tokio::test]
    async fn test_list_strict_receive_payment_paths_request() {
        use crate::paths::{PATHS_PATH, PATHS_STRICT_RECEIVE_PATH};

        // Test creating and sending a request with source assets. Only the response status will be checked, as the request will not yield comparable data.
        let request = ListStrictReceivePaymentPathsRequest::new()
            .set_destination_asset(AssetType::Alphanumeric4(AssetData {
                asset_code: "USDC".to_string(),
                asset_issuer: "GBJJ5OCBXNZWHSJJ4YQ6ECK24MBJSZMLEMINHKGGEWUA5RU2EDMPN6MS"
                    .to_string(),
            }))
            .unwrap()
            .set_destination_amount("42".to_string())
            .unwrap()
            .set_source(Source::SourceAssets(vec![
                IssuedOrNative::Native,
                IssuedOrNative::Native,
                IssuedOrNative::Issued(AssetData {
                    asset_code: "USDC".to_string(),
                    asset_issuer: "GBAKINTNEGR7PO6Z6XW2S5ITT5VARNW6DZ5K4OYSLFNEA2CSMUM2UEF4"
                        .to_string(),
                }),
            ]))
            .unwrap();

        let expected_parameters: &str =
            "?destination_asset_type=credit_alphanum4&destination_asset_issuer=GBJJ5OCBXNZWHSJJ4YQ6ECK24MBJSZMLEMINHKGGEWUA5RU2EDMPN6MS&destination_asset_code=USDC&destination_amount=42&source_assets=native%2Cnative%2CUSDC%3AGBAKINTNEGR7PO6Z6XW2S5ITT5VARNW6DZ5K4OYSLFNEA2CSMUM2UEF4";

        assert_eq!(request.get_query_parameters(), expected_parameters);

        let url = "base_url";
        assert_eq!(
            format!(
                "{}/{}/{}{}",
                url,
                PATHS_PATH,
                PATHS_STRICT_RECEIVE_PATH,
                request.get_query_parameters()
            ),
            request.build_url(url)
        );

        let horizon_client = HorizonClient::new("https://horizon-testnet.stellar.org").unwrap();

        let response = horizon_client
            .get_list_strict_receive_payment_paths(&request)
            .await;

        assert!(response.clone().is_ok());

        // Test creating and sending a request with destination account.
        let request = ListStrictReceivePaymentPathsRequest::new()
            .set_destination_asset(AssetType::Native)
            .unwrap()
            .set_destination_amount("100".to_string())
            .unwrap()
            .set_source(Source::SourceAccount(
                "GCDE6MVFIOYF7YZCSVA6V7MDCFTNWMIOF5PQU3DWPH27AHNX4ERY6AKS".to_string(),
            ))
            .unwrap();

        let expected_parameters: &str =
            "?destination_asset_type=native&destination_amount=100&source_account=GCDE6MVFIOYF7YZCSVA6V7MDCFTNWMIOF5PQU3DWPH27AHNX4ERY6AKS";
        assert_eq!(request.get_query_parameters(), expected_parameters);

        let url = "base_url";
        assert_eq!(
            format!(
                "{}/{}/{}{}",
                url,
                PATHS_PATH,
                PATHS_STRICT_RECEIVE_PATH,
                request.get_query_parameters()
            ),
            request.build_url(url)
        );

        let response = horizon_client
            .get_list_strict_receive_payment_paths(&request)
            .await;

        assert!(response.clone().is_ok());
        let binding = response.unwrap();
        let response = &binding.embedded().records()[0];
        assert_eq!(response.source_asset_type(), SOURCE_ASSET_TYPE);
        assert_eq!(response.source_amount(), SOURCE_AMOUNT);
        assert_eq!(response.destination_asset_type(), DESTINATION_ASSET_TYPE);
        assert_eq!(response.destination_amount(), DESTINATION_AMOUNT);

        // Test creating a request with an empty source assets vector.
        let request = ListStrictReceivePaymentPathsRequest::new()
            .set_destination_asset(AssetType::Native)
            .unwrap()
            .set_destination_amount("42".to_string())
            .unwrap()
            .set_source(Source::SourceAssets(Vec::new()));
        assert_eq!(request.err().unwrap(), "SourceAssets cannot be empty");

        // Test creating a request with an invalid asset source account ID.
        let request = ListStrictReceivePaymentPathsRequest::new()
            .set_destination_asset(AssetType::Native)
            .unwrap()
            .set_destination_amount("42".to_string())
            .unwrap()
            .set_source(Source::SourceAccount("invalid_account_id".to_string()));
        assert_eq!(
            request.err().unwrap(),
            "Public key must be 56 characters long"
        );

        // Test creating a request with an invalid source account ID.
        let request = ListStrictReceivePaymentPathsRequest::new()
            .set_destination_asset(AssetType::Native)
            .unwrap()
            .set_destination_amount("42".to_string())
            .unwrap()
            .set_source(Source::SourceAssets(vec![IssuedOrNative::Native]))
            .unwrap()
            .set_destination_account("invalid_account_id");
        assert_eq!(
            request.err().unwrap(),
            "Public key must be 56 characters long"
        );
    }

    #[tokio::test]
    async fn test_list_strict_send_payment_paths_request() {
        use crate::paths::{PATHS_PATH, PATHS_STRICT_SEND_PATH};

        // Test creating and sending a request with destination assets. Only the response status will be checked, as the request will not yield comparable data.
        let request = ListStrictSendPaymentPathsRequest::new()
            .set_source_asset(AssetType::Alphanumeric4(AssetData {
                asset_code: "USDC".to_string(),
                asset_issuer: "GBJJ5OCBXNZWHSJJ4YQ6ECK24MBJSZMLEMINHKGGEWUA5RU2EDMPN6MS"
                    .to_string(),
            }))
            .unwrap()
            .set_source_amount("42".to_string())
            .unwrap()
            .set_destination(Destination::DestinationAssets(vec![
                IssuedOrNative::Native,
                IssuedOrNative::Native,
                IssuedOrNative::Issued(AssetData {
                    asset_code: "USDC".to_string(),
                    asset_issuer: "GBAKINTNEGR7PO6Z6XW2S5ITT5VARNW6DZ5K4OYSLFNEA2CSMUM2UEF4"
                        .to_string(),
                }),
            ]))
            .unwrap();

        let expected_parameters: &str =
            "?source_amount=42&destination_assets=native%2Cnative%2CUSDC%3AGBAKINTNEGR7PO6Z6XW2S5ITT5VARNW6DZ5K4OYSLFNEA2CSMUM2UEF4&source_asset_type=credit_alphanum4&source_asset_issuer=GBJJ5OCBXNZWHSJJ4YQ6ECK24MBJSZMLEMINHKGGEWUA5RU2EDMPN6MS&source_asset_code=USDC";

        assert_eq!(request.get_query_parameters(), expected_parameters);

        let url = "base_url";
        assert_eq!(
            format!(
                "{}/{}/{}{}",
                url,
                PATHS_PATH,
                PATHS_STRICT_SEND_PATH,
                request.get_query_parameters()
            ),
            request.build_url(url)
        );

        let horizon_client = HorizonClient::new("https://horizon-testnet.stellar.org").unwrap();

        let response = horizon_client
            .get_list_strict_send_payment_paths(&request)
            .await;

        assert!(response.clone().is_ok());

        // Test creating and sending a request with destination account.
        let request = ListStrictSendPaymentPathsRequest::new()
            .set_source_asset(AssetType::Native)
            .unwrap()
            .set_source_amount("100".to_string())
            .unwrap()
            .set_destination(Destination::DestinationAccount(
                "GBAKINTNEGR7PO6Z6XW2S5ITT5VARNW6DZ5K4OYSLFNEA2CSMUM2UEF4".to_string(),
            ))
            .unwrap();

        let expected_parameters: &str =
            "?source_amount=100&destination_account=GBAKINTNEGR7PO6Z6XW2S5ITT5VARNW6DZ5K4OYSLFNEA2CSMUM2UEF4&source_asset_type=native";

        assert_eq!(request.get_query_parameters(), expected_parameters);

        let url = "base_url";
        assert_eq!(
            format!(
                "{}/{}/{}{}",
                url,
                PATHS_PATH,
                PATHS_STRICT_SEND_PATH,
                request.get_query_parameters()
            ),
            request.build_url(url)
        );

        let response = horizon_client
            .get_list_strict_send_payment_paths(&request)
            .await;

        assert!(response.clone().is_ok());
        let binding = response.unwrap();
        let response = &binding.embedded().records()[0];
        assert_eq!(response.source_asset_type(), SOURCE_ASSET_TYPE);
        assert_eq!(response.source_amount(), SOURCE_AMOUNT);
        assert_eq!(response.destination_asset_type(), DESTINATION_ASSET_TYPE);
        assert_eq!(response.destination_amount(), DESTINATION_AMOUNT);

        // Test creating a request with an empty destination assets vector.
        let request = ListStrictSendPaymentPathsRequest::new()
            .set_source_asset(AssetType::Native)
            .unwrap()
            .set_source_amount("42".to_string())
            .unwrap()
            .set_destination(Destination::DestinationAssets(Vec::new()));
        assert_eq!(request.err().unwrap(), "DestinationAssets cannot be empty");

        // Test creating a request with an invalid destination asset account ID.
        let request = ListStrictSendPaymentPathsRequest::new()
            .set_source_asset(AssetType::Native)
            .unwrap()
            .set_source_amount("42".to_string())
            .unwrap()
            .set_destination(Destination::DestinationAccount(
                "invalid_account_id".to_string(),
            ));
        assert_eq!(
            request.err().unwrap(),
            "Public key must be 56 characters long"
        );

        // Test creating a request with an invalid destination account ID.
        let request = ListStrictSendPaymentPathsRequest::new()
            .set_source_asset(AssetType::Native)
            .unwrap()
            .set_source_amount("42".to_string())
            .unwrap()
            .set_destination(Destination::DestinationAccount(
                "invalid_account_id".to_string(),
            ));
        assert_eq!(
            request.err().unwrap(),
            "Public key must be 56 characters long"
        );
    }
}