Skip to content

Commit

Permalink
wallet helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
Yakuhito committed Oct 2, 2024
1 parent cb72aa4 commit ff0fb14
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ use js::{Coin, CoinSpend, CoinState, EveProof, Proof, ServerCoin};
use napi::bindgen_prelude::*;
use napi::Result;
use native_tls::TlsConnector;
use std::collections::HashMap;
use std::{net::SocketAddr, sync::Arc};
use tokio::sync::mpsc::UnboundedSender;
use tokio::sync::Mutex;
use wallet::{
PossibleLaunchersResponse as RustPossibleLaunchersResponse,
Expand Down Expand Up @@ -449,6 +451,7 @@ impl Tls {
pub struct Peer {
inner: Arc<RustPeer>,
peak: Arc<Mutex<Option<NewPeakWallet>>>,
coin_listeners: Arc<Mutex<HashMap<RustBytes32, UnboundedSender<()>>>>,
}

#[napi]
Expand Down Expand Up @@ -479,8 +482,10 @@ impl Peer {

let inner = Arc::new(peer);
let peak = Arc::new(Mutex::new(None));
let coin_listeners = Arc::new(Mutex::new(HashMap::new()));

let peak_clone = peak.clone();
let coin_listeners_clone = coin_listeners.clone();
tokio::spawn(async move {
while let Some(message) = receiver.recv().await {
if message.msg_type == ProtocolMessageTypes::NewPeakWallet {
Expand All @@ -492,7 +497,11 @@ impl Peer {
}
});

Ok(Self { inner, peak })
Ok(Self {
inner,
peak,
coin_listeners,
})
}

#[napi]
Expand Down
30 changes: 30 additions & 0 deletions src/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1176,3 +1176,33 @@ pub async fn look_up_possible_launchers(
.collect(),
})
}

pub async fn subscribe_to_coin_states(
peer: &Peer,
coin_id: Bytes32,
previous_height: Option<u32>,
previous_header_hash: Bytes32,
) -> Result<Option<u32>, WalletError> {
let response = peer
.request_coin_state(vec![coin_id], previous_height, previous_header_hash, true)
.await
.map_err(WalletError::Client)?
.map_err(|_| WalletError::RejectCoinState)?;

if let Some(coin_state) = response.coin_states.first() {
return Ok(coin_state.spent_height);
}

Err(WalletError::UnknownCoin)
}

pub async fn unsubscribe_from_coin_states(
peer: &Peer,
coin_id: Bytes32,
) -> Result<(), WalletError> {
peer.remove_coin_subscriptions(Some(vec![coin_id]))
.await
.map_err(WalletError::Client)?;

Ok(())
}

0 comments on commit ff0fb14

Please sign in to comment.