Skip to content

Marketplace Listings API: buy, sell and verify listings #58

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jan 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 92 additions & 6 deletions node/src/bin/space-cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ use spaced::{
store::Sha256,
wallets::AddressKind,
};
use wallet::bitcoin::secp256k1::schnorr::Signature;
use wallet::export::WalletExport;
use wallet::Listing;

#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
Expand Down Expand Up @@ -174,6 +176,46 @@ enum Commands {
#[arg(long, short)]
fee_rate: u64,
},
/// Buy a space from the specified listing
#[command(name = "buy")]
Buy {
/// The space to buy
space: String,
/// The listing price
price: u64,
/// The seller's signature
#[arg(long)]
signature: String,
/// The seller's address
#[arg(long)]
seller: String,
/// Fee rate to use in sat/vB
#[arg(long, short)]
fee_rate: Option<u64>,
},
/// List a space you own for sale
#[command(name = "sell")]
Sell {
/// The space to sell
space: String,
/// Amount in satoshis
price: u64,
},
/// Verify a listing
#[command(name = "verifylisting")]
VerifyListing {
/// The space to buy
space: String,
/// The listing price
price: u64,
/// The seller's signature
#[arg(long)]
signature: String,
/// The seller's address
#[arg(long)]
seller: String,
},

/// Get a spaceout - a Bitcoin output relevant to the Spaces protocol.
#[command(name = "getspaceout")]
GetSpaceOut {
Expand Down Expand Up @@ -452,7 +494,7 @@ async fn handle_commands(
fee_rate,
false,
)
.await?
.await?
}
Commands::Bid {
space,
Expand All @@ -469,7 +511,7 @@ async fn handle_commands(
fee_rate,
confirmed_only,
)
.await?
.await?
}
Commands::CreateBidOuts { pairs, fee_rate } => {
cli.send_request(None, Some(pairs), fee_rate, false).await?
Expand All @@ -488,7 +530,7 @@ async fn handle_commands(
fee_rate,
false,
)
.await?
.await?
}
Commands::Transfer {
spaces,
Expand All @@ -505,7 +547,7 @@ async fn handle_commands(
fee_rate,
false,
)
.await?
.await?
}
Commands::SendCoins {
amount,
Expand All @@ -521,7 +563,7 @@ async fn handle_commands(
fee_rate,
false,
)
.await?
.await?
}
Commands::SetRawFallback {
mut space,
Expand Down Expand Up @@ -550,7 +592,7 @@ async fn handle_commands(
fee_rate,
false,
)
.await?;
.await?;
}
Commands::ListUnspent => {
let spaces = cli.client.wallet_list_unspent(&cli.wallet).await?;
Expand Down Expand Up @@ -614,6 +656,50 @@ async fn handle_commands(
hash_space(&space).map_err(|e| ClientError::Custom(e.to_string()))?
);
}
Commands::Buy { space, price, signature, seller, fee_rate } => {
let listing = Listing {
space: normalize_space(&space),
price,
seller,
signature: Signature::from_slice(hex::decode(signature)
.map_err(|_| ClientError::Custom("Signature must be in hex format".to_string()))?.as_slice())
.map_err(|_| ClientError::Custom("Invalid signature".to_string()))?,
};
let result = cli
.client
.wallet_buy(
&cli.wallet,
listing,
fee_rate.map(|rate| FeeRate::from_sat_per_vb(rate).expect("valid fee rate")),
cli.skip_tx_check,
).await?;
println!("{}", serde_json::to_string_pretty(&result).expect("result"));
}
Commands::Sell { space, price, } => {
let result = cli
.client
.wallet_sell(
&cli.wallet,
space,
price,
).await?;
println!("{}", serde_json::to_string_pretty(&result).expect("result"));
}
Commands::VerifyListing { space, price, signature, seller } => {
let listing = Listing {
space: normalize_space(&space),
price,
seller,
signature: Signature::from_slice(hex::decode(signature)
.map_err(|_| ClientError::Custom("Signature must be in hex format".to_string()))?.as_slice())
.map_err(|_| ClientError::Custom("Invalid signature".to_string()))?,
};

let result = cli
.client
.verify_listing(listing).await?;
println!("{}", serde_json::to_string_pretty(&result).expect("result"));
}
}

