use std::path::PathBuf;
use alloy_primitives::Address;
use clap::Parser;
use serde_json::json;
use uuid::Uuid;
use super::{CmdError, CmdResult, Ctx};
use crate::envelope::Envelope;
use taskfast_client::api::types::RetrySubmissionFeeRequest;
use taskfast_client::map_api_error;
alloy_sol_types::sol! {
function transfer(address to, uint256 amount);
function transferWithMemo(address to, uint256 amount, bytes32 memo_hash);
}
pub fn validate_fee_calldata(
calldata: &[u8],
expected_recipient: &str,
expected_amount: &str,
expected_memo_hash: Option<&str>,
) -> Result<(), CmdError> {
use alloy_sol_types::SolCall;
let expected_to: Address = expected_recipient.parse().map_err(|e| {
CmdError::Server(format!(
"server returned invalid recipient `{expected_recipient}`: {e}"
))
})?;
let expected_amt: alloy_primitives::U256 = expected_amount.parse().map_err(|e| {
CmdError::Server(format!(
"server returned invalid amount `{expected_amount}`: {e}"
))
})?;
if let Ok(call) = transferWithMemoCall::abi_decode(calldata) {
if call.to != expected_to {
return Err(CmdError::Validation {
code: "calldata_mismatch".into(),
message: format!(
"calldata recipient ({:#x}) does not match server recipient ({:#x})",
call.to, expected_to
),
});
}
if call.amount != expected_amt {
return Err(CmdError::Validation {
code: "calldata_mismatch".into(),
message: format!(
"calldata amount ({}) does not match server amount ({})",
call.amount, expected_amt
),
});
}
if let Some(expected_memo) = expected_memo_hash {
let expected_memo_b256: alloy_primitives::B256 =
expected_memo.parse().map_err(|e| {
CmdError::Server(format!(
"server returned invalid memo_hash `{expected_memo}`: {e}"
))
})?;
if call.memo_hash != expected_memo_b256 {
return Err(CmdError::Validation {
code: "calldata_mismatch".into(),
message: format!(
"calldata memo_hash ({:#x}) does not match server memo_hash ({:#x})",
call.memo_hash, expected_memo_b256
),
});
}
}
return Ok(());
}
if let Ok(call) = transferCall::abi_decode(calldata) {
if call.to != expected_to {
return Err(CmdError::Validation {
code: "calldata_mismatch".into(),
message: format!(
"calldata recipient ({:#x}) does not match server recipient ({:#x})",
call.to, expected_to
),
});
}
if call.amount != expected_amt {
return Err(CmdError::Validation {
code: "calldata_mismatch".into(),
message: format!(
"calldata amount ({}) does not match server amount ({})",
call.amount, expected_amt
),
});
}
return Ok(());
}
Err(CmdError::Validation {
code: "invalid_calldata".into(),
message: "payload_to_sign is not a valid ERC-20 transfer or TIP-20 transferWithMemo call"
.into(),
})
}
#[derive(Debug, clap::Subcommand)]
pub enum Command {
Retry(RetryArgs),
}
#[derive(Debug, Parser)]
pub struct RetryArgs {
pub task_id: String,
#[arg(long)]
pub submission_fee_voucher: 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>,
}
pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
match cmd {
Command::Retry(a) => retry(ctx, a).await,
}
}
async fn retry(ctx: &Ctx, args: RetryArgs) -> CmdResult {
let task_id = Uuid::parse_str(&args.task_id)
.map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
let state_store = ctx.state_store();
if let Some(voucher) = args.submission_fee_voucher {
if voucher.trim().is_empty() {
return Err(CmdError::Usage(
"--submission-fee-voucher is empty; the server requires the poster's freshly signed \
fee transfer (or the hash of one the poster broadcast). The original voucher \
cannot be reused."
.into(),
));
}
if ctx.dry_run {
return Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"action": "would_retry_fee",
"task_id": task_id.to_string(),
"submission_fee_voucher": voucher,
}),
));
}
let client = ctx.client()?;
let body = RetrySubmissionFeeRequest {
submission_fee_voucher: voucher.parse().map_err(|e| {
CmdError::Usage(format!(
"--submission-fee-voucher is not 0x-prefixed hex (the server would answer \
400 invalid_submission_fee_voucher): {e}"
))
})?,
};
let resp = match client.inner().retry_submission_fee(&task_id, &body).await {
Ok(v) => {
let _ = state_store.clear_pending_fee_retry(&task_id);
v.into_inner()
}
Err(e) => return Err(map_api_error(e).await.into()),
};
return Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"task_id": resp.task_id,
"status": resp.status,
"message": resp.message,
}),
));
}
let client = ctx.client()?;
let pending_voucher = state_store.get_pending_fee_retry(&task_id);
let voucher_to_submit = if let Some(saved_tx_hash) = pending_voucher {
eprintln!(
"taskfast: found pending broadcast transaction {saved_tx_hash} for task {task_id}; \
reusing to avoid double-payment"
);
saved_tx_hash
} else {
let payment = match client
.inner()
.get_submission_fee_retry_payment(&task_id)
.await
{
Ok(v) => v.into_inner(),
Err(e) => return Err(map_api_error(e).await.into()),
};
if ctx.dry_run {
return Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"action": "would_retry_fee",
"task_id": task_id.to_string(),
"token_address": payment.token_address,
"recipient": payment.recipient,
"amount": payment.amount,
"memo_text": payment.memo_text,
"memo_hash": payment.memo_hash,
}),
));
}
let token_address_str = payment
.token_address
.as_deref()
.ok_or_else(|| CmdError::Server("server returned no token_address".into()))?;
let payload_str = payment
.payload_to_sign
.as_deref()
.ok_or_else(|| CmdError::Server("server returned no payload_to_sign".into()))?;
let calldata = super::wallet_args::decode_0x_bytes(payload_str).map_err(|e| {
CmdError::Server(format!("server returned invalid payload_to_sign: {e}"))
})?;
let recipient_str = payment
.recipient
.as_deref()
.ok_or_else(|| CmdError::Server("server returned no recipient".into()))?;
let amount_str = payment
.amount
.as_deref()
.ok_or_else(|| CmdError::Server("server returned no amount".into()))?;
validate_fee_calldata(
&calldata,
recipient_str,
amount_str,
payment.memo_hash.as_ref().map(|s| s.as_str()),
)?;
let rpc_url = match args.rpc_url {
Some(override_url) => {
super::validate_override_rpc_url(
&override_url,
ctx.environment.network(),
ctx.allow_custom_endpoints,
)?;
override_url
}
None => super::wallet_args::resolve_proxy_rpc_url(&client, ctx).await?,
};
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()),
"submission fee",
)?;
let tx_hash = super::wallet_args::sign_and_send_submission_fee(
ctx,
&client,
&rpc_url,
keystore_path,
signer,
token_address_str,
alloy_primitives::Bytes::from(calldata),
)
.await?;
let tx_hash_hex = format!("{tx_hash:#x}");
if let Err(e) = state_store.record_pending_fee_retry(&task_id, &tx_hash_hex) {
eprintln!("taskfast: warning: failed to persist pending fee retry to state store: {e}");
}
tx_hash_hex
};
let body = RetrySubmissionFeeRequest {
submission_fee_voucher: voucher_to_submit
.parse()
.map_err(|e| CmdError::Server(format!("tx hash rejected by schema pattern: {e}")))?,
};
let resp = match client.inner().retry_submission_fee(&task_id, &body).await {
Ok(v) => {
let _ = state_store.clear_pending_fee_retry(&task_id);
v.into_inner()
}
Err(e) => {
let server_err = map_api_error(e).await;
if let taskfast_client::Error::Validation { code, .. } = &server_err {
if code == "retry_not_needed" {
let _ = state_store.clear_pending_fee_retry(&task_id);
}
}
let retry_cmd = format!(
"taskfast fee retry {task_id} --submission-fee-voucher {voucher_to_submit}"
);
eprintln!(
"taskfast: fee transfer was broadcast ({voucher_to_submit}) but server retry failed: {server_err}.\n\
The pending transaction has been saved locally; re-running `taskfast fee retry {task_id}` will reuse it.\n\
Alternatively, run:\n {retry_cmd}"
);
return Err(server_err.into());
}
};
Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"task_id": resp.task_id,
"status": resp.status,
"message": resp.message,
"submission_fee_voucher": voucher_to_submit,
}),
))
}