taskfast-cli 0.22.0

`taskfast` CLI: worker + poster hot-loop operations, JSON-envelope output.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
// SPDX-License-Identifier: MIT
//! End-to-end tests for `taskfast fee retry` (the voucher-carrying and
//! wallet-signing successor of `task retry-fee`) and for the old command's redirect.

use alloy_signer_local::PrivateKeySigner;
use serde_json::{json, Value};
use wiremock::matchers::{body_json, body_partial_json, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

use taskfast_cli::cmd::fee::{run, Command, RetryArgs};
use taskfast_cli::cmd::task::{self, IdOnlyArgs};
use taskfast_cli::cmd::{CmdError, Ctx};
use taskfast_cli::{Envelope, Environment};

const TASK_ID: &str = "00000000-0000-0000-0000-0000000000aa";
const VOUCHER: &str = "0xdeadbeef";
const TOKEN_ADDR: &str = "0x20c0000000000000000000000000000000000000";
const RECIPIENT: &str = "0x9999999999999999999999999999999999999999";
const AMOUNT: &str = "250000";
const MEMO_TEXT: &str =
    "submission_fee_retry: task 00000000-0000-0000-0000-0000000000aa replaces 123";
const MEMO_HASH: &str = "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef";

fn ctx_for(server: &MockServer) -> Ctx {
    Ctx {
        api_key: Some("test-key".into()),
        environment: Environment::Local,
        api_base: Some(server.uri()),
        config_path: std::path::PathBuf::from("/dev/null"),
        dry_run: false,
        quiet: true,
        ..Default::default()
    }
}

fn envelope_value(env: &Envelope) -> serde_json::Value {
    serde_json::to_value(env).expect("serialize envelope")
}

fn retry_with_voucher(voucher: &str) -> Command {
    Command::Retry(RetryArgs {
        task_id: TASK_ID.into(),
        submission_fee_voucher: Some(voucher.into()),
        wallet_address: None,
        keystore: None,
        wallet_password_file: None,
        rpc_url: None,
    })
}

fn retry_wallet(
    keystore: &str,
    pw_file: &str,
    wallet_addr: &str,
    rpc_url: Option<String>,
) -> Command {
    Command::Retry(RetryArgs {
        task_id: TASK_ID.into(),
        submission_fee_voucher: None,
        wallet_address: Some(wallet_addr.into()),
        keystore: Some(keystore.into()),
        wallet_password_file: Some(std::path::PathBuf::from(pw_file)),
        rpc_url,
    })
}

fn sample_calldata() -> String {
    use alloy_sol_types::SolCall;
    let call = taskfast_cli::cmd::fee::transferWithMemoCall {
        to: RECIPIENT.parse().unwrap(),
        amount: alloy_primitives::U256::from(250000),
        memo_hash: MEMO_HASH.parse().unwrap(),
    };
    format!("0x{}", hex::encode(call.abi_encode()))
}

struct TestWallet {
    _tmp: tempfile::TempDir,
    keystore_path: String,
    password_path: String,
    address: String,
}

fn create_test_wallet() -> TestWallet {
    let signer = PrivateKeySigner::random();
    let address = format!("{:#x}", signer.address());
    let tmp = tempfile::tempdir().expect("tempdir");
    let keystore_path = tmp.path().join("wallet.json");
    taskfast_agent::keystore::save_signer(&signer, &keystore_path, "pw").expect("save keystore");
    let password_path = tmp.path().join("pw");
    std::fs::write(&password_path, b"pw").expect("write pw");
    TestWallet {
        _tmp: tmp,
        keystore_path: keystore_path.to_str().unwrap().to_string(),
        password_path: password_path.to_str().unwrap().to_string(),
        address,
    }
}

async fn mount_rpc_mocks(server: &MockServer, chain_id: u64, tx_hash_hex: &str) {
    let rpc_ok = |result: Value| {
        ResponseTemplate::new(200).set_body_json(json!({
            "jsonrpc": "2.0",
            "id": 1,
            "result": result,
        }))
    };
    Mock::given(method("POST"))
        .and(body_partial_json(json!({"method": "eth_chainId"})))
        .respond_with(rpc_ok(json!(format!("{:#x}", chain_id))))
        .mount(server)
        .await;
    Mock::given(method("POST"))
        .and(body_partial_json(
            json!({"method": "eth_getTransactionCount"}),
        ))
        .respond_with(rpc_ok(json!("0x0")))
        .mount(server)
        .await;
    Mock::given(method("POST"))
        .and(body_partial_json(json!({"method": "eth_gasPrice"})))
        .respond_with(rpc_ok(json!("0x3b9aca00")))
        .mount(server)
        .await;
    Mock::given(method("POST"))
        .and(body_partial_json(json!({"method": "eth_estimateGas"})))
        .respond_with(rpc_ok(json!("0x4b094")))
        .mount(server)
        .await;
    Mock::given(method("POST"))
        .and(body_partial_json(
            json!({"method": "eth_sendRawTransaction"}),
        ))
        .respond_with(rpc_ok(json!(tx_hash_hex)))
        .mount(server)
        .await;
}

async fn mock_task_status(server: &MockServer, next_action: Option<&str>, message: Option<&str>) {
    Mock::given(method("GET"))
        .and(path(format!("/tasks/{TASK_ID}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "id": TASK_ID,
            "title": "retry test",
            "status": "blocked_on_submission_fee_debt",
            "submission_fee_status": if next_action.is_some() { "failed" } else { "pending_confirmation" },
            "actionable": false,
            "blocked_reason": "submission_fee_debt",
            "next_action": next_action,
            "message": message,
        })))
        .mount(server)
        .await;
}