Ok(())
Expand Down
65 changes: 63 additions & 2 deletions node/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use tokio::{
sync::{broadcast, mpsc, oneshot, RwLock},
task::JoinSet,
};
use wallet::{bdk_wallet as bdk, bdk_wallet::template::Bip86, bitcoin::hashes::Hash, export::WalletExport, Balance, DoubleUtxo, WalletConfig, WalletDescriptors, WalletInfo, WalletOutput};
use wallet::{bdk_wallet as bdk, bdk_wallet::template::Bip86, bitcoin::hashes::Hash, export::WalletExport, Balance, DoubleUtxo, Listing, SpacesWallet, WalletConfig, WalletDescriptors, WalletInfo, WalletOutput};

use crate::{
checker::TxChecker,
Expand Down Expand Up @@ -95,6 +95,10 @@ pub enum ChainStateCommand {
target: usize,
resp: Responder<anyhow::Result<Vec<RolloutEntry>>>,
},
VerifyListing {
listing: Listing,
resp: Responder<anyhow::Result<()>>,
},
}

#[derive(Clone)]
Expand Down Expand Up @@ -181,6 +185,29 @@ pub trait Rpc {
skip_tx_check: bool,
) -> Result<Vec<TxResponse>, ErrorObjectOwned>;

#[method(name = "walletbuy")]
async fn wallet_buy(
&self,
wallet: &str,
listing: Listing,
fee_rate: Option<FeeRate>,
skip_tx_check: bool,
) -> Result<TxResponse, ErrorObjectOwned>;

#[method(name = "walletsell")]
async fn wallet_sell(
&self,
wallet: &str,
space: String,
amount: u64,
) -> Result<Listing, ErrorObjectOwned>;

#[method(name = "verifylisting")]
async fn verify_listing(
&self,
listing: Listing,
) -> Result<(), ErrorObjectOwned>;

#[method(name = "walletlisttransactions")]
async fn wallet_list_transactions(
&self,
Expand All @@ -199,7 +226,7 @@ pub trait Rpc {

#[method(name = "walletlistspaces")]
async fn wallet_list_spaces(&self, wallet: &str)
-> Result<ListSpacesResponse, ErrorObjectOwned>;
-> Result<ListSpacesResponse, ErrorObjectOwned>;

#[method(name = "walletlistunspent")]
async fn wallet_list_unspent(
Expand Down Expand Up @@ -754,6 +781,29 @@ impl RpcServer for RpcServerImpl {
.map_err(|error| ErrorObjectOwned::owned(-1, error.to_string(), None::<String>))
}

async fn wallet_buy(&self, wallet: &str, listing: Listing, fee_rate: Option<FeeRate>, skip_tx_check: bool) -> Result<TxResponse, ErrorObjectOwned> {
self.wallet(&wallet)
.await?
.send_buy(listing, fee_rate, skip_tx_check)
.await
.map_err(|error| ErrorObjectOwned::owned(-1, error.to_string(), None::<String>))
}

async fn wallet_sell(&self, wallet: &str, space: String, amount: u64) -> Result<Listing, ErrorObjectOwned> {
self.wallet(&wallet)
.await?
.send_sell(space, amount)
.await
.map_err(|error| ErrorObjectOwned::owned(-1, error.to_string(), None::<String>))
}

async fn verify_listing(&self, listing: Listing) -> Result<(), ErrorObjectOwned> {
self.store
.verify_listing(listing)
.await
.map_err(|error| ErrorObjectOwned::owned(-1, error.to_string(), None::<String>))
}

async fn wallet_list_transactions(
&self,
wallet: &str,
Expand Down Expand Up @@ -953,6 +1003,9 @@ impl AsyncChainState {
let rollouts = chain_state.get_rollout(target);
_ = resp.send(rollouts);
}
ChainStateCommand::VerifyListing { listing, resp } => {
_ = resp.send(SpacesWallet::verify_listing::<Sha256>(chain_state, &listing).map(|_| ()));
}
}
}

Expand Down Expand Up @@ -986,6 +1039,14 @@ impl AsyncChainState {
resp_rx.await?
}

pub async fn verify_listing(&self, listing: Listing) -> anyhow::Result<()> {
let (resp, resp_rx) = oneshot::channel();
self.sender
.send(ChainStateCommand::VerifyListing { listing, resp })
.await?;
resp_rx.await?
}

pub async fn get_rollout(&self, target: usize) -> anyhow::Result<Vec<RolloutEntry>> {
let (resp, resp_rx) = oneshot::channel();
self.sender
Expand Down
Loading
Loading