refactor: use MintUrl::from_str

This commit is contained in:
thesimplekid
2024-09-03 10:56:52 +01:00
parent 125001211c
commit 5f87df2cef
20 changed files with 51 additions and 42 deletions

View File

@@ -41,10 +41,14 @@ impl From<Wallet> for JsWallet {
#[wasm_bindgen(js_class = Wallet)] #[wasm_bindgen(js_class = Wallet)]
impl JsWallet { impl JsWallet {
#[wasm_bindgen(constructor)] #[wasm_bindgen(constructor)]
pub async fn new(mints_url: String, unit: JsCurrencyUnit, seed: Vec<u8>) -> Self { pub async fn new(mints_url: String, unit: JsCurrencyUnit, seed: Vec<u8>) -> Result<JsWallet> {
let db = WalletRexieDatabase::new().await.unwrap(); let db = WalletRexieDatabase::new().await.unwrap();
Wallet::new(&mints_url, unit.into(), Arc::new(db), &seed, None).into() Ok(
Wallet::new(&mints_url, unit.into(), Arc::new(db), &seed, None)
.map_err(into_err)?
.into(),
)
} }
#[wasm_bindgen(js_name = totalBalance)] #[wasm_bindgen(js_name = totalBalance)]

View File

@@ -4,6 +4,7 @@
#![warn(rustdoc::bare_urls)] #![warn(rustdoc::bare_urls)]
use std::collections::HashMap; use std::collections::HashMap;
use std::str::FromStr;
use std::sync::Arc; use std::sync::Arc;
use anyhow::Result; use anyhow::Result;
@@ -11,6 +12,7 @@ use axum::routing::{get, post};
use axum::Router; use axum::Router;
use cdk::cdk_lightning::{self, MintLightning}; use cdk::cdk_lightning::{self, MintLightning};
use cdk::mint::Mint; use cdk::mint::Mint;
use cdk::mint_url::MintUrl;
use cdk::nuts::{CurrencyUnit, PaymentMethod}; use cdk::nuts::{CurrencyUnit, PaymentMethod};
use router_handlers::*; use router_handlers::*;
@@ -26,7 +28,7 @@ pub async fn create_mint_router(
let state = MintState { let state = MintState {
ln, ln,
mint, mint,
mint_url: mint_url.to_string(), mint_url: MintUrl::from_str(mint_url)?,
quote_ttl, quote_ttl,
}; };
@@ -60,7 +62,7 @@ pub async fn create_mint_router(
struct MintState { struct MintState {
ln: HashMap<LnKey, Arc<dyn MintLightning<Err = cdk_lightning::Error> + Send + Sync>>, ln: HashMap<LnKey, Arc<dyn MintLightning<Err = cdk_lightning::Error> + Send + Sync>>,
mint: Arc<Mint>, mint: Arc<Mint>,
mint_url: String, mint_url: MintUrl,
quote_ttl: u64, quote_ttl: u64,
} }

View File

@@ -81,7 +81,7 @@ pub async fn get_mint_bolt11_quote(
let quote = state let quote = state
.mint .mint
.new_mint_quote( .new_mint_quote(
state.mint_url.into(), state.mint_url,
create_invoice_response.request.to_string(), create_invoice_response.request.to_string(),
payload.unit, payload.unit,
payload.amount, payload.amount,

View File

@@ -141,7 +141,7 @@ async fn main() -> Result<()> {
localstore.clone(), localstore.clone(),
&mnemonic.to_seed_normalized(""), &mnemonic.to_seed_normalized(""),
None, None,
); )?;
if let Some(proxy_url) = args.proxy.as_ref() { if let Some(proxy_url) = args.proxy.as_ref() {
wallet.set_client(HttpClient::with_proxy(proxy_url.clone(), None, true)?); wallet.set_client(HttpClient::with_proxy(proxy_url.clone(), None, true)?);
} }

View File

@@ -39,7 +39,7 @@ pub async fn mint(
{ {
Some(wallet) => wallet.clone(), Some(wallet) => wallet.clone(),
None => { None => {
let wallet = Wallet::new(&mint_url.to_string(), unit, localstore, seed, None); let wallet = Wallet::new(&mint_url.to_string(), unit, localstore, seed, None)?;
multi_mint_wallet.add_wallet(wallet.clone()).await; multi_mint_wallet.add_wallet(wallet.clone()).await;
wallet wallet

View File

@@ -148,7 +148,7 @@ async fn receive_token(
localstore, localstore,
seed, seed,
None, None,
); )?;
multi_mint_wallet.add_wallet(wallet).await; multi_mint_wallet.add_wallet(wallet).await;
} }

View File

@@ -31,7 +31,7 @@ pub async fn test_mint_double_receive() -> Result<()> {
Arc::new(WalletMemoryDatabase::default()), Arc::new(WalletMemoryDatabase::default()),
&mnemonic.to_seed_normalized(""), &mnemonic.to_seed_normalized(""),
None, None,
); )?;
let wallet = Arc::new(wallet); let wallet = Arc::new(wallet);
@@ -56,7 +56,7 @@ pub async fn test_mint_double_receive() -> Result<()> {
Arc::new(WalletMemoryDatabase::default()), Arc::new(WalletMemoryDatabase::default()),
&mnemonic.to_seed_normalized(""), &mnemonic.to_seed_normalized(""),
None, None,
); )?;
let rec = wallet_two let rec = wallet_two
.receive(&token.to_string(), SplitTarget::default(), &[], &[]) .receive(&token.to_string(), SplitTarget::default(), &[], &[])

View File

@@ -27,7 +27,7 @@ pub async fn test_p2pk_swap() -> Result<()> {
Arc::new(WalletMemoryDatabase::default()), Arc::new(WalletMemoryDatabase::default()),
&mnemonic.to_seed_normalized(""), &mnemonic.to_seed_normalized(""),
None, None,
); )?;
let wallet = Arc::new(wallet); let wallet = Arc::new(wallet);

View File

@@ -32,6 +32,9 @@ pub enum Error {
/// BIP32 Error /// BIP32 Error
#[error(transparent)] #[error(transparent)]
BIP32(#[from] bitcoin::bip32::Error), BIP32(#[from] bitcoin::bip32::Error),
/// Mint Url Error
#[error(transparent)]
MintUrl(#[from] cdk::mint_url::Error),
/// Could Not Initialize Database /// Could Not Initialize Database
#[error("Could not initialize database")] #[error("Could not initialize database")]
CouldNotInitialize, CouldNotInitialize,

View File

@@ -8,6 +8,7 @@ use async_trait::async_trait;
use bitcoin::bip32::DerivationPath; use bitcoin::bip32::DerivationPath;
use cdk::cdk_database::{self, MintDatabase}; use cdk::cdk_database::{self, MintDatabase};
use cdk::mint::{MintKeySetInfo, MintQuote}; use cdk::mint::{MintKeySetInfo, MintQuote};
use cdk::mint_url::MintUrl;
use cdk::nuts::nut05::QuoteState; use cdk::nuts::nut05::QuoteState;
use cdk::nuts::{ use cdk::nuts::{
BlindSignature, CurrencyUnit, Id, MeltQuoteState, MintQuoteState, Proof, Proofs, PublicKey, BlindSignature, CurrencyUnit, Id, MeltQuoteState, MintQuoteState, Proof, Proofs, PublicKey,
@@ -792,7 +793,7 @@ fn sqlite_row_to_mint_quote(row: SqliteRow) -> Result<MintQuote, Error> {
Ok(MintQuote { Ok(MintQuote {
id: row_id, id: row_id,
mint_url: row_mint_url.into(), mint_url: MintUrl::from_str(&row_mint_url)?,
amount: Amount::from(row_amount as u64), amount: Amount::from(row_amount as u64),
unit: CurrencyUnit::from_str(&row_unit).map_err(Error::from)?, unit: CurrencyUnit::from_str(&row_unit).map_err(Error::from)?,
request: row_request, request: row_request,

View File

@@ -35,6 +35,9 @@ pub enum Error {
/// Secret Error /// Secret Error
#[error(transparent)] #[error(transparent)]
CDKSECRET(#[from] cdk::secret::Error), CDKSECRET(#[from] cdk::secret::Error),
/// Mint Url
#[error(transparent)]
MintUrl(#[from] cdk::mint_url::Error),
/// BIP32 Error /// BIP32 Error
#[error(transparent)] #[error(transparent)]
BIP32(#[from] bitcoin::bip32::Error), BIP32(#[from] bitcoin::bip32::Error),

View File

@@ -199,12 +199,15 @@ FROM mint
let mints = rec let mints = rec
.into_iter() .into_iter()
.map(|row| { .flat_map(|row| {
let mint_url: String = row.get("mint_url"); let mint_url: String = row.get("mint_url");
// Attempt to parse mint_url and convert mint_info
let mint_result = MintUrl::from_str(&mint_url).ok();
let mint_info = sqlite_row_to_mint_info(&row).ok(); let mint_info = sqlite_row_to_mint_info(&row).ok();
(mint_url.into(), mint_info) // Combine mint_result and mint_info into an Option tuple
mint_result.map(|mint| (mint, mint_info))
}) })
.collect(); .collect();
@@ -811,7 +814,7 @@ fn sqlite_row_to_mint_quote(row: &SqliteRow) -> Result<MintQuote, Error> {
Ok(MintQuote { Ok(MintQuote {
id: row_id, id: row_id,
mint_url: row_mint_url.into(), mint_url: MintUrl::from_str(&row_mint_url)?,
amount: Amount::from(row_amount as u64), amount: Amount::from(row_amount as u64),
unit: CurrencyUnit::from_str(&row_unit).map_err(Error::from)?, unit: CurrencyUnit::from_str(&row_unit).map_err(Error::from)?,
request: row_request, request: row_request,
@@ -869,7 +872,7 @@ fn sqlite_row_to_proof_info(row: &SqliteRow) -> Result<ProofInfo, Error> {
Ok(ProofInfo { Ok(ProofInfo {
proof, proof,
y: PublicKey::from_slice(&y)?, y: PublicKey::from_slice(&y)?,
mint_url: row_mint_url.into(), mint_url: MintUrl::from_str(&row_mint_url)?,
state: State::from_str(&row_state)?, state: State::from_str(&row_state)?,
spending_condition: row_spending_condition.and_then(|r| serde_json::from_str(&r).ok()), spending_condition: row_spending_condition.and_then(|r| serde_json::from_str(&r).ok()),
unit: CurrencyUnit::from_str(&row_unit).map_err(Error::from)?, unit: CurrencyUnit::from_str(&row_unit).map_err(Error::from)?,

View File

@@ -20,7 +20,7 @@ async fn main() -> Result<(), Error> {
let unit = CurrencyUnit::Sat; let unit = CurrencyUnit::Sat;
let amount = Amount::from(10); let amount = Amount::from(10);
let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None); let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None).unwrap();
let quote = wallet.mint_quote(amount).await.unwrap(); let quote = wallet.mint_quote(amount).await.unwrap();

View File

@@ -20,7 +20,7 @@ async fn main() -> Result<(), Error> {
let unit = CurrencyUnit::Sat; let unit = CurrencyUnit::Sat;
let amount = Amount::from(10); let amount = Amount::from(10);
let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None); let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None).unwrap();
let quote = wallet.mint_quote(amount).await.unwrap(); let quote = wallet.mint_quote(amount).await.unwrap();

View File

@@ -20,7 +20,7 @@ async fn main() {
let localstore = WalletMemoryDatabase::default(); let localstore = WalletMemoryDatabase::default();
let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None); let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None).unwrap();
for amount in [64] { for amount in [64] {
let amount = Amount::from(amount); let amount = Amount::from(amount);

View File

@@ -22,7 +22,7 @@ async fn main() {
let localstore = WalletMemoryDatabase::default(); let localstore = WalletMemoryDatabase::default();
let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None); let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None).unwrap();
let quote = wallet.mint_quote(amount).await.unwrap(); let quote = wallet.mint_quote(amount).await.unwrap();

View File

@@ -2,8 +2,8 @@
use thiserror::Error; use thiserror::Error;
use crate::cdk_database;
use crate::error::{ErrorCode, ErrorResponse}; use crate::error::{ErrorCode, ErrorResponse};
use crate::{cdk_database, mint_url};
/// CDK Mint Error /// CDK Mint Error
#[derive(Debug, Error)] #[derive(Debug, Error)]
@@ -101,6 +101,9 @@ pub enum Error {
/// Database Error /// Database Error
#[error(transparent)] #[error(transparent)]
Database(#[from] cdk_database::Error), Database(#[from] cdk_database::Error),
/// Mint Url Error
#[error(transparent)]
MintUrl(#[from] mint_url::Error),
/// Custom Error /// Custom Error
#[error("`{0}`")] #[error("`{0}`")]
Custom(String), Custom(String),

View File

@@ -1,6 +1,7 @@
//! Cashu Mint //! Cashu Mint
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::str::FromStr;
use std::sync::Arc; use std::sync::Arc;
use bitcoin::bip32::{ChildNumber, DerivationPath, ExtendedPrivKey}; use bitcoin::bip32::{ChildNumber, DerivationPath, ExtendedPrivKey};
@@ -155,7 +156,7 @@ impl Mint {
} }
Ok(Self { Ok(Self {
mint_url: MintUrl::from(mint_url), mint_url: MintUrl::from_str(mint_url)?,
keysets: Arc::new(RwLock::new(active_keysets)), keysets: Arc::new(RwLock::new(active_keysets)),
secp_ctx, secp_ctx,
xpriv, xpriv,

View File

@@ -82,17 +82,6 @@ impl<'de> Deserialize<'de> for MintUrl {
} }
} }
impl<S> From<S> for MintUrl
where
S: Into<String>,
{
fn from(url: S) -> Self {
let url: String = url.into();
let formatted_url = Self::format_url(&url).unwrap();
Self(formatted_url)
}
}
impl FromStr for MintUrl { impl FromStr for MintUrl {
type Err = Error; type Err = Error;

View File

@@ -79,18 +79,18 @@ impl Wallet {
localstore: Arc<dyn WalletDatabase<Err = cdk_database::Error> + Send + Sync>, localstore: Arc<dyn WalletDatabase<Err = cdk_database::Error> + Send + Sync>,
seed: &[u8], seed: &[u8],
target_proof_count: Option<usize>, target_proof_count: Option<usize>,
) -> Self { ) -> Result<Self, Error> {
let xpriv = ExtendedPrivKey::new_master(Network::Bitcoin, seed) let xpriv = ExtendedPrivKey::new_master(Network::Bitcoin, seed)
.expect("Could not create master key"); .expect("Could not create master key");
Self { Ok(Self {
mint_url: MintUrl::from(mint_url), mint_url: MintUrl::from_str(mint_url)?,
unit, unit,
client: HttpClient::new(), client: HttpClient::new(),
localstore, localstore,
xpriv, xpriv,
target_proof_count: target_proof_count.unwrap_or(3), target_proof_count: target_proof_count.unwrap_or(3),
} })
} }
/// Change HTTP client /// Change HTTP client
@@ -489,7 +489,7 @@ impl Wallet {
/// let unit = CurrencyUnit::Sat; /// let unit = CurrencyUnit::Sat;
/// ///
/// let localstore = WalletMemoryDatabase::default(); /// let localstore = WalletMemoryDatabase::default();
/// let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None); /// let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None)?;
/// let amount = Amount::from(100); /// let amount = Amount::from(100);
/// ///
/// let quote = wallet.mint_quote(amount).await?; /// let quote = wallet.mint_quote(amount).await?;
@@ -583,7 +583,7 @@ impl Wallet {
/// let unit = CurrencyUnit::Sat; /// let unit = CurrencyUnit::Sat;
/// ///
/// let localstore = WalletMemoryDatabase::default(); /// let localstore = WalletMemoryDatabase::default();
/// let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None); /// let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None).unwrap();
/// let amount = Amount::from(100); /// let amount = Amount::from(100);
/// ///
/// let quote = wallet.mint_quote(amount).await?; /// let quote = wallet.mint_quote(amount).await?;
@@ -1270,7 +1270,7 @@ impl Wallet {
/// let unit = CurrencyUnit::Sat; /// let unit = CurrencyUnit::Sat;
/// ///
/// let localstore = WalletMemoryDatabase::default(); /// let localstore = WalletMemoryDatabase::default();
/// let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None); /// let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None).unwrap();
/// let bolt11 = "lnbc100n1pnvpufspp5djn8hrq49r8cghwye9kqw752qjncwyfnrprhprpqk43mwcy4yfsqdq5g9kxy7fqd9h8vmmfvdjscqzzsxqyz5vqsp5uhpjt36rj75pl7jq2sshaukzfkt7uulj456s4mh7uy7l6vx7lvxs9qxpqysgqedwz08acmqwtk8g4vkwm2w78suwt2qyzz6jkkwcgrjm3r3hs6fskyhvud4fan3keru7emjm8ygqpcrwtlmhfjfmer3afs5hhwamgr4cqtactdq".to_string(); /// let bolt11 = "lnbc100n1pnvpufspp5djn8hrq49r8cghwye9kqw752qjncwyfnrprhprpqk43mwcy4yfsqdq5g9kxy7fqd9h8vmmfvdjscqzzsxqyz5vqsp5uhpjt36rj75pl7jq2sshaukzfkt7uulj456s4mh7uy7l6vx7lvxs9qxpqysgqedwz08acmqwtk8g4vkwm2w78suwt2qyzz6jkkwcgrjm3r3hs6fskyhvud4fan3keru7emjm8ygqpcrwtlmhfjfmer3afs5hhwamgr4cqtactdq".to_string();
/// let quote = wallet.melt_quote(bolt11, None).await?; /// let quote = wallet.melt_quote(bolt11, None).await?;
/// ///
@@ -1488,7 +1488,7 @@ impl Wallet {
/// let unit = CurrencyUnit::Sat; /// let unit = CurrencyUnit::Sat;
/// ///
/// let localstore = WalletMemoryDatabase::default(); /// let localstore = WalletMemoryDatabase::default();
/// let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None); /// let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None).unwrap();
/// let bolt11 = "lnbc100n1pnvpufspp5djn8hrq49r8cghwye9kqw752qjncwyfnrprhprpqk43mwcy4yfsqdq5g9kxy7fqd9h8vmmfvdjscqzzsxqyz5vqsp5uhpjt36rj75pl7jq2sshaukzfkt7uulj456s4mh7uy7l6vx7lvxs9qxpqysgqedwz08acmqwtk8g4vkwm2w78suwt2qyzz6jkkwcgrjm3r3hs6fskyhvud4fan3keru7emjm8ygqpcrwtlmhfjfmer3afs5hhwamgr4cqtactdq".to_string(); /// let bolt11 = "lnbc100n1pnvpufspp5djn8hrq49r8cghwye9kqw752qjncwyfnrprhprpqk43mwcy4yfsqdq5g9kxy7fqd9h8vmmfvdjscqzzsxqyz5vqsp5uhpjt36rj75pl7jq2sshaukzfkt7uulj456s4mh7uy7l6vx7lvxs9qxpqysgqedwz08acmqwtk8g4vkwm2w78suwt2qyzz6jkkwcgrjm3r3hs6fskyhvud4fan3keru7emjm8ygqpcrwtlmhfjfmer3afs5hhwamgr4cqtactdq".to_string();
/// let quote = wallet.melt_quote(bolt11, None).await?; /// let quote = wallet.melt_quote(bolt11, None).await?;
/// let quote_id = quote.id; /// let quote_id = quote.id;
@@ -1796,7 +1796,7 @@ impl Wallet {
/// let unit = CurrencyUnit::Sat; /// let unit = CurrencyUnit::Sat;
/// ///
/// let localstore = WalletMemoryDatabase::default(); /// let localstore = WalletMemoryDatabase::default();
/// let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None); /// let wallet = Wallet::new(mint_url, unit, Arc::new(localstore), &seed, None).unwrap();
/// let token = "cashuAeyJ0b2tlbiI6W3sicHJvb2ZzIjpbeyJhbW91bnQiOjEsInNlY3JldCI6ImI0ZjVlNDAxMDJhMzhiYjg3NDNiOTkwMzU5MTU1MGYyZGEzZTQxNWEzMzU0OTUyN2M2MmM5ZDc5MGVmYjM3MDUiLCJDIjoiMDIzYmU1M2U4YzYwNTMwZWVhOWIzOTQzZmRhMWEyY2U3MWM3YjNmMGNmMGRjNmQ4NDZmYTc2NWFhZjc3OWZhODFkIiwiaWQiOiIwMDlhMWYyOTMyNTNlNDFlIn1dLCJtaW50IjoiaHR0cHM6Ly90ZXN0bnV0LmNhc2h1LnNwYWNlIn1dLCJ1bml0Ijoic2F0In0="; /// let token = "cashuAeyJ0b2tlbiI6W3sicHJvb2ZzIjpbeyJhbW91bnQiOjEsInNlY3JldCI6ImI0ZjVlNDAxMDJhMzhiYjg3NDNiOTkwMzU5MTU1MGYyZGEzZTQxNWEzMzU0OTUyN2M2MmM5ZDc5MGVmYjM3MDUiLCJDIjoiMDIzYmU1M2U4YzYwNTMwZWVhOWIzOTQzZmRhMWEyY2U3MWM3YjNmMGNmMGRjNmQ4NDZmYTc2NWFhZjc3OWZhODFkIiwiaWQiOiIwMDlhMWYyOTMyNTNlNDFlIn1dLCJtaW50IjoiaHR0cHM6Ly90ZXN0bnV0LmNhc2h1LnNwYWNlIn1dLCJ1bml0Ijoic2F0In0=";
/// let amount_receive = wallet.receive(token, SplitTarget::default(), &[], &[]).await?; /// let amount_receive = wallet.receive(token, SplitTarget::default(), &[], &[]).await?;
/// Ok(()) /// Ok(())