use std::path::{Path, PathBuf};
use clap::Parser;
use serde_json::json;
use super::{CmdError, CmdResult, Ctx};
use crate::config::Config;
use crate::envelope::Envelope;
use alloy_signer_local::PrivateKeySigner;
use taskfast_agent::bootstrap::{create_agent_headless, get_readiness, validate_auth};
use taskfast_agent::faucet::{request_testnet_funds, FaucetDrop};
use taskfast_agent::keystore;
use taskfast_agent::wallet;
use taskfast_agent::webhooks;
use taskfast_client::api::types::{AgentCreateRequest, AgentReadiness, WebhookConfigRequest};
use taskfast_client::TaskFastClient;
use super::webhook::persist_secret;
const WALLET_STATUS_COMPLETE: &str = "complete";
#[derive(Debug, Parser)]
#[allow(clippy::struct_excessive_bools)]
pub struct Args {
#[arg(long, conflicts_with = "generate_wallet")]
pub wallet_address: Option<String>,
#[arg(long)]
pub generate_wallet: bool,
#[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
pub wallet_password_file: Option<PathBuf>,
#[arg(long)]
pub keystore_path: Option<PathBuf>,
#[arg(long)]
pub skip_wallet: bool,
#[arg(long)]
pub fund: bool,
#[arg(long, env = "TASKFAST_HUMAN_API_KEY")]
pub human_api_key: Option<String>,
#[arg(long, default_value = "taskfast-agent")]
pub agent_name: String,
#[arg(long, default_value = "Headless agent registered via taskfast init")]
pub agent_description: String,
#[arg(long = "agent-capability", value_name = "CAP")]
pub agent_capabilities: Vec<String>,
#[arg(long)]
pub webhook_url: Option<String>,
#[arg(long)]
pub webhook_secret_file: Option<PathBuf>,
#[arg(long = "webhook-event", value_name = "EVENT")]
pub webhook_events: Vec<String>,
#[arg(long)]
pub no_default_events: bool,
#[arg(long, env = "TASKFAST_NO_INTERACTIVE")]
pub no_interactive: bool,
#[arg(skip)]
pub inline_wallet_password: Option<String>,
}
pub async fn run(ctx: &Ctx, args: Args) -> CmdResult {
let interactive = !args.no_interactive && crate::cmd::init_tui::is_interactive();
run_with_prompter(
ctx,
args,
&crate::cmd::init_tui::DialoguerPrompter,
interactive,
)
.await
}
pub async fn run_with_prompter<P: crate::cmd::init_tui::Prompter>(
ctx: &Ctx,
mut args: Args,
prompter: &P,
interactive: bool,
) -> CmdResult {
let cfg_path = ctx.config_path.clone();
let mut cfg = Config::load(&cfg_path)?;
let (api_key, agent_outcome) = match resolve_api_key(ctx, &cfg) {
Ok(k) => (k, AgentOutcome::PreExisting),
Err(CmdError::MissingApiKey) => {
let pat = resolve_pat(ctx, &args, interactive, prompter).await?;
let minted = mint_agent(ctx, &args, &pat).await?;
match minted {
MintedAgent::DryRun { ref intent } => {
return Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
build_dry_run_mint_envelope(&cfg_path, intent),
));
}
MintedAgent::Live { ref api_key, .. } => {
(api_key.clone(), AgentOutcome::Minted(minted))
}
}
}
Err(e) => return Err(e),
};
if interactive
&& matches!(agent_outcome, AgentOutcome::Minted(_))
&& args.wallet_address.is_none()
&& !args.generate_wallet
&& !args.skip_wallet
{
apply_wallet_mode_prompt(&mut args, prompter)?;
}
let effective_ctx = Ctx {
api_key: Some(api_key.clone()),
..ctx.clone()
};
let client = effective_ctx.client()?;
let profile = match validate_auth(&client).await {
Ok(p) => p,
Err(taskfast_client::Error::Auth(msg))
if matches!(agent_outcome, AgentOutcome::PreExisting) =>
{
return Err(CmdError::Auth(stale_key_hint(
&msg, &cfg_path, &cfg, ctx, &args,
)));
}
Err(e) => return Err(CmdError::from(e)),
};
assert_active(&profile)?;
if !ctx.dry_run {
super::enforce_server_network_invariant(&effective_ctx, &client).await?;
}
let readiness = get_readiness(&client).await.map_err(CmdError::from)?;
let wallet_outcome = if args.skip_wallet {
WalletOutcome::Skipped
} else if readiness.checks.wallet.status == WALLET_STATUS_COMPLETE
&& args.wallet_address.is_none()
&& !args.generate_wallet
{
WalletOutcome::AlreadyConfigured
} else {
provision_wallet(&client, &args, ctx.dry_run).await?
};
cfg.environment = Some(ctx.environment);
cfg.api_key = Some(api_key.clone());
if let Some(addr) = wallet_outcome.address() {
cfg.wallet_address = Some(addr.to_string());
}
if let Some(path) = wallet_outcome.keystore_path() {
cfg.keystore_path = Some(path.to_path_buf());
}
if let AgentOutcome::Minted(MintedAgent::Live { id: Some(id), .. }) = &agent_outcome {
cfg.agent_id = Some(id.clone());
}
if let Some(url) = args.webhook_url.as_deref().filter(|s| !s.trim().is_empty()) {
cfg.webhook_url = Some(url.to_string());
}
if let Some(path) = args.webhook_secret_file.as_ref() {
cfg.webhook_secret_path = Some(path.clone());
}
let config_written = if ctx.dry_run {
false
} else {
cfg.save(&cfg_path)?;
true
};
let faucet_outcome = maybe_request_faucet(
&args,
ctx.environment.network(),
&wallet_outcome,
ctx.dry_run,
)
.await;
let webhook_outcome = maybe_configure_webhook(&client, &args, ctx.dry_run).await;
let final_readiness = get_readiness(&client).await.map_err(CmdError::from)?;
warn_if_unfunded(
&client,
ctx,
cfg.wallet_address.as_deref(),
&faucet_outcome,
&final_readiness,
)
.await;
let data = build_envelope_data(
&cfg_path,
config_written,
&wallet_outcome,
&agent_outcome,
&final_readiness,
&faucet_outcome,
&webhook_outcome,
ctx.dry_run,
);
Ok(Envelope::success(ctx.environment, ctx.dry_run, data))
}
enum AgentOutcome {
PreExisting,
Minted(MintedAgent),
}
enum MintedAgent {
Live {
api_key: String,
id: Option<String>,
name: Option<String>,
},
DryRun {
intent: MintIntent,
},
}
struct MintIntent {
name: String,
description: String,
capabilities: Vec<String>,
}
async fn resolve_pat<P: crate::cmd::init_tui::Prompter>(
ctx: &Ctx,
args: &Args,
interactive: bool,
prompter: &P,
) -> Result<String, CmdError> {
if let Some(p) = args.human_api_key.as_deref().filter(|s| !s.is_empty()) {
return Ok(p.to_string());
}
if !interactive {
return Err(CmdError::MissingApiKey);
}
let accounts_url = crate::accounts_url(ctx.base_url());
let pat = prompter
.pat(&accounts_url)
.map_err(|e| CmdError::Usage(format!("PAT prompt failed: {e}")))?;
let pat_client = TaskFastClient::from_api_key(ctx.base_url(), &pat).map_err(CmdError::from)?;
let profile = pat_client.get_user_profile().await.ok().flatten();
eprintln!("{}", crate::cmd::init_tui::greeting(profile.as_ref()));
Ok(pat)
}
fn apply_wallet_mode_prompt<P: crate::cmd::init_tui::Prompter>(
args: &mut Args,
prompter: &P,
) -> Result<(), CmdError> {
use crate::cmd::init_tui::WalletMode;
let mode = prompter
.wallet_mode()
.map_err(|e| CmdError::Usage(format!("wallet-mode prompt failed: {e}")))?;
match mode {
WalletMode::Byow => {
let addr = prompter
.wallet_address()
.map_err(|e| CmdError::Usage(format!("wallet-address prompt failed: {e}")))?;
args.wallet_address = Some(addr.trim().to_string());
}
WalletMode::Generate => {
args.generate_wallet = true;
let pw = prompter
.wallet_password()
.map_err(|e| CmdError::Usage(format!("password prompt failed: {e}")))?;
args.inline_wallet_password = Some(pw);
}
WalletMode::Skip => {
args.skip_wallet = true;
}
}
Ok(())
}
async fn mint_agent(ctx: &Ctx, args: &Args, pat: &str) -> Result<MintedAgent, CmdError> {
if pat.is_empty() {
return Err(CmdError::Usage("PAT is empty".into()));
}
let capabilities = if args.agent_capabilities.is_empty() {
vec!["general".to_string()]
} else {
args.agent_capabilities.clone()
};
if ctx.dry_run {
return Ok(MintedAgent::DryRun {
intent: MintIntent {
name: args.agent_name.clone(),
description: args.agent_description.clone(),
capabilities,
},
});
}
let pat_client = TaskFastClient::from_api_key(ctx.base_url(), pat).map_err(CmdError::from)?;
let body = AgentCreateRequest {
owner_id: None,
name: args.agent_name.clone(),
description: args.agent_description.clone(),
capabilities,
rate: None,
max_task_budget: None,
daily_spend_limit: None,
payout_method: None,
payment_method: None,
tempo_wallet_address: None,
};
let resp = create_agent_headless(&pat_client, &body)
.await
.map_err(CmdError::from)?;
let api_key = resp
.api_key
.clone()
.ok_or_else(|| CmdError::Server("POST /agents returned no api_key despite 201".into()))?;
Ok(MintedAgent::Live {
api_key,
id: resp.id.map(|u| u.to_string()),
name: resp.name.clone(),
})
}
fn build_dry_run_mint_envelope(cfg_path: &Path, intent: &MintIntent) -> serde_json::Value {
json!({
"agent": {
"action": "would_mint",
"name": intent.name,
"description": intent.description,
"capabilities": intent.capabilities,
},
"config_file": {
"path": cfg_path.display().to_string(),
"written": false,
"would_write": true,
},
"ready_to_work": false,
})
}
fn resolve_api_key(ctx: &Ctx, cfg: &Config) -> Result<String, CmdError> {
if let Some(k) = ctx.api_key.as_deref() {
if !k.is_empty() {
return Ok(k.to_string());
}
}
if let Some(k) = cfg.api_key.as_deref() {
if !k.is_empty() {
return Ok(k.to_string());
}
}
Err(CmdError::MissingApiKey)
}
fn stale_key_hint(msg: &str, cfg_path: &Path, cfg: &Config, ctx: &Ctx, args: &Args) -> String {
let source = if cfg.api_key.as_deref().is_some_and(|k| !k.is_empty()) {
format!("config file {}", cfg_path.display())
} else if ctx.api_key.is_some() {
"--api-key flag or TASKFAST_API_KEY env".to_string()
} else {
"unknown".to_string()
};
let had_pat = args.human_api_key.is_some();
let pat_note = if had_pat {
"\n note: --human-api-key was provided but ignored because an existing api_key was found; \
the PAT mints a new agent only when no api_key is resolvable."
} else {
""
};
format!(
"{msg}\n hint: agent api_key rejected — likely stale (agent deleted or key rotated).\n \
source: {source}\n fix: delete {path} (and unset TASKFAST_API_KEY if set), then re-run \
`taskfast --env {env} init --human-api-key <tf_user_...>` to mint a fresh agent.{pat_note}",
path = cfg_path.display(),
env = ctx.environment.as_str(),
)
}
fn assert_active(profile: &taskfast_client::api::types::AgentProfile) -> Result<(), CmdError> {
match profile.status.as_deref() {
Some("active") => Ok(()),
Some(other) => Err(CmdError::Validation {
code: "agent_not_active".into(),
message: format!("agent status is {other}; owner must reactivate"),
}),
None => Err(CmdError::Server(
"GET /agents/me returned no status field".into(),
)),
}
}
enum WalletOutcome {
AlreadyConfigured,
ByoRegistered { address: String },
Generated {
address: String,
keystore_path: PathBuf,
},
DryRunGenerated { address: String },
Skipped,
}
impl WalletOutcome {
fn address(&self) -> Option<&str> {
match self {
Self::ByoRegistered { address }
| Self::Generated { address, .. }
| Self::DryRunGenerated { address } => Some(address),
Self::AlreadyConfigured | Self::Skipped => None,
}
}
fn keystore_path(&self) -> Option<&Path> {
match self {
Self::Generated { keystore_path, .. } => Some(keystore_path),
_ => None,
}
}
fn tag(&self) -> &'static str {
match self {
Self::AlreadyConfigured => "already_configured",
Self::ByoRegistered { .. } => "byo_registered",
Self::Generated { .. } => "generated",
Self::DryRunGenerated { .. } => "dry_run_generated",
Self::Skipped => "skipped",
}
}
}
async fn provision_wallet(
client: &TaskFastClient,
args: &Args,
dry_run: bool,
) -> Result<WalletOutcome, CmdError> {
if let Some(addr) = args.wallet_address.as_deref() {
if dry_run {
return Ok(WalletOutcome::Skipped);
}
wallet::register_wallet(client, addr)
.await
.map_err(CmdError::from)?;
return Ok(WalletOutcome::ByoRegistered {
address: addr.to_string(),
});
}
if !args.generate_wallet {
return Err(CmdError::Usage(
"pass --wallet-address <0x...> or --generate-wallet (or --skip-wallet to defer)".into(),
));
}
let signer = wallet::generate_signer();
let address = format!("0x{}", hex::encode(signer.address().as_slice()));
if dry_run {
return Ok(WalletOutcome::DryRunGenerated { address });
}
let password = resolve_wallet_password(args)?;
let keystore_path = persist_keystore(&signer, args, &password)?;
wallet::register_wallet(client, &address)
.await
.map_err(CmdError::from)?;
Ok(WalletOutcome::Generated {
address,
keystore_path,
})
}
fn resolve_wallet_password(args: &Args) -> Result<String, CmdError> {
if let Some(pw) = args.inline_wallet_password.as_deref() {
if !pw.is_empty() {
return Ok(pw.to_string());
}
}
if let Ok(pw) = std::env::var("TASKFAST_WALLET_PASSWORD") {
if !pw.is_empty() {
return Ok(pw);
}
}
let path = args.wallet_password_file.as_deref().ok_or_else(|| {
CmdError::Usage(
"--generate-wallet requires --wallet-password-file or TASKFAST_WALLET_PASSWORD".into(),
)
})?;
let raw = std::fs::read_to_string(path).map_err(|e| {
CmdError::Usage(format!(
"cannot read wallet password file {}: {e}",
path.display()
))
})?;
let trimmed = raw.trim_end_matches(['\n', '\r']);
if trimmed.is_empty() {
return Err(CmdError::Usage(format!(
"wallet password file {} is empty",
path.display()
)));
}
Ok(trimmed.to_string())
}
fn persist_keystore(
signer: &PrivateKeySigner,
args: &Args,
password: &str,
) -> Result<PathBuf, CmdError> {
let path = match &args.keystore_path {
Some(p) => p.clone(),
None => keystore::default_keyfile_path(signer.address()).map_err(CmdError::from)?,
};
keystore::save_signer(signer, &path, password).map_err(CmdError::from)
}
enum FaucetOutcome {
Skipped { reason: &'static str },
Requested { drops: Vec<FaucetDrop> },
Failed { error: String },
}
async fn maybe_request_faucet(
args: &Args,
network: crate::Network,
wallet: &WalletOutcome,
dry_run: bool,
) -> FaucetOutcome {
if dry_run {
return FaucetOutcome::Skipped { reason: "dry_run" };
}
if !args.fund {
return FaucetOutcome::Skipped {
reason: "fund_flag_not_set",
};
}
if !matches!(network, crate::Network::Testnet) {
return FaucetOutcome::Skipped { reason: "mainnet" };
}
let address = match wallet {
WalletOutcome::Generated { address, .. } => address.clone(),
WalletOutcome::ByoRegistered { address } => address.clone(),
_ => {
return FaucetOutcome::Skipped {
reason: "no_fresh_wallet",
};
}
};
let http = reqwest::Client::new();
match request_testnet_funds(&http, &address).await {
Ok(drops) => FaucetOutcome::Requested { drops },
Err(e) => FaucetOutcome::Failed {
error: e.to_string(),
},
}
}
fn parse_wei_hex(s: Option<&str>) -> Option<u128> {
let s = s?.trim();
let hex = s.strip_prefix("0x").unwrap_or(s);
if hex.is_empty() {
return None;
}
u128::from_str_radix(hex, 16).ok()
}
fn build_funding_warning(
faucet_error: Option<&str>,
balance_wei: Option<u128>,
address: &str,
rpc_url: Option<&str>,
funding_hint: Option<&str>,
) -> Option<String> {
let zero_balance = balance_wei.is_some_and(|b| b == 0);
if faucet_error.is_none() && !zero_balance {
return None;
}
let mut lines = Vec::new();
match (faucet_error, zero_balance) {
(Some(err), _) => lines.push(format!(
"WARNING: testnet faucet funding failed (--fund): {err}"
)),
(None, true) => lines.push(format!(
"WARNING: wallet {address} balance is zero at the end of init"
)),
(None, false) => return None,
}
lines.push(
" the next on-chain command will fail until the wallet is funded. \
manual fallback:"
.to_string(),
);
if let Some(rpc) = rpc_url {
lines.push(format!(
" cast rpc tempo_fundAddress '[\"{address}\"]' --raw --rpc-url {rpc}"
));
}
lines.push(" or fund at https://wallet.tempo.xyz".to_string());
if let Some(hint) = funding_hint {
lines.push(format!(" server funding hint: {hint}"));
}
Some(lines.join("\n"))
}
async fn warn_if_unfunded(
client: &TaskFastClient,
ctx: &Ctx,
wallet_address: Option<&str>,
faucet: &FaucetOutcome,
readiness: &AgentReadiness,
) {
if ctx.dry_run {
return;
}
if !matches!(ctx.environment.network(), crate::Network::Testnet) {
return;
}
let Some(address) = wallet_address else {
return;
};
let faucet_error = match faucet {
FaucetOutcome::Failed { error } => Some(error.as_str()),
_ => None,
};
let balance_wei = match client.inner().get_wallet_balance().await {
Ok(resp) => parse_wei_hex(resp.into_inner().available_balance.as_deref()),
Err(e) => {
tracing::warn!(error = %e, "init: balance check unavailable; skipping zero-balance warning");
None
}
};
if build_funding_warning(
faucet_error,
balance_wei,
address,
None,
readiness.checks.funded.funding_hint.as_deref(),
)
.is_none()
{
return;
}
let rpc_url = client
.fetch_network_config()
.await
.ok()
.and_then(|cfg| cfg.entry(ctx.environment.network().as_str()).ok())
.map(|entry| entry.rpc_url.clone());
if let Some(warning) = build_funding_warning(
faucet_error,
balance_wei,
address,
rpc_url.as_deref(),
readiness.checks.funded.funding_hint.as_deref(),
) {
eprintln!("{warning}");
}
}
#[cfg_attr(test, derive(Debug))]
enum WebhookOutcome {
Skipped,
DryRun {
url: String,
events: Vec<String>,
secret_file: Option<PathBuf>,
},
Registered {
url: String,
secret_returned: bool,
secret_persisted: bool,
secret_file: Option<PathBuf>,
subscribed: Option<Vec<String>>,
},
Failed {
error: String,
},
}
fn resolve_webhook_events(args: &Args) -> Vec<String> {
if !args.webhook_events.is_empty() {
return args.webhook_events.clone();
}
if args.no_default_events {
return Vec::new();
}
crate::cmd::webhook::DEFAULT_WORKER_EVENTS
.iter()
.map(|s| (*s).to_string())
.collect()
}
async fn maybe_configure_webhook(
client: &TaskFastClient,
args: &Args,
dry_run: bool,
) -> WebhookOutcome {
let Some(url) = args.webhook_url.as_deref().filter(|s| !s.trim().is_empty()) else {
return WebhookOutcome::Skipped;
};
let events = resolve_webhook_events(args);
if dry_run {
return WebhookOutcome::DryRun {
url: url.to_string(),
events,
secret_file: args.webhook_secret_file.clone(),
};
}
let body = WebhookConfigRequest {
url: url.to_string(),
secret: None,
events: None,
};
let cfg = match webhooks::configure_webhook(client, &body).await {
Ok(c) => c,
Err(e) => {
return WebhookOutcome::Failed {
error: e.to_string(),
};
}
};
let secret_persisted = match (cfg.secret.as_deref(), args.webhook_secret_file.as_ref()) {
(Some(secret), Some(path)) => match persist_secret(path, secret) {
Ok(()) => true,
Err(e) => {
return WebhookOutcome::Failed {
error: e.to_string(),
};
}
},
_ => false,
};
let subscribed = if events.is_empty() {
None
} else {
match webhooks::update_subscriptions(client, events).await {
Ok(subs) => Some(subs.subscribed_event_types),
Err(e) => {
return WebhookOutcome::Failed {
error: e.to_string(),
};
}
}
};
WebhookOutcome::Registered {
url: cfg.url,
secret_returned: cfg.secret.is_some(),
secret_persisted,
secret_file: args.webhook_secret_file.clone(),
subscribed,
}
}
fn build_envelope_data(
cfg_path: &Path,
config_written: bool,
wallet: &WalletOutcome,
agent: &AgentOutcome,
readiness: &AgentReadiness,
faucet: &FaucetOutcome,
webhook: &WebhookOutcome,
dry_run: bool,
) -> serde_json::Value {
let mut wallet_obj = json!({
"status": wallet.tag(),
});
if let Some(addr) = wallet.address() {
wallet_obj["address"] = json!(addr);
}
if let Some(path) = wallet.keystore_path() {
wallet_obj["keystore_path"] = json!(path.display().to_string());
}
let mut cfg_obj = json!({
"path": cfg_path.display().to_string(),
"written": config_written,
});
if dry_run && !config_written {
cfg_obj["would_write"] = json!(true);
}
let faucet_obj = match faucet {
FaucetOutcome::Skipped { reason } => {
let mut o = json!({
"status": "skipped",
"reason": reason,
});
if *reason == "mainnet" {
o["funding_hint"] = json!({
"url": "https://wallet.tempo.xyz",
"message": "Production wallets must be funded manually by the owning human at wallet.tempo.xyz before posting or settling.",
});
}
o
}
FaucetOutcome::Requested { drops } => json!({
"status": "requested",
"drops": drops.iter().map(|d| json!({
"token": d.token,
"tx_hash": d.tx_hash,
})).collect::<Vec<_>>(),
}),
FaucetOutcome::Failed { error } => json!({
"status": "failed",
"error": error,
}),
};
let webhook_obj = match webhook {
WebhookOutcome::Skipped => json!({ "status": "skipped" }),
WebhookOutcome::DryRun {
url,
events,
secret_file,
} => {
let mut o = json!({
"status": "would_register",
"url": url,
"events": events,
});
if let Some(p) = secret_file {
o["secret_file"] = json!(p.display().to_string());
}
o
}
WebhookOutcome::Registered {
url,
secret_returned,
secret_persisted,
secret_file,
subscribed,
} => {
let mut o = json!({
"status": "registered",
"url": url,
"secret_returned": secret_returned,
"secret_persisted": secret_persisted,
});
if let Some(p) = secret_file {
o["secret_file"] = json!(p.display().to_string());
}
if let Some(subs) = subscribed {
o["subscribed"] = json!(subs);
}
o
}
WebhookOutcome::Failed { error } => json!({
"status": "failed",
"error": error,
}),
};
let mut out = json!({
"wallet": wallet_obj,
"config_file": cfg_obj,
"faucet": faucet_obj,
"webhook": webhook_obj,
"readiness": readiness,
"ready_to_work": readiness.ready_to_work,
});
if let AgentOutcome::Minted(MintedAgent::Live { id, name, .. }) = agent {
let mut a = json!({ "action": "minted" });
if let Some(id) = id {
a["id"] = json!(id);
}
if let Some(name) = name {
a["name"] = json!(name);
}
out["agent"] = a;
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Environment;
fn base_args() -> Args {
Args {
wallet_address: None,
generate_wallet: false,
wallet_password_file: None,
keystore_path: None,
skip_wallet: false,
fund: false,
human_api_key: None,
agent_name: "taskfast-agent".into(),
agent_description: "Headless agent registered via taskfast init".into(),
agent_capabilities: Vec::new(),
webhook_url: None,
webhook_secret_file: None,
webhook_events: Vec::new(),
no_default_events: false,
no_interactive: true,
inline_wallet_password: None,
}
}
fn ctx_with_key(key: Option<&str>) -> Ctx {
Ctx {
api_key: key.map(String::from),
environment: Environment::Local,
api_base: None,
config_path: PathBuf::from("/dev/null"),
dry_run: false,
quiet: true,
..Default::default()
}
}
fn cfg_with_key(key: Option<&str>) -> Config {
Config {
api_key: key.map(str::to_string),
..Config::default()
}
}
#[test]
fn resolve_api_key_prefers_ctx_over_config() {
let ctx = ctx_with_key(Some("from-flag"));
let cfg = cfg_with_key(Some("from-file"));
assert_eq!(resolve_api_key(&ctx, &cfg).unwrap(), "from-flag");
}
#[test]
fn resolve_api_key_falls_back_to_config() {
let ctx = ctx_with_key(None);
let cfg = cfg_with_key(Some("from-file"));
assert_eq!(resolve_api_key(&ctx, &cfg).unwrap(), "from-file");
}
#[test]
fn resolve_api_key_empty_string_is_treated_as_absent() {
let ctx = ctx_with_key(Some(""));
let cfg = cfg_with_key(Some(""));
match resolve_api_key(&ctx, &cfg) {
Err(CmdError::MissingApiKey) => {}
other => panic!("expected MissingApiKey, got {other:?}"),
}
}
#[test]
fn provision_without_wallet_flag_errors_as_usage() {
let args = base_args();
assert!(args.wallet_address.is_none() && !args.generate_wallet);
}
#[test]
fn wallet_outcome_tag_is_stable() {
assert_eq!(WalletOutcome::AlreadyConfigured.tag(), "already_configured");
assert_eq!(
WalletOutcome::ByoRegistered {
address: "0x00".into()
}
.tag(),
"byo_registered"
);
assert_eq!(
WalletOutcome::Generated {
address: "0x00".into(),
keystore_path: PathBuf::from("/tmp/x")
}
.tag(),
"generated"
);
assert_eq!(
WalletOutcome::DryRunGenerated {
address: "0x00".into()
}
.tag(),
"dry_run_generated"
);
assert_eq!(WalletOutcome::Skipped.tag(), "skipped");
}
#[test]
fn resolve_webhook_events_uses_defaults_when_events_empty() {
let args = Args {
webhook_url: Some("https://h.example/x".into()),
..base_args()
};
let events = resolve_webhook_events(&args);
assert_eq!(events, crate::cmd::webhook::DEFAULT_WORKER_EVENTS);
}
#[test]
fn resolve_webhook_events_respects_no_default_events_opt_out() {
let args = Args {
webhook_url: Some("https://h.example/x".into()),
no_default_events: true,
..base_args()
};
assert!(resolve_webhook_events(&args).is_empty());
}
#[test]
fn resolve_webhook_events_explicit_events_override_defaults() {
let args = Args {
webhook_url: Some("https://h.example/x".into()),
webhook_events: vec!["task_assigned".into()],
..base_args()
};
assert_eq!(resolve_webhook_events(&args), vec!["task_assigned"]);
}
#[test]
fn resolve_webhook_events_explicit_events_win_over_no_default_events() {
let args = Args {
webhook_url: Some("https://h.example/x".into()),
webhook_events: vec!["bid_accepted".into()],
no_default_events: true,
..base_args()
};
assert_eq!(resolve_webhook_events(&args), vec!["bid_accepted"]);
}
#[test]
fn funding_warning_faucet_failure_lists_manual_fallback() {
let w = build_funding_warning(
Some("faucet returned status 405: method not allowed"),
Some(0),
"0xabc0000000000000000000000000000000000000",
Some("https://rpc.testnet.example"),
None,
)
.expect("faucet failure must warn");
assert!(w.contains("faucet returned status 405"), "got: {w}");
assert!(w.contains("0xabc0000000000000000000000000000000000000"));
assert!(w.contains(
"cast rpc tempo_fundAddress \
'[\"0xabc0000000000000000000000000000000000000\"]' \
--raw --rpc-url https://rpc.testnet.example"
));
assert!(w.contains("https://wallet.tempo.xyz"));
}
#[test]
fn funding_warning_zero_balance_without_faucet_failure_still_warns() {
let w = build_funding_warning(
None,
Some(0),
"0xabc0000000000000000000000000000000000000",
Some("https://rpc.testnet.example"),
None,
)
.expect("zero balance must warn");
assert!(w.contains("zero"), "got: {w}");
assert!(w.contains("https://wallet.tempo.xyz"));
}
#[test]
fn funding_warning_silent_when_funded() {
assert!(build_funding_warning(
None,
Some(42),
"0xabc0000000000000000000000000000000000000",
Some("https://rpc.testnet.example"),
None,
)
.is_none());
}
#[test]
fn funding_warning_silent_when_balance_unknown_and_faucet_did_not_fail() {
assert!(build_funding_warning(
None,
None,
"0xabc0000000000000000000000000000000000000",
Some("https://rpc.testnet.example"),
None,
)
.is_none());
}
#[test]
fn funding_warning_without_rpc_url_omits_cast_line_keeps_web_fallback() {
let w = build_funding_warning(
Some("faucet http request failed"),
Some(0),
"0xabc0000000000000000000000000000000000000",
None,
None,
)
.expect("must still warn");
assert!(!w.contains("cast rpc"), "got: {w}");
assert!(w.contains("https://wallet.tempo.xyz"));
}
#[test]
fn funding_warning_surfaces_server_funding_hint() {
let w = build_funding_warning(
None,
Some(0),
"0xabc0000000000000000000000000000000000000",
None,
Some("https://wallet.tempo.xyz/topup"),
)
.expect("must warn");
assert!(w.contains("https://wallet.tempo.xyz/topup"), "got: {w}");
}
#[test]
fn parse_wei_hex_handles_0x_zero_and_plain_hex_forms() {
assert_eq!(parse_wei_hex(Some("0x0")), Some(0));
assert_eq!(
parse_wei_hex(Some(
"0x000000000000000000000000000000000000000000000000000000000000000a"
)),
Some(10)
);
assert_eq!(parse_wei_hex(None), None);
assert_eq!(parse_wei_hex(Some("0x")), None);
}
#[tokio::test]
async fn maybe_configure_webhook_dry_run_surfaces_default_events() {
let client = TaskFastClient::from_api_key("http://127.0.0.1:1/", "k").unwrap();
let args = Args {
webhook_url: Some("https://h.example/x".into()),
..base_args()
};
let outcome = maybe_configure_webhook(&client, &args, true).await;
match outcome {
WebhookOutcome::DryRun { events, url, .. } => {
assert_eq!(url, "https://h.example/x");
assert_eq!(events, crate::cmd::webhook::DEFAULT_WORKER_EVENTS);
}
other => panic!("expected DryRun, got {other:?}"),
}
}
#[tokio::test]
async fn maybe_configure_webhook_dry_run_respects_no_default_events() {
let client = TaskFastClient::from_api_key("http://127.0.0.1:1/", "k").unwrap();
let args = Args {
webhook_url: Some("https://h.example/x".into()),
no_default_events: true,
..base_args()
};
let outcome = maybe_configure_webhook(&client, &args, true).await;
match outcome {
WebhookOutcome::DryRun { events, .. } => assert!(events.is_empty()),
other => panic!("expected DryRun, got {other:?}"),
}
}
#[tokio::test]
async fn maybe_configure_webhook_no_url_is_skipped() {
let client = TaskFastClient::from_api_key("http://127.0.0.1:1/", "k").unwrap();
let outcome = maybe_configure_webhook(&client, &base_args(), true).await;
assert!(matches!(outcome, WebhookOutcome::Skipped));
}
}