lib.rs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. //! CDK lightning backend for Strike
  2. #![warn(missing_docs)]
  3. #![warn(rustdoc::bare_urls)]
  4. use std::pin::Pin;
  5. use std::sync::Arc;
  6. use anyhow::{anyhow, bail};
  7. use async_trait::async_trait;
  8. use axum::Router;
  9. use cdk::amount::Amount;
  10. use cdk::cdk_lightning::{
  11. self, CreateInvoiceResponse, MintLightning, PayInvoiceResponse, PaymentQuoteResponse, Settings,
  12. };
  13. use cdk::nuts::{
  14. CurrencyUnit, MeltMethodSettings, MeltQuoteBolt11Request, MeltQuoteState, MintMethodSettings,
  15. MintQuoteState,
  16. };
  17. use cdk::util::unix_time;
  18. use cdk::{mint, Bolt11Invoice};
  19. use error::Error;
  20. use futures::stream::StreamExt;
  21. use futures::Stream;
  22. use strike_rs::{
  23. Amount as StrikeAmount, Currency as StrikeCurrencyUnit, InvoiceRequest, InvoiceState,
  24. PayInvoiceQuoteRequest, Strike as StrikeApi,
  25. };
  26. use tokio::sync::Mutex;
  27. use uuid::Uuid;
  28. pub mod error;
  29. /// Strike
  30. #[derive(Clone)]
  31. pub struct Strike {
  32. strike_api: StrikeApi,
  33. mint_settings: MintMethodSettings,
  34. melt_settings: MeltMethodSettings,
  35. unit: CurrencyUnit,
  36. receiver: Arc<Mutex<Option<tokio::sync::mpsc::Receiver<String>>>>,
  37. webhook_url: String,
  38. }
  39. impl Strike {
  40. /// Create new [`Strike`] wallet
  41. pub async fn new(
  42. api_key: String,
  43. mint_settings: MintMethodSettings,
  44. melt_settings: MeltMethodSettings,
  45. unit: CurrencyUnit,
  46. receiver: Arc<Mutex<Option<tokio::sync::mpsc::Receiver<String>>>>,
  47. webhook_url: String,
  48. ) -> Result<Self, Error> {
  49. let strike = StrikeApi::new(&api_key, None)?;
  50. Ok(Self {
  51. strike_api: strike,
  52. mint_settings,
  53. melt_settings,
  54. receiver,
  55. unit,
  56. webhook_url,
  57. })
  58. }
  59. }
  60. #[async_trait]
  61. impl MintLightning for Strike {
  62. type Err = cdk_lightning::Error;
  63. fn get_settings(&self) -> Settings {
  64. Settings {
  65. mpp: false,
  66. unit: self.unit,
  67. mint_settings: self.mint_settings.clone(),
  68. melt_settings: self.melt_settings,
  69. invoice_description: true,
  70. }
  71. }
  72. async fn wait_any_invoice(
  73. &self,
  74. ) -> Result<Pin<Box<dyn Stream<Item = String> + Send>>, Self::Err> {
  75. self.strike_api
  76. .subscribe_to_invoice_webhook(self.webhook_url.clone())
  77. .await?;
  78. let receiver = self
  79. .receiver
  80. .lock()
  81. .await
  82. .take()
  83. .ok_or(anyhow!("No receiver"))?;
  84. let strike_api = self.strike_api.clone();
  85. Ok(futures::stream::unfold(
  86. (receiver, strike_api),
  87. |(mut receiver, strike_api)| async move {
  88. match receiver.recv().await {
  89. Some(msg) => {
  90. let check = strike_api.find_invoice(&msg).await;
  91. match check {
  92. Ok(state) => {
  93. if state.state == InvoiceState::Paid {
  94. Some((msg, (receiver, strike_api)))
  95. } else {
  96. None
  97. }
  98. }
  99. _ => None,
  100. }
  101. }
  102. None => None,
  103. }
  104. },
  105. )
  106. .boxed())
  107. }
  108. async fn get_payment_quote(
  109. &self,
  110. melt_quote_request: &MeltQuoteBolt11Request,
  111. ) -> Result<PaymentQuoteResponse, Self::Err> {
  112. if melt_quote_request.unit != self.unit {
  113. return Err(Self::Err::Anyhow(anyhow!("Unsupported unit")));
  114. }
  115. let source_currency = match melt_quote_request.unit {
  116. CurrencyUnit::Sat => StrikeCurrencyUnit::BTC,
  117. CurrencyUnit::Msat => StrikeCurrencyUnit::BTC,
  118. CurrencyUnit::Usd => StrikeCurrencyUnit::USD,
  119. CurrencyUnit::Eur => StrikeCurrencyUnit::EUR,
  120. _ => return Err(Self::Err::UnsupportedUnit),
  121. };
  122. let payment_quote_request = PayInvoiceQuoteRequest {
  123. ln_invoice: melt_quote_request.request.to_string(),
  124. source_currency,
  125. };
  126. let quote = self.strike_api.payment_quote(payment_quote_request).await?;
  127. let fee = from_strike_amount(quote.lightning_network_fee, &melt_quote_request.unit)?;
  128. Ok(PaymentQuoteResponse {
  129. request_lookup_id: quote.payment_quote_id,
  130. amount: from_strike_amount(quote.amount, &melt_quote_request.unit)?.into(),
  131. fee: fee.into(),
  132. state: MeltQuoteState::Unpaid,
  133. })
  134. }
  135. async fn pay_invoice(
  136. &self,
  137. melt_quote: mint::MeltQuote,
  138. _partial_msats: Option<Amount>,
  139. _max_fee_msats: Option<Amount>,
  140. ) -> Result<PayInvoiceResponse, Self::Err> {
  141. let pay_response = self
  142. .strike_api
  143. .pay_quote(&melt_quote.request_lookup_id)
  144. .await?;
  145. let state = match pay_response.state {
  146. InvoiceState::Paid => MeltQuoteState::Paid,
  147. InvoiceState::Unpaid => MeltQuoteState::Unpaid,
  148. InvoiceState::Completed => MeltQuoteState::Paid,
  149. InvoiceState::Pending => MeltQuoteState::Pending,
  150. };
  151. let total_spent = from_strike_amount(pay_response.total_amount, &melt_quote.unit)?.into();
  152. let bolt11: Bolt11Invoice = melt_quote.request.parse()?;
  153. Ok(PayInvoiceResponse {
  154. payment_hash: bolt11.payment_hash().to_string(),
  155. payment_preimage: None,
  156. status: state,
  157. total_spent,
  158. unit: melt_quote.unit,
  159. })
  160. }
  161. async fn create_invoice(
  162. &self,
  163. amount: Amount,
  164. _unit: &CurrencyUnit,
  165. description: String,
  166. unix_expiry: u64,
  167. ) -> Result<CreateInvoiceResponse, Self::Err> {
  168. let time_now = unix_time();
  169. assert!(unix_expiry > time_now);
  170. let request_lookup_id = Uuid::new_v4();
  171. let invoice_request = InvoiceRequest {
  172. correlation_id: Some(request_lookup_id.to_string()),
  173. amount: to_strike_unit(amount, &self.unit)?,
  174. description: Some(description),
  175. };
  176. let create_invoice_response = self.strike_api.create_invoice(invoice_request).await?;
  177. let quote = self
  178. .strike_api
  179. .invoice_quote(&create_invoice_response.invoice_id)
  180. .await?;
  181. let request: Bolt11Invoice = quote.ln_invoice.parse()?;
  182. let expiry = request.expires_at().map(|t| t.as_secs());
  183. Ok(CreateInvoiceResponse {
  184. request_lookup_id: create_invoice_response.invoice_id,
  185. request: quote.ln_invoice.parse()?,
  186. expiry,
  187. })
  188. }
  189. async fn check_invoice_status(
  190. &self,
  191. request_lookup_id: &str,
  192. ) -> Result<MintQuoteState, Self::Err> {
  193. let invoice = self.strike_api.find_invoice(request_lookup_id).await?;
  194. let state = match invoice.state {
  195. InvoiceState::Paid => MintQuoteState::Paid,
  196. InvoiceState::Unpaid => MintQuoteState::Unpaid,
  197. InvoiceState::Completed => MintQuoteState::Paid,
  198. InvoiceState::Pending => MintQuoteState::Pending,
  199. };
  200. Ok(state)
  201. }
  202. }
  203. impl Strike {
  204. /// Create invoice webhook
  205. pub async fn create_invoice_webhook(
  206. &self,
  207. webhook_endpoint: &str,
  208. sender: tokio::sync::mpsc::Sender<String>,
  209. ) -> anyhow::Result<Router> {
  210. let subs = self.strike_api.get_current_subscriptions().await?;
  211. tracing::debug!("Got {} current subscriptions", subs.len());
  212. for sub in subs {
  213. tracing::info!("Deleting webhook: {}", &sub.id);
  214. if let Err(err) = self.strike_api.delete_subscription(&sub.id).await {
  215. tracing::error!("Error deleting webhook subscription: {} {}", sub.id, err);
  216. }
  217. }
  218. self.strike_api
  219. .create_invoice_webhook_router(webhook_endpoint, sender)
  220. .await
  221. }
  222. }
  223. pub(crate) fn from_strike_amount(
  224. strike_amount: StrikeAmount,
  225. target_unit: &CurrencyUnit,
  226. ) -> anyhow::Result<u64> {
  227. match target_unit {
  228. CurrencyUnit::Sat => strike_amount.to_sats(),
  229. CurrencyUnit::Msat => Ok(strike_amount.to_sats()? * 1000),
  230. CurrencyUnit::Usd => {
  231. if strike_amount.currency == StrikeCurrencyUnit::USD {
  232. Ok((strike_amount.amount * 100.0).round() as u64)
  233. } else {
  234. bail!("Could not convert strike USD");
  235. }
  236. }
  237. CurrencyUnit::Eur => {
  238. if strike_amount.currency == StrikeCurrencyUnit::EUR {
  239. Ok((strike_amount.amount * 100.0).round() as u64)
  240. } else {
  241. bail!("Could not convert to EUR");
  242. }
  243. }
  244. _ => bail!("Unsupported unit"),
  245. }
  246. }
  247. pub(crate) fn to_strike_unit<T>(
  248. amount: T,
  249. current_unit: &CurrencyUnit,
  250. ) -> anyhow::Result<StrikeAmount>
  251. where
  252. T: Into<u64>,
  253. {
  254. let amount = amount.into();
  255. match current_unit {
  256. CurrencyUnit::Sat => Ok(StrikeAmount::from_sats(amount)),
  257. CurrencyUnit::Msat => Ok(StrikeAmount::from_sats(amount / 1000)),
  258. CurrencyUnit::Usd => {
  259. let dollars = (amount as f64 / 100_f64) * 100.0;
  260. Ok(StrikeAmount {
  261. currency: StrikeCurrencyUnit::USD,
  262. amount: dollars.round() / 100.0,
  263. })
  264. }
  265. CurrencyUnit::Eur => {
  266. let euro = (amount as f64 / 100_f64) * 100.0;
  267. Ok(StrikeAmount {
  268. currency: StrikeCurrencyUnit::EUR,
  269. amount: euro.round() / 100.0,
  270. })
  271. }
  272. _ => bail!("Unsupported unit"),
  273. }
  274. }