Skip to main content

taskfast_cli/cmd/
fee.rs

1// SPDX-License-Identifier: MIT
2//! `taskfast fee retry` — re-attempt a failed submission-fee charge.
3//!
4//! Wraps `GET /tasks/{id}/retry-fee` and `POST /tasks/{id}/retry-fee`.
5//! Since 2026-11-01 the server requires the poster's freshly signed fee transfer
6//! (a 0x-hex signed ERC-20 transfer, or the hash of one the poster already broadcast)
7//! in the request body; the original voucher cannot be reused.
8//!
9//! When `--submission-fee-voucher` is omitted, the CLI fetches the payment parameters
10//! (`GET /tasks/{id}/retry-fee`), validates the network allowlists, verifies that
11//! the calldata matches the payment parameters, signs and broadcasts the payment
12//! using the poster's keystore wallet under the per-wallet lock, and submits the
13//! transaction hash to the server.
14//!
15//! If the broadcast succeeds but the server submission fails, the transaction hash
16//! is persisted in `.taskfast/` via `StateStore`. Re-running the command reuses
17//! the broadcast transaction hash rather than paying twice.
18//!
19//! When `--submission-fee-voucher` is passed, the CLI passes the value through unchanged.
20//! 409 `retry_not_needed` / `retry_in_progress` / `fee_executed_unmatched` surface with
21//! their stable codes.
22
23use std::path::PathBuf;
24
25use alloy_primitives::Address;
26use clap::Parser;
27use serde_json::json;
28use uuid::Uuid;
29
30use super::{CmdError, CmdResult, Ctx};
31use crate::envelope::Envelope;
32
33use taskfast_client::api::types::RetrySubmissionFeeRequest;
34use taskfast_client::map_api_error;
35
36alloy_sol_types::sol! {
37    function transfer(address to, uint256 amount);
38    function transferWithMemo(address to, uint256 amount, bytes32 memo_hash);
39}
40
41/// Verify that the calldata in `payload_to_sign` encodes an ERC-20 `transfer`
42/// or TIP-20 `transferWithMemo` call with recipient, amount, and memo matching
43/// the server's payment parameters.
44pub fn validate_fee_calldata(
45    calldata: &[u8],
46    expected_recipient: &str,
47    expected_amount: &str,
48    expected_memo_hash: Option<&str>,
49) -> Result<(), CmdError> {
50    use alloy_sol_types::SolCall;
51
52    let expected_to: Address = expected_recipient.parse().map_err(|e| {
53        CmdError::Server(format!(
54            "server returned invalid recipient `{expected_recipient}`: {e}"
55        ))
56    })?;
57    let expected_amt: alloy_primitives::U256 = expected_amount.parse().map_err(|e| {
58        CmdError::Server(format!(
59            "server returned invalid amount `{expected_amount}`: {e}"
60        ))
61    })?;
62
63    if let Ok(call) = transferWithMemoCall::abi_decode(calldata) {
64        if call.to != expected_to {
65            return Err(CmdError::Validation {
66                code: "calldata_mismatch".into(),
67                message: format!(
68                    "calldata recipient ({:#x}) does not match server recipient ({:#x})",
69                    call.to, expected_to
70                ),
71            });
72        }
73        if call.amount != expected_amt {
74            return Err(CmdError::Validation {
75                code: "calldata_mismatch".into(),
76                message: format!(
77                    "calldata amount ({}) does not match server amount ({})",
78                    call.amount, expected_amt
79                ),
80            });
81        }
82        if let Some(expected_memo) = expected_memo_hash {
83            let expected_memo_b256: alloy_primitives::B256 =
84                expected_memo.parse().map_err(|e| {
85                    CmdError::Server(format!(
86                        "server returned invalid memo_hash `{expected_memo}`: {e}"
87                    ))
88                })?;
89            if call.memo_hash != expected_memo_b256 {
90                return Err(CmdError::Validation {
91                    code: "calldata_mismatch".into(),
92                    message: format!(
93                        "calldata memo_hash ({:#x}) does not match server memo_hash ({:#x})",
94                        call.memo_hash, expected_memo_b256
95                    ),
96                });
97            }
98        }
99        return Ok(());
100    }
101
102    if let Ok(call) = transferCall::abi_decode(calldata) {
103        if call.to != expected_to {
104            return Err(CmdError::Validation {
105                code: "calldata_mismatch".into(),
106                message: format!(
107                    "calldata recipient ({:#x}) does not match server recipient ({:#x})",
108                    call.to, expected_to
109                ),
110            });
111        }
112        if call.amount != expected_amt {
113            return Err(CmdError::Validation {
114                code: "calldata_mismatch".into(),
115                message: format!(
116                    "calldata amount ({}) does not match server amount ({})",
117                    call.amount, expected_amt
118                ),
119            });
120        }
121        return Ok(());
122    }
123
124    Err(CmdError::Validation {
125        code: "invalid_calldata".into(),
126        message: "payload_to_sign is not a valid ERC-20 transfer or TIP-20 transferWithMemo call"
127            .into(),
128    })
129}
130
131#[derive(Debug, clap::Subcommand)]
132pub enum Command {
133    /// Poster: re-attempt the submission-fee charge with a freshly signed fee transfer.
134    Retry(RetryArgs),
135}
136
137#[derive(Debug, Parser)]
138pub struct RetryArgs {
139    /// Task UUID (parked at `blocked_on_submission_fee_debt`).
140    pub task_id: String,
141
142    /// The poster's freshly signed submission-fee transfer (0x-hex), or the
143    /// hash of one already broadcast. The original voucher cannot be reused.
144    /// When omitted, the CLI builds, signs and sends the replacement fee
145    /// payment with the poster's wallet.
146    #[arg(long)]
147    pub submission_fee_voucher: Option<String>,
148
149    /// Poster wallet address (0x-prefixed). Matches `TEMPO_WALLET_ADDRESS`.
150    #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
151    pub wallet_address: Option<String>,
152
153    /// Keystore reference. Accepts a bare path or `file:/path`.
154    #[arg(long, env = "TEMPO_KEY_SOURCE")]
155    pub keystore: Option<String>,
156
157    /// Path to a file holding the keystore password.
158    #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
159    pub wallet_password_file: Option<PathBuf>,
160
161    /// Tempo RPC endpoint override.
162    #[arg(long, env = "TEMPO_RPC_URL")]
163    pub rpc_url: Option<String>,
164}
165
166pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
167    match cmd {
168        Command::Retry(a) => retry(ctx, a).await,
169    }
170}
171
172async fn retry(ctx: &Ctx, args: RetryArgs) -> CmdResult {
173    let task_id = Uuid::parse_str(&args.task_id)
174        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
175    let state_store = ctx.state_store();
176
177    if let Some(voucher) = args.submission_fee_voucher {
178        if voucher.trim().is_empty() {
179            return Err(CmdError::Usage(
180                "--submission-fee-voucher is empty; the server requires the poster's freshly signed \
181                 fee transfer (or the hash of one the poster broadcast). The original voucher \
182                 cannot be reused."
183                    .into(),
184            ));
185        }
186        if ctx.dry_run {
187            return Ok(Envelope::success(
188                ctx.environment,
189                ctx.dry_run,
190                json!({
191                    "action": "would_retry_fee",
192                    "task_id": task_id.to_string(),
193                    "submission_fee_voucher": voucher,
194                }),
195            ));
196        }
197        let client = ctx.client()?;
198        let body = RetrySubmissionFeeRequest {
199            submission_fee_voucher: voucher.parse().map_err(|e| {
200                CmdError::Usage(format!(
201                    "--submission-fee-voucher is not 0x-prefixed hex (the server would answer \
202                     400 invalid_submission_fee_voucher): {e}"
203                ))
204            })?,
205        };
206        let resp = match client.inner().retry_submission_fee(&task_id, &body).await {
207            Ok(v) => {
208                let _ = state_store.clear_pending_fee_retry(&task_id);
209                v.into_inner()
210            }
211            Err(e) => return Err(map_api_error(e).await.into()),
212        };
213        return Ok(Envelope::success(
214            ctx.environment,
215            ctx.dry_run,
216            json!({
217                "task_id": resp.task_id,
218                "status": resp.status,
219                "message": resp.message,
220            }),
221        ));
222    }
223
224    // Pass-through form was not provided. Check whether a previous broadcast
225    // was recorded in local state, avoiding double-payment if server submit failed.
226    let client = ctx.client()?;
227    let pending_voucher = state_store.get_pending_fee_retry(&task_id);
228
229    let voucher_to_submit = if let Some(saved_tx_hash) = pending_voucher {
230        eprintln!(
231            "taskfast: found pending broadcast transaction {saved_tx_hash} for task {task_id}; \
232             reusing to avoid double-payment"
233        );
234        saved_tx_hash
235    } else {
236        // Read payment data from server. Server's GET /retry-fee guards status
237        // and returns 409 retry_not_needed / invalid_status when not retryable.
238        let payment = match client
239            .inner()
240            .get_submission_fee_retry_payment(&task_id)
241            .await
242        {
243            Ok(v) => v.into_inner(),
244            Err(e) => return Err(map_api_error(e).await.into()),
245        };
246
247        if ctx.dry_run {
248            return Ok(Envelope::success(
249                ctx.environment,
250                ctx.dry_run,
251                json!({
252                    "action": "would_retry_fee",
253                    "task_id": task_id.to_string(),
254                    "token_address": payment.token_address,
255                    "recipient": payment.recipient,
256                    "amount": payment.amount,
257                    "memo_text": payment.memo_text,
258                    "memo_hash": payment.memo_hash,
259                }),
260            ));
261        }
262
263        let token_address_str = payment
264            .token_address
265            .as_deref()
266            .ok_or_else(|| CmdError::Server("server returned no token_address".into()))?;
267
268        let payload_str = payment
269            .payload_to_sign
270            .as_deref()
271            .ok_or_else(|| CmdError::Server("server returned no payload_to_sign".into()))?;
272        let calldata = super::wallet_args::decode_0x_bytes(payload_str).map_err(|e| {
273            CmdError::Server(format!("server returned invalid payload_to_sign: {e}"))
274        })?;
275
276        let recipient_str = payment
277            .recipient
278            .as_deref()
279            .ok_or_else(|| CmdError::Server("server returned no recipient".into()))?;
280        let amount_str = payment
281            .amount
282            .as_deref()
283            .ok_or_else(|| CmdError::Server("server returned no amount".into()))?;
284
285        validate_fee_calldata(
286            &calldata,
287            recipient_str,
288            amount_str,
289            payment.memo_hash.as_ref().map(|s| s.as_str()),
290        )?;
291
292        let rpc_url = match args.rpc_url {
293            Some(override_url) => {
294                super::validate_override_rpc_url(
295                    &override_url,
296                    ctx.environment.network(),
297                    ctx.allow_custom_endpoints,
298                )?;
299                override_url
300            }
301            None => super::wallet_args::resolve_proxy_rpc_url(&client, ctx).await?,
302        };
303
304        let keystore_path = super::wallet_args::resolve_keystore_path(
305            args.keystore.as_deref(),
306            ctx.keystore_path.as_deref(),
307        );
308        let signer = super::wallet_args::load_signer_and_validate(
309            keystore_path.as_deref(),
310            args.wallet_password_file.as_deref(),
311            args.wallet_address
312                .as_deref()
313                .or(ctx.wallet_address.as_deref()),
314            "submission fee",
315        )?;
316
317        let tx_hash = super::wallet_args::sign_and_send_submission_fee(
318            ctx,
319            &client,
320            &rpc_url,
321            keystore_path,
322            signer,
323            token_address_str,
324            alloy_primitives::Bytes::from(calldata),
325        )
326        .await?;
327        let tx_hash_hex = format!("{tx_hash:#x}");
328
329        if let Err(e) = state_store.record_pending_fee_retry(&task_id, &tx_hash_hex) {
330            eprintln!("taskfast: warning: failed to persist pending fee retry to state store: {e}");
331        }
332
333        tx_hash_hex
334    };
335
336    let body = RetrySubmissionFeeRequest {
337        submission_fee_voucher: voucher_to_submit
338            .parse()
339            .map_err(|e| CmdError::Server(format!("tx hash rejected by schema pattern: {e}")))?,
340    };
341
342    let resp = match client.inner().retry_submission_fee(&task_id, &body).await {
343        Ok(v) => {
344            let _ = state_store.clear_pending_fee_retry(&task_id);
345            v.into_inner()
346        }
347        Err(e) => {
348            let server_err = map_api_error(e).await;
349            if let taskfast_client::Error::Validation { code, .. } = &server_err {
350                if code == "retry_not_needed" {
351                    let _ = state_store.clear_pending_fee_retry(&task_id);
352                }
353            }
354            let retry_cmd = format!(
355                "taskfast fee retry {task_id} --submission-fee-voucher {voucher_to_submit}"
356            );
357            eprintln!(
358                "taskfast: fee transfer was broadcast ({voucher_to_submit}) but server retry failed: {server_err}.\n\
359                 The pending transaction has been saved locally; re-running `taskfast fee retry {task_id}` will reuse it.\n\
360                 Alternatively, run:\n  {retry_cmd}"
361            );
362            return Err(server_err.into());
363        }
364    };
365
366    Ok(Envelope::success(
367        ctx.environment,
368        ctx.dry_run,
369        json!({
370            "task_id": resp.task_id,
371            "status": resp.status,
372            "message": resp.message,
373            "submission_fee_voucher": voucher_to_submit,
374        }),
375    ))
376}