This repository was archived by the owner on Feb 3, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathlib.rs
More file actions
2389 lines (2147 loc) · 76.7 KB
/
lib.rs
File metadata and controls
2389 lines (2147 loc) · 76.7 KB
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
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// wasm is considered "extra_unused_type_parameters"
#![allow(
incomplete_features,
clippy::extra_unused_type_parameters,
clippy::arc_with_non_send_sync
)]
extern crate mutiny_core;
pub mod error;
mod indexed_db;
mod models;
mod utils;
pub mod waila;
use crate::error::MutinyJsError;
use crate::indexed_db::IndexedDbStorage;
use crate::models::*;
use bip39::Mnemonic;
use bitcoin::bip32::ExtendedPrivKey;
use bitcoin::consensus::deserialize;
use bitcoin::hashes::hex::FromHex;
use bitcoin::hashes::sha256;
use bitcoin::secp256k1::PublicKey;
use bitcoin::{Address, Network, OutPoint, Transaction, Txid};
use fedimint_core::{api::InviteCode, config::FederationId};
use fedimint_mint_client::OOBNotes;
use futures::lock::Mutex;
use gloo_utils::format::JsValueSerdeExt;
use hex_conservative::DisplayHex;
use lightning::{log_error, log_info, log_warn, routing::gossip::NodeId, util::logger::Logger};
use lightning_invoice::Bolt11Invoice;
use lnurl::lightning_address::LightningAddress;
use lnurl::lnurl::LnUrl;
use moksha_core::token::TokenV3;
use mutiny_core::auth::MutinyAuthClient;
use mutiny_core::lnurlauth::AuthManager;
use mutiny_core::nostr::nip49::NIP49URI;
use mutiny_core::nostr::nwc::{BudgetedSpendingConditions, NwcProfileTag, SpendingConditions};
use mutiny_core::nostr::NostrKeySource;
use mutiny_core::storage::{DeviceLock, MutinyStorage, DEVICE_LOCK_KEY};
use mutiny_core::utils::{now, parse_npub, parse_npub_or_nip05, sleep, spawn};
use mutiny_core::vss::MutinyVssClient;
use mutiny_core::{encrypt::encryption_key_from_pass, InvoiceHandler, MutinyWalletConfigBuilder};
use mutiny_core::{labels::Contact, MutinyWalletBuilder};
use mutiny_core::{
labels::LabelStorage,
nodemanager::{create_lsp_config, NodeManager},
};
use mutiny_core::{logging::MutinyLogger, nostr::ProfileType};
use nostr::{Keys, ToBech32};
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::Arc;
use wasm_bindgen::prelude::*;
static INITIALIZED: once_cell::sync::Lazy<Mutex<bool>> =
once_cell::sync::Lazy::new(|| Mutex::new(false));
#[cfg(test)]
async fn uninit() {
let mut init = INITIALIZED.lock().await;
*init = false;
}
#[wasm_bindgen]
pub struct MutinyWallet {
mnemonic: Mnemonic,
inner: mutiny_core::MutinyWallet<IndexedDbStorage>,
}
/// The [MutinyWallet] is the main entry point for interacting with the Mutiny Wallet.
/// It is responsible for managing the on-chain wallet and the lightning nodes.
///
/// It can be used to create a new wallet, or to load an existing wallet.
///
/// It can be configured to use all different custom backend services, or to use the default
/// services provided by Mutiny.
#[wasm_bindgen]
impl MutinyWallet {
/// Creates a new [MutinyWallet] with the given parameters.
/// The mnemonic seed is read from storage, unless one is provided.
/// If no mnemonic is provided, a new one is generated and stored.
#[wasm_bindgen(constructor)]
#[allow(clippy::too_many_arguments)]
pub async fn new(
password: Option<String>,
mnemonic_str: Option<String>,
websocket_proxy_addr: Option<String>,
network_str: Option<String>,
user_esplora_url: Option<String>,
user_rgs_url: Option<String>,
lsp_url: Option<String>,
lsp_connection_string: Option<String>,
lsp_token: Option<String>,
auth_url: Option<String>,
subscription_url: Option<String>,
storage_url: Option<String>,
scorer_url: Option<String>,
do_not_connect_peers: Option<bool>,
skip_device_lock: Option<bool>,
safe_mode: Option<bool>,
skip_hodl_invoices: Option<bool>,
nsec_override: Option<String>,
nip_07_key: Option<String>,
primal_url: Option<String>,
) -> Result<MutinyWallet, MutinyJsError> {
let start = instant::Instant::now();
// if both are set throw an error
// todo default to nsec if both are for same key?
if nsec_override.is_some() && nip_07_key.is_some() {
return Err(MutinyJsError::InvalidArgumentsError);
}
utils::set_panic_hook();
let mut init = INITIALIZED.lock().await;
if *init {
return Err(MutinyJsError::AlreadyRunning);
} else {
*init = true;
}
match Self::new_internal(
password,
mnemonic_str,
websocket_proxy_addr,
network_str,
user_esplora_url,
user_rgs_url,
lsp_url,
lsp_connection_string,
lsp_token,
auth_url,
subscription_url,
storage_url,
scorer_url,
do_not_connect_peers,
skip_device_lock,
safe_mode,
skip_hodl_invoices,
nsec_override,
nip_07_key,
primal_url,
)
.await
{
Ok(m) => {
log_info!(
m.inner.logger,
"Wallet startup took {}ms",
start.elapsed().as_millis()
);
Ok(m)
}
Err(e) => {
// mark uninitialized because we failed to startup
*init = false;
Err(e)
}
}
}
#[allow(clippy::too_many_arguments)]
async fn new_internal(
password: Option<String>,
mnemonic_str: Option<String>,
websocket_proxy_addr: Option<String>,
network_str: Option<String>,
user_esplora_url: Option<String>,
user_rgs_url: Option<String>,
lsp_url: Option<String>,
lsp_connection_string: Option<String>,
lsp_token: Option<String>,
auth_url: Option<String>,
subscription_url: Option<String>,
storage_url: Option<String>,
scorer_url: Option<String>,
do_not_connect_peers: Option<bool>,
skip_device_lock: Option<bool>,
safe_mode: Option<bool>,
skip_hodl_invoices: Option<bool>,
nsec_override: Option<String>,
nip_07_key: Option<String>,
primal_url: Option<String>,
) -> Result<MutinyWallet, MutinyJsError> {
let safe_mode = safe_mode.unwrap_or(false);
let logger = Arc::new(MutinyLogger::default());
let cipher = password
.as_ref()
.filter(|p| !p.is_empty())
.map(|p| encryption_key_from_pass(p))
.transpose()?;
let network: Network = network_str
.map(|s| s.parse().expect("Invalid network"))
.unwrap_or(Network::Bitcoin);
let override_mnemonic = mnemonic_str.map(|s| Mnemonic::from_str(&s)).transpose()?;
let mnemonic =
IndexedDbStorage::get_mnemonic(override_mnemonic, password.as_deref(), cipher.clone())
.await?;
let seed = mnemonic.to_seed("");
let xprivkey = ExtendedPrivKey::new_master(network, &seed).unwrap();
let (auth_client, vss_client) = if safe_mode {
(None, None)
} else if let Some(auth_url) = auth_url.clone() {
let auth_manager = AuthManager::new(xprivkey).unwrap();
let lnurl_client = Arc::new(
lnurl::Builder::default()
.build_async()
.expect("failed to make lnurl client"),
);
let auth_client = Arc::new(MutinyAuthClient::new(
auth_manager,
lnurl_client,
logger.clone(),
auth_url,
));
// immediately start fetching JWT
let auth = auth_client.clone();
let logger_clone = logger.clone();
spawn(async move {
// if this errors, it's okay, we'll call it again when we fetch vss
if let Err(e) = auth.authenticate().await {
log_warn!(
logger_clone,
"Failed to authenticate on startup, will retry on next call: {e}"
);
}
});
let vss = storage_url.map(|url| {
Arc::new(MutinyVssClient::new_authenticated(
auth_client.clone(),
url,
xprivkey.private_key,
logger.clone(),
))
});
(Some(auth_client), vss)
} else {
let vss = storage_url.map(|url| {
Arc::new(MutinyVssClient::new_unauthenticated(
url,
xprivkey.private_key,
logger.clone(),
))
});
(None, vss)
};
let storage = IndexedDbStorage::new(password, cipher, vss_client, logger.clone()).await?;
let mut config_builder = MutinyWalletConfigBuilder::new(xprivkey).with_network(network);
if let Some(w) = websocket_proxy_addr {
config_builder.with_websocket_proxy_addr(w);
}
if let Some(url) = user_esplora_url {
config_builder.with_user_esplora_url(url);
}
if let Some(url) = user_rgs_url {
config_builder.with_user_rgs_url(url);
}
if let Some(url) = lsp_url {
config_builder.with_lsp_url(url);
}
if let Some(url) = lsp_connection_string {
config_builder.with_lsp_connection_string(url);
}
if let Some(url) = lsp_token {
config_builder.with_lsp_token(url);
}
if let Some(a) = auth_client {
config_builder.with_auth_client(a);
}
if let Some(url) = subscription_url {
config_builder.with_subscription_url(url);
}
if let Some(url) = scorer_url {
config_builder.with_scorer_url(url);
}
if let Some(url) = primal_url {
config_builder.with_primal_url(url);
}
if let Some(true) = skip_device_lock {
config_builder.with_skip_device_lock();
}
if let Some(false) = skip_hodl_invoices {
config_builder.do_not_skip_hodl_invoices();
}
if let Some(true) = do_not_connect_peers {
config_builder.do_not_connect_peers();
}
if safe_mode {
config_builder.with_safe_mode();
}
let config = config_builder.build();
let mut mw_builder = MutinyWalletBuilder::new(xprivkey, storage).with_config(config);
mw_builder.with_session_id(logger.session_id.clone());
if let Some(nsec) = nsec_override {
let keys = Keys::parse(nsec).map_err(|_| MutinyJsError::InvalidArgumentsError)?;
mw_builder.with_nostr_key_source(NostrKeySource::Imported(keys));
}
if let Some(key) = nip_07_key {
let npub = parse_npub(&key)?;
mw_builder.with_nostr_key_source(NostrKeySource::Extension(npub));
}
let inner = mw_builder.build().await?;
Ok(MutinyWallet { mnemonic, inner })
}
pub fn is_safe_mode(&self) -> bool {
self.inner.is_safe_mode()
}
/// Returns if there is a saved wallet in storage.
/// This is checked by seeing if a mnemonic seed exists in storage.
#[wasm_bindgen]
pub async fn has_node_manager() -> Result<bool, MutinyJsError> {
Ok(IndexedDbStorage::has_mnemonic().await?)
}
/// Returns the number of remaining seconds until the device lock expires.
#[wasm_bindgen]
pub async fn get_device_lock_remaining_secs(
password: Option<String>,
auth_url: Option<String>,
storage_url: Option<String>,
) -> Result<Option<u64>, MutinyJsError> {
let logger = Arc::new(MutinyLogger::default());
let cipher = password
.as_ref()
.filter(|p| !p.is_empty())
.map(|p| encryption_key_from_pass(p))
.transpose()?;
let mnemonic =
IndexedDbStorage::get_mnemonic(None, password.as_deref(), cipher.clone()).await?;
let seed = mnemonic.to_seed("");
// Network doesn't matter here, only for encoding
let xprivkey = ExtendedPrivKey::new_master(Network::Bitcoin, &seed).unwrap();
let vss_client = if let Some(auth_url) = auth_url {
let auth_manager = AuthManager::new(xprivkey).unwrap();
let lnurl_client = Arc::new(
lnurl::Builder::default()
.build_async()
.expect("failed to make lnurl client"),
);
let auth_client = Arc::new(MutinyAuthClient::new(
auth_manager,
lnurl_client,
logger.clone(),
auth_url,
));
storage_url.map(|url| {
Arc::new(MutinyVssClient::new_authenticated(
auth_client.clone(),
url,
xprivkey.private_key,
logger.clone(),
))
})
} else {
storage_url.map(|url| {
Arc::new(MutinyVssClient::new_unauthenticated(
url,
xprivkey.private_key,
logger.clone(),
))
})
};
if let Some(vss) = vss_client {
let obj = vss.get_object(DEVICE_LOCK_KEY).await?;
let lock = serde_json::from_value::<DeviceLock>(obj.value)?;
return Ok(Some(lock.remaining_secs()));
};
Ok(None)
}
/// Starts up all the nodes again.
/// Not needed after [NodeManager]'s `new()` function.
#[wasm_bindgen]
pub async fn start(&mut self) -> Result<(), MutinyJsError> {
Ok(self.inner.start().await?)
}
/// Stops all of the nodes and background processes.
/// Returns after node has been stopped.
#[wasm_bindgen]
pub async fn stop(&self) -> Result<(), MutinyJsError> {
Ok(self.inner.node_manager.stop().await?)
}
/// Broadcast a transaction to the network.
/// The transaction is broadcast through the configured esplora server.
#[wasm_bindgen]
pub async fn broadcast_transaction(&self, str: String) -> Result<(), MutinyJsError> {
let tx_bytes =
Vec::from_hex(str.as_str()).map_err(|_| MutinyJsError::WalletOperationFailed)?;
let tx: Transaction =
deserialize(&tx_bytes).map_err(|_| MutinyJsError::WalletOperationFailed)?;
Ok(self.inner.node_manager.broadcast_transaction(tx).await?)
}
/// Returns the mnemonic seed phrase for the wallet.
#[wasm_bindgen]
pub fn show_seed(&self) -> String {
self.mnemonic.to_string()
}
/// Returns the user's npub
#[wasm_bindgen]
pub fn get_npub(&self) -> String {
self.inner.nostr.public_key.to_bech32().expect("bech32")
}
/// Returns the network of the wallet.
#[wasm_bindgen]
pub fn get_network(&self) -> String {
self.inner.node_manager.get_network().to_string()
}
/// Gets a new bitcoin address from the wallet.
/// Will generate a new address on every call.
///
/// It is recommended to create a new address for every transaction.
#[wasm_bindgen]
pub fn get_new_address(
&self,
labels: Vec<String>,
) -> Result<MutinyBip21RawMaterials, MutinyJsError> {
let address = self.inner.node_manager.get_new_address(labels.clone())?;
Ok(MutinyBip21RawMaterials {
address: address.to_string(),
invoice: None,
btc_amount: None,
labels,
})
}
/// Gets the current balance of the on-chain wallet.
#[wasm_bindgen]
pub fn get_wallet_balance(&self) -> Result<u64, MutinyJsError> {
Ok(self.inner.node_manager.get_wallet_balance()?)
}
/// Creates a BIP 21 invoice. This creates a new address and a lightning invoice.
/// The lightning invoice may return errors related to the LSP. Check the error and
/// fallback to `get_new_address` and warn the user that Lightning is not available.
///
///
/// Errors that might be returned include:
///
/// - [`MutinyJsError::LspGenericError`]: This is returned for various reasons, including if a
/// request to the LSP server fails for any reason, or if the server returns
/// a status other than 500 that can't be parsed into a `ProposalResponse`.
///
/// - [`MutinyJsError::LspFundingError`]: Returned if the LSP server returns an error with
/// a status of 500, indicating an "Internal Server Error", and a message
/// stating "Cannot fund new channel at this time". This means that the LSP cannot support
/// a new channel at this time.
///
/// - [`MutinyJsError::LspAmountTooHighError`]: Returned if the LSP server returns an error with
/// a status of 500, indicating an "Internal Server Error", and a message stating "Invoice
/// amount is too high". This means that the LSP cannot support the amount that the user
/// requested. The user should request a smaller amount from the LSP.
///
/// - [`MutinyJsError::LspConnectionError`]: Returned if the LSP server returns an error with
/// a status of 500, indicating an "Internal Server Error", and a message that starts with
/// "Failed to connect to peer". This means that the LSP is not connected to our node.
///
/// If the server returns a status of 500 with a different error message,
/// a [`MutinyJsError::LspGenericError`] is returned.
#[wasm_bindgen]
pub async fn create_bip21(
&self,
amount: Option<u64>,
labels: Vec<String>,
) -> Result<MutinyBip21RawMaterials, MutinyJsError> {
Ok(self.inner.create_bip21(amount, labels).await?.into())
}
/// Sends an on-chain transaction to the given address.
/// The amount is in satoshis and the fee rate is in sat/vbyte.
///
/// If a fee rate is not provided, one will be used from the fee estimator.
#[wasm_bindgen]
pub async fn send_to_address(
&self,
destination_address: String,
amount: u64,
labels: Vec<String>,
fee_rate: Option<f32>,
) -> Result<String, MutinyJsError> {
let send_to = Address::from_str(&destination_address)?;
Ok(self
.inner
.node_manager
.send_to_address(send_to, amount, labels, fee_rate)
.await?
.to_string())
}
#[wasm_bindgen]
pub async fn send_payjoin(
&self,
payjoin_uri: String,
amount: u64, /* override the uri amount if desired */
labels: Vec<String>,
fee_rate: Option<f32>,
) -> Result<String, MutinyJsError> {
// I know walia parses `pj=` and `pjos=` but payjoin::Uri parses the whole bip21 uri
let pj_uri = payjoin::Uri::try_from(payjoin_uri.as_str())
.map_err(|_| MutinyJsError::InvalidArgumentsError)?;
Ok(self
.inner
.node_manager
.send_payjoin(pj_uri, amount, labels, fee_rate)
.await?
.to_string())
}
/// Sweeps all the funds from the wallet to the given address.
/// The fee rate is in sat/vbyte.
///
/// If a fee rate is not provided, one will be used from the fee estimator.
#[wasm_bindgen]
pub async fn sweep_wallet(
&self,
destination_address: String,
labels: Vec<String>,
fee_rate: Option<f32>,
) -> Result<String, MutinyJsError> {
let send_to = Address::from_str(&destination_address)?;
Ok(self
.inner
.node_manager
.sweep_wallet(send_to, labels, fee_rate)
.await?
.to_string())
}
/// Estimates the onchain fee for a transaction sending to the given address.
/// The amount is in satoshis and the fee rate is in sat/vbyte.
pub fn estimate_tx_fee(
&self,
destination_address: String,
amount: u64,
fee_rate: Option<f32>,
) -> Result<u64, MutinyJsError> {
let addr = Address::from_str(&destination_address)?.assume_checked();
Ok(self
.inner
.node_manager
.estimate_tx_fee(addr, amount, fee_rate)?)
}
/// Estimates the onchain fee for a transaction sweep our on-chain balance
/// to the given address.
///
/// The fee rate is in sat/vbyte.
pub fn estimate_sweep_tx_fee(
&self,
destination_address: String,
fee_rate: Option<f32>,
) -> Result<u64, MutinyJsError> {
let addr = Address::from_str(&destination_address)?.assume_checked();
Ok(self
.inner
.node_manager
.estimate_sweep_tx_fee(addr, fee_rate)?)
}
/// Estimates the onchain fee for a opening a lightning channel.
/// The amount is in satoshis and the fee rate is in sat/vbyte.
pub fn estimate_channel_open_fee(
&self,
amount: u64,
fee_rate: Option<f32>,
) -> Result<u64, MutinyJsError> {
Ok(self
.inner
.node_manager
.estimate_channel_open_fee(amount, fee_rate)?)
}
/// Estimates the onchain fee for sweeping our on-chain balance to open a lightning channel.
/// The fee rate is in sat/vbyte.
pub fn estimate_sweep_channel_open_fee(
&self,
fee_rate: Option<f32>,
) -> Result<u64, MutinyJsError> {
Ok(self
.inner
.node_manager
.estimate_sweep_channel_open_fee(fee_rate)?)
}
/// Estimates the lightning fee for a transaction. Amount is either from the invoice
/// if one is available or a passed in amount (priority). It will try to predict either
/// sending the payment through a federation or through lightning, depending on balances.
/// The amount and fee is in satoshis.
/// Returns None if it has no good way to calculate fee.
pub async fn estimate_ln_fee(
&self,
invoice_str: Option<String>,
amt_sats: Option<u64>,
) -> Result<Option<u64>, MutinyJsError> {
let invoice = match invoice_str {
Some(i) => Some(Bolt11Invoice::from_str(&i)?),
None => None,
};
Ok(self
.inner
.estimate_ln_fee(invoice.as_ref(), amt_sats)
.await?)
}
/// Bumps the given transaction by replacing the given tx with a transaction at
/// the new given fee rate in sats/vbyte
pub async fn bump_fee(&self, txid: String, fee_rate: f32) -> Result<String, MutinyJsError> {
let txid = Txid::from_str(&txid)?;
let result = self.inner.node_manager.bump_fee(txid, fee_rate).await?;
Ok(result.to_string())
}
/// Checks if the given address has any transactions.
/// If it does, it returns the details of the first transaction.
///
/// This should be used to check if a payment has been made to an address.
#[wasm_bindgen]
pub async fn check_address(
&self,
address: String,
) -> Result<JsValue /* Option<TransactionDetails> */, MutinyJsError> {
let address = Address::from_str(&address)?;
Ok(JsValue::from_serde(
&self.inner.node_manager.check_address(address).await?,
)?)
}
/// Lists all the on-chain transactions in the wallet.
/// These are sorted by confirmation time.
#[wasm_bindgen]
pub fn list_onchain(&self) -> Result<JsValue /* Vec<TransactionDetails> */, MutinyJsError> {
Ok(JsValue::from_serde(
&self.inner.node_manager.list_onchain()?,
)?)
}
/// Gets the details of a specific on-chain transaction.
#[wasm_bindgen]
pub fn get_transaction(
&self,
txid: String,
) -> Result<JsValue /* Option<TransactionDetails> */, MutinyJsError> {
let txid = Txid::from_str(&txid)?;
Ok(JsValue::from_serde(
&self.inner.node_manager.get_transaction(txid)?,
)?)
}
/// Gets the current balance of the wallet.
/// This includes both on-chain and lightning funds.
///
/// This will not include any funds in an unconfirmed lightning channel.
#[wasm_bindgen]
pub async fn get_balance(&self) -> Result<MutinyBalance, MutinyJsError> {
Ok(self.inner.get_balance().await?.into())
}
/// Lists all the UTXOs in the wallet.
#[wasm_bindgen]
pub fn list_utxos(&self) -> Result<JsValue, MutinyJsError> {
Ok(JsValue::from_serde(&self.inner.node_manager.list_utxos()?)?)
}
/// Gets a fee estimate for an low priority transaction.
/// Value is in sat/vbyte.
#[wasm_bindgen]
pub fn estimate_fee_low(&self) -> u32 {
self.inner.node_manager.estimate_fee_low()
}
/// Gets a fee estimate for an average priority transaction.
/// Value is in sat/vbyte.
#[wasm_bindgen]
pub fn estimate_fee_normal(&self) -> u32 {
self.inner.node_manager.estimate_fee_normal()
}
/// Gets a fee estimate for an high priority transaction.
/// Value is in sat/vbyte.
#[wasm_bindgen]
pub fn estimate_fee_high(&self) -> u32 {
self.inner.node_manager.estimate_fee_high()
}
/// Creates a new lightning node and adds it to the manager.
#[wasm_bindgen]
pub async fn new_node(&self) -> Result<NodeIdentity, MutinyJsError> {
Ok(self.inner.node_manager.new_node().await?.into())
}
/// Lists the pubkeys of the lightning node in the manager.
#[wasm_bindgen]
pub async fn list_nodes(&self) -> Result<JsValue /* Vec<String> */, MutinyJsError> {
Ok(JsValue::from_serde(
&self.inner.node_manager.list_nodes().await?,
)?)
}
/// Changes all the node's LSPs to the given config. If any of the nodes have an active channel with the
/// current LSP, it will fail to change the LSP.
///
/// Requires a restart of the node manager to take effect.
pub async fn change_lsp(
&self,
lsp_url: Option<String>,
lsp_connection_string: Option<String>,
lsp_token: Option<String>,
) -> Result<(), MutinyJsError> {
let lsp_config = create_lsp_config(lsp_url, lsp_connection_string, lsp_token)?;
self.inner.node_manager.change_lsp(lsp_config).await?;
Ok(())
}
/// Attempts to connect to a peer from the selected node.
#[wasm_bindgen]
pub async fn connect_to_peer(
&self,
connection_string: String,
label: Option<String>,
) -> Result<(), MutinyJsError> {
Ok(self
.inner
.node_manager
.connect_to_peer(None, &connection_string, label)
.await?)
}
/// Disconnects from a peer from the selected node.
#[wasm_bindgen]
pub async fn disconnect_peer(&self, peer: String) -> Result<(), MutinyJsError> {
let peer = PublicKey::from_str(&peer)?;
Ok(self.inner.node_manager.disconnect_peer(None, peer).await?)
}
/// Deletes a peer from the selected node.
/// This will make it so that the node will not attempt to
/// reconnect to the peer.
#[wasm_bindgen]
pub async fn delete_peer(&self, peer: String) -> Result<(), MutinyJsError> {
let peer = NodeId::from_str(&peer).map_err(|_| MutinyJsError::InvalidArgumentsError)?;
Ok(self.inner.node_manager.delete_peer(None, &peer).await?)
}
/// Sets the label of a peer from the selected node.
#[wasm_bindgen]
pub fn label_peer(&self, node_id: String, label: Option<String>) -> Result<(), MutinyJsError> {
let node_id =
NodeId::from_str(&node_id).map_err(|_| MutinyJsError::InvalidArgumentsError)?;
self.inner.node_manager.label_peer(&node_id, label)?;
Ok(())
}
/// Creates a lightning invoice. The amount should be in satoshis.
/// If no amount is provided, the invoice will be created with no amount.
/// If no description is provided, the invoice will be created with no description.
///
/// If the manager has more than one node it will create a phantom invoice.
/// If there is only one node it will create an invoice just for that node.
#[wasm_bindgen]
pub async fn create_invoice(
&self,
amount: u64,
labels: Vec<String>,
) -> Result<MutinyInvoice, MutinyJsError> {
Ok(self.inner.create_invoice(amount, labels).await?.into())
}
/// Pays a lightning invoice from the selected node.
/// An amount should only be provided if the invoice does not have an amount.
/// The amount should be in satoshis.
#[wasm_bindgen]
pub async fn pay_invoice(
&self,
invoice_str: String,
amt_sats: Option<u64>,
labels: Vec<String>,
) -> Result<MutinyInvoice, MutinyJsError> {
let invoice = Bolt11Invoice::from_str(&invoice_str)?;
Ok(self
.inner
.pay_invoice(&invoice, amt_sats, labels)
.await?
.into())
}
/// Sends a spontaneous payment to a node from the selected node.
/// The amount should be in satoshis.
#[wasm_bindgen]
pub async fn keysend(
&self,
to_node: String,
amt_sats: u64,
message: Option<String>,
labels: Vec<String>,
) -> Result<MutinyInvoice, MutinyJsError> {
let to_node = PublicKey::from_str(&to_node)?;
Ok(self
.inner
.node_manager
.keysend(None, to_node, amt_sats, message, labels)
.await?
.into())
}
/// Decodes a lightning invoice into useful information.
/// Will return an error if the invoice is for a different network.
#[wasm_bindgen]
pub async fn decode_invoice(
&self,
invoice: String,
network: Option<String>,
) -> Result<MutinyInvoice, MutinyJsError> {
let invoice = Bolt11Invoice::from_str(&invoice)?;
let network = network
.map(|n| Network::from_str(&n).map_err(|_| MutinyJsError::InvalidArgumentsError))
.transpose()?;
Ok(self.inner.decode_invoice(invoice, network)?.into())
}
/// Calls upon a LNURL to get the parameters for it.
/// This contains what kind of LNURL it is (pay, withdrawal, auth, etc).
#[wasm_bindgen]
pub async fn decode_lnurl(&self, lnurl: String) -> Result<LnUrlParams, MutinyJsError> {
let lnurl = LnUrl::from_str(&lnurl)?;
Ok(self.inner.decode_lnurl(lnurl).await?.into())
}
/// Calls upon a LNURL and pays it.
/// This will fail if the LNURL is not a LNURL pay.
#[wasm_bindgen]
pub async fn lnurl_pay(
&self,
lnurl: String,
amount_sats: u64,
zap_npub: Option<String>,
labels: Vec<String>,
comment: Option<String>,
) -> Result<MutinyInvoice, MutinyJsError> {
let lnurl = LnUrl::from_str(&lnurl)?;
let zap_npub = match zap_npub.filter(|z| !z.is_empty()) {
Some(z) => Some(parse_npub(&z)?),
None => None,
};
Ok(self
.inner
.lnurl_pay(&lnurl, amount_sats, zap_npub, labels, comment)
.await?
.into())
}
/// Calls upon a LNURL and withdraws from it.
/// This will fail if the LNURL is not a LNURL withdrawal.
#[wasm_bindgen]
pub async fn lnurl_withdraw(
&self,
lnurl: String,
amount_sats: u64,
) -> Result<bool, MutinyJsError> {
let lnurl = LnUrl::from_str(&lnurl)?;
Ok(self.inner.lnurl_withdraw(&lnurl, amount_sats).await?)
}
/// Calls upon a Cash mint and melts the token from it.
#[wasm_bindgen]
pub async fn melt_cashu_token(
&self,
maybe_token: String,
) -> Result<JsValue /* Vec<MutinyInvoice> */, MutinyJsError> {
let token = TokenV3::deserialize(maybe_token)?;
let result = self.inner.melt_cashu_token(token).await?;
let invoices: Vec<MutinyInvoice> = result.into_iter().map(|i| i.into()).collect();
Ok(JsValue::from_serde(&invoices)?)
}
/// Authenticates with a LNURL-auth for the given profile.
#[wasm_bindgen]
pub async fn lnurl_auth(&self, lnurl: String) -> Result<(), MutinyJsError> {
let lnurl = LnUrl::from_str(&lnurl)?;
Ok(self.inner.lnurl_auth(lnurl).await?)
}
/// Gets an invoice from the node manager.
/// This includes sent and received invoices.
#[wasm_bindgen]
pub async fn get_invoice(&self, invoice: String) -> Result<MutinyInvoice, MutinyJsError> {
let invoice = Bolt11Invoice::from_str(&invoice)?;
Ok(self.inner.get_invoice(&invoice).await?.into())
}
/// Gets an invoice from the node manager.
/// This includes sent and received invoices.
#[wasm_bindgen]
pub async fn get_invoice_by_hash(&self, hash: String) -> Result<MutinyInvoice, MutinyJsError> {
let hash: sha256::Hash = sha256::Hash::from_str(&hash)?;
Ok(self.inner.get_invoice_by_hash(&hash).await?.into())
}
/// Gets an invoice from the node manager.
/// This includes sent and received invoices.
#[wasm_bindgen]
pub async fn list_invoices(&self) -> Result<JsValue /* Vec<MutinyInvoice> */, MutinyJsError> {
Ok(JsValue::from_serde(&self.inner.list_invoices()?)?)
}
/// Gets an channel closure from the node manager.
#[wasm_bindgen]
pub async fn get_channel_closure(
&self,
user_channel_id: String,
) -> Result<ChannelClosure, MutinyJsError> {
let user_channel_id: [u8; 16] = FromHex::from_hex(&user_channel_id)?;
Ok(self
.inner
.node_manager
.get_channel_closure(u128::from_be_bytes(user_channel_id))
.await?
.into())
}
/// Gets all channel closures from the node manager.
///
/// The channel closures are sorted by the time they were closed.
#[wasm_bindgen]
pub async fn list_channel_closures(
&self,
) -> Result<JsValue /* Vec<ChannelClosure> */, MutinyJsError> {
let mut channel_closures = self.inner.node_manager.list_channel_closures().await?;
channel_closures.sort();
Ok(JsValue::from_serde(&channel_closures)?)
}
/// Opens a channel from our selected node to the given pubkey.
/// The amount is in satoshis.
///
/// The node must be online and have a connection to the peer.
/// The wallet much have enough funds to open the channel.
#[wasm_bindgen]
pub async fn open_channel(
&self,
to_pubkey: Option<String>,
amount: u64,
fee_rate: Option<f32>,
) -> Result<MutinyChannel, MutinyJsError> {
let to_pubkey = match to_pubkey {
Some(pubkey_str) if !pubkey_str.trim().is_empty() => {
Some(PublicKey::from_str(&pubkey_str)?)
}
_ => None,
};
Ok(self
.inner
.node_manager
.open_channel(None, to_pubkey, amount, fee_rate, None)
.await?
.into())
}
/// Opens a channel from our selected node to the given pubkey.
/// It will spend the all the on-chain utxo in full to fund the channel.
///
/// The node must be online and have a connection to the peer.
pub async fn sweep_all_to_channel(
&self,