Skip to content

Commit

Permalink
feat(NUT02): add input_fee_ppk
Browse files Browse the repository at this point in the history
chore: instrument log on mint fns
  • Loading branch information
thesimplekid committed Jul 11, 2024
1 parent 8477dc7 commit 17263b0
Show file tree
Hide file tree
Showing 33 changed files with 995 additions and 500 deletions.
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@

### Changed
cdk(wallet): `wallet:receive` will not claim `proofs` from a mint other then the wallet's mint ([thesimplekid]).
cdk(NUT00): `Token` is changed from a struct to enum of either `TokenV4` or `Tokenv3` ([thesimplekid]).
cdk(NUT00): `Token` is changed from a `struct` to `enum` of either `TokenV4` or `Tokenv3` ([thesimplekid]).
cdk(NUT00): Rename `MintProofs` to `TokenV3Token` ([thesimplekid]).


Expand All @@ -40,6 +40,8 @@ cdk-mintd: Mint binary ([thesimplekid]).
cdk-cln: cln backend for mint ([thesimplekid]).
cdk-axum: Mint axum server ([thesimplekid]).
cdk: NUT06 `MintInfo` and `NUTs` builder ([thesimplekid]).
cdk: NUT00 `PreMintSecret` added Keyset id ([thesimplekid])
cdk: NUT02 Support fees ([thesimplekid])