async fn mock_payment_data(server: &MockServer, token_address: &str) {
    Mock::given(method("GET"))
        .and(path(format!("/tasks/{TASK_ID}/retry-fee")))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "token_address": token_address,
            "recipient": RECIPIENT,
            "amount": AMOUNT,
            "memo_text": MEMO_TEXT,
            "memo_hash": MEMO_HASH,
            "payload_to_sign": sample_calldata(),
        })))
        .mount(server)
        .await;
}

async fn error_with_status(status: u16, code: &str) -> CmdError {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/retry-fee")))
        .respond_with(ResponseTemplate::new(status).set_body_json(json!({
            "error": code,
            "message": "server says no",
        })))
        .mount(&server)
        .await;
    run(&ctx_for(&server), retry_with_voucher(VOUCHER))
        .await
        .expect_err("server refusal must surface")
}

#[tokio::test]
async fn fee_retry_sends_voucher_unchanged_in_body() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/retry-fee")))
        .and(body_json(json!({ "submission_fee_voucher": VOUCHER })))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "task_id": TASK_ID,
            "status": "pending_evaluation",
            "message": "Submission fee charge re-attempted",
        })))
        .expect(1)
        .mount(&server)
        .await;

    let env = run(&ctx_for(&server), retry_with_voucher(VOUCHER))
        .await
        .expect("ok");
    let v = envelope_value(&env);
    assert_eq!(v["data"]["task_id"], TASK_ID);
    assert_eq!(v["data"]["status"], "pending_evaluation");
}

