use std::path::PathBuf;
use std::time::Duration;
use alloy_primitives::{Address, Bytes, B256, U256};
use alloy_sol_types::SolCall;
use clap::{Parser, ValueEnum};
use serde_json::json;
use uuid::Uuid;
use super::{
is_proxy_rpc_url, resolve_duration, validate_override_rpc_url, CmdError, CmdResult, Ctx,
};
use crate::envelope::Envelope;
use taskfast_agent::chain::{compute_task_ref, TaskBond};
use taskfast_agent::tempo_rpc::TempoRpcClient;
use taskfast_client::api::types::{
GetStakeQuoteStakeSource, ReportStakePostTxBody, ReportStakePostTxBodyStakeSource,
};
use taskfast_client::map_api_error;
const DEFAULT_VERIFY_TIMEOUT: Duration = Duration::from_mins(1);
const VERIFY_POLL_INTERVAL: Duration = Duration::from_secs(3);
fn default_receipt_timeout(chain_id: i64) -> Duration {
match u64::try_from(chain_id) {
Ok(id) => crate::tempo_session::default_receipt_timeout_for_chain_id(id),
_ => crate::tempo_session::DEFAULT_RECEIPT_TIMEOUT_TESTNET,
}
}
#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
pub enum BondStakeSource {
OperatorSelf,
ExternalBacker,
}
impl BondStakeSource {
fn to_quote(self) -> GetStakeQuoteStakeSource {
match self {
Self::OperatorSelf => GetStakeQuoteStakeSource::OperatorSelf,
Self::ExternalBacker => GetStakeQuoteStakeSource::ExternalBacker,
}
}
fn to_report(self) -> ReportStakePostTxBodyStakeSource {
match self {
Self::OperatorSelf => ReportStakePostTxBodyStakeSource::OperatorSelf,
Self::ExternalBacker => ReportStakePostTxBodyStakeSource::ExternalBacker,
}
}
}
#[derive(Debug, clap::Subcommand)]
pub enum Command {
Post(PostArgs),
}
#[derive(Debug, Parser)]
pub struct PostArgs {
pub task_id: String,
#[arg(long, env = "BOND_ADDRESS")]
pub task_bond: Option<String>,
#[arg(long)]
pub token: Option<String>,
#[arg(long)]
pub amount: Option<i64>,
#[arg(long, value_enum, default_value_t = BondStakeSource::OperatorSelf)]
pub source: BondStakeSource,
#[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_WALLET_ADDRESS")]
pub wallet_address: Option<String>,
#[arg(long, env = "TEMPO_RPC_URL")]
pub rpc_url: Option<String>,
#[arg(long)]
pub skip_allowance_check: bool,
#[arg(long, env = "TASKFAST_RECEIPT_TIMEOUT", value_parser = humantime::parse_duration)]
pub receipt_timeout: Option<Duration>,
#[arg(long, env = "TASKFAST_BOND_VERIFY_TIMEOUT", value_parser = humantime::parse_duration)]
pub verify_timeout: Option<Duration>,
}
pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
match cmd {
Command::Post(a) => post(ctx, a).await,
}
}
async fn post(ctx: &Ctx, args: PostArgs) -> CmdResult {
let task_id = Uuid::parse_str(&args.task_id)
.map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
let client = ctx.client()?;
let quote = match client
.inner()
.get_stake_quote(&task_id, Some(args.source.to_quote()))
.await
{
Ok(v) => v.into_inner(),
Err(e) => return Err(map_api_error(e).await.into()),
};
if quote.bond_status.as_deref() == Some("posted") {
return Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"action": "already_posted",
"task_id": task_id.to_string(),
"bond_status": "posted",
}),
));
}
let amount_i64 = args.amount.unwrap_or(quote.required_amount);
if amount_i64 < quote.required_amount {
return Err(CmdError::Usage(format!(
"--amount {amount_i64} is below the quoted required_amount {}; a smaller bond never verifies",
quote.required_amount
)));
}
let amount = U256::from(u64::try_from(amount_i64).map_err(|_| {
CmdError::Usage(format!(
"amount {amount_i64} must be a non-negative integer"
))
})?);
if amount.is_zero() {
return Err(CmdError::Usage("bond amount resolves to 0".into()));
}
let task_bond_override: Option<Address> = args
.task_bond
.as_deref()
.map(|tb| {
tb.parse().map_err(|e| {
CmdError::Usage(format!(
"--task-bond `{tb}` is not a valid EVM address: {e}"
))
})
})
.transpose()?;
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(),
args.wallet_address
.as_deref()
.or(ctx.wallet_address.as_deref()),
"bond post",
)?;
let (rpc_url, chain_id, default_stablecoin, task_bond_contract) =
resolve_network(ctx, &client, &args).await?;
let task_bond: Address = match task_bond_override {
Some(a) => a,
None => {
let tb = task_bond_contract.ok_or_else(|| {
CmdError::Server(
"deployment does not advertise a TaskBond contract \
(`task_bond_contract` in /config/network) for this network; \
pass --task-bond to override"
.into(),
)
})?;
tb.parse().map_err(|e| {
CmdError::Server(format!(
"deployment task_bond_contract `{tb}` is not a valid EVM address: {e}"
))
})?
}
};
let token: Address = match args.token.as_deref() {
Some(t) => t.parse().map_err(|e| {
CmdError::Usage(format!("--token `{t}` is not a valid EVM address: {e}"))
})?,
None => {
let ds = default_stablecoin.ok_or_else(|| {
CmdError::Usage(
"no --token given and the deployment advertises no default_stablecoin; \
pass --token <erc20-address>"
.into(),
)
})?;
ds.parse().map_err(|e| {
CmdError::Server(format!(
"deployment default_stablecoin `{ds}` is not a valid EVM address: {e}"
))
})?
}
};
let task_ref = compute_task_ref(task_id);
let salt = B256::from(rand::random::<[u8; 32]>());
let post_calldata: Bytes = TaskBond::postCall {
token,
amount,
taskRef: task_ref,
salt,
}
.abi_encode()
.into();
if ctx.dry_run {
return Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"action": "would_post_bond",
"task_id": task_id.to_string(),
"task_bond": format!("{task_bond:#x}"),
"token": format!("{token:#x}"),
"amount": amount_i64,
"task_ref": format!("{task_ref:#x}"),
"salt": format!("{salt:#x}"),
"post_calldata": format!("0x{}", hex::encode(&post_calldata)),
"rpc_url": rpc_url,
"chain_id": chain_id,
}),
));
}
let http = ctx.rpc_http_client(&client, &rpc_url);
let rpc = TempoRpcClient::new(http, rpc_url.clone());
let receipt_timeout = resolve_duration(
args.receipt_timeout,
ctx.receipt_timeout,
default_receipt_timeout(chain_id),
);
let session =
crate::tempo_session::TempoSession::new(signer, keystore_path, rpc, receipt_timeout);
let balance = session.erc20_balance_of(token, session.address()).await?;
if balance < amount {
return Err(CmdError::Usage(format!(
"poster balance {balance} < required bond {amount} on token {token:#x}"
)));
}
let mut approval_tx_hex: Option<String> = None;
if !args.skip_allowance_check {
approval_tx_hex = session
.ensure_allowance(token, task_bond, amount)
.await?
.map(|h| format!("{h:#x}"));
}
let post_tx = session
.send_transaction_and_wait(
task_bond,
post_calldata,
"TaskBond.post",
Some(" — report aborted"),
)
.await?;
let post_tx_hex = format!("{post_tx:#x}");
let body = ReportStakePostTxBody {
tx_hash: post_tx_hex.clone(),
stake_source: args.source.to_report(),
};
let report = match client.inner().report_stake_post_tx(&task_id, &body).await {
Ok(r) => r.into_inner(),
Err(e) => return Err(map_api_error(e).await.into()),
};
let verify_timeout = args.verify_timeout.unwrap_or(DEFAULT_VERIFY_TIMEOUT);
let final_status = poll_until_posted(&client, &task_id, args.source, verify_timeout).await;
Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"task_id": report.task_id,
"status": report.status,
"verification": report.verification,
"bond_status": final_status,
"post_tx_hash": post_tx_hex,
"approval_tx_hash": approval_tx_hex,
"token": format!("{token:#x}"),
"amount": amount_i64,
"task_ref": format!("{task_ref:#x}"),
"salt": format!("{salt:#x}"),
}),
))
}
async fn poll_until_posted(
client: &taskfast_client::TaskFastClient,
task_id: &Uuid,
source: BondStakeSource,
timeout: Duration,
) -> Option<String> {
let deadline = tokio::time::Instant::now() + timeout;
let mut last: Option<String> = None;
loop {
if let Ok(v) = client
.inner()
.get_stake_quote(task_id, Some(source.to_quote()))
.await
{
last = v.into_inner().bond_status;
if last.as_deref() == Some("posted") {
return last;
}
}
if tokio::time::Instant::now() + VERIFY_POLL_INTERVAL >= deadline {
return last;
}
tokio::time::sleep(VERIFY_POLL_INTERVAL).await;
}
}
async fn resolve_network(
ctx: &Ctx,
client: &taskfast_client::TaskFastClient,
args: &PostArgs,
) -> Result<(String, i64, Option<String>, Option<String>), CmdError> {
let network = ctx.environment.network();
let cfg = client.fetch_network_config().await.map_err(|e| match e {
taskfast_client::Error::Auth(_) | taskfast_client::Error::Validation { .. } => {
CmdError::Server(format!("fetch network config from {}: {e}", ctx.base_url()))
}
other => CmdError::from(other),
})?;
let name = network.as_str();
let entry = cfg.entry(name).map_err(|e| {
CmdError::Server(format!(
"deployment at {} does not advertise network `{name}`: {e}",
ctx.base_url()
))
})?;
let rpc_url = if let Some(ref override_url) = args.rpc_url {
validate_override_rpc_url(override_url, network, ctx.allow_custom_endpoints)?;
override_url.clone()
} else {
if !is_proxy_rpc_url(&entry.rpc_url, ctx.base_url()) {
return Err(CmdError::Server(format!(
"deployment at {} returned rpc_url {:?} for network `{name}`, which is not on \
the same host. Refusing to route RPC traffic off-host.",
ctx.base_url(),
entry.rpc_url,
)));
}
entry.rpc_url.clone()
};
Ok((
rpc_url,
entry.chain_id,
entry.default_stablecoin.clone(),
entry.task_bond_contract.clone(),
))
}