### Fixed
cdk: NUT06 deseralize `MintInfo` ([thesimplekid]).
Expand Down
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ cdk-axum = { version = "0.1", path = "./crates/cdk-axum", default-features = fal
tokio = { version = "1", default-features = false }
thiserror = "1"
tracing = { version = "0.1", default-features = false, features = ["attributes", "log"] }
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
serde = { version = "1", default-features = false, features = ["derive"] }
serde_json = "1"
serde-wasm-bindgen = "0.6.5"
Expand Down
29 changes: 18 additions & 11 deletions bindings/cdk-js/src/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::sync::Arc;

use cdk::amount::SplitTarget;
use cdk::nuts::{Proofs, SecretKey};
use cdk::wallet::Wallet;
use cdk::wallet::{SendKind, Wallet};
use cdk::Amount;
use cdk_rexie::WalletRexieDatabase;
use wasm_bindgen::prelude::*;
Expand Down Expand Up @@ -44,7 +44,7 @@ impl JsWallet {
pub async fn new(mints_url: String, unit: JsCurrencyUnit, seed: Vec<u8>) -> Self {
let db = WalletRexieDatabase::new().await.unwrap();

Wallet::new(&mints_url, unit.into(), Arc::new(db), &seed).into()
Wallet::new(&mints_url, unit.into(), Arc::new(db), &seed, None).into()
}

#[wasm_bindgen(js_name = totalBalance)]
Expand Down Expand Up @@ -81,12 +81,6 @@ impl JsWallet {
.map(|i| i.into()))
}

#[wasm_bindgen(js_name = refreshMint)]
pub async fn refresh_mint_keys(&self) -> Result<()> {
self.inner.refresh_mint_keys().await.map_err(into_err)?;
Ok(())
}

#[wasm_bindgen(js_name = mintQuote)]
pub async fn mint_quote(&mut self, amount: u64) -> Result<JsMintQuote> {
let quote = self
Expand Down Expand Up @@ -200,7 +194,7 @@ impl JsWallet {
.inner
.receive(
&encoded_token,
&SplitTarget::default(),
SplitTarget::default(),
&signing_keys,
&preimages,
)
Expand Down Expand Up @@ -234,7 +228,14 @@ impl JsWallet {
.map(|a| SplitTarget::Value(*a.deref()))
.unwrap_or_default();
self.inner
.send(Amount::from(amount), memo, conditions, &target)
.send(
Amount::from(amount),
memo,
conditions,
&target,
&SendKind::default(),
false,
)
.await
.map_err(into_err)
}
Expand Down Expand Up @@ -267,7 +268,13 @@ impl JsWallet {
.unwrap_or_default();
let post_swap_proofs = self
.inner
.swap(Some(Amount::from(amount)), &target, proofs, conditions)
.swap(
Some(Amount::from(amount)),
target,
proofs,
conditions,
false,
)
.await
.map_err(into_err)?;

Expand Down
2 changes: 1 addition & 1 deletion crates/cdk-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ serde = { workspace = true, features = ["derive"] }
serde_json.workspace = true
tokio.workspace = true
tracing.workspace = true
tracing-subscriber = "0.3.18"
tracing-subscriber.workspace = true
rand = "0.8.5"
home.workspace = true
nostr-sdk = { version = "0.32.0", default-features = false, features = [
Expand Down
14 changes: 10 additions & 4 deletions crates/cdk-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use cdk_sqlite::WalletSqliteDatabase;
use clap::{Parser, Subcommand};
use rand::Rng;
use tracing::Level;
use tracing_subscriber::EnvFilter;

mod sub_commands;

Expand Down Expand Up @@ -69,11 +70,15 @@ enum Commands {

#[tokio::main]
async fn main() -> Result<()> {
// Parse input
let args: Cli = Cli::parse();
tracing_subscriber::fmt()
.with_max_level(args.log_level)
.init();
let default_filter = args.log_level;

let sqlx_filter = "sqlx=warn";

let env_filter = EnvFilter::new(format!("{},{}", default_filter, sqlx_filter));

// Parse input
tracing_subscriber::fmt().with_env_filter(env_filter).init();

let work_dir = match &args.work_dir {
Some(work_dir) => work_dir.clone(),
Expand Down Expand Up @@ -131,6 +136,7 @@ async fn main() -> Result<()> {
cdk::nuts::CurrencyUnit::Sat,
localstore.clone(),
&mnemonic.to_seed_normalized(""),
None,
);

wallets.insert(mint, wallet);
Expand Down
8 changes: 7 additions & 1 deletion crates/cdk-cli/src/sub_commands/mint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,13 @@ pub async fn mint(
let mint_url = sub_command_args.mint_url.clone();
let wallet = match wallets.get(&mint_url) {
Some(wallet) => wallet.clone(),
None => Wallet::new(&mint_url.to_string(), CurrencyUnit::Sat, localstore, seed),
None => Wallet::new(
&mint_url.to_string(),
CurrencyUnit::Sat,
localstore,
seed,
None,
),
};

let quote = wallet
Expand Down
3 changes: 2 additions & 1 deletion crates/cdk-cli/src/sub_commands/receive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,11 +136,12 @@ async fn receive_token(
CurrencyUnit::Sat,
Arc::clone(localstore),
seed,
None,
),
};

let amount = wallet
.receive(token_str, &SplitTarget::default(), signing_keys, preimage)
.receive(token_str, SplitTarget::default(), signing_keys, preimage)
.await?;
Ok(amount)
}
Expand Down
19 changes: 19 additions & 0 deletions crates/cdk-cli/src/sub_commands/send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::str::FromStr;
use anyhow::{bail, Result};
use cdk::amount::SplitTarget;
use cdk::nuts::{Conditions, PublicKey, SpendingConditions, Token};
use cdk::wallet::types::SendKind;
use cdk::wallet::Wallet;
use cdk::{Amount, UncheckedUrl};
use clap::Args;
Expand Down Expand Up @@ -35,6 +36,15 @@ pub struct SendSubCommand {
/// Token as V3 token
#[arg(short, long)]
v3: bool,
/// Should the send be offline only
#[arg(short, long)]
offline: bool,
/// Include fee to redeam in token
#[arg(short, long)]
include_fee: bool,
/// Amount willing to overpay to avoid a swap
#[arg(short, long)]
tolerance: Option<u64>,
}

pub async fn send(
Expand Down Expand Up @@ -146,12 +156,21 @@ pub async fn send(

let wallet = mints_amounts[mint_number].0.clone();

let send_kind = match (sub_command_args.offline, sub_command_args.tolerance) {
(true, Some(amount)) => SendKind::OfflineTolerance(Amount::from(amount)),
(true, None) => SendKind::OfflineExact,
(false, Some(amount)) => SendKind::OnlineTolerance(Amount::from(amount)),
(false, None) => SendKind::OnlineExact,
};

let token = wallet
.send(
token_amount,
sub_command_args.memo.clone(),
conditions,
&SplitTarget::default(),
&send_kind,
sub_command_args.include_fee,
)
.await?;

Expand Down
2 changes: 1 addition & 1 deletion crates/cdk-mintd/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ config = { version = "0.13.3", features = ["toml"] }
clap = { version = "4.4.8", features = ["derive", "env", "default"] }
tokio.workspace = true
tracing.workspace = true
tracing-subscriber = "0.3.18"
tracing-subscriber.workspace = true
futures = "0.3.28"
serde.workspace = true
bip39.workspace = true
Expand Down
1 change: 1 addition & 0 deletions crates/cdk-mintd/example.config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ url = "https://mint.thesimplekid.dev/"
listen_host = "127.0.0.1"
listen_port = 8085
mnemonic = ""
# input_fee_ppk = 0



Expand Down
1 change: 1 addition & 0 deletions crates/cdk-mintd/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub struct Info {
pub listen_port: u16,
pub mnemonic: String,
pub seconds_quote_is_valid_for: Option<u64>,
pub input_fee_ppk: Option<u64>,
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
Expand Down
14 changes: 11 additions & 3 deletions crates/cdk-mintd/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ use cli::CLIArgs;
use config::{DatabaseEngine, LnBackend};
use futures::StreamExt;
use tower_http::cors::CorsLayer;
use tracing_subscriber::EnvFilter;

mod cli;
mod config;
Expand All @@ -37,9 +38,13 @@ const DEFAULT_QUOTE_TTL_SECS: u64 = 1800;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();
let default_filter = "debug";

let sqlx_filter = "sqlx=warn";

let env_filter = EnvFilter::new(format!("{},{}", default_filter, sqlx_filter));

tracing_subscriber::fmt().with_env_filter(env_filter).init();

let args = CLIArgs::parse();

Expand Down Expand Up @@ -206,13 +211,16 @@ async fn main() -> anyhow::Result<()> {

let mnemonic = Mnemonic::from_str(&settings.info.mnemonic)?;

let input_fee_ppk = settings.info.input_fee_ppk.unwrap_or(0);

let mint = Mint::new(
&settings.info.url,
&mnemonic.to_seed_normalized(""),
mint_info,
localstore,
absolute_ln_fee_reserve,
relative_ln_fee,
input_fee_ppk,
)
.await?;

Expand Down
10 changes: 10 additions & 0 deletions crates/cdk-redb/src/wallet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,7 @@ impl WalletDatabase for WalletRedbDatabase {
let mut table = write_txn
.open_multimap_table(MINT_KEYSETS_TABLE)
.map_err(Error::from)?;
let mut keysets_table = write_txn.open_table(KEYSETS_TABLE).map_err(Error::from)?;

for keyset in keysets {
table
Expand All @@ -296,6 +297,15 @@ impl WalletDatabase for WalletRedbDatabase {
keyset.id.to_bytes().as_slice(),
)
.map_err(Error::from)?;

keysets_table
.insert(
keyset.id.to_bytes().as_slice(),
serde_json::to_string(&keyset)
.map_err(Error::from)?
.as_str(),
)
.map_err(Error::from)?;
}
}
write_txn.commit().map_err(Error::from)?;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ALTER TABLE keyset ADD input_fee_ppk INTEGER;
9 changes: 6 additions & 3 deletions crates/cdk-sqlite/src/mint/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -407,9 +407,9 @@ WHERE id=?
async fn add_keyset_info(&self, keyset: MintKeySetInfo) -> Result<(), Self::Err> {
sqlx::query(
r#"
INSERT INTO keyset
(id, unit, active, valid_from, valid_to, derivation_path, max_order)
VALUES (?, ?, ?, ?, ?, ?, ?);
INSERT OR REPLACE INTO keyset
(id, unit, active, valid_from, valid_to, derivation_path, max_order, input_fee_ppk)
VALUES (?, ?, ?, ?, ?, ?, ?, ?);
"#,
)
.bind(keyset.id.to_string())
Expand All @@ -419,6 +419,7 @@ VALUES (?, ?, ?, ?, ?, ?, ?);
.bind(keyset.valid_to.map(|v| v as i64))
.bind(keyset.derivation_path.to_string())
.bind(keyset.max_order)
.bind(keyset.input_fee_ppk as i64)
.execute(&self.pool)
.await
.map_err(Error::from)?;
Expand Down Expand Up @@ -714,6 +715,7 @@ fn sqlite_row_to_keyset_info(row: SqliteRow) -> Result<MintKeySetInfo, Error> {
let row_valid_to: Option<i64> = row.try_get("valid_to").map_err(Error::from)?;
let row_derivation_path: String = row.try_get("derivation_path").map_err(Error::from)?;
let row_max_order: u8 = row.try_get("max_order").map_err(Error::from)?;
let row_keyset_ppk: Option<i64> = row.try_get("input_fee_ppk").map_err(Error::from)?;

Ok(MintKeySetInfo {
id: Id::from_str(&row_id).map_err(Error::from)?,
Expand All @@ -723,6 +725,7 @@ fn sqlite_row_to_keyset_info(row: SqliteRow) -> Result<MintKeySetInfo, Error> {
valid_to: row_valid_to.map(|v| v as u64),
derivation_path: DerivationPath::from_str(&row_derivation_path).map_err(Error::from)?,
max_order: row_max_order,
input_fee_ppk: row_keyset_ppk.unwrap_or(0) as u64,
})
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ALTER TABLE keyset ADD input_fee_ppk INTEGER;
7 changes: 5 additions & 2 deletions crates/cdk-sqlite/src/wallet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,14 +211,15 @@ FROM mint
sqlx::query(
r#"
INSERT OR REPLACE INTO keyset
(mint_url, id, unit, active)
VALUES (?, ?, ?, ?);
(mint_url, id, unit, active, input_fee_ppk)
VALUES (?, ?, ?, ?, ?);
"#,
)
.bind(mint_url.to_string())
.bind(keyset.id.to_string())
.bind(keyset.unit.to_string())
.bind(keyset.active)
.bind(keyset.input_fee_ppk as i64)
.execute(&self.pool)
.await
.map_err(Error::from)?;
Expand Down Expand Up @@ -708,11 +709,13 @@ fn sqlite_row_to_keyset(row: &SqliteRow) -> Result<KeySetInfo, Error> {
let row_id: String = row.try_get("id").map_err(Error::from)?;
let row_unit: String = row.try_get("unit").map_err(Error::from)?;
let active: bool = row.try_get("active").map_err(Error::from)?;
let row_keyset_ppk: Option<i64> = row.try_get("input_fee_ppk").map_err(Error::from)?;

Ok(KeySetInfo {
id: Id::from_str(&row_id)?,
unit: CurrencyUnit::from_str(&row_unit).map_err(Error::from)?,
active,
input_fee_ppk: row_keyset_ppk.unwrap_or(0) as u64,
})
}

Expand Down
4 changes: 4 additions & 0 deletions crates/cdk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ required-features = ["wallet"]
name = "wallet"
required-features = ["wallet"]

[[example]]
name = "proof_selection"
required-features = ["wallet"]

[dev-dependencies]
rand = "0.8.5"
bip39.workspace = true
Expand Down
Loading

0 comments on commit 17263b0

Please sign in to comment.