#[tokio::test]
async fn fee_retry_signs_and_broadcasts_when_voucher_omitted() {
    let api_server = MockServer::start().await;
    let rpc_server = MockServer::start().await;
    let wallet = create_test_wallet();
    let tx_hash_hex = format!("0x{}", "bb".repeat(32));

    mock_task_status(&api_server, Some("retry_submission_fee"), None).await;
    mock_payment_data(&api_server, TOKEN_ADDR).await;
    mount_rpc_mocks(&rpc_server, 42431, &tx_hash_hex).await;

    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/retry-fee")))
        .and(body_json(json!({ "submission_fee_voucher": tx_hash_hex })))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "task_id": TASK_ID,
            "status": "pending_evaluation",
            "message": "Submission fee charge re-attempted",
        })))
        .expect(1)
        .mount(&api_server)
        .await;

    let cmd = retry_wallet(
        &wallet.keystore_path,
        &wallet.password_path,
        &wallet.address,
        Some(rpc_server.uri()),
    );
    let mut ctx = ctx_for(&api_server);
    ctx.allow_custom_endpoints = true;

    let env = run(&ctx, cmd).await.expect("fee retry succeeded");
    let v = envelope_value(&env);
    assert_eq!(v["data"]["task_id"], TASK_ID);
    assert_eq!(v["data"]["status"], "pending_evaluation");
    assert_eq!(v["data"]["submission_fee_voucher"], tx_hash_hex);

    // Inspect the broadcast transaction sent to eth_sendRawTransaction
    let raw_tx_requests = rpc_server
        .received_requests()
        .await
        .expect("received requests")
        .into_iter()
        .filter(|req| {
            let body: serde_json::Value = serde_json::from_slice(&req.body).unwrap_or_default();
            body.get("method").and_then(|m| m.as_str()) == Some("eth_sendRawTransaction")
        })
        .collect::<Vec<_>>();
    assert_eq!(raw_tx_requests.len(), 1);
    let rpc_body: serde_json::Value =
        serde_json::from_slice(&raw_tx_requests[0].body).expect("parse jsonrpc");
    let raw_hex = rpc_body["params"][0].as_str().expect("raw tx hex");
    let raw_bytes = hex::decode(raw_hex.strip_prefix("0x").unwrap_or(raw_hex)).expect("decode hex");

    use alloy_consensus::Transaction;
    use alloy_consensus::TxEnvelope;
    use alloy_eips::eip2718::Decodable2718;

    let envelope = TxEnvelope::decode_2718(&mut raw_bytes.as_slice()).expect("decode 2718 tx");
    assert_eq!(
        envelope.to(),
        Some(TOKEN_ADDR.parse::<alloy_primitives::Address>().unwrap()),
        "target of transaction must be allowlisted fee token, NOT recipient"
    );
    let expected_calldata = hex::decode(sample_calldata().strip_prefix("0x").unwrap()).unwrap();
    assert_eq!(
        envelope.input().as_ref(),
        expected_calldata.as_slice(),
        "calldata must match payload_to_sign exactly"
    );
    assert_eq!(envelope.chain_id(), Some(42431));
}

#[tokio::test]
async fn fee_retry_sends_nothing_when_server_reports_retry_not_needed() {
    let api_server = MockServer::start().await;
    let rpc_server = MockServer::start().await;
    let wallet = create_test_wallet();

    Mock::given(method("GET"))
        .and(path(format!("/tasks/{TASK_ID}/retry-fee")))
        .respond_with(ResponseTemplate::new(409).set_body_json(json!({
            "error": "retry_not_needed",
            "message": "Task is not awaiting fee retry",
        })))
        .mount(&api_server)
        .await;

    let cmd = retry_wallet(
        &wallet.keystore_path,
        &wallet.password_path,
        &wallet.address,
        Some(rpc_server.uri()),
    );
    let mut ctx = ctx_for(&api_server);
    ctx.allow_custom_endpoints = true;

    let err = run(&ctx, cmd).await.expect_err("should refuse");
    match err {
        CmdError::Validation { code, message } => {
            assert_eq!(code, "retry_not_needed");
            assert!(
                message.contains("Task is not awaiting fee retry"),
                "expected server reason, got {message}"
            );
        }
        other => panic!("expected Validation error, got {other:?}"),
    }

    assert!(
        rpc_server.received_requests().await.unwrap().is_empty(),
        "zero node requests must be made when server returns retry_not_needed"
    );
}

async fn mount_network_config_mock(server: &MockServer) -> String {
    let uri = server.uri();
    let payload = json!({
        "networks": {
            "testnet": {
                "chain_id": 42431,
                "rpc_url": format!("{uri}/rpc/testnet"),
                "wss_url": "wss://testnet.example.invalid",
                "explorer_url": "https://explorer-testnet.example.invalid",
                "default_stablecoin": "PathUSD"
            }
        }
    });
    Mock::given(method("GET"))
        .and(path("/config/network"))
        .respond_with(ResponseTemplate::new(200).set_body_json(payload))
        .mount(server)
        .await;
    format!("{uri}/rpc/testnet")
}

