Skip to main content

soroban_cli/commands/tx/new/
create_passive_sell_offer.rs

1use clap::Parser;
2
3use crate::{commands::tx, tx::builder, xdr};
4
5#[derive(Parser, Debug, Clone)]
6#[group(skip)]
7pub struct Cmd {
8    #[command(flatten)]
9    pub tx: tx::Args,
10
11    #[clap(flatten)]
12    pub op: Args,
13}
14
15#[derive(Debug, clap::Args, Clone)]
16pub struct Args {
17    /// Asset to sell
18    #[arg(long)]
19    pub selling: builder::Asset,
20
21    /// Asset to buy
22    #[arg(long)]
23    pub buying: builder::Asset,
24
25    /// Amount of selling asset to offer, in stroops. 1 stroop = 0.0000001 of the asset (e.g. 1 XLM = `10_000_000` stroops).
26    #[arg(long)]
27    pub amount: builder::Amount,
28
29    /// Price of 1 unit of selling asset in terms of buying asset as "numerator:denominator" (e.g., "1:2" means 0.5)
30    #[arg(long)]
31    pub price: String,
32}
33
34impl TryFrom<&Cmd> for xdr::OperationBody {
35    type Error = tx::args::Error;
36    fn try_from(
37        Cmd {
38            tx,
39            op:
40                Args {
41                    selling,
42                    buying,
43                    amount,
44                    price,
45                },
46        }: &Cmd,
47    ) -> Result<Self, Self::Error> {
48        let price_parts: Vec<&str> = price.split(':').collect();
49        if price_parts.len() != 2 {
50            return Err(tx::args::Error::InvalidPrice(price.clone()));
51        }
52
53        let n: i32 = price_parts[0]
54            .parse()
55            .map_err(|_| tx::args::Error::InvalidPrice(price.clone()))?;
56        let d: i32 = price_parts[1]
57            .parse()
58            .map_err(|_| tx::args::Error::InvalidPrice(price.clone()))?;
59
60        if d == 0 {
61            return Err(tx::args::Error::InvalidPrice(
62                "denominator cannot be zero".to_string(),
63            ));
64        }
65
66        Ok(xdr::OperationBody::CreatePassiveSellOffer(
67            xdr::CreatePassiveSellOfferOp {
68                selling: tx.resolve_asset(selling)?,
69                buying: tx.resolve_asset(buying)?,
70                amount: amount.into(),
71                price: xdr::Price { n, d },
72            },
73        ))
74    }
75}