lightspark 0.10.2

Lightspark Rust SDK
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
// Copyright ©, 2023-present, Lightspark Group, Inc. - All Rights Reserved

use chrono::{Duration, Utc};
use lightspark::key::RSASigningKey;
use lightspark::objects::bitcoin_network::BitcoinNetwork;

use lightspark::objects::currency_amount::CurrencyAmount;
use lightspark::objects::deposit::Deposit;

use lightspark::objects::lightspark_node::{LightsparkNode, LightsparkNodeEnum};
use lightspark::objects::lightspark_node_with_o_s_k::LightsparkNodeWithOSK;
use lightspark::objects::transaction::Transaction;
use lightspark::objects::withdrawal_mode::WithdrawalMode;
use lightspark::{client::LightsparkClient, request::auth_provider::AccountAuthProvider};
use serde_json::Value;

use std::collections::HashMap;

fn print_fees(fees: Option<CurrencyAmount>) {
    if let Some(fee) = fees {
        println!(
            "        Paid {} {} in fees.",
            fee.preferred_currency_value_approx, fee.preferred_currency_unit
        );
    }
}

#[tokio::main]
async fn main() {
    // Setting up the account.
    let api_id = std::env::var("LIGHTSPARK_API_TOKEN_CLIENT_ID").unwrap();
    let api_token = std::env::var("LIGHTSPARK_API_TOKEN_CLIENT_SECRET").unwrap();

    let node_password = std::env::var("LIGHTSPARK_TEST_NODE_PASSWORD").unwrap();
    let base_url = std::env::var("LIGHTSPARK_EXAMPLE_BASE_URL").unwrap();

    // Create LightsparkClient
    let auth_provider = AccountAuthProvider::new(api_id, api_token);
    let mut client = match LightsparkClient::<RSASigningKey>::new(auth_provider) {
        Ok(value) => value,
        Err(err) => {
            println!("{}", err);
            return;
        }
    };

    client.requester.set_base_url(Some(base_url));

    // Bitcoin Fee estimate
    if let Ok(fee_estimate) = client
        .get_bitcoin_fee_estimates(BitcoinNetwork::Regtest)
        .await
    {
        println!(
            "Fees for a fast transaction {} {}",
            fee_estimate.fee_fast.preferred_currency_value_approx,
            fee_estimate.fee_fast.preferred_currency_unit
        );

        println!(
            "Fees for a cheap transaction {} {}",
            fee_estimate.fee_min.preferred_currency_value_approx,
            fee_estimate.fee_min.preferred_currency_unit
        );
    }
    println!();

    // Get current account
    let account = match client.get_current_account().await {
        Ok(v) => v,
        Err(err) => {
            println!("{}", err);
            return;
        }
    };

    if let Some(name) = account.name.clone() {
        println!("You account name is {}", name);
    }

    // Get current account's API tokens
    let connection = match account.get_api_tokens(&client.requester, None, None).await {
        Ok(v) => v,
        Err(err) => {
            println!("{}", err);
            return;
        }
    };
    println!(
        "You initially have {} active API token(s).",
        connection.count
    );
    println!();

    // Create a new API Token
    if let Ok(new_api_token) = client.create_api_token("Test token", true, true).await {
        println!("Created API token {}.", new_api_token.0.id);

        let connection = match account.get_api_tokens(&client.requester, None, None).await {
            Ok(v) => v,
            Err(err) => {
                println!("{}", err);
                return;
            }
        };
        println!("You now have {} active API token(s).", connection.count);
        println!();

        // Delete the created API token
        match client.delete_api_token(new_api_token.0.id.as_str()).await {
            Ok(()) => println!("Deleted API token {}", new_api_token.0.id),
            Err(err) => {
                println!("{}", err);
                return;
            }
        };
    } else {
        println!("Creating API token error.");
    }

    let conductivity = account
        .get_conductivity(&client.requester, Some(vec![BitcoinNetwork::Regtest]), None)
        .await;
    if let Ok(Some(conductivity)) = conductivity {
        println!(
            "Your account's conductivity on REGTEST is {}/10.",
            conductivity
        );
        println!();
    }

    // Get account balance
    let local_balance = account
        .get_local_balance(&client.requester, Some(vec![BitcoinNetwork::Regtest]), None)
        .await;
    if let Ok(Some(local_balance)) = local_balance {
        println!(
            "Your local balance is {} {}",
            local_balance.preferred_currency_value_approx, local_balance.preferred_currency_unit
        )
    }

    let remote_balance = account
        .get_remote_balance(&client.requester, Some(vec![BitcoinNetwork::Regtest]), None)
        .await;
    if let Ok(Some(remote_balance)) = remote_balance {
        println!(
            "Your remote balance is {} {}",
            remote_balance.preferred_currency_value_approx, remote_balance.preferred_currency_unit
        )
    }

    println!();

    // Get nodes in the account.
    let node_connections = match account
        .get_nodes(
            &client.requester,
            Some(50),
            Some(vec![BitcoinNetwork::Regtest]),
            None,
            None,
        )
        .await
    {
        Ok(v) => v,
        Err(_) => panic!("Unable to fetch the nodes"),
    };
    println!("You have {} node(s).", node_connections.count);

    let mut node_id: Option<String> = None;
    let mut node_name: Option<String> = None;
    println!("{}", node_connections.entities.len());
    for node in node_connections.entities {
        let inner: Box<dyn LightsparkNode> = match node {
            LightsparkNodeEnum::LightsparkNodeWithOSK(t) => Box::new(t),
            LightsparkNodeEnum::LightsparkNodeWithRemoteSigning(t) => Box::new(t),
        };
        println!("node info");
        node_name = Some(inner.get_display_name().clone());
        node_id = Some(inner.get_id().clone());
        println!("{} {}", inner.get_display_name(), inner.get_id());
    }
    println!();

    let node_id = node_id.unwrap();
    let node_name = node_name.unwrap();

    // Fund node in test mode.
    match client.fund_node(node_id.as_str(), 10000).await {
        Ok(amount) => {
            println!(
                "Found {} {} to {}",
                amount.preferred_currency_value_approx, amount.preferred_currency_unit, node_name
            );
        }
        Err(err) => {
            println!("{}", err);
        }
    }

    // Get transactions in the account
    let transactions_connection = match account
        .get_transactions(
            &client.requester,
            Some(30),
            None,
            None,
            None,
            None,
            Some(BitcoinNetwork::Regtest),
            None,
            None,
            None,
        )
        .await
    {
        Ok(v) => v,
        Err(err) => {
            println!("{}", err);
            return;
        }
    };
    println!(
        "There is a total of {} transaction(s) on this account:",
        transactions_connection.count
    );

    let mut deposit_transaction_id: Option<String> = None;
    for transaction in transactions_connection.entities {
        let mut fee: Option<CurrencyAmount> = None;
        let inner: Box<dyn Transaction> = match transaction {
            lightspark::objects::transaction::TransactionEnum::Deposit(t) => {
                fee = t.fees.clone();
                Box::new(t)
            }
            lightspark::objects::transaction::TransactionEnum::Withdrawal(t) => {
                fee = t.fees.clone();
                Box::new(t)
            }
            lightspark::objects::transaction::TransactionEnum::OutgoingPayment(t) => Box::new(t),
            lightspark::objects::transaction::TransactionEnum::IncomingPayment(t) => Box::new(t),
            lightspark::objects::transaction::TransactionEnum::ChannelOpeningTransaction(t) => {
                fee = t.fees.clone();
                Box::new(t)
            }
            lightspark::objects::transaction::TransactionEnum::ChannelClosingTransaction(t) => {
                fee = t.fees.clone();
                Box::new(t)
            }
            lightspark::objects::transaction::TransactionEnum::RoutingTransaction(t) => Box::new(t),
        };
        let type_name = Transaction::type_name(inner.as_ref());
        println!(
            "    - {} at {}: {} {} ({})",
            type_name,
            inner.get_created_at(),
            inner.get_amount().preferred_currency_value_approx,
            inner.get_amount().preferred_currency_unit,
            inner.get_status()
        );

        if type_name == "Deposit" {
            deposit_transaction_id = Some(inner.get_id().clone());
        }

        print_fees(fee);
    }

    println!();

    // Pagination
    let page_size = 10;
    let mut iterations = 0;
    let mut has_next = true;
    let mut after: Option<String> = None;
    while has_next && iterations < 30 {
        iterations += 1;
        let transactions_connection = match account
            .get_transactions(
                &client.requester,
                Some(page_size),
                after.clone(),
                None,
                None,
                None,
                Some(BitcoinNetwork::Regtest),
                None,
                None,
                None,
            )
            .await
        {
            Ok(v) => v,
            Err(err) => {
                println!("{}", err);
                return;
            }
        };

        let num = transactions_connection.entities.len();
        println!(
            "We got {} transactions for the page (iteration #{})",
            num, iterations
        );

        if transactions_connection.page_info.has_next_page.unwrap() {
            has_next = true;
            after = transactions_connection.page_info.end_cursor;
            println!("  And we have another page!")
        } else {
            has_next = false;
            println!("  And we're done!")
        }
    }
    println!();

    // Get transactions in the past 24 hours
    let time = Utc::now() - Duration::try_hours(24).unwrap();
    let transactions_connection = match account
        .get_transactions(
            &client.requester,
            None,
            None,
            None,
            Some(time),
            None,
            Some(BitcoinNetwork::Regtest),
            None,
            None,
            None,
        )
        .await
    {
        Ok(v) => v,
        Err(err) => {
            println!("{}", err);
            return;
        }
    };
    println!(
        "We had {} transactions in the past 24 hours.",
        transactions_connection.count
    );

    // Get a transaction detail.
    if let Some(deposit_transaction_id) = deposit_transaction_id {
        let deposit: Deposit = match client
            .get_entity::<Deposit>(deposit_transaction_id.as_str())
            .await
        {
            Ok(v) => v,
            Err(err) => {
                println!("{}", err);
                return;
            }
        };
        println!("Details of deposit transaction");
        println!("id: {}", deposit.id);
        println!(
            "amount: {} {}",
            deposit.amount.preferred_currency_value_approx, deposit.amount.preferred_currency_unit
        );
        println!("created at: {}", deposit.created_at);
        println!("updated at: {}", deposit.updated_at);
        println!();
    }

    // Create a lightning invoice
    let invoice = match client
        .create_invoice(&node_id, 42000, Some("Pizza"), None)
        .await
    {
        Ok(v) => v,
        Err(err) => {
            println!("{}", err);
            return;
        }
    };
    println!("Invoice created from {}:", node_name);
    println!(
        "Encoded invoice = {}",
        invoice.data.encoded_payment_request.clone()
    );
    println!();

    // Create a test invoice
    let test_invoice = match client
        .create_test_mode_invoice(&node_id, 42000, Some("Test"), None)
        .await
    {
        Ok(v) => v,
        Err(err) => {
            println!("{}", err);
            return;
        }
    };
    println!("Test invoice created from {}:", node_name);
    println!("Encoded invoice = {}", test_invoice.clone());

    // Decode a payment request
    let decoded_request = match client
        .get_decoded_payment_request(invoice.data.encoded_payment_request.as_str())
        .await
    {
        Ok(v) => v,
        Err(err) => {
            println!("{}", err);
            return;
        }
    };
    println!("Decoded payment request:");
    println!(
        "    amount = {} {}",
        decoded_request.amount.preferred_currency_value_approx,
        decoded_request.amount.preferred_currency_unit
    );
    if let Some(memo) = decoded_request.memo {
        println!("    memo = {}", memo);
    }
    println!();

    // Unlock the node
    match client
        .recover_node_signing_key(node_id.as_str(), node_password.as_str())
        .await
    {
        Ok(v) => {
            println!("{}'s signing key has been loaded.", node_name);
            v
        }
        Err(err) => {
            println!("{}", err);
            return;
        }
    };

    // Lightning Fee Estimate
    //
    // match client
    //     .get_lightning_fee_estimate_for_invoice(
    //         node_id.as_str(),
    //         /* Encoded Invoice */,
    //         /* Amount */,
    //     )
    //     .await
    // {
    //     Ok(amount) => {
    //         println!(
    //             "Estimate fee for paying this invoice is {} {}",
    //             amount.preferred_currency_value_approx, amount.preferred_currency_unit
    //         );
    //     }
    //     Err(err) => {
    //         println!("{}", err);
    //     }
    // };

    // Pay Invoice
    //
    // let payment = match client
    //     .pay_invoice(
    //         node_id.as_str(),
    //         /* Encoded Invoice */,
    //         60,
    //         None,
    //         /* Payment Amount */,
    //     )
    //     .await
    // {
    //     Ok(v) => v,
    //     Err(err) => {
    //         println!("{}", err);
    //         return;
    //     }
    // };

    // Key Send
    //
    // match client
    //     .get_lightning_fee_estimate_for_node(
    //        node_id.as_str(),
    //        /* Node Public Key */,
    //        500000)
    //     .await
    // {
    //     Ok(amount) => {
    //         println!(
    //             "Estimate fee for paying this node is {} {}",
    //             amount.preferred_currency_value_approx, amount.preferred_currency_unit
    //         );
    //     }
    //     Err(err) => {
    //         println!("{}", err);
    //     }
    // };

    // Key Send
    //
    // let payment = match client
    //     .send_payment(
    //         node_id.as_str(),
    //         /* Node Public Key */,
    //         60,
    //         2000000,
    //         500,
    //     )
    //     .await
    // {
    //     Ok(v) => v,
    //     Err(err) => {
    //         println!("{}", err);
    //         return;
    //     }
    // };
    // println!(
    //     "Payment directly to node without invoice done with ID = {}",
    //     payment.id
    // );
    // println!();

    let address = match client.create_node_wallet_address(&node_id).await {
        Ok(v) => v,
        Err(err) => {
            println!("{}", err);
            return;
        }
    };
    println!("Got a bitcoin address for {}: {}", node_name, address);
    println!();

    if let Ok(withdrawal_request) = client
        .request_withdrawal(
            node_id.as_str(),
            address.as_str(),
            1000,
            WithdrawalMode::WalletOnly,
        )
        .await
    {
        println!(
            "Money was withdrawn with request ID = {}",
            withdrawal_request.id
        );
        println!();
    }

    // Fetch the channels for the node
    let node = match client
        .get_entity::<LightsparkNodeWithOSK>(node_id.as_str())
        .await
    {
        Ok(v) => v,
        Err(err) => {
            println!("{}", err);
            return;
        }
    };
    if let Ok(channels_connection) = node
        .get_channels(&client.requester, Some(10), None, None, None, None)
        .await
    {
        println!(
            "{} has {} channel(s):",
            node_name, channels_connection.count
        );
        for channel in channels_connection.entities {
            if let Some(node_entity) = channel.remote_node {
                if let Ok(remote_node) = client
                    .get_entity::<LightsparkNodeWithOSK>(node_entity.id.as_str())
                    .await
                {
                    let alias = remote_node.alias.unwrap_or("UNKNOWN".to_owned());
                    if let Some(local_balance) = channel.local_balance {
                        if let Some(remote_balance) = channel.remote_balance {
                            println!(
                                "    - With {}. Local/remote balance = {} {} {}",
                                alias,
                                local_balance.preferred_currency_value_approx,
                                remote_balance.preferred_currency_value_approx,
                                remote_balance.preferred_currency_unit
                            );
                        }
                    }
                }
            }
        }
    }
    println!();

    // Execute a custom graphql operation
    let mut variables: HashMap<&str, Value> = HashMap::new();
    variables.insert("networks", BitcoinNetwork::Regtest.into());

    let result = match client
        .execute_graphql_request(
            "query Test($networks: [BitcoinNetwork!]!) {
            current_account {
                name
                nodes(bitcoin_networks: $networks) {
                    count
                }
            }
        }",
            variables,
        )
        .await
    {
        Ok(v) => v,
        Err(err) => {
            println!("{}", err);
            return;
        }
    };

    let name = result["current_account"]["name"].clone();
    let count = result["current_account"]["nodes"]["count"].clone();
    println!(
        "The account {} has {} nodes on the REGTEST network.",
        name, count
    );
}