#[tokio::test]
async fn fee_retry_guards_unknown_chain_id() {
    let api_server = MockServer::start().await;
    let wallet = create_test_wallet();

    let _ = mount_network_config_mock(&api_server).await;
    mock_task_status(&api_server, Some("retry_submission_fee"), None).await;
    mock_payment_data(&api_server, TOKEN_ADDR).await;

    let rpc_ok = |result: Value| {
        ResponseTemplate::new(200).set_body_json(json!({
            "jsonrpc": "2.0",
            "id": 1,
            "result": result,
        }))
    };
    Mock::given(method("POST"))
        .and(path("/rpc/testnet"))
        .and(body_partial_json(json!({"method": "eth_chainId"})))
        .respond_with(rpc_ok(json!("0xf423f"))) // 999999 (unknown chain)
        .mount(&api_server)
        .await;

    let cmd = retry_wallet(
        &wallet.keystore_path,
        &wallet.password_path,
        &wallet.address,
        None,
    );
    let mut ctx = ctx_for(&api_server);
    ctx.environment = Environment::Local;
    ctx.allow_custom_endpoints = false;

    let err = run(&ctx, cmd).await.expect_err("unknown chain should fail");
    match err {
        CmdError::Validation { code, message } => {
            assert_eq!(code, "unknown_chain");
            assert!(message.contains("999999"), "{message}");
        }
        other => panic!("expected Validation unknown_chain, got {other:?}"),
    }
}

#[tokio::test]
async fn fee_retry_guards_disallowed_fee_token() {
    let api_server = MockServer::start().await;
    let rpc_server = MockServer::start().await;
    let wallet = create_test_wallet();
    let tx_hash_hex = format!("0x{}", "bb".repeat(32));

    mock_task_status(&api_server, Some("retry_submission_fee"), None).await;
    // An arbitrary token address not in the PathUSD allowlist
    let bad_token = "0x1111111111111111111111111111111111111111";
    mock_payment_data(&api_server, bad_token).await;
    mount_rpc_mocks(&rpc_server, 42431, &tx_hash_hex).await;

    let cmd = retry_wallet(
        &wallet.keystore_path,
        &wallet.password_path,
        &wallet.address,
        Some(rpc_server.uri()),
    );
    let mut ctx = ctx_for(&api_server);
    ctx.allow_custom_endpoints = true;

    let err = run(&ctx, cmd).await.expect_err("bad token should fail");
    match err {
        CmdError::Validation { code, message } => {
            assert_eq!(code, "fee_token_not_allowed");
            assert!(message.contains(bad_token), "{message}");
        }
        other => panic!("expected fee_token_not_allowed, got {other:?}"),
    }
}

#[tokio::test]
async fn fee_retry_dry_run_prints_payment_data_without_chain_or_submit() {
    let api_server = MockServer::start().await;
    let rpc_server = MockServer::start().await;
    let wallet = create_test_wallet();

    mock_task_status(&api_server, Some("retry_submission_fee"), None).await;
    mock_payment_data(&api_server, TOKEN_ADDR).await;

    let cmd = retry_wallet(
        &wallet.keystore_path,
        &wallet.password_path,
        &wallet.address,
        Some(rpc_server.uri()),
    );
    let mut ctx = ctx_for(&api_server);
    ctx.dry_run = true;
    ctx.allow_custom_endpoints = true;

    let env = run(&ctx, cmd).await.expect("dry-run succeeds");
    let v = envelope_value(&env);
    assert_eq!(v["dry_run"], true);
    assert_eq!(v["data"]["task_id"], TASK_ID);
    assert_eq!(v["data"]["token_address"], TOKEN_ADDR);
    assert!(v["data"].get("token").is_none());
    assert_eq!(v["data"]["recipient"], RECIPIENT);
    assert_eq!(v["data"]["amount"], AMOUNT);
    assert_eq!(v["data"]["memo_text"], MEMO_TEXT);
    assert_eq!(v["data"]["memo_hash"], MEMO_HASH);
    assert!(v["data"].get("memo").is_none());

    assert!(rpc_server.received_requests().await.unwrap().is_empty());
}

