npubcash.rs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. //! FFI bindings for the NpubCash client SDK
  2. //!
  3. //! This module provides FFI-compatible bindings for interacting with the NpubCash API.
  4. //! The client can be used standalone without requiring a wallet.
  5. use std::sync::Arc;
  6. use cdk_npubcash::{JwtAuthProvider, NpubCashClient as CdkNpubCashClient};
  7. use crate::error::FfiError;
  8. use crate::types::MintQuote;
  9. /// FFI-compatible NpubCash client
  10. ///
  11. /// This client provides access to the NpubCash API for fetching quotes
  12. /// and managing user settings.
  13. #[derive(uniffi::Object)]
  14. pub struct NpubCashClient {
  15. inner: Arc<CdkNpubCashClient>,
  16. }
  17. #[uniffi::export(async_runtime = "tokio")]
  18. impl NpubCashClient {
  19. /// Create a new NpubCash client
  20. ///
  21. /// # Arguments
  22. ///
  23. /// * `base_url` - Base URL of the NpubCash service (e.g., "https://npub.cash")
  24. /// * `nostr_secret_key` - Nostr secret key for authentication. Accepts either:
  25. /// - Hex-encoded secret key (64 characters)
  26. /// - Bech32 `nsec` format (e.g., "nsec1...")
  27. ///
  28. /// # Errors
  29. ///
  30. /// Returns an error if the secret key is invalid or cannot be parsed
  31. #[uniffi::constructor]
  32. pub fn new(base_url: String, nostr_secret_key: String) -> Result<Self, FfiError> {
  33. let keys = parse_nostr_secret_key(&nostr_secret_key)?;
  34. let auth_provider = Arc::new(JwtAuthProvider::new(base_url.clone(), keys));
  35. let client = CdkNpubCashClient::new(base_url, auth_provider);
  36. Ok(Self {
  37. inner: Arc::new(client),
  38. })
  39. }
  40. /// Fetch quotes from NpubCash
  41. ///
  42. /// # Arguments
  43. ///
  44. /// * `since` - Optional Unix timestamp to fetch quotes from. If `None`, fetches all quotes.
  45. ///
  46. /// # Returns
  47. ///
  48. /// A list of quotes from the NpubCash service. The client automatically handles
  49. /// pagination to fetch all available quotes.
  50. ///
  51. /// # Errors
  52. ///
  53. /// Returns an error if the API request fails or authentication fails
  54. pub async fn get_quotes(&self, since: Option<u64>) -> Result<Vec<NpubCashQuote>, FfiError> {
  55. let quotes = self
  56. .inner
  57. .get_quotes(since)
  58. .await
  59. .map_err(|e| FfiError::internal(e.to_string()))?;
  60. Ok(quotes.into_iter().map(Into::into).collect())
  61. }
  62. /// Set the mint URL for the user on the NpubCash server
  63. ///
  64. /// Updates the default mint URL used by the NpubCash server when creating quotes.
  65. ///
  66. /// # Arguments
  67. ///
  68. /// * `mint_url` - URL of the Cashu mint to use (e.g., "https://mint.example.com")
  69. ///
  70. /// # Errors
  71. ///
  72. /// Returns an error if the API request fails or authentication fails
  73. pub async fn set_mint_url(&self, mint_url: String) -> Result<NpubCashUserResponse, FfiError> {
  74. let response = self
  75. .inner
  76. .set_mint_url(mint_url)
  77. .await
  78. .map_err(|e| FfiError::internal(e.to_string()))?;
  79. Ok(response.into())
  80. }
  81. }
  82. /// A quote from the NpubCash service
  83. #[derive(Debug, Clone, uniffi::Record)]
  84. pub struct NpubCashQuote {
  85. /// Unique identifier for the quote
  86. pub id: String,
  87. /// Amount in the specified unit
  88. pub amount: u64,
  89. /// Currency or unit for the amount (e.g., "sat")
  90. pub unit: String,
  91. /// Unix timestamp when the quote was created
  92. pub created_at: u64,
  93. /// Unix timestamp when the quote was paid (if paid)
  94. pub paid_at: Option<u64>,
  95. /// Unix timestamp when the quote expires
  96. pub expires_at: Option<u64>,
  97. /// Mint URL associated with the quote
  98. pub mint_url: Option<String>,
  99. /// Lightning invoice request
  100. pub request: Option<String>,
  101. /// Quote state (e.g., "PAID", "PENDING")
  102. pub state: Option<String>,
  103. /// Whether the quote is locked
  104. pub locked: Option<bool>,
  105. }
  106. impl From<cdk_npubcash::Quote> for NpubCashQuote {
  107. fn from(quote: cdk_npubcash::Quote) -> Self {
  108. Self {
  109. id: quote.id,
  110. amount: quote.amount,
  111. unit: quote.unit,
  112. created_at: quote.created_at,
  113. paid_at: quote.paid_at,
  114. expires_at: quote.expires_at,
  115. mint_url: quote.mint_url,
  116. request: quote.request,
  117. state: quote.state,
  118. locked: quote.locked,
  119. }
  120. }
  121. }
  122. /// Convert a NpubCash quote to a wallet MintQuote
  123. ///
  124. /// This allows the quote to be used with the wallet's minting functions.
  125. /// Note that the resulting MintQuote will not have a secret key set,
  126. /// which may be required for locked quotes.
  127. ///
  128. /// # Arguments
  129. ///
  130. /// * `quote` - The NpubCash quote to convert
  131. ///
  132. /// # Returns
  133. ///
  134. /// A MintQuote that can be used with wallet minting functions
  135. #[uniffi::export]
  136. pub fn npubcash_quote_to_mint_quote(quote: NpubCashQuote) -> MintQuote {
  137. let cdk_quote = cdk_npubcash::Quote {
  138. id: quote.id,
  139. amount: quote.amount,
  140. unit: quote.unit,
  141. created_at: quote.created_at,
  142. paid_at: quote.paid_at,
  143. expires_at: quote.expires_at,
  144. mint_url: quote.mint_url,
  145. request: quote.request,
  146. state: quote.state,
  147. locked: quote.locked,
  148. };
  149. let mint_quote: cdk::wallet::MintQuote = cdk_quote.into();
  150. mint_quote.into()
  151. }
  152. /// Response from updating user settings on NpubCash
  153. #[derive(Debug, Clone, uniffi::Record)]
  154. pub struct NpubCashUserResponse {
  155. /// Whether the request resulted in an error
  156. pub error: bool,
  157. /// User's public key
  158. pub pubkey: String,
  159. /// Configured mint URL
  160. pub mint_url: Option<String>,
  161. /// Whether quotes are locked
  162. pub lock_quote: bool,
  163. }
  164. impl From<cdk_npubcash::UserResponse> for NpubCashUserResponse {
  165. fn from(response: cdk_npubcash::UserResponse) -> Self {
  166. Self {
  167. error: response.error,
  168. pubkey: response.data.user.pubkey,
  169. mint_url: response.data.user.mint_url,
  170. lock_quote: response.data.user.lock_quote,
  171. }
  172. }
  173. }
  174. /// Derive Nostr keys from a wallet seed
  175. ///
  176. /// This function derives the same Nostr keys that a wallet would use for NpubCash
  177. /// authentication. It takes the first 32 bytes of the seed as the secret key.
  178. ///
  179. /// # Arguments
  180. ///
  181. /// * `seed` - The wallet seed bytes (must be at least 32 bytes)
  182. ///
  183. /// # Returns
  184. ///
  185. /// The hex-encoded Nostr secret key that can be used with `NpubCashClient::new()`
  186. ///
  187. /// # Errors
  188. ///
  189. /// Returns an error if the seed is too short or key derivation fails
  190. #[uniffi::export]
  191. pub fn npubcash_derive_secret_key_from_seed(seed: Vec<u8>) -> Result<String, FfiError> {
  192. if seed.len() < 32 {
  193. return Err(FfiError::internal(
  194. "Seed must be at least 32 bytes".to_string(),
  195. ));
  196. }
  197. // Use the first 32 bytes of the seed as the secret key
  198. let secret_key = nostr_sdk::SecretKey::from_slice(&seed[..32])
  199. .map_err(|e| FfiError::internal(format!("Failed to derive secret key: {}", e)))?;
  200. Ok(secret_key.to_secret_hex())
  201. }
  202. /// Get the public key for a given Nostr secret key
  203. ///
  204. /// # Arguments
  205. ///
  206. /// * `nostr_secret_key` - Nostr secret key. Accepts either:
  207. /// - Hex-encoded secret key (64 characters)
  208. /// - Bech32 `nsec` format (e.g., "nsec1...")
  209. ///
  210. /// # Returns
  211. ///
  212. /// The hex-encoded public key
  213. ///
  214. /// # Errors
  215. ///
  216. /// Returns an error if the secret key is invalid
  217. #[uniffi::export]
  218. pub fn npubcash_get_pubkey(nostr_secret_key: String) -> Result<String, FfiError> {
  219. let keys = parse_nostr_secret_key(&nostr_secret_key)?;
  220. Ok(keys.public_key().to_hex())
  221. }
  222. /// Parse a Nostr secret key from either hex or nsec format
  223. fn parse_nostr_secret_key(key: &str) -> Result<nostr_sdk::Keys, FfiError> {
  224. // Try parsing as nsec (bech32) first
  225. if key.starts_with("nsec") {
  226. nostr_sdk::Keys::parse(key)
  227. .map_err(|e| FfiError::internal(format!("Invalid nsec key: {}", e)))
  228. } else {
  229. // Try parsing as hex
  230. let secret_key = nostr_sdk::SecretKey::parse(key)
  231. .map_err(|e| FfiError::internal(format!("Invalid hex secret key: {}", e)))?;
  232. Ok(nostr_sdk::Keys::new(secret_key))
  233. }
  234. }