]> Untitled Git - bdk-cli/commitdiff
refactor: drop the types module and build JSON in each command
authorVihiga Tyonum <withtvpeter@gmail.com>
Mon, 30 Nov 2026 18:11:29 +0000 (19:11 +0100)
committerVihiga Tyonum <withtvpeter@gmail.com>
Tue, 1 Dec 2026 10:49:31 +0000 (11:49 +0100)
JSON is the only output format, so the result structs in
src/utils/types.rs were only intermediate shapes. execute() now
returns serde_json::Value and each command builds its output with
json! in its own handler, so a command's output is defined in one
place.

Helpers in src/utils return domain values instead of output structs:
the descriptor helpers return KeychainDescriptors (descriptors,
keymap, fingerprint), and the handler decides what to print.

14 files changed:
CHANGELOG.md
NEW_FEATURE.md
src/handlers/config.rs
src/handlers/descriptor.rs
src/handlers/dns/mod.rs
src/handlers/hwi.rs
src/handlers/key.rs
src/handlers/mod.rs
src/handlers/offline.rs
src/handlers/online.rs
src/utils/descriptors.rs
src/utils/mod.rs
src/utils/output.rs
src/utils/types.rs [deleted file]

index 85926de97accb360c81da2a8ce30580edd22cded..e7a266ccf2c85ad9d84f13295f94a0126ec51dca 100644 (file)
@@ -26,6 +26,7 @@ page. See [DEVELOPMENT_CYCLE.md](DEVELOPMENT_CYCLE.md) for more details.
 - Gated `full_scan`'s `--scan-stop-gap` to the Electrum and Esplora backends that use it; RPC and CBF wallets now reject the flag instead of silently ignoring it, while a `STOP_GAP` environment variable keeps working for supported backends and no longer breaks unsupported ones
 - Changed `payjoin history` to return JSON instead of a rendered table
 - Fixed `wallet config --force` silently changing an existing wallet's network, which left the wallet unable to load; it is now rejected
+- Changed `receive_payjoin`, `send_payjoin`, `resume_payjoin`, `payjoin_history` and `resolve_dns_recipient` to print their JSON directly instead of as a string inside a `message` field; `resolve_dns_recipient` now leaves out `description`, `min_amount` and `max_amount` when they are not set
 
 ## [4.0.0]
 
index 543fc16451c316503dc05636f9adc8923ddd0875..b2c7890134632169abeacf867e774be9797bc5a8 100644 (file)
@@ -10,7 +10,7 @@ Before writing code, it helps to understand the three major components of a bdk-
 
 __Clap Parser:__ Defines the CLI arguments the user types. 
 
-__The AppCommand Trait__: The trait every command must implement to define its execution logic and return a formatted output. It has the `execute` method and a type `FormatOutput` for formatting the command's response. If the command involves I/O, there is an AsyncAppCommand to use.
+__The AppCommand Trait__: The trait every command must implement to define its execution logic. Its `execute` method returns the command's output as a `serde_json::Value`. If the command involves I/O, there is an AsyncAppCommand to use.
 
 __The Typestate (AppContext<T>):__ Defines the environment your command runs in. Every command is a struct that implements the AppCommand's trait execute method against a typestate context. There are three context (src/handlers/mod):
 