#[tokio::test]
async fn fee_retry_server_500_after_broadcast_returns_typed_server_error() {
    let api_server = MockServer::start().await;
    let rpc_server = MockServer::start().await;
    let wallet = create_test_wallet();
    let tx_hash_hex = format!("0x{}", "cc".repeat(32));

    mock_payment_data(&api_server, TOKEN_ADDR).await;
    mount_rpc_mocks(&rpc_server, 42431, &tx_hash_hex).await;

    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/retry-fee")))
        .respond_with(ResponseTemplate::new(500).set_body_json(json!({
            "error": "internal_server_error",
            "message": "database exploded",
        })))
        .mount(&api_server)
        .await;

    let cmd = retry_wallet(
        &wallet.keystore_path,
        &wallet.password_path,
        &wallet.address,
        Some(rpc_server.uri()),
    );
    let mut ctx = ctx_for(&api_server);
    ctx.allow_custom_endpoints = true;

    let err = run(&ctx, cmd)
        .await
        .expect_err("500 after broadcast must error");
    match err {
        CmdError::Server(msg) => {
            assert!(msg.contains("database exploded"));
        }
        other => panic!("expected Server error, got {other:?}"),
    }
}

#[tokio::test]
async fn fee_retry_post_broadcast_server_409_preserves_error_code() {
    let api_server = MockServer::start().await;
    let rpc_server = MockServer::start().await;
    let wallet = create_test_wallet();
    let tx_hash_hex = format!("0x{}", "ee".repeat(32));

    mock_payment_data(&api_server, TOKEN_ADDR).await;
    mount_rpc_mocks(&rpc_server, 42431, &tx_hash_hex).await;

    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/retry-fee")))
        .respond_with(ResponseTemplate::new(409).set_body_json(json!({
            "error": "retry_in_progress",
            "message": "another retry holds the task",
        })))
        .mount(&api_server)
        .await;

    let cmd = retry_wallet(
        &wallet.keystore_path,
        &wallet.password_path,
        &wallet.address,
        Some(rpc_server.uri()),
    );
    let mut ctx = ctx_for(&api_server);
    ctx.allow_custom_endpoints = true;

    let err = run(&ctx, cmd).await.expect_err("409 must fail");
    match err {
        CmdError::Validation { code, message } => {
            assert_eq!(code, "retry_in_progress");
            assert!(message.contains("another retry holds the task"));
        }
        other => panic!("expected Validation retry_in_progress, got {other:?}"),
    }
}

