rust-blocktank-client 0.0.16

A Rust client for the Blocktank LSP HTTP API
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
#[cfg(test)]
mod tests {
    use rust_blocktank_client::BlocktankError;
    use rust_blocktank_client::{
        BlocktankClient, BtOrderState2, CreateCjitOptions, CreateOrderOptions,
    };
    use std::env;

    const STAGING_SERVER: &str = "https://api.stag0.blocktank.to/blocktank/api/v2";

    // Helper function to create a client for testing
    fn create_test_client() -> BlocktankClient {
        let base_url =
            env::var("BLOCKTANK_TEST_URL").unwrap_or_else(|_| STAGING_SERVER.to_string());
        BlocktankClient::new(Some(&base_url)).expect("Failed to create BlocktankClient")
    }

    // Helper function to create an order for testing
    async fn create_test_order(
        client: &BlocktankClient,
        balance: u64,
        weeks: u32,
    ) -> rust_blocktank_client::IBtOrder {
        let options = Some(CreateOrderOptions {
            client_balance_sat: 0,
            ..Default::default()
        });

        client
            .create_order(balance, weeks, options)
            .await
            .expect("Failed to create test order")
    }

    #[tokio::test]
    async fn test_get_info() {
        let client = create_test_client();

        let result = client.get_info().await;

        match result {
            Ok(info) => {
                println!("Service Info: {:?}", info);
                assert!(!info.nodes.is_empty(), "Expected at least one node");
                assert!(
                    info.options.min_channel_size_sat > 0,
                    "Minimum channel size should be greater than 0"
                );
                assert!(
                    info.options.min_expiry_weeks > 0,
                    "Minimum expiry weeks should be greater than 0"
                );
                assert!(
                    info.options.max_expiry_weeks >= info.options.min_expiry_weeks,
                    "Max expiry weeks should be greater than or equal to min expiry weeks"
                );
            }
            Err(err) => panic!("API call to get_info failed: {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_estimate_order_fee() {
        let client = create_test_client();

        // Set up test parameters
        let lsp_balance_sat: u64 = 100_000;
        let channel_expiry_weeks: u32 = 4;
        let options = Some(CreateOrderOptions {
            client_balance_sat: 0,
            ..Default::default()
        });

        // Estimate order fee
        let result = client
            .estimate_order_fee(lsp_balance_sat, channel_expiry_weeks, options)
            .await;

        match result {
            Ok(fee_estimate) => {
                println!("Fee estimate: {:?}", fee_estimate);
                assert!(fee_estimate.fee_sat > 0, "Fee should be greater than 0");
                assert!(
                    fee_estimate.min_0_conf_tx_fee.sat_per_vbyte > 0.0,
                    "Minimum fee rate should be greater than 0"
                );
            }
            Err(err) => panic!("API call to estimate_order_fee failed: {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_estimate_order_fee_full() {
        let client = create_test_client();

        // Set up test parameters
        let lsp_balance_sat: u64 = 100_000;
        let channel_expiry_weeks: u32 = 4;
        let options = Some(CreateOrderOptions {
            client_balance_sat: 0,
            ..Default::default()
        });

        // Estimate full order fee
        let result = client
            .estimate_order_fee_full(lsp_balance_sat, channel_expiry_weeks, options)
            .await;

        match result {
            Ok(fee_estimate) => {
                println!("Full fee estimate: {:?}", fee_estimate);
                assert!(
                    fee_estimate.service_fee_sat > 0,
                    "Service fee should be greater than 0"
                );
                assert!(
                    fee_estimate.network_fee_sat > 0,
                    "Network fee should be greater than 0"
                );
                assert_eq!(
                    fee_estimate.fee_sat,
                    fee_estimate.service_fee_sat + fee_estimate.network_fee_sat,
                    "Total fee should equal sum of service fee and network fee"
                );
            }
            Err(err) => panic!("API call to estimate_order_fee_full failed: {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_create_order() {
        let client = create_test_client();

        // Set up test parameters
        let lsp_balance_sat: u64 = 100_000;
        let channel_expiry_weeks: u32 = 4;
        // Store the zero_conf value to check later
        let zero_conf = true;
        let options = Some(CreateOrderOptions {
            client_balance_sat: 0,
            zero_conf,
            ..Default::default()
        });

        // Create the order
        let result = client
            .create_order(lsp_balance_sat, channel_expiry_weeks, options)
            .await;

        match result {
            Ok(order) => {
                println!("Created order: {:?}", order);

                // Basic order properties
                assert!(!order.id.is_empty(), "Order ID should not be empty");
                assert_eq!(
                    order.lsp_balance_sat, lsp_balance_sat,
                    "LSP balance should match requested amount"
                );
                assert_eq!(
                    order.channel_expiry_weeks, channel_expiry_weeks,
                    "Channel expiry weeks should match requested value"
                );
                assert_eq!(
                    order.state2,
                    Some(BtOrderState2::Created),
                    "Initial order state should be Created"
                );

                // Payment details
                if let Some(payment) = &order.payment {
                    if let Some(bolt11) = &payment.bolt11_invoice {
                        assert!(
                            bolt11.request.starts_with("lnbc"),
                            "Should have a valid lightning invoice"
                        );
                    }
                    if let Some(onchain) = &payment.onchain {
                        assert!(
                            !onchain.address.is_empty(),
                            "Should have an onchain address"
                        );
                    }
                }

                // LSP node information
                if let Some(lsp_node) = &order.lsp_node {
                    assert!(
                        !lsp_node.pubkey.is_empty(),
                        "LSP node should have a pubkey"
                    );
                    assert!(
                        !lsp_node.connection_strings.is_empty(),
                        "LSP node should have connection strings"
                    );
                }
                let _is_zero_conf: bool = order.zero_conf;
                // Timestamp parsing and comparing
                assert!(
                    !order.created_at.is_empty(),
                    "Created timestamp should be set"
                );
                assert!(
                    !order.order_expires_at.is_empty(),
                    "Expiry timestamp should be set"
                );
            }
            Err(err) => panic!("API call to create_order failed: {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_error_zero_balance() {
        let client = create_test_client();

        // Set up test parameters with invalid (zero) balance
        let lsp_balance_sat: u64 = 0; // Invalid: should be > 0
        let channel_expiry_weeks: u32 = 4;
        let options = Some(CreateOrderOptions {
            client_balance_sat: 0,
            ..Default::default()
        });

        // Attempt to create the order, expecting an error
        let result = client
            .create_order(lsp_balance_sat, channel_expiry_weeks, options)
            .await;

        match result {
            Ok(_) => panic!("Expected an error for zero balance, but request succeeded"),
            Err(err) => {
                println!("Expected error received: {:?}", err);
                match err {
                    BlocktankError::InvalidParameter { message } => {
                        assert!(
                            message.contains("lsp_balance_sat"),
                            "Error message should mention lsp_balance_sat parameter"
                        );
                    }
                    _ => panic!("Unexpected error type: {:?}", err),
                }
            }
        }
    }

    #[tokio::test]
    async fn test_get_order() {
        let client = create_test_client();

        // Create an order first
        let created_order = create_test_order(&client, 100_000, 4).await;

        // Fetch the individual order by ID
        let result = client.get_order(&created_order.id).await;

        match result {
            Ok(order) => {
                println!("Retrieved order: {:?}", order);

                // Verify the retrieved order matches the created order
                assert_eq!(order.id, created_order.id, "Order IDs should match");
                assert_eq!(
                    order.lsp_balance_sat, created_order.lsp_balance_sat,
                    "LSP balance should match"
                );
                assert_eq!(
                    order.channel_expiry_weeks, created_order.channel_expiry_weeks,
                    "Channel expiry weeks should match"
                );
                assert_eq!(
                    order.state2, created_order.state2,
                    "Order state should match"
                );
            }
            Err(err) => panic!("API call to get_order failed: {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_get_nonexistent_order() {
        let client = create_test_client();

        // Test with a non-existent order ID
        let fake_id = "nonexistent_order_id_12345";
        let result = client.get_order(fake_id).await;

        // This should fail with an appropriate error
        assert!(result.is_err(), "Expected error for non-existent order ID");
        println!("Expected error received: {:?}", result.err());
    }

    #[tokio::test]
    async fn test_get_orders() {
        let client = create_test_client();

        // First create an order so we have a known ID to fetch
        let created_order = create_test_order(&client, 100_000, 4).await;

        // Now test get_orders with the created order's ID
        let order_ids = vec![created_order.id.clone()];
        let result = client.get_orders(&order_ids).await;

        match result {
            Ok(orders) => {
                println!("Retrieved orders: {:?}", orders);

                // Verify we got the expected number of orders
                assert_eq!(orders.len(), 1, "Should have retrieved exactly one order");

                // Verify the retrieved order matches the created order
                let retrieved_order = &orders[0];
                assert_eq!(
                    retrieved_order.id, created_order.id,
                    "Order IDs should match"
                );
                assert_eq!(
                    retrieved_order.lsp_balance_sat, created_order.lsp_balance_sat,
                    "LSP balance should match"
                );
                assert_eq!(
                    retrieved_order.channel_expiry_weeks, created_order.channel_expiry_weeks,
                    "Channel expiry weeks should match"
                );
            }
            Err(err) => panic!("API call to get_orders failed: {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_get_orders_multiple() {
        let client = create_test_client();

        // Create multiple orders with different balances
        let order_configs = vec![
            (100_000u64, 4u32), // 100k sats, 4 weeks
            (150_000u64, 6u32), // 150k sats, 6 weeks
        ];

        let mut created_order_ids = Vec::new();
        let mut created_orders = Vec::new();

        // Create the orders
        for (balance, weeks) in order_configs {
            let order = create_test_order(&client, balance, weeks).await;
            created_order_ids.push(order.id.clone());
            created_orders.push(order);
        }

        // Fetch the created orders
        let result = client.get_orders(&created_order_ids).await;

        match result {
            Ok(orders) => {
                println!("Retrieved orders: {:?}", orders);

                // Verify we got all orders
                assert_eq!(
                    orders.len(),
                    created_orders.len(),
                    "Should have retrieved all created orders"
                );

                // Verify each retrieved order matches its created counterpart
                for (created, retrieved) in created_orders.iter().zip(orders.iter()) {
                    assert_eq!(retrieved.id, created.id, "Order IDs should match");
                    assert_eq!(
                        retrieved.lsp_balance_sat, created.lsp_balance_sat,
                        "LSP balance should match"
                    );
                    assert_eq!(
                        retrieved.channel_expiry_weeks, created.channel_expiry_weeks,
                        "Channel expiry weeks should match"
                    );
                }
            }
            Err(err) => panic!("API call to get_orders failed: {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_get_min_zero_conf_tx_fee() {
        let client = create_test_client();

        // Create an order first
        let created_order = create_test_order(&client, 100_000, 4).await;

        // Get minimum zero conf transaction fee
        let result = client.get_min_zero_conf_tx_fee(&created_order.id).await;

        match result {
            Ok(fee_window) => {
                println!("Min 0-conf tx fee window: {:?}", fee_window);

                // Basic validation
                assert!(
                    fee_window.sat_per_vbyte > 0.0,
                    "Minimum fee rate should be greater than 0"
                );
                assert!(
                    !fee_window.validity_ends_at.is_empty(),
                    "Validity end timestamp should be set"
                );
            }
            Err(err) => {
                // This might fail depending on the order state or service configuration
                println!("Error in get_min_zero_conf_tx_fee: {:?}", err);
            }
        }
    }

    #[tokio::test]
    async fn test_create_cjit_entry() {
        let client = create_test_client();

        // Get service info to obtain a valid node for testing
        let info = client.get_info().await.expect("Failed to get service info");
        let node = info.nodes.first().expect("Expected at least one node");
        let node_id = &node.pubkey;

        // Set up test parameters
        let channel_size_sat: u64 = 100_000;
        let invoice_sat: u64 = 10_000;
        let invoice_description = "Test CJIT entry";
        let channel_expiry_weeks: u32 = 4;
        let options = Some(CreateCjitOptions {
            source: Some("test".to_string()),
            ..Default::default()
        });

        // Create CJIT entry
        let result = client
            .create_cjit_entry(
                channel_size_sat,
                invoice_sat,
                invoice_description,
                node_id,
                channel_expiry_weeks,
                options,
            )
            .await;

        match result {
            Ok(cjit_entry) => {
                println!("Created CJIT entry: {:?}", cjit_entry);

                // Basic validation
                assert!(
                    !cjit_entry.id.is_empty(),
                    "CJIT entry ID should not be empty"
                );
                assert_eq!(
                    cjit_entry.channel_size_sat, channel_size_sat,
                    "Channel size should match requested amount"
                );
                assert_eq!(
                    cjit_entry.node_id,
                    node_id.clone(),
                    "Node ID should match requested value"
                );

                // Check invoice
                assert!(
                    !cjit_entry.invoice.request.is_empty(),
                    "Invoice request should not be empty"
                );
            }
            Err(err) => {
                // This might fail depending on service configuration
                println!(
                    "Error in create_cjit_entry (this may be expected in staging): {:?}",
                    err
                );
            }
        }
    }

    #[tokio::test]
    async fn test_workflow() {
        // This test simulates a complete workflow from creating an order to getting details
        let client = create_test_client();

        // Step 1: Get service info
        let _info = client.get_info().await.expect("Failed to get service info");
        println!("Service info retrieved");

        // Step 2: Estimate fees
        let lsp_balance_sat: u64 = 100_000;
        let channel_expiry_weeks: u32 = 4;

        let fee_estimate = client
            .estimate_order_fee_full(lsp_balance_sat, channel_expiry_weeks, None)
            .await
            .expect("Failed to estimate fees");

        println!(
            "Fee estimate: service={}, network={}, total={}",
            fee_estimate.service_fee_sat, fee_estimate.network_fee_sat, fee_estimate.fee_sat
        );

        // Step 3: Create an order
        let use_zero_conf = true;
        let options = Some(CreateOrderOptions {
            client_balance_sat: 0,
            zero_conf: use_zero_conf,
            ..Default::default()
        });

        let order = client
            .create_order(lsp_balance_sat, channel_expiry_weeks, options)
            .await
            .expect("Failed to create order");

        println!("Order created with ID: {}", order.id);

        // Step 4: Get order details
        let retrieved_order = client
            .get_order(&order.id)
            .await
            .expect("Failed to retrieve order");

        assert_eq!(
            retrieved_order.id, order.id,
            "Retrieved order should match created order"
        );
        println!("Successfully retrieved order details");

        // Note: We can't test open_channel in a unit test as it requires actual node connection
        // But we can check min zero conf fee (which might fail depending on order state)
        let _ = client.get_min_zero_conf_tx_fee(&order.id).await;

        println!("Complete workflow test passed successfully");
    }

    #[tokio::test]
    async fn test_regtest_mine() {
        let client = create_test_client();

        // Test mining with a specific number of blocks (1 block)
        let result = client.regtest_mine(Some(1)).await;
        match result {
            Ok(_) => {
                println!("Successfully mined 1 block");
                // Success is just returning without an error
            }
            Err(err) => {
                let err_string = err.to_string();
                // Skip the test if we're not in regtest mode or have other expected errors
                if err_string.contains("not in regtest mode")
                    || err_string.contains("400 Bad Request")
                {
                    println!("Expected error in staging environment: {}", err);
                } else {
                    panic!(
                        "API call to regtest_mine failed with unexpected error: {:?}",
                        err
                    );
                }
            }
        }
    }
}