use clap::{Parser, ValueEnum};
use serde_json::json;
use uuid::Uuid;
use super::{CmdError, CmdResult, Ctx};
use crate::envelope::Envelope;
use taskfast_client::api::types::{PostStakeBody, PostStakeBodyStakeSource};
use taskfast_client::map_api_error;
#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
pub enum StakeSource {
OperatorSelf,
ExternalBacker,
}
impl StakeSource {
fn to_api(self) -> PostStakeBodyStakeSource {
match self {
Self::OperatorSelf => PostStakeBodyStakeSource::OperatorSelf,
Self::ExternalBacker => PostStakeBodyStakeSource::ExternalBacker,
}
}
fn as_str(self) -> &'static str {
match self {
Self::OperatorSelf => "operator_self",
Self::ExternalBacker => "external_backer",
}
}
}
#[derive(Debug, Parser)]
pub struct Args {
pub task_id: String,
#[arg(long)]
pub amount: i64,
#[arg(long, value_enum, default_value_t = StakeSource::OperatorSelf)]
pub source: StakeSource,
#[arg(long)]
pub wallet: Option<String>,
}
pub async fn run(ctx: &Ctx, args: Args) -> CmdResult {
let task_id = Uuid::parse_str(&args.task_id)
.map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
if args.amount < 1 {
return Err(CmdError::Usage(
"--amount must be a positive integer (bond base units)".into(),
));
}
let wallet_address = match args.source {
StakeSource::ExternalBacker => match args.wallet.as_deref() {
Some(w) if !w.trim().is_empty() => Some(super::parse_wallet_address(w)?),
_ => {
return Err(CmdError::Usage(
"--wallet is required with --source external-backer".into(),
));
}
},
StakeSource::OperatorSelf => None,
};
if ctx.dry_run {
return Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"action": "would_stake",
"task_id": task_id.to_string(),
"amount": args.amount,
"stake_source": args.source.as_str(),
"wallet_address": wallet_address,
}),
));
}
let client = ctx.client()?;
let body = PostStakeBody {
amount: std::num::NonZeroU64::new(args.amount as u64)
.expect("amount validated to >= 1 above"),
stake_source: args.source.to_api(),
wallet_address,
};
let resp = match client.inner().post_stake(&task_id, &body).await {
Ok(v) => v.into_inner(),
Err(e) => return Err(map_api_error(e).await.into()),
};
Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({ "stake": resp }),
))
}