#[tokio::test]
async fn fee_retry_reuses_pending_broadcast_tx_on_server_failure() {
    let api_server = MockServer::start().await;
    let rpc_server = MockServer::start().await;
    let wallet = create_test_wallet();
    let tx_hash_hex = format!("0x{}", "dd".repeat(32));

    mock_payment_data(&api_server, TOKEN_ADDR).await;
    mount_rpc_mocks(&rpc_server, 42431, &tx_hash_hex).await;

    // First attempt: POST /retry-fee returns 500
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/retry-fee")))
        .respond_with(ResponseTemplate::new(500).set_body_json(json!({
            "error": "internal_server_error",
            "message": "database exploded",
        })))
        .up_to_n_times(1)
        .mount(&api_server)
        .await;

    let tmp_config = tempfile::tempdir().expect("tempdir");
    let config_path = tmp_config.path().join("config.json");

    let cmd = retry_wallet(
        &wallet.keystore_path,
        &wallet.password_path,
        &wallet.address,
        Some(rpc_server.uri()),
    );
    let mut ctx = ctx_for(&api_server);
    ctx.config_path = config_path.clone();
    ctx.allow_custom_endpoints = true;

    let err = run(&ctx, cmd).await.expect_err("first run must fail");
    assert!(matches!(err, CmdError::Server(msg) if msg.contains("database exploded")));

    // Verify exactly 1 broadcast occurred on RPC node
    let initial_broadcasts = rpc_server
        .received_requests()
        .await
        .unwrap()
        .into_iter()
        .filter(|req| {
            let body: serde_json::Value = serde_json::from_slice(&req.body).unwrap_or_default();
            body.get("method").and_then(|m| m.as_str()) == Some("eth_sendRawTransaction")
        })
        .count();
    assert_eq!(initial_broadcasts, 1);

    // Second attempt: server returns 200
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK_ID}/retry-fee")))
        .and(body_json(json!({ "submission_fee_voucher": tx_hash_hex })))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "task_id": TASK_ID,
            "status": "pending_evaluation",
            "message": "Submission fee charge re-attempted",
        })))
        .mount(&api_server)
        .await;

    let cmd2 = retry_wallet(
        &wallet.keystore_path,
        &wallet.password_path,
        &wallet.address,
        Some(rpc_server.uri()),
    );
    let env = run(&ctx, cmd2)
        .await
        .expect("second run must reuse tx and succeed");
    let v = envelope_value(&env);
    assert_eq!(v["data"]["task_id"], TASK_ID);
    assert_eq!(v["data"]["submission_fee_voucher"], tx_hash_hex);

    // Verify zero additional broadcasts were sent to RPC node!
    let total_broadcasts = rpc_server
        .received_requests()
        .await
        .unwrap()
        .into_iter()
        .filter(|req| {
            let body: serde_json::Value = serde_json::from_slice(&req.body).unwrap_or_default();
            body.get("method").and_then(|m| m.as_str()) == Some("eth_sendRawTransaction")
        })
        .count();
    assert_eq!(total_broadcasts, 1, "no second broadcast allowed!");

    // Verify pending tx was cleared on success
    let store = ctx.state_store();
    let task_uuid = uuid::Uuid::parse_str(TASK_ID).unwrap();
    assert_eq!(store.get_pending_fee_retry(&task_uuid), None);
}

#[tokio::test]
async fn fee_retry_guards_calldata_recipient_mismatch() {
    let api_server = MockServer::start().await;
    let rpc_server = MockServer::start().await;
    let wallet = create_test_wallet();

    use alloy_sol_types::SolCall;
    let attacker_recipient = "0x8888888888888888888888888888888888888888";
    let bad_call = taskfast_cli::cmd::fee::transferWithMemoCall {
        to: attacker_recipient.parse().unwrap(),
        amount: alloy_primitives::U256::from(250000),
        memo_hash: MEMO_HASH.parse().unwrap(),
    };
    let bad_calldata = format!("0x{}", hex::encode(bad_call.abi_encode()));

    Mock::given(method("GET"))
        .and(path(format!("/tasks/{TASK_ID}/retry-fee")))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "token_address": TOKEN_ADDR,
            "recipient": RECIPIENT,
            "amount": AMOUNT,
            "memo_text": MEMO_TEXT,
            "memo_hash": MEMO_HASH,
            "payload_to_sign": bad_calldata,
        })))
        .mount(&api_server)
        .await;

    let cmd = retry_wallet(
        &wallet.keystore_path,
        &wallet.password_path,
        &wallet.address,
        Some(rpc_server.uri()),
    );
    let mut ctx = ctx_for(&api_server);
    ctx.allow_custom_endpoints = true;

    let err = run(&ctx, cmd)
        .await
        .expect_err("calldata mismatch must fail");
    match err {
        CmdError::Validation { code, message } => {
            assert_eq!(code, "calldata_mismatch");
            assert!(message.contains("recipient"), "{message}");
        }
        other => panic!("expected calldata_mismatch, got {other:?}"),
    }

    assert!(rpc_server.received_requests().await.unwrap().is_empty());
}

#[tokio::test]
async fn fee_retry_empty_voucher_is_usage_error_without_http() {
    let server = MockServer::start().await;
    let err = run(&ctx_for(&server), retry_with_voucher("  "))
        .await
        .expect_err("empty");
    match err {
        CmdError::Usage(m) => assert!(m.contains("freshly signed"), "{m}"),
        other => panic!("expected Usage, got {other:?}"),
    }
    assert!(server.received_requests().await.unwrap().is_empty());
}

