use std::path::PathBuf;
use alloy_primitives::{Address, Bytes};
use clap::Parser;
use serde_json::json;
use uuid::Uuid;
use super::wallet_args::{decode_0x_bytes, resolve_proxy_rpc_url, sign_and_send_submission_fee};
use super::{validate_override_rpc_url, CmdError, CmdResult, Ctx};
use crate::envelope::Envelope;
use taskfast_client::api::types::{
CompletionCriterionInput, TaskDraftPrepareRequest, TaskDraftPrepareRequestAssignmentType,
TaskDraftPrepareRequestPickupDeadlineHours, TaskDraftSubmitRequest,
TaskDraftSubmitRequestSignature,
};
use taskfast_client::map_api_error;
#[derive(Debug, Parser)]
pub struct Args {
#[arg(long)]
pub title: String,
#[arg(long)]
pub description: String,
#[arg(long)]
pub budget: Option<String>,
#[arg(long, value_delimiter = ',')]
pub capabilities: Vec<String>,
#[arg(long = "criterion")]
pub criteria: Vec<String>,
#[arg(long)]
pub criteria_file: Option<PathBuf>,
#[arg(long)]
pub pickup_deadline_hours: i64,
#[arg(long)]
pub execution_deadline: Option<String>,
#[arg(long)]
pub venue: Option<String>,
#[arg(long, default_value = "open")]
pub assignment_type: AssignmentType,
#[arg(long)]
pub direct_agent_id: Option<String>,
#[arg(long, env = "TEMPO_WALLET_ADDRESS")]
pub wallet_address: Option<String>,
#[arg(long, env = "TEMPO_KEY_SOURCE")]
pub keystore: Option<String>,
#[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
pub wallet_password_file: Option<PathBuf>,
#[arg(long, env = "TEMPO_RPC_URL")]
pub rpc_url: Option<String>,
#[arg(long)]
pub yes: bool,
}
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum AssignmentType {
Open,
Direct,
}
impl AssignmentType {
fn as_str(self) -> &'static str {
match self {
Self::Open => "open",
Self::Direct => "direct",
}
}
}
impl From<AssignmentType> for TaskDraftPrepareRequestAssignmentType {
fn from(a: AssignmentType) -> Self {
match a {
AssignmentType::Open => Self::Open,
AssignmentType::Direct => Self::Direct,
}
}
}
fn pickup_hours_to_wire(
hours: i64,
) -> Result<TaskDraftPrepareRequestPickupDeadlineHours, CmdError> {
TaskDraftPrepareRequestPickupDeadlineHours::try_from(hours).map_err(|_| CmdError::Validation {
code: "pickup_deadline_invalid".into(),
message: format!(
"pickup window of {hours}h is not an allowed bidding window per the \
API contract; the server owns the valid set (422 pickup_deadline_required)"
),
})
}
pub async fn run(ctx: &Ctx, args: Args) -> CmdResult {
let pre = preflight(ctx, &args)?;
let prep_body = TaskDraftPrepareRequest {
assignment_type: args.assignment_type.into(),
budget_max: args.budget.clone(),
completion_criteria: pre.completion_criteria,
description: args.description.clone(),
direct_agent_id: pre.direct_agent_id,
execution_deadline: pre.execution_deadline,
pickup_deadline_hours: pre.pickup_hours,
poster_wallet_address: pre
.wallet_address
.parse()
.map_err(|e| CmdError::Usage(format!("--wallet-address rejected by schema: {e}")))?,
required_capabilities: args.capabilities.clone(),
settlement_venue: args.venue.clone(),
title: args.title.clone(),
};
if ctx.dry_run {
let rpc_url = match pre.rpc_url_override {
Some(override_url) => override_url,
None => format!(
"{}/rpc/{}",
ctx.base_url().trim_end_matches('/'),
ctx.environment.network().as_str()
),
};
return Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"action": "would_post",
"draft_id": serde_json::Value::Null,
"title": args.title,
"assignment_type": args.assignment_type.as_str(),
"budget_max": args.budget,
"settlement_venue": args.venue,
"required_capabilities": args.capabilities,
"completion_criteria_count": prep_body.completion_criteria.len(),
"rpc_url": rpc_url,
"wallet_address": pre.wallet_address,
}),
));
}
let client = ctx.client()?;
let rpc_url = match pre.rpc_url_override {
Some(override_url) => override_url,
None => resolve_proxy_rpc_url(&client, ctx).await?,
};
let prep = match client.inner().prepare_task_draft(&prep_body).await {
Ok(r) => r.into_inner(),
Err(e) => return Err(map_api_error(e).await.into()),
};
let calldata = decode_0x_bytes(&prep.payload_to_sign)
.map_err(|e| CmdError::Server(format!("server returned invalid payload_to_sign: {e}")))?;
let keystore_path = super::wallet_args::resolve_keystore_path(
args.keystore.as_deref(),
ctx.keystore_path.as_deref(),
);
let signer = super::wallet_args::load_signer_and_validate(
keystore_path.as_deref(),
args.wallet_password_file.as_deref(),
Some(&pre.wallet_address),
"submission fee",
)?;
let tx_hash = sign_and_send_submission_fee(
ctx,
&client,
&rpc_url,
keystore_path,
signer,
&prep.token_address,
Bytes::from(calldata),
)
.await?;
let tx_hash_hex = format!("{tx_hash:#x}");
let signature: TaskDraftSubmitRequestSignature = tx_hash_hex
.parse()
.map_err(|e| CmdError::Server(format!("tx hash rejected by schema pattern: {e}")))?;
let submit_body = TaskDraftSubmitRequest { signature };
let submitted = match client
.inner()
.submit_task_draft(&prep.draft_id, &submit_body)
.await
{
Ok(r) => r.into_inner(),
Err(e) => return Err(map_api_error(e).await.into()),
};
let blocked = submitted.status == "blocked_on_submission_fee_debt";
if blocked {
eprintln!(
"taskfast: task {} parked at blocked_on_submission_fee_debt — \
submission-fee transfer confirming on-chain; it opens automatically \
once confirmed. Poll `taskfast task get {}`.",
submitted.id, submitted.id
);
}
let message = blocked.then(|| {
"Task created. Submission fee transaction is pending on-chain \
confirmation before the task becomes actionable."
.to_string()
});
Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"task_id": submitted.id,
"draft_id": prep.draft_id,
"submission_fee_tx_hash": tx_hash_hex,
"status": submitted.status,
"submission_fee_status": submitted.submission_fee_status,
"message": message,
}),
))
}
struct Preflight {
wallet_address: String,
direct_agent_id: Option<Uuid>,
execution_deadline: Option<chrono::DateTime<chrono::Utc>>,
completion_criteria: Vec<CompletionCriterionInput>,
pickup_hours: TaskDraftPrepareRequestPickupDeadlineHours,
rpc_url_override: Option<String>,
}
fn problem_text(e: &CmdError) -> String {
match e {
CmdError::Usage(m) => m.clone(),
CmdError::Validation { message, .. } => message.clone(),
other => other.to_string(),
}
}
fn preflight(ctx: &Ctx, args: &Args) -> Result<Preflight, CmdError> {
let mut problems: Vec<String> = Vec::new();
if args.description.trim().is_empty() {
problems.push(
"--description must not be empty (server requires a non-blank description)".into(),
);
}
if let Err(e) = ctx.enforce_budget_gate(args.budget.as_deref(), args.yes, "post a task") {
problems.push(problem_text(&e));
}
let wallet_address = match args
.wallet_address
.as_deref()
.or(ctx.wallet_address.as_deref())
{
Some(w) => match w.parse::<Address>() {
Ok(_) => Some(w.to_string()),
Err(e) => {
problems.push(format!("--wallet-address is not a valid EVM address: {e}"));
None
}
},
None => {
problems.push(
"--wallet-address (or TEMPO_WALLET_ADDRESS, or wallet_address in config) required to post a task".into(),
);
None
}
};
let direct_agent_id = match (args.assignment_type, args.direct_agent_id.as_deref()) {
(AssignmentType::Direct, Some(s)) => match Uuid::parse_str(s) {
Ok(u) => Some(Some(u)),
Err(e) => {
problems.push(format!("--direct-agent-id not a UUID: {e}"));
None
}
},
(AssignmentType::Direct, None) => {
problems.push("--assignment-type=direct requires --direct-agent-id".into());
None
}
(AssignmentType::Open, _) => Some(None),
};
let execution_deadline =
match parse_iso_opt(args.execution_deadline.as_deref(), "--execution-deadline") {
Ok(v) => Some(v),
Err(e) => {
problems.push(problem_text(&e));
None
}
};
let completion_criteria = match resolve_criteria(args.criteria_file.as_deref(), &args.criteria)
{
Ok(v) => Some(v),
Err(e) => {
problems.push(problem_text(&e));
None
}
};
let pickup_hours = match pickup_hours_to_wire(args.pickup_deadline_hours) {
Ok(w) => Some(w),
Err(e) => {
problems.push(problem_text(&e));
None
}
};
let rpc_url_override = match args.rpc_url.as_deref() {
Some(u) => match validate_override_rpc_url(
u,
ctx.environment.network(),
ctx.allow_custom_endpoints,
) {
Ok(u) => Some(Some(u.to_string())),
Err(e) => {
problems.push(problem_text(&e));
None
}
},
None => Some(None),
};
if !problems.is_empty() {
let n = problems.len();
let list = problems
.iter()
.enumerate()
.map(|(i, p)| format!(" {}. {p}", i + 1))
.collect::<Vec<_>>()
.join("\n");
return Err(CmdError::Usage(format!(
"post preflight found {n} problem{}:\n{list}",
if n == 1 { "" } else { "s" }
)));
}
Ok(Preflight {
wallet_address: wallet_address.expect("no problems ⇒ wallet present"),
direct_agent_id: direct_agent_id.expect("no problems ⇒ direct id resolved"),
execution_deadline: execution_deadline.expect("no problems ⇒ deadline resolved"),
completion_criteria: completion_criteria.expect("no problems ⇒ criteria resolved"),
pickup_hours: pickup_hours.expect("no problems ⇒ pickup hours valid"),
rpc_url_override: rpc_url_override.expect("no problems ⇒ rpc override resolved"),
})
}
fn resolve_criteria(
file: Option<&std::path::Path>,
inline: &[String],
) -> Result<Vec<CompletionCriterionInput>, CmdError> {
let mut out = Vec::with_capacity(inline.len());
if let Some(path) = file {
let raw = std::fs::read_to_string(path).map_err(|e| {
CmdError::Usage(format!("read --criteria-file {}: {e}", path.display()))
})?;
let parsed: Vec<CompletionCriterionInput> = serde_json::from_str(&raw).map_err(|e| {
CmdError::Usage(format!(
"--criteria-file {} is not a JSON array of CompletionCriterionInput: {e}",
path.display()
))
})?;
out.extend(parsed);
}
for (i, raw) in inline.iter().enumerate() {
let one: CompletionCriterionInput = serde_json::from_str(raw)
.map_err(|e| CmdError::Usage(format!("--criterion[{i}] not valid JSON: {e}")))?;
out.push(one);
}
Ok(out)
}
fn parse_iso_opt(
s: Option<&str>,
flag: &str,
) -> Result<Option<chrono::DateTime<chrono::Utc>>, CmdError> {
match s {
None => Ok(None),
Some(raw) => chrono::DateTime::parse_from_rfc3339(raw)
.map(|d| Some(d.with_timezone(&chrono::Utc)))
.map_err(|e| CmdError::Usage(format!("{flag} not a valid RFC3339 timestamp: {e}"))),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Network;
#[test]
fn validate_override_rejects_without_opt_in() {
let err = validate_override_rpc_url("https://mallory.example", Network::Mainnet, false)
.expect_err("override without opt-in must be refused");
match err {
CmdError::Usage(msg) => {
assert!(msg.contains("--allow-custom-endpoints"), "msg: {msg}");
}
other => panic!("expected Usage, got {other:?}"),
}
}
#[test]
fn validate_override_accepts_with_opt_in() {
validate_override_rpc_url("https://my-node.example", Network::Testnet, true)
.expect("opt-in bypasses the guard");
}
#[test]
fn validate_override_rejects_plain_http_on_mainnet() {
let err = validate_override_rpc_url("http://my-node.example", Network::Mainnet, true)
.expect_err("plain-http on mainnet is always refused (except loopback)");
assert!(matches!(err, CmdError::Usage(msg) if msg.contains("plain-HTTP")));
}
#[test]
fn validate_override_allows_plain_http_loopback_on_mainnet() {
validate_override_rpc_url("http://127.0.0.1:8545", Network::Mainnet, true)
.expect("loopback bypasses mainnet-HTTPS check");
validate_override_rpc_url("http://localhost:8545", Network::Mainnet, true)
.expect("loopback bypasses mainnet-HTTPS check");
}
#[test]
fn validate_override_allows_plain_http_on_testnet() {
validate_override_rpc_url("http://my-testnet.example", Network::Testnet, true)
.expect("testnet does not enforce HTTPS");
}
#[test]
fn pickup_hours_conversion_follows_api_contract() {
let err = pickup_hours_to_wire(3).expect_err("3 is outside the contract set");
assert!(matches!(err, CmdError::Validation { .. }));
let wire = pickup_hours_to_wire(24).expect("24 is contract-valid");
assert_eq!(i64::from(wire), 24);
}
#[test]
fn network_name_matches_config_map_keys() {
assert_eq!(Network::Mainnet.as_str(), "mainnet");
assert_eq!(Network::Testnet.as_str(), "testnet");
}
}