@@ -52,22 +52,11 @@ pub struct WalletDetailsCommand {
 
 ```
 
-##### Step 2: Define the Output Type
+##### Step 2: Decide where the output is built
 
-Every command must return a structured result that can be serialized into standard JSON. Define a struct that implements serde::Serialize ( placed in `src/utils/types.rs`).
-
-```Rust
-use serde::Serialize;
-use bdk_wallet::bitcoin::Network;
-
-#[derive(Debug, Serialize)]
-pub struct WalletDetailsResult {
-    pub network: Network,
-    pub fingerprint: String,
-    #[serde(skip_serializing_if = "Option::is_none")]
-    pub external_descriptor: Option<String>,
-}
-```
+Every command prints JSON, and that JSON is built in exactly one place: the command's own `execute` method. To find what a command prints, read its `execute`.
+- Helpers in `src/utils/` return domain values (bdk/bitcoin types, `String`s, small structs such as `KeychainDescriptors`) so they can be reused. They never build JSON.
+- `execute` turns those values into the output with `serde_json::json!`. 
 
 ##### Step 3: Implement the AppCommand Trait
 
@@ -78,31 +67,27 @@ Because our command needs to read wallet data, we will use the OfflineOperations
 ```Rust
 use crate::handlers::{AppCommand, AppContext, OfflineOperations};
 use crate::error::BDKCliError as Error;
+use serde_json::{Value, json};
 
 impl AppCommand<AppContext<OfflineOperations<'_>>> for WalletDetailsCommand {
-    // 1. Declare the output type we defined in Step 2
-    type Output = WalletDetailsResult;
-
-    // 2. Implement the execute function
-    fn execute(&self, context: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+    
+    // Implement the execute function
+    fn execute(&self, context: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
         // Access the loaded wallet via the context state
         let wallet = &context.state.wallet;
         
-        let network = wallet.network();
-        let fingerprint = wallet.fingerprint().to_string();
-        
-        let external_descriptor = if self.show_descriptors {
-            Some(wallet.public_descriptor(bdk_wallet::KeychainKind::External).to_string())
-        } else {
-            None
-        };
-
-        // Return the structured Result
-        Ok(WalletDetailsResult {
-            network,
-            fingerprint,
-            external_descriptor,
-        })
+       let mut output = json!({
+            "network": wallet.network(),
+            "fingerprint": wallet.fingerprint().to_string(),
+        });
+
+        // Only include the descriptor when it was asked for
+        if self.show_descriptors {
+            output["external_descriptor"] =
+                json!(wallet.public_descriptor(bdk_wallet::KeychainKind::External).to_string());
+        }
+
+        Ok(output)
     }
 }
 ```
index bed4f13ef77c85b0ce49a918b1f88972707c3e72..4ed38d3eaf7d1fe2ddf147f7039d2cec915fcbee 100644 (file)
@@ -10,16 +10,14 @@ use crate::client::ClientType;
 use crate::commands::{WalletOpts, WalletsSubCommand};
 use crate::config::{WalletConfig, WalletConfigInner, remove_wallet_from_config_file};
 use crate::error::BDKCliError as Error;
-use crate::handlers::Init;
-use crate::handlers::{AppCommand, AppContext};
+use crate::handlers::{AppCommand, AppContext, Init};
 #[cfg(any(feature = "sqlite", feature = "redb"))]
 use crate::persister::DatabaseType;
 use crate::persister::wallet_data_exists;
-use crate::utils::descriptors::validate_descriptor_pair;
-use crate::utils::output::FormatOutput;
-use crate::utils::types::{StatusResult, WalletsListResult};
+use crate::utils::{descriptors::validate_descriptor_pair, output::FormatOutput};
 use bdk_wallet::bitcoin::Network;
 use clap::Args;
+use serde_json::{Value, json};
 
 #[derive(Args, Debug, Clone, PartialEq)]
 pub struct SaveConfigCommand {
@@ -32,9 +30,7 @@ pub struct SaveConfigCommand {
 }
 
 impl AppCommand<AppContext<Init>> for SaveConfigCommand {
-    type Output = StatusResult;
-
-    fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Value, Error> {
         if ctx.network == Network::Bitcoin {
             eprintln!("WARNING: Configuring for Bitcoin MAINNET. Experimental software!");
         }
@@ -160,13 +156,13 @@ impl AppCommand<AppContext<Init>> for SaveConfigCommand {
             .save(&ctx.datadir)
             .map_err(|error| Error::Generic(error.to_string()))?;
 
-        Ok(StatusResult {
-            message: format!(
-                "Wallet '{}' initialized successfully in {:?}",
-                wallet_name,
-                ctx.datadir.join("config.toml")
-            ),
-        })
+        Ok(json!({
+           "message": format!(
+                 "Wallet '{}' initialized successfully in {:?}",
+                 wallet_name,
+                 ctx.datadir.join("config.toml")
+             ),
+        }))
     }
 }
 
@@ -174,15 +170,13 @@ impl AppCommand<AppContext<Init>> for SaveConfigCommand {
 pub struct ListWalletsCommand;
 
 impl AppCommand<AppContext<Init>> for ListWalletsCommand {
-    type Output = WalletsListResult;
-
-    fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Value, Error> {
         let config = match WalletConfig::load(&ctx.datadir)? {
             Some(cfg) => cfg,
             None => return Err(Error::Generic("No wallets configured yet.".into())),
         };
 
-        Ok(WalletsListResult(config.wallets))
+        Ok(serde_json::to_value(config.wallets)?)
     }
 }
 
@@ -194,9 +188,7 @@ pub struct DeleteWalletConfigCommand {
 }
 
 impl AppCommand<AppContext<Init>> for DeleteWalletConfigCommand {
-    type Output = StatusResult;
-
-    fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Value, Error> {
         let config = match WalletConfig::load(&ctx.datadir)? {
             Some(config) => config,
             None => return Err(Error::Generic("No wallets configured yet.".into())),
@@ -236,12 +228,12 @@ impl AppCommand<AppContext<Init>> for DeleteWalletConfigCommand {
 
         remove_wallet_from_config_file(&ctx.datadir, &self.wallet_name)?;
 
-        Ok(StatusResult {
-            message: format!(
-                "Wallet configuration '{}' deleted successfully",
-                self.wallet_name
-            ),
-        })
+        Ok(json!({
+            "message": format!(
+                 "Wallet configuration '{}' deleted successfully",
+                 self.wallet_name
+             ),
+        }))
     }
 }
 
index 598617aecb3ec6c742b8b017a83ab7886fa0b509..5453010a2205d501632a21f7a1dc01371b43baab 100644 (file)
@@ -1,5 +1,4 @@
 use crate::handlers::Init;
-use crate::utils::types::DescriptorResult;
 use crate::{
     error::BDKCliError as Error,
     handlers::{AppCommand, AppContext},
@@ -12,15 +11,13 @@ use crate::{
     },
 };
 use clap::Parser;
+use serde_json::{Value, json};
 #[cfg(feature = "compiler")]
 use {
     crate::utils::descriptors::{CompileScriptType, compile_policy},
     bdk_wallet::miniscript::descriptor::DescriptorPublicKey,
 };
 
-#[cfg(feature = "silent-payments")]
-use crate::utils::types::StatusResult;
-
 #[derive(Parser, Debug, Clone, PartialEq)]
 pub struct DescriptorCommand {
     /// Descriptor type (script type)
@@ -36,19 +33,38 @@ pub struct DescriptorCommand {
     key: Option<String>,
 }
 impl AppCommand<AppContext<Init>> for DescriptorCommand {
-    type Output = DescriptorResult;
-
-    fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Self::Output, Error> {
-        match &self.key {
-            Some(key) => {
-                if is_mnemonic(key) {
-                    generate_descriptor_from_mnemonic(key, ctx.network.into(), &self.desc_type)
-                } else {
-                    generate_descriptors(&self.desc_type, key, ctx.network.into())
-                }
+    fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Value, Error> {
+        let network = ctx.network.into();
+        let (descriptors, mnemonic) = match &self.key {
+            Some(key) if is_mnemonic(key) => (
+                generate_descriptor_from_mnemonic(key, network, &self.desc_type)?,
+                Some(key.clone()),
+            ),
+            Some(key) => (generate_descriptors(&self.desc_type, key, network)?, None),
+            None => {
+                let (mnemonic, descriptors) =
+                    generate_descriptor_with_mnemonic(network, &self.desc_type)?;
+                (descriptors, Some(mnemonic.to_string()))
             }
-            None => generate_descriptor_with_mnemonic(ctx.network.into(), &self.desc_type),
+        };
+
+        let mut output = json!({
+            "public_descriptors": {
+                "external": descriptors.external.to_string(),
+                "internal": descriptors.internal.to_string(),
+            },
+        });
+        if !descriptors.keymap.is_empty() {
+            output["private_descriptors"] = json!({
+                "external": descriptors.external.to_string_with_secret(&descriptors.keymap),
+                "internal": descriptors.internal.to_string_with_secret(&descriptors.keymap),
+            });
         }
+        if let Some(mnemonic) = mnemonic {
+            output["mnemonic"] = json!(mnemonic);
+        }
+        output["fingerprint"] = json!(descriptors.fingerprint.to_string());
+        Ok(output)
     }
 }
 
@@ -76,24 +92,18 @@ pub struct CompileCommand {
 
 #[cfg(feature = "compiler")]
 impl AppCommand<AppContext<Init>> for CompileCommand {
-    type Output = DescriptorResult;
-
-    fn execute(&self, _ctx: &mut AppContext<Init>) -> Result<Self::Output, Error> {
+    fn execute(&self, _ctx: &mut AppContext<Init>) -> Result<Value, Error> {
         let (descriptor, r) = if self.placeholders {
             compile_policy::<String>(&self.policy, self.script_type)?
         } else {
             compile_policy::<DescriptorPublicKey>(&self.policy, self.script_type)?
         };
 
-        Ok(DescriptorResult {
-            descriptor: Some(descriptor),
-            mnemonic: None,
-            multipath_descriptor: None,
-            public_descriptors: None,
-            private_descriptors: None,
-            fingerprint: None,
-            r,
-        })
+        let mut output = json!({ "descriptor": descriptor });
+        if let Some(r) = r {
+            output["r"] = json!(r);
+        }
+        Ok(output)
     }
 }
 
@@ -110,14 +120,10 @@ pub struct SilentPaymentCodeCommand {
 
 #[cfg(feature = "silent-payments")]
 impl AppCommand<AppContext<Init>> for SilentPaymentCodeCommand {
-    type Output = StatusResult;
-
-    fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Value, Error> {
         let sp_code =
             bdk_sp::encoding::SilentPaymentCode::new_v0(self.scan, self.spend, ctx.network);
 
-        Ok(StatusResult {
-            message: sp_code.to_string(),
-        })
+        Ok(json!({ "message": sp_code.to_string() }))
     }
 }
index e1c5b8df0a1b0b533d7eb4d0697056db8c130ca6..2e3309ca4ad284fa2ca337087cde1c6eaa8279cd 100644 (file)
@@ -5,7 +5,6 @@ use crate::handlers::dns::dns_payment_instructions::{
     parse_dns_instructions, process_instructions, resolve_dns_recipient,
 };
 use crate::handlers::{AppContext, AsyncAppCommand, Init, OfflineOperations};
-use crate::utils::types::{PsbtResult, StatusResult};
 use crate::utils::{
     check_standard_weight, max_signed_weight, parse_dns_recipient, parse_fee_rate,
     parse_op_return_base64, parse_op_return_string, parse_outpoint, parse_recipient,
@@ -13,6 +12,7 @@ use crate::utils::{
 use bdk_wallet::KeychainKind;
 use bdk_wallet::bitcoin::{Amount, FeeRate, OutPoint, ScriptBuf, Sequence, script::PushBytesBuf};
 use clap::Parser;
+use serde_json::{Value, json};
 use std::collections::BTreeMap;
 
 /// Resolves BIP-353 DNS payment instructions for a human-readable name.
@@ -26,15 +26,11 @@ pub struct ResolveDnsRecipientCommand {
 }
 
 impl AsyncAppCommand<AppContext<Init>> for ResolveDnsRecipientCommand {
-    type Output = StatusResult;
-
-    async fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Self::Output, Error> {
+    async fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Value, Error> {
         let resolved = resolve_dns_recipient(&self.hrn, ctx.network, &self.resolver)
             .await
             .map_err(|e| Error::Generic(format!("{:?}", e)))?;
-        Ok(StatusResult {
-            message: resolved.display()?,
-        })
+        Ok(json!({ "message": resolved.display()? }))
     }
 }
 
@@ -82,12 +78,7 @@ pub struct CreateDnsTxCommand {
 }
 
 impl AsyncAppCommand<AppContext<OfflineOperations<'_>>> for CreateDnsTxCommand {
-    type Output = PsbtResult;
-
-    async fn execute(
-        &self,
-        ctx: &mut AppContext<OfflineOperations<'_>>,
-    ) -> Result<Self::Output, Error> {
+    async fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
         let network = ctx.network;
         let mut recipients: Vec<(ScriptBuf, u64)> = self.recipients.clone();
 
@@ -159,6 +150,6 @@ impl AsyncAppCommand<AppContext<OfflineOperations<'_>>> for CreateDnsTxCommand {
 
         let psbt = tx_builder.finish()?;
         check_standard_weight(max_signed_weight(ctx.state.wallet, &psbt)?)?;
-        Ok(PsbtResult::new(&psbt, Some(false)))
+        Ok(json!({ "psbt": psbt.to_string(), "is_finalized": false }))
     }
 }
index 4bf285a42c75c83b1e546e0163f75a261a4f88f7..ab1d555e3fc6487edf949f4dbbdef253aaa70ee9 100644 (file)
@@ -14,7 +14,7 @@
 use async_hwi::AddressScript;
 use bdk_wallet::KeychainKind;
 use clap::{Parser, Subcommand};
-use serde_json::json;
+use serde_json::{Value, json};
 use std::str::FromStr;
 
 use crate::error::BDKCliError as Error;
@@ -61,9 +61,7 @@ pub enum HwiSubCommand {
 }
 
 impl AsyncAppCommand<AppContext<Init>> for HwiCommand {
-    type Output = serde_json::Value;
-
-    async fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Self::Output, Error> {
+    async fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Value, Error> {
         let network = ctx.network;
         // Device-only commands operate without a wallet policy.
         let hwi_wallet = HwiWallet::default();
@@ -198,7 +196,7 @@ impl WalletHwiCommand {
         &self,
         ctx: &mut AppContext<OfflineOperations<'_>>,
         wallet_name: &str,
-    ) -> Result<serde_json::Value, Error> {
+    ) -> Result<Value, Error> {
         let network = ctx.network;
 
         let target_fp = self.fingerprint.as_deref();
index 4b67b11ac8da0222d61121dedecf9c7a5fd9c4cd..6a25a40fe781d907f8e854c35aede6467183d8e5 100644 (file)
@@ -1,15 +1,16 @@
 use crate::commands::KeySubCommand;
 use crate::error::BDKCliError as Error;
 use crate::handlers::{AppCommand, AppContext, Init};
-use crate::utils::{output::FormatOutput, types::KeyResult};
+use crate::utils::output::FormatOutput;
 use bdk_wallet::bip39::{Language, Mnemonic};
-use bdk_wallet::bitcoin::bip32::{DerivationPath, KeySource, Xpriv};
+use bdk_wallet::bitcoin::bip32::{DerivationPath, Fingerprint, KeySource, Xpriv};
 use bdk_wallet::bitcoin::{Network, key::Secp256k1};
 use bdk_wallet::keys::{
     DerivableKey, DescriptorKey, ExtendedKey, GeneratableKey, GeneratedKey, bip39::WordCount,
 };
 use bdk_wallet::miniscript::{self, Segwitv0};
 use clap::{Parser, ValueEnum};
+use serde_json::{Value, json};
 
 impl KeySubCommand {
     pub fn execute(&self, ctx: &mut AppContext<Init>) -> Result<(), Error> {
@@ -63,13 +64,19 @@ pub struct GenerateKeyCommand {
 }
 
 impl AppCommand<AppContext<Init>> for GenerateKeyCommand {
-    type Output = KeyResult;
-
-    fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Value, Error> {
         let mnemonic: GeneratedKey<_, miniscript::BareCtx> =
             Mnemonic::generate((self.word_count.into(), Language::English))
                 .map_err(|_| Error::Generic("Mnemonic generation error".to_string()))?;
-        derive_master_key_from_mnemonic(mnemonic.into_key(), self.password.clone(), ctx.network)
+        let mnemonic = mnemonic.into_key();
+        let (xprv, fingerprint) =
+            derive_master_key_from_mnemonic(&mnemonic, self.password.clone(), ctx.network)?;
+
+        Ok(json!({
+            "xprv": xprv.to_string(),
+            "mnemonic": mnemonic.to_string(),
+            "fingerprint": fingerprint.to_string(),
+        }))
     }
 }
 
@@ -84,9 +91,7 @@ pub struct DeriveKeyCommand {
 }
 
 impl AppCommand<AppContext<Init>> for DeriveKeyCommand {
-    type Output = KeyResult;
-
-    fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Value, Error> {
         let secp = Secp256k1::new();
 
         let derived_xprv = &self.xprv.derive_priv(&secp, &self.path)?;
@@ -105,12 +110,10 @@ impl AppCommand<AppContext<Init>> for DeriveKeyCommand {
         if let DescriptorKey::Secret(desc_seckey, _, _) = derived_xprv_desc_key {
             let desc_pubkey = desc_seckey.to_public(&secp)?;
 
-            Ok(KeyResult {
-                xprv: desc_seckey.to_string(),
-                xpub: Some(desc_pubkey.to_string()),
-                mnemonic: None,
-                fingerprint: None,
-            })
+            Ok(json!({
+                "xprv": desc_seckey.to_string(),
+                "xpub": desc_pubkey.to_string(),
+            }))
         } else {
             Err(Error::Generic(
                 "Derived key is not a secret key".to_string(),
@@ -130,20 +133,25 @@ pub struct RestoreKeyCommand {
 }
 
 impl AppCommand<AppContext<Init>> for RestoreKeyCommand {
-    type Output = KeyResult;
-
-    fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Value, Error> {
         let mnemonic = Mnemonic::parse_in(Language::English, &self.mnemonic)?;
-        derive_master_key_from_mnemonic(mnemonic, self.password.clone(), ctx.network)
+        let (xprv, fingerprint) =
+            derive_master_key_from_mnemonic(&mnemonic, self.password.clone(), ctx.network)?;
+
+        Ok(json!({
+            "xprv": xprv.to_string(),
+            "mnemonic": mnemonic.to_string(),
+            "fingerprint": fingerprint.to_string(),
+        }))
     }
 }
 
 /// Derives the master key from a mnemonic and optional passphrase.
 fn derive_master_key_from_mnemonic(
-    mnemonic: Mnemonic,
+    mnemonic: &Mnemonic,
     password: Option<String>,
     network: Network,
-) -> Result<KeyResult, Error> {
+) -> Result<(Xpriv, Fingerprint), Error> {
     let secp = Secp256k1::new();
     let xkey: ExtendedKey = (mnemonic.clone(), password).into_extended_key()?;
     let xprv = xkey
@@ -151,10 +159,5 @@ fn derive_master_key_from_mnemonic(
         .ok_or_else(|| Error::Generic("Private key info not found".to_string()))?;
     let fingerprint = xprv.fingerprint(&secp);
 
-    Ok(KeyResult {
-        xprv: xprv.to_string(),
-        mnemonic: Some(mnemonic.to_string()),
-        fingerprint: Some(fingerprint.to_string()),
-        xpub: None,
-    })
+    Ok((xprv, fingerprint))
 }
index bf8be129a32b99aca0999fc6954950ceacd2b13f..eb2fbe539eb9af861c83c747257b20f1f5bfdd12 100644 (file)
@@ -25,8 +25,9 @@ pub mod repl;
 use crate::client::BlockchainClient;
 use std::path::PathBuf;
 
-use crate::{error::BDKCliError as Error, utils::output::FormatOutput};
+use crate::error::BDKCliError as Error;
 use bdk_wallet::{Wallet, bitcoin::Network};
+use serde_json::Value;
 
 // The state for no wallet, no client.
 pub struct Init;
@@ -105,9 +106,7 @@ impl<'a> AppContext<OnlineOperations<'a>> {
 }
 
 pub trait AppCommand<C> {
-    type Output: FormatOutput;
-
-    fn execute(&self, ctx: &mut C) -> Result<Self::Output, Error>;
+    fn execute(&self, ctx: &mut C) -> Result<Value, Error>;
 }
 
 #[cfg(any(
@@ -119,9 +118,7 @@ pub trait AppCommand<C> {
     feature = "hwi"
 ))]
 pub trait AsyncAppCommand<C> {
-    type Output: FormatOutput;
-
-    async fn execute(&self, ctx: &mut C) -> Result<Self::Output, Error>;
+    async fn execute(&self, ctx: &mut C) -> Result<Value, Error>;
 }
 
 #[cfg(test)]
index 9aa15fcb9fc1c63f0fe8ad8056c4980f9f5dc04a..31aee423decfe33d775da4a164aa806fd189bd97 100644 (file)
@@ -1,22 +1,17 @@
 use crate::commands::OfflineWalletSubCommand;
 use crate::error::BDKCliError as Error;
 use crate::handlers::{AppCommand, AppContext, OfflineOperations};
-use crate::utils::output::{FormatOutput, ListResult};
-use crate::utils::types::{
-    AddressResult, BalanceResult, KeychainPair, PsbtResult, RawPsbt, TransactionDetails,
-    UnspentDetails,
-};
+use crate::utils::output::FormatOutput;
 use crate::utils::{
     check_standard_weight, max_signed_weight, parse_address, parse_fee_rate,
     parse_op_return_base64, parse_op_return_string, parse_outpoint, parse_recipient,
 };
-use bdk_wallet::bitcoin::base64::Engine;
-use bdk_wallet::bitcoin::base64::prelude::BASE64_STANDARD;
-use bdk_wallet::bitcoin::script::PushBytesBuf;
+use bdk_wallet::bitcoin::base64::{Engine, prelude::BASE64_STANDARD};
 use bdk_wallet::bitcoin::{Address, Amount, FeeRate, OutPoint, Psbt, ScriptBuf, Sequence, Txid};
+use bdk_wallet::bitcoin::{consensus::encode::serialize_hex, script::PushBytesBuf};
 use bdk_wallet::{KeychainKind, SignOptions};
 use clap::Parser;
-use serde_json::json;
+use serde_json::{Value, json};
 use std::collections::BTreeMap;
 #[cfg(feature = "silent-payments")]
 use {
@@ -33,7 +28,6 @@ use {
 #[cfg(feature = "message_signer")]
 use {
     crate::utils::parse_signature_format,
-    crate::utils::types::MessageResult,
     bdk_message_signer::{MessageProof, MessageSigner},
 };
 
@@ -100,12 +94,13 @@ impl OfflineWalletSubCommand {
 pub struct NewAddressCommand;
 
 impl AppCommand<AppContext<OfflineOperations<'_>>> for NewAddressCommand {
-    type Output = AddressResult;
-
-    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
         let wallet = &mut ctx.state.wallet;
         let address_info = wallet.reveal_next_address(KeychainKind::External);
-        Ok(AddressResult::from(address_info))
+        Ok(json!({
+            "address": address_info.address.to_string(),
+            "index": address_info.index,
+        }))
     }
 }
 
@@ -113,12 +108,13 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for NewAddressCommand {
 pub struct UnusedAddressCommand;
 
 impl AppCommand<AppContext<OfflineOperations<'_>>> for UnusedAddressCommand {
-    type Output = AddressResult;
-
-    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
         let wallet = &mut ctx.state.wallet;
         let address_info = wallet.next_unused_address(KeychainKind::External);
-        Ok(AddressResult::from(address_info))
+        Ok(json!({
+            "address": address_info.address.to_string(),
+            "index": address_info.index,
+        }))
     }
 }
 
@@ -126,20 +122,25 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for UnusedAddressCommand {
 pub struct UnspentCommand;
 
 impl AppCommand<AppContext<OfflineOperations<'_>>> for UnspentCommand {
-    type Output = ListResult<UnspentDetails>;
-
-    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
         let wallet = &mut ctx.state.wallet;
         let outputs: Vec<_> = wallet.list_unspent().collect();
-        let utxos = outputs
+        let utxos: Vec<Value> = outputs
             .into_iter()
             .map(|utxo| {
-                let is_locked = wallet.is_outpoint_locked(utxo.outpoint);
-                UnspentDetails::from_local_output(&utxo, ctx.network, is_locked)
+                json!({
+                    "outpoint": utxo.outpoint.to_string(),
+                    "txout": utxo.txout,
+                    "keychain": format!("{:?}", utxo.keychain),
+                    "is_spent": utxo.is_spent,
+                    "derivation_index": utxo.derivation_index,
+                    "chain_position": utxo.chain_position,
+                    "is_locked": wallet.is_outpoint_locked(utxo.outpoint),
+                })
             })
             .collect();
 
-        Ok(ListResult::new(utxos))
+        Ok(json!({ "count": utxos.len(), "items": utxos }))
     }
 }
 
@@ -147,37 +148,24 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for UnspentCommand {
 pub struct TransactionsCommand;
 
 impl AppCommand<AppContext<OfflineOperations<'_>>> for TransactionsCommand {
-    type Output = ListResult<TransactionDetails>;
-
-    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
         let transactions = &mut ctx.state.wallet.transactions();
 
-        let txns: Vec<TransactionDetails> = transactions
+        let txns: Vec<Value> = transactions
             .map(|tx| {
-                let total_value = tx
-                    .tx_node
-                    .output
-                    .iter()
-                    .map(|output| output.value.to_sat())
-                    .sum::<u64>();
-
-                TransactionDetails {
-                    txid: tx.tx_node.txid.to_string(),
-                    is_coinbase: tx.tx_node.is_coinbase(),
-                    wtxid: tx.tx_node.compute_wtxid().to_string(),
-                    version: serde_json::to_value(tx.tx_node.version).unwrap_or(json!(1)),
-                    version_display: tx.tx_node.version.to_string(),
-                    is_rbf: tx.tx_node.is_explicitly_rbf(),
-                    inputs: serde_json::to_value(&tx.tx_node.input).unwrap_or_default(),
-                    outputs: serde_json::to_value(&tx.tx_node.output).unwrap_or_default(),
-                    input_count: tx.tx_node.input.len(),
-                    output_count: tx.tx_node.output.len(),
-                    total_value,
-                }
+                json!({
+                    "txid": tx.tx_node.txid.to_string(),
+                   "is_coinbase": tx.tx_node.is_coinbase(),
+                    "wtxid": tx.tx_node.compute_wtxid().to_string(),
+                    "version": tx.tx_node.version,
+                    "is_rbf": tx.tx_node.is_explicitly_rbf(),
+                    "inputs": tx.tx_node.input,
+                    "outputs": tx.tx_node.output,
+                })
             })
             .collect();
 
-        Ok(ListResult::new(txns))
+        Ok(json!({ "count": txns.len(), "items": txns }))
     }
 }
 
@@ -185,11 +173,15 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for TransactionsCommand {
 pub struct BalanceCommand;
 
 impl AppCommand<AppContext<OfflineOperations<'_>>> for BalanceCommand {
-    type Output = BalanceResult;
-
-    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
         let balance = ctx.state.wallet.balance();
-        Ok(BalanceResult::from(balance))
+        Ok(json!({
+            "total": balance.total().to_sat(),
+            "trusted_pending": balance.trusted_pending.to_sat(),
+            "untrusted_pending": balance.untrusted_pending.to_sat(),
+            "immature": balance.immature.to_sat(),
+            "confirmed": balance.confirmed.to_sat(),
+        }))
     }
 }
 #[derive(Debug, Parser, Clone, PartialEq)]
@@ -252,9 +244,7 @@ pub struct CreateTxCommand {
 }
 
 impl AppCommand<AppContext<OfflineOperations<'_>>> for CreateTxCommand {
-    type Output = PsbtResult;
-
-    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
         let mut tx_builder = ctx.state.wallet.build_tx();
 
         if self.send_all {
@@ -319,7 +309,7 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for CreateTxCommand {
 
         check_standard_weight(max_signed_weight(ctx.state.wallet, &psbt)?)?;
 
-        Ok(PsbtResult::new(&psbt, Some(false)))
+        Ok(json!({ "psbt": psbt.to_string(), "is_finalized": false }))
     }
 }
 
@@ -377,9 +367,7 @@ pub struct CreateSpTxCommand {
 
 #[cfg(feature = "silent-payments")]
 impl AppCommand<AppContext<OfflineOperations<'_>>> for CreateSpTxCommand {
-    type Output = RawPsbt;
-
-    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
         let mut tx_builder = ctx.state.wallet.build_tx();
 
         let sp_recipients: Vec<SilentPaymentCode> = self
@@ -539,7 +527,7 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for CreateSpTxCommand {
 
         let raw_tx = psbt.extract_tx()?;
 
-        Ok(RawPsbt::new(&raw_tx))
+        Ok(json!({ "raw_tx": serialize_hex(&raw_tx) }))
     }
 }
 
@@ -577,9 +565,7 @@ pub struct BumpFeeCommand {
 }
 
 impl AppCommand<AppContext<OfflineOperations<'_>>> for BumpFeeCommand {
-    type Output = PsbtResult;
-
-    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
         let wallet = &mut ctx.state.wallet;
 
         let mut tx_builder = wallet.build_fee_bump(self.txid)?;
@@ -606,7 +592,7 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for BumpFeeCommand {
 
         check_standard_weight(max_signed_weight(wallet, &psbt)?)?;
 
-        Ok(PsbtResult::new(&psbt, Some(false)))
+        Ok(json!({ "psbt": psbt.to_string(), "is_finalized": false }))
     }
 }
 
@@ -614,17 +600,12 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for BumpFeeCommand {
 pub struct PoliciesCommand;
 
 impl AppCommand<AppContext<OfflineOperations<'_>>> for PoliciesCommand {
-    type Output = KeychainPair<serde_json::Value>;
-
-    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
         let wallet = &mut ctx.state.wallet;
         let external_policy = wallet.policies(KeychainKind::External)?;
         let internal_policy = wallet.policies(KeychainKind::Internal)?;
 
-        Ok(KeychainPair {
-            external: serde_json::to_value(&external_policy).unwrap_or(serde_json::json!(null)),
-            internal: serde_json::to_value(&internal_policy).unwrap_or(serde_json::json!(null)),
-        })
+        Ok(json!({ "external": external_policy, "internal": internal_policy }))
     }
 }
 
@@ -632,14 +613,12 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for PoliciesCommand {
 pub struct PublicDescriptorCommand;
 
 impl AppCommand<AppContext<OfflineOperations<'_>>> for PublicDescriptorCommand {
-    type Output = KeychainPair<String>;
-
-    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
         let wallet = &mut ctx.state.wallet;
-        Ok(KeychainPair {
-            external: wallet.public_descriptor(KeychainKind::External).to_string(),
-            internal: wallet.public_descriptor(KeychainKind::Internal).to_string(),
-        })
+        Ok(json!({
+            "external": wallet.public_descriptor(KeychainKind::External).to_string(),
+            "internal": wallet.public_descriptor(KeychainKind::Internal).to_string(),
+        }))
     }
 }
 
@@ -659,9 +638,7 @@ pub struct SignCommand {
 }
 
 impl AppCommand<AppContext<OfflineOperations<'_>>> for SignCommand {
-    type Output = PsbtResult;
-
-    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
         let wallet = &mut ctx.state.wallet;
         let psbt_bytes = BASE64_STANDARD.decode(&self.psbt)?;
         let mut psbt = Psbt::deserialize(&psbt_bytes)?;
@@ -672,7 +649,7 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for SignCommand {
             ..Default::default()
         };
         let finalized = wallet.sign(&mut psbt, signopt)?;
-        Ok(PsbtResult::new(&psbt, Some(finalized)))
+        Ok(json!({ "psbt": psbt.to_string(), "is_finalized": finalized }))
     }
 }
 
@@ -684,14 +661,12 @@ pub struct ExtractPsbtCommand {
 }
 
 impl AppCommand<AppContext<OfflineOperations<'_>>> for ExtractPsbtCommand {
-    type Output = RawPsbt;
-
-    fn execute(&self, _ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+    fn execute(&self, _ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
         let psbt_serialized = BASE64_STANDARD.decode(self.psbt.clone())?;
         let psbt = Psbt::deserialize(&psbt_serialized)?;
         let raw_tx = psbt.extract_tx()?;
 
-        Ok(RawPsbt::new(&raw_tx))
+        Ok(json!({ "raw_tx": serialize_hex(&raw_tx) }))
     }
 }
 
@@ -711,9 +686,7 @@ pub struct FinalizePsbtCommand {
 }
 
 impl AppCommand<AppContext<OfflineOperations<'_>>> for FinalizePsbtCommand {
-    type Output = PsbtResult;
-
-    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
         let wallet = &mut ctx.state.wallet;
         let psbt_bytes = BASE64_STANDARD.decode(&self.psbt)?;
         let mut psbt = Psbt::deserialize(&psbt_bytes)?;
@@ -726,7 +699,7 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for FinalizePsbtCommand {
 
         let finalized = wallet.finalize_psbt(&mut psbt, signopt)?;
 
-        Ok(PsbtResult::new(&psbt, Some(finalized)))
+        Ok(json!({ "psbt": psbt.to_string(), "is_finalized": finalized }))
     }
 }
 
@@ -738,9 +711,7 @@ pub struct CombinePsbtCommand {
 }
 
 impl AppCommand<AppContext<OfflineOperations<'_>>> for CombinePsbtCommand {
-    type Output = PsbtResult;
-
-    fn execute(&self, _ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+    fn execute(&self, _ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
         let mut psbts = self
             .psbt
             .iter()
@@ -761,7 +732,7 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for CombinePsbtCommand {
                     Ok(acc)
                 })?;
 
-        Ok(PsbtResult::new(&final_psbt, Some(false)))
+        Ok(json!({ "psbt": final_psbt.to_string(), "is_finalized": false }))
     }
 }
 
@@ -787,9 +758,7 @@ pub struct SignMessageCommand {
 
 #[cfg(feature = "message_signer")]
 impl AppCommand<AppContext<OfflineOperations<'_>>> for SignMessageCommand {
-    type Output = MessageResult;
-
-    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
         let wallet = &mut ctx.state.wallet;
         let address: Address = parse_address(&self.address)?;
         let signature_format = parse_signature_format(&self.signature_type)?;
@@ -808,10 +777,7 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for SignMessageCommand {
             self.utxos.clone(),
         )?;
 
-        Ok(MessageResult {
-            proof: Some(proof.to_base64()),
-            ..Default::default()
-        })
+        Ok(json!({ "proof": proof.to_base64() }))
     }
 }
 
@@ -833,9 +799,7 @@ pub struct VerifyMessageCommand {
 
 #[cfg(feature = "message_signer")]
 impl AppCommand<AppContext<OfflineOperations<'_>>> for VerifyMessageCommand {
-    type Output = MessageResult;
-
-    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
         let wallet = &ctx.state.wallet;
 
         let address: Address = parse_address(&self.address)?;
@@ -845,11 +809,11 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for VerifyMessageCommand {
 
         let is_valid = wallet.verify_message(&parsed_proof, &self.message, &address)?;
 
-        Ok(MessageResult {
-            valid: Some(is_valid.valid),
-            proven_amount: is_valid.proven_amount.map(|a| a.to_sat()),
-            ..Default::default()
-        })
+        let mut output = json!({ "valid": is_valid.valid });
+        if let Some(amount) = is_valid.proven_amount {
+            output["proven_amount"] = json!(amount.to_sat());
+        }
+        Ok(output)
     }
 }
 
@@ -861,8 +825,7 @@ pub struct LockUtxoCommand {
 }
 
 impl AppCommand<AppContext<OfflineOperations<'_>>> for LockUtxoCommand {
-    type Output = ListResult<String>;
-    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
         let wallet = &mut ctx.state.wallet;
         for out_point in &self.utxos {
             if wallet.get_utxo(*out_point).is_none() {
@@ -871,11 +834,11 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for LockUtxoCommand {
             }
             wallet.lock_outpoint(*out_point);
         }
-        let locked = wallet
+        let locked: Vec<String> = wallet
             .list_locked_outpoints()
             .map(|o| o.to_string())
             .collect();
-        Ok(ListResult::new(locked))
+        Ok(json!({ "count": locked.len(), "items": locked }))
     }
 }
 
@@ -887,17 +850,16 @@ pub struct UnlockUtxoCommand {
 }
 
 impl AppCommand<AppContext<OfflineOperations<'_>>> for UnlockUtxoCommand {
-    type Output = ListResult<String>;
-    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
         let wallet = &mut ctx.state.wallet;
         for out_point in &self.utxos {
             wallet.unlock_outpoint(*out_point);
         }
-        let locked = wallet
+        let locked: Vec<String> = wallet
             .list_locked_outpoints()
             .map(|o| o.to_string())
             .collect();
-        Ok(ListResult::new(locked))
+        Ok(json!({ "count": locked.len(), "items": locked }))
     }
 }
 
@@ -905,13 +867,12 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for UnlockUtxoCommand {
 pub struct LockedUtxosCommand {}
 
 impl AppCommand<AppContext<OfflineOperations<'_>>> for LockedUtxosCommand {
-    type Output = ListResult<String>;
-    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+    fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
         let wallet = &mut ctx.state.wallet;
-        let locked = wallet
+        let locked: Vec<String> = wallet
             .list_locked_outpoints()
             .map(|o| o.to_string())
             .collect();
-        Ok(ListResult::new(locked))
+        Ok(json!({ "count": locked.len(), "items": locked }))
     }
 }
index 15ac2aee8754d6eafab15825e9fde3c30745e399..7e11d84cf1e89cd62d8f89c1d020551ee4b4f11c 100644 (file)
@@ -28,15 +28,12 @@ use {
     crate::commands::OnlineWalletSubCommand,
     crate::error::BDKCliError as Error,
     crate::handlers::{AppContext, AsyncAppCommand, OnlineOperations, payjoin::PayjoinManager},
-    crate::utils::{
-        is_final,
-        output::FormatOutput,
-        types::{StatusResult, TransactionResult},
-    },
+    crate::utils::{is_final, output::FormatOutput},
     bdk_wallet::bitcoin::{
         Psbt, Transaction, Txid, base64::Engine, base64::prelude::BASE64_STANDARD,
         consensus::Decodable, hex::FromHex,
     },
+    serde_json::{Value, json},
 };
 #[cfg(any(
     feature = "electrum",
@@ -47,33 +44,37 @@ use {
 impl OnlineWalletSubCommand {
     pub async fn execute(&self, ctx: &mut AppContext<OnlineOperations<'_>>) -> Result<(), Error> {
         match self {
-            OnlineWalletSubCommand::FullScan(full_scan_command) => {
-                let response: StatusResult = full_scan_command.execute(ctx).await?;
-                response.write_out(std::io::stdout())
-            }
-            OnlineWalletSubCommand::Sync(sync_command) => {
-                let response: StatusResult = sync_command.execute(ctx).await?;
-                response.write_out(std::io::stdout())
-            }
-            OnlineWalletSubCommand::Broadcast(broadcast_command) => {
-                let response: TransactionResult = broadcast_command.execute(ctx).await?;
-                response.write_out(std::io::stdout())
-            }
+            OnlineWalletSubCommand::FullScan(full_scan_command) => full_scan_command
+                .execute(ctx)
+                .await?
+                .write_out(std::io::stdout()),
+            OnlineWalletSubCommand::Sync(sync_command) => sync_command
+                .execute(ctx)
+                .await?
+                .write_out(std::io::stdout()),
+            OnlineWalletSubCommand::Broadcast(broadcast_command) => broadcast_command
+                .execute(ctx)
+                .await?
+                .write_out(std::io::stdout()),
             OnlineWalletSubCommand::ReceivePayjoin(receive_payjoin_command) => {
-                let response: StatusResult = receive_payjoin_command.execute(ctx).await?;
-                response.write_out(std::io::stdout())
-            }
-            OnlineWalletSubCommand::SendPayjoin(send_payjoin_command) => {
-                let response: StatusResult = send_payjoin_command.execute(ctx).await?;
-                response.write_out(std::io::stdout())
-            }
-            OnlineWalletSubCommand::ResumePayjoin(resume_payjoin_command) => {
-                let response: StatusResult = resume_payjoin_command.execute(ctx).await?;
-                response.write_out(std::io::stdout())
+                receive_payjoin_command
+                    .execute(ctx)
+                    .await?
+                    .write_out(std::io::stdout())
             }
+            OnlineWalletSubCommand::SendPayjoin(send_payjoin_command) => send_payjoin_command
+                .execute(ctx)
+                .await?
+                .write_out(std::io::stdout()),
+            OnlineWalletSubCommand::ResumePayjoin(resume_payjoin_command) => resume_payjoin_command
+                .execute(ctx)
+                .await?
+                .write_out(std::io::stdout()),
             OnlineWalletSubCommand::PayjoinHistory(payjoin_history_command) => {
-                let response: StatusResult = payjoin_history_command.execute(ctx).await?;
-                response.write_out(std::io::stdout())
+                payjoin_history_command
+                    .execute(ctx)
+                    .await?
+                    .write_out(std::io::stdout())
             }
         }
     }
@@ -143,12 +144,7 @@ impl FullScanCommand {
     feature = "rpc"
 ))]
 impl AsyncAppCommand<AppContext<OnlineOperations<'_>>> for FullScanCommand {
-    type Output = StatusResult;
-
-    async fn execute(
-        &self,
-        ctx: &mut AppContext<OnlineOperations<'_>>,
-    ) -> Result<Self::Output, Error> {
+    async fn execute(&self, ctx: &mut AppContext<OnlineOperations<'_>>) -> Result<Value, Error> {
         let wallet = &mut ctx.state.wallet;
         let client = ctx.state.client;
 
@@ -242,9 +238,7 @@ impl AsyncAppCommand<AppContext<OnlineOperations<'_>>> for FullScanCommand {
                 sync_kyoto_client(wallet, client).await?;
             }
         }
-        Ok(StatusResult {
-            message: "Full scan completed successfully.".to_string(),
-        })
+        Ok(json!({ "message": "Full scan completed successfully." }))
     }
 }
 
@@ -279,12 +273,7 @@ pub struct SyncCommand;
     feature = "rpc"
 ))]
 impl AsyncAppCommand<AppContext<OnlineOperations<'_>>> for SyncCommand {
-    type Output = StatusResult;
-
-    async fn execute(
-        &self,
-        ctx: &mut AppContext<OnlineOperations<'_>>,
-    ) -> Result<Self::Output, Error> {
+    async fn execute(&self, ctx: &mut AppContext<OnlineOperations<'_>>) -> Result<Value, Error> {
         let wallet = &mut ctx.state.wallet;
         let client = ctx.state.client;
         #[cfg(any(feature = "electrum", feature = "esplora"))]
@@ -371,9 +360,7 @@ impl AsyncAppCommand<AppContext<OnlineOperations<'_>>> for SyncCommand {
             #[cfg(feature = "cbf")]
             KyotoClient { client } => sync_kyoto_client(wallet, client).await?,
         }
-        Ok(StatusResult {
-            message: "Wallet synced successfully.".to_string(),
-        })
+        Ok(json!({ "message": "Wallet synced successfully." }))
     }
 }
 
@@ -404,12 +391,7 @@ pub struct BroadcastCommand {
     feature = "rpc"
 ))]
 impl AsyncAppCommand<AppContext<OnlineOperations<'_>>> for BroadcastCommand {
-    type Output = TransactionResult;
-
-    async fn execute(
-        &self,
-        ctx: &mut AppContext<OnlineOperations<'_>>,
-    ) -> Result<Self::Output, Error> {
+    async fn execute(&self, ctx: &mut AppContext<OnlineOperations<'_>>) -> Result<Value, Error> {
         let client = ctx.state.client;
 
         let tx = match (&self.psbt, &self.tx) {
@@ -437,9 +419,7 @@ impl AsyncAppCommand<AppContext<OnlineOperations<'_>>> for BroadcastCommand {
 
         let txid: Txid = client.broadcast(tx).await?;
 
-        Ok(TransactionResult {
-            txid: txid.to_string(),
-        })
+        Ok(json!({ "txid": txid.to_string() }))
     }
 }
 
@@ -468,12 +448,7 @@ pub struct ReceivePayjoinCommand {
     feature = "rpc"
 ))]
 impl AsyncAppCommand<AppContext<OnlineOperations<'_>>> for ReceivePayjoinCommand {
-    type Output = StatusResult;
-
-    async fn execute(
-        &self,
-        ctx: &mut AppContext<OnlineOperations<'_>>,
-    ) -> Result<Self::Output, Error> {
+    async fn execute(&self, ctx: &mut AppContext<OnlineOperations<'_>>) -> Result<Value, Error> {
         let wallet_name = ctx.state.wallet_name.clone();
         let datadir = ctx.datadir.clone();
         let wallet = &mut ctx.state.wallet;
@@ -490,7 +465,7 @@ impl AsyncAppCommand<AppContext<OnlineOperations<'_>>> for ReceivePayjoinCommand
             )
             .await?;
 
-        Ok(StatusResult { message: result })
+        Ok(json!({ "message": result }))
     }
 }
 
@@ -520,12 +495,7 @@ pub struct SendPayjoinCommand {
     feature = "rpc"
 ))]
 impl AsyncAppCommand<AppContext<OnlineOperations<'_>>> for SendPayjoinCommand {
-    type Output = StatusResult;
-
-    async fn execute(
-        &self,
-        ctx: &mut AppContext<OnlineOperations<'_>>,
-    ) -> Result<Self::Output, Error> {
+    async fn execute(&self, ctx: &mut AppContext<OnlineOperations<'_>>) -> Result<Value, Error> {
         let wallet_name = ctx.state.wallet_name.clone();
         let datadir = ctx.datadir.clone();
         let wallet = &mut ctx.state.wallet;
@@ -541,7 +511,7 @@ impl AsyncAppCommand<AppContext<OnlineOperations<'_>>> for SendPayjoinCommand {
             )
             .await?;
 
-        Ok(StatusResult { message: result })
+        Ok(json!({ "message": result }))
     }
 }
 
@@ -565,12 +535,7 @@ pub struct ResumePayjoinCommand {
     feature = "rpc"
 ))]
 impl AsyncAppCommand<AppContext<OnlineOperations<'_>>> for ResumePayjoinCommand {
-    type Output = StatusResult;
-
-    async fn execute(
-        &self,
-        ctx: &mut AppContext<OnlineOperations<'_>>,
-    ) -> Result<Self::Output, Error> {
+    async fn execute(&self, ctx: &mut AppContext<OnlineOperations<'_>>) -> Result<Value, Error> {
         let wallet_name = ctx.state.wallet_name.clone();
         let datadir = ctx.datadir.clone();
         let wallet = &mut ctx.state.wallet;
@@ -586,7 +551,7 @@ impl AsyncAppCommand<AppContext<OnlineOperations<'_>>> for ResumePayjoinCommand
             )
             .await?;
 
-        Ok(StatusResult { message: result })
+        Ok(json!({ "message": result }))
     }
 }
 
@@ -600,17 +565,12 @@ pub struct PayjoinHistoryCommand;
     feature = "rpc"
 ))]
 impl AsyncAppCommand<AppContext<OnlineOperations<'_>>> for PayjoinHistoryCommand {
-    type Output = StatusResult;
-
-    async fn execute(
-        &self,
-        ctx: &mut AppContext<OnlineOperations<'_>>,
-    ) -> Result<Self::Output, Error> {
+    async fn execute(&self, ctx: &mut AppContext<OnlineOperations<'_>>) -> Result<Value, Error> {
         let wallet_name = ctx.state.wallet_name.clone();
         let datadir = ctx.datadir.clone();
 
         let result = PayjoinManager::history(Some(datadir), &wallet_name)?;
 
-        Ok(StatusResult { message: result })
+        Ok(json!({ "message": result }))
     }
 }
index 15e8bca7b26e19a7ddebd64aab6e712e089aefa5..fd34aa3f08429c6bff1a9891bd768d8681d53945 100644 (file)
@@ -25,26 +25,33 @@ use bdk_wallet::{
     bip39::{Language, Mnemonic},
     bitcoin::{
         NetworkKind,
-        bip32::{DerivationPath, Xpriv, Xpub},
+        bip32::{DerivationPath, Fingerprint, Xpriv, Xpub},
         secp256k1::Secp256k1,
     },
     keys::{GeneratedKey, bip39::WordCount},
     miniscript::{
         Descriptor, Miniscript, Segwitv0, Terminal,
-        descriptor::{DescriptorXKey, Wildcard},
+        descriptor::{DescriptorXKey, KeyMap, Wildcard},
     },
     template::DescriptorTemplate,
 };
 
 use crate::error::BDKCliError as Error;
-use crate::utils::types::DescriptorResult;
-use crate::utils::types::KeychainPair;
+
+/// External and internal descriptors generated from a single key.
+pub struct KeychainDescriptors {
+    pub external: Descriptor<DescriptorPublicKey>,
+    pub internal: Descriptor<DescriptorPublicKey>,
+    /// Secret keys for both descriptors; empty when generated from an xpub.
+    pub keymap: KeyMap,
+    pub fingerprint: Fingerprint,
+}
 
 pub fn generate_descriptors(
     desc_type: &str,
     key: &str,
     network: NetworkKind,
-) -> Result<DescriptorResult, Error> {
+) -> Result<KeychainDescriptors, Error> {
     let is_private = key.starts_with("xprv") || key.starts_with("tprv");
 
     if is_private {
@@ -71,7 +78,7 @@ fn generate_private_descriptors(
     desc_type: &str,
     key: &str,
     network: NetworkKind,
-) -> Result<DescriptorResult, Error> {
+) -> Result<KeychainDescriptors, Error> {
     use bdk_wallet::template::{Bip44, Bip49, Bip84, Bip86};
 
     let secp = Secp256k1::new();
@@ -102,25 +109,14 @@ fn generate_private_descriptors(
         }
     };
 
-    let external_priv = external_desc.to_string_with_secret(&external_keymap);
-    let external_pub = external_desc.to_string();
-    let internal_priv = internal_desc.to_string_with_secret(&internal_keymap);
-    let internal_pub = internal_desc.to_string();
-
-    Ok(DescriptorResult {
-        descriptor: None,
-        multipath_descriptor: None,
-        public_descriptors: Some(KeychainPair {
-            external: external_pub,
-            internal: internal_pub,
-        }),
-        private_descriptors: Some(KeychainPair {
-            external: external_priv,
-            internal: internal_priv,
-        }),
-        mnemonic: None,
-        fingerprint: Some(fingerprint.to_string()),
-        r: None,
+    let mut keymap = external_keymap;
+    keymap.extend(internal_keymap);
+
+    Ok(KeychainDescriptors {
+        external: external_desc,
+        internal: internal_desc,
+        keymap,
+        fingerprint,
     })
 }
 
@@ -129,11 +125,11 @@ pub fn generate_public_descriptors(
     desc_type: &str,
     key: &str,
     derivation_path: &DerivationPath,
-) -> Result<DescriptorResult, Error> {
+) -> Result<KeychainDescriptors, Error> {
     let xpub: Xpub = key.parse()?;
     let fingerprint = xpub.fingerprint();
 
-    let build_descriptor = |branch: &str| -> Result<String, Error> {
+    let build_descriptor = |branch: &str| -> Result<Descriptor<DescriptorPublicKey>, Error> {
         let branch_path = DerivationPath::from_str(branch)?;
         let desc_xpub = DescriptorXKey {
             origin: Some((fingerprint, derivation_path.clone())),
@@ -142,23 +138,14 @@ pub fn generate_public_descriptors(
             wildcard: Wildcard::Unhardened,
         };
         let desc_pub = DescriptorPublicKey::XPub(desc_xpub);
-        let descriptor = build_public_descriptor(desc_type, desc_pub)?;
-        Ok(descriptor.to_string())
+        build_public_descriptor(desc_type, desc_pub)
     };
 
-    let external_pub = build_descriptor("0")?;
-    let internal_pub = build_descriptor("1")?;
-    Ok(DescriptorResult {
-        descriptor: None,
-        multipath_descriptor: None,
-        public_descriptors: Some(KeychainPair {
-            external: external_pub,
-            internal: internal_pub,
-        }),
-        private_descriptors: None,
-        mnemonic: None,
-        fingerprint: Some(fingerprint.to_string()),
-        r: None,
+    Ok(KeychainDescriptors {
+        external: build_descriptor("0")?,
+        internal: build_descriptor("1")?,
+        keymap: KeyMap::new(),
+        fingerprint,
     })
 }
 
@@ -188,16 +175,15 @@ pub fn build_public_descriptor(
 pub fn generate_descriptor_with_mnemonic(
     network: NetworkKind,
     desc_type: &str,
-) -> Result<DescriptorResult, Error> {
+) -> Result<(Mnemonic, KeychainDescriptors), Error> {
     let mnemonic: GeneratedKey<Mnemonic, Segwitv0> =
         Mnemonic::generate((WordCount::Words12, Language::English)).map_err(Error::BIP39Error)?;
 
     let seed = mnemonic.to_seed("");
     let xprv = Xpriv::new_master(network, &seed)?;
 
-    let mut result = generate_descriptors(desc_type, &xprv.to_string(), network)?;
-    result.mnemonic = Some(mnemonic.to_string());
-    Ok(result)
+    let descriptors = generate_descriptors(desc_type, &xprv.to_string(), network)?;
+    Ok((mnemonic.into_key(), descriptors))
 }
 
 /// Generate descriptors from existing mnemonic
@@ -205,14 +191,12 @@ pub fn generate_descriptor_from_mnemonic(
     mnemonic_str: &str,
     network: NetworkKind,
     desc_type: &str,
-) -> Result<DescriptorResult, Error> {
+) -> Result<KeychainDescriptors, Error> {
     let mnemonic = Mnemonic::parse_in(Language::English, mnemonic_str)?;
     let seed = mnemonic.to_seed("");
     let xprv = Xpriv::new_master(network, &seed)?;
 
-    let mut result = generate_descriptors(desc_type, &xprv.to_string(), network)?;
-    result.mnemonic = Some(mnemonic_str.to_string());
-    Ok(result)
+    generate_descriptors(desc_type, &xprv.to_string(), network)
 }
 
 /// Returns the number of derivation paths in `descriptor`.
index 15138df5e7c033df626856181c53005e04e8543b..cf9cee13879e16a35d932d37bb14ccc4399d174c 100644 (file)
@@ -5,4 +5,3 @@ pub use common::*;
 #[cfg(feature = "hwi")]
 pub mod hwi;
 pub mod runtime;
-pub mod types;
index b2cd32a24233356e89c2525269266abd67a05096..efbd4ffe5d2425fbd176a1262ea60a590385a450 100644 (file)
@@ -19,19 +19,3 @@ pub trait FormatOutput: Serialize {
 }
 
 impl<T: Serialize> FormatOutput for T {}
-
-/// A generic wrapper for commands that return a list of items.
-#[derive(Serialize)]
-pub struct ListResult<T> {
-    pub count: usize,
-    pub items: Vec<T>,
-}
-
-impl<T> ListResult<T> {
-    pub fn new(items: Vec<T>) -> Self {
-        Self {
-            count: items.len(),
-            items,
-        }
-    }
-}
diff --git a/src/utils/types.rs b/src/utils/types.rs
deleted file mode 100644 (file)
index f6bd4cf..0000000
+++ /dev/null
@@ -1,207 +0,0 @@
-use std::collections::HashMap;
-
-use crate::config::WalletConfigInner;
-use bdk_wallet::Balance;
-use bdk_wallet::bitcoin::{
-    Network, Psbt, Transaction, base64::Engine, consensus::encode::serialize_hex,
-};
-use bdk_wallet::{AddressInfo, LocalOutput};
-use serde::Serialize;
-use serde_json::json;
-
-/// Represent address result
-#[derive(Serialize)]
-pub struct AddressResult {
-    pub address: String,
-    pub index: u32,
-}
-
-impl From<AddressInfo> for AddressResult {
-    fn from(info: AddressInfo) -> Self {
-        Self {
-            address: info.address.to_string(),
-            index: info.index,
-        }
-    }
-}
-
-#[allow(unused)]
-/// Represents the data for a single transaction
-#[derive(Serialize)]
-pub struct TransactionDetails {
-    pub txid: String,
-    pub is_coinbase: bool,
-    pub wtxid: String,
-    pub version: serde_json::Value,
-    pub is_rbf: bool,
-    pub inputs: serde_json::Value,
-    pub outputs: serde_json::Value,
-    #[serde(skip)]
-    pub version_display: String,
-    #[serde(skip)]
-    pub input_count: usize,
-    #[serde(skip)]
-    pub output_count: usize,
-    #[serde(skip)]
-    pub total_value: u64,
-}
-
-/// single UTXO
-#[derive(Serialize)]
-pub struct UnspentDetails {
-    pub outpoint: String,
-    pub txout: serde_json::Value,
-    pub keychain: String,
-    pub is_spent: bool,
-    pub derivation_index: u32,
-    pub chain_position: serde_json::Value,
-    pub is_locked: bool,
-}
-
-impl UnspentDetails {
-    pub fn from_local_output(utxo: &LocalOutput, _network: Network, is_locked: bool) -> Self {
-        let outpoint_str = utxo.outpoint.to_string();
-
-        Self {
-            outpoint: outpoint_str.clone(),
-            txout: serde_json::to_value(&utxo.txout).unwrap_or(json!({})),
-            keychain: format!("{:?}", utxo.keychain),
-            is_spent: utxo.is_spent,
-            derivation_index: utxo.derivation_index,
-            chain_position: serde_json::to_value(utxo.chain_position).unwrap_or(json!({})),
-            is_locked,
-        }
-    }
-}
-
-#[derive(Serialize)]
-pub struct PsbtResult {
-    pub psbt: String,
-
-    #[serde(skip_serializing_if = "Option::is_none")]
-    pub is_finalized: Option<bool>,
-}
-
-impl PsbtResult {
-    pub fn new(psbt: &Psbt, finalized: Option<bool>) -> Self {
-        Self {
-            psbt: bdk_wallet::bitcoin::base64::prelude::BASE64_STANDARD.encode(psbt.serialize()),
-            is_finalized: finalized,
-        }
-    }
-}
-
-#[derive(Serialize)]
-pub struct RawPsbt {
-    pub raw_tx: String,
-}
-
-impl RawPsbt {
-    pub fn new(tx: &Transaction) -> Self {
-        Self {
-            raw_tx: serialize_hex(tx),
-        }
-    }
-}
-
-#[derive(Serialize)]
-pub struct KeychainPair<T> {
-    pub external: T,
-    pub internal: T,
-}
-
-#[cfg(feature = "message_signer")]
-#[derive(Serialize, Debug, Default)]
-pub struct MessageResult {
-    #[serde(skip_serializing_if = "Option::is_none")]
-    pub proof: Option<String>,
-
-    #[serde(skip_serializing_if = "Option::is_none")]
-    pub valid: Option<bool>,
-
-    #[serde(skip_serializing_if = "Option::is_none")]
-    pub proven_amount: Option<u64>,
-}
-
-#[derive(Serialize, Debug)]
-pub struct StatusResult {
-    pub message: String,
-}
-
-#[cfg(any(
-    feature = "electrum",
-    feature = "esplora",
-    feature = "cbf",
-    feature = "rpc"
-))]
-#[derive(Serialize, Debug)]
-pub struct TransactionResult {
-    pub txid: String,
-}
-
-/// Return type definition
-#[derive(Serialize)]
-#[serde(transparent)]
-pub struct WalletsListResult(pub HashMap<String, WalletConfigInner>);
-
-/// return type
-#[derive(Serialize)]
-pub struct DescriptorResult {
-    #[serde(skip_serializing_if = "Option::is_none")]
-    pub descriptor: Option<String>,
-
-    #[serde(skip_serializing_if = "Option::is_none")]
-    pub multipath_descriptor: Option<String>,
-
-    #[serde(skip_serializing_if = "Option::is_none")]
-    pub public_descriptors: Option<KeychainPair<String>>,
-
-    #[serde(skip_serializing_if = "Option::is_none")]
-    pub private_descriptors: Option<KeychainPair<String>>,
-
-    #[serde(skip_serializing_if = "Option::is_none")]
-    pub mnemonic: Option<String>,
-
-    #[serde(skip_serializing_if = "Option::is_none")]
-    pub fingerprint: Option<String>,
-
-    /// Randomness factor `r` used to derive the taproot unspendable internal key (H + rG).
-    #[serde(skip_serializing_if = "Option::is_none")]
-    pub r: Option<String>,
-}
-
-#[derive(Serialize)]
-pub struct KeyResult {
-    pub xprv: String,
-
-    #[serde(skip_serializing_if = "Option::is_none")]
-    pub xpub: Option<String>,
-
-    #[serde(skip_serializing_if = "Option::is_none")]
-    pub mnemonic: Option<String>,
-
-    #[serde(skip_serializing_if = "Option::is_none")]
-    pub fingerprint: Option<String>,
-}
-
-/// Balance representation
-#[derive(Serialize)]
-pub struct BalanceResult {
-    pub total: u64,
-    pub trusted_pending: u64,
-    pub untrusted_pending: u64,
-    pub immature: u64,
-    pub confirmed: u64,
-}
-
-impl From<Balance> for BalanceResult {
-    fn from(b: Balance) -> Self {
-        Self {
-            total: b.total().to_sat(),
-            confirmed: b.confirmed.to_sat(),
-            trusted_pending: b.trusted_pending.to_sat(),
-            untrusted_pending: b.untrusted_pending.to_sat(),
-            immature: b.immature.to_sat(),
-        }
-    }
-}