#[tokio::test]
async fn fee_retry_non_hex_voucher_is_usage_error_without_http() {
    let server = MockServer::start().await;
    let err = run(&ctx_for(&server), retry_with_voucher("not-hex"))
        .await
        .expect_err("non-hex");
    assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
    assert!(server.received_requests().await.unwrap().is_empty());
}

#[tokio::test]
async fn fee_retry_dry_run_with_voucher_prints_task_and_voucher_without_http() {
    let server = MockServer::start().await;
    let mut ctx = ctx_for(&server);
    ctx.dry_run = true;
    let env = run(&ctx, retry_with_voucher(VOUCHER))
        .await
        .expect("dry-run");
    let v = envelope_value(&env);
    assert_eq!(v["dry_run"], true);
    assert_eq!(v["data"]["task_id"], TASK_ID);
    assert_eq!(v["data"]["submission_fee_voucher"], VOUCHER);
    assert!(server.received_requests().await.unwrap().is_empty());
}

#[tokio::test]
async fn fee_retry_400_invalid_voucher_keeps_stable_code() {
    match error_with_status(400, "invalid_submission_fee_voucher").await {
        CmdError::Validation { code, .. } => assert_eq!(code, "invalid_submission_fee_voucher"),
        other => panic!("expected Validation, got {other:?}"),
    }
}

#[tokio::test]
async fn fee_retry_409_retry_not_needed_keeps_stable_code() {
    match error_with_status(409, "retry_not_needed").await {
        CmdError::Validation { code, .. } => assert_eq!(code, "retry_not_needed"),
        other => panic!("expected Validation, got {other:?}"),
    }
}

#[tokio::test]
async fn fee_retry_409_retry_in_progress_keeps_stable_code() {
    match error_with_status(409, "retry_in_progress").await {
        CmdError::Validation { code, .. } => assert_eq!(code, "retry_in_progress"),
        other => panic!("expected Validation, got {other:?}"),
    }
}

#[tokio::test]
async fn fee_retry_409_fee_executed_unmatched_keeps_stable_code() {
    match error_with_status(409, "fee_executed_unmatched").await {
        CmdError::Validation { code, .. } => assert_eq!(code, "fee_executed_unmatched"),
        other => panic!("expected Validation, got {other:?}"),
    }
}

#[tokio::test]
async fn fee_retry_403_is_auth() {
    assert!(matches!(
        error_with_status(403, "forbidden").await,
        CmdError::Auth(_)
    ));
}

#[tokio::test]
async fn fee_retry_bad_uuid_is_usage_error_without_http() {
    let server = MockServer::start().await;
    let err = run(
        &ctx_for(&server),
        Command::Retry(RetryArgs {
            task_id: "bad".into(),
            submission_fee_voucher: Some(VOUCHER.into()),
            wallet_address: None,
            keystore: None,
            wallet_password_file: None,
            rpc_url: None,
        }),
    )
    .await
    .expect_err("bad uuid");
    assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
    assert!(server.received_requests().await.unwrap().is_empty());
}

#[tokio::test]
async fn old_task_retry_fee_redirects_without_http() {
    let server = MockServer::start().await;
    let err = task::run(
        &ctx_for(&server),
        task::Command::RetryFee(IdOnlyArgs { id: TASK_ID.into() }),
    )
    .await
    .expect_err("redirect");
    match err {
        CmdError::Usage(m) => assert!(m.contains("taskfast fee retry"), "{m}"),
        other => panic!("expected Usage, got {other:?}"),
    }
    assert!(server.received_requests().await.unwrap().is_empty());
}

#[tokio::test]
async fn old_task_retry_fee_dry_run_prints_the_same_redirect() {
    let server = MockServer::start().await;
    let mut ctx = ctx_for(&server);
    ctx.dry_run = true;
    let err = task::run(
        &ctx,
        task::Command::RetryFee(IdOnlyArgs { id: TASK_ID.into() }),
    )
    .await
    .expect_err("redirect even in dry-run");
    assert!(
        matches!(&err, CmdError::Usage(m) if m.contains("taskfast fee retry")),
        "got {err:?}"
    );
}