amp-rust 0.0.4

A Rust client for the Blockstream AMP API, providing interfaces for asset management, user operations, and token handling on the Liquid Network.
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
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
use amp_rs::signer::{Signer, SignerError};
use amp_rs::{AmpError, ElementsRpc, TxInput, Unspent};
use async_trait::async_trait;
use httpmock::prelude::*;

use serde_json::json;
use std::collections::HashMap;

/// Mock signer for testing transaction signing integration
#[derive(Debug, Clone)]
struct MockSigner {
    should_succeed: bool,
    return_value: Option<String>,
    expected_input: Option<String>,
    call_count: std::sync::Arc<std::sync::Mutex<usize>>,
}

impl MockSigner {
    /// Creates a new mock signer that will succeed with a default signed transaction
    fn new_success() -> Self {
        Self {
            should_succeed: true,
            return_value: None,
            expected_input: None,
            call_count: std::sync::Arc::new(std::sync::Mutex::new(0)),
        }
    }

    /// Creates a new mock signer that will fail with a signing error
    fn new_failure() -> Self {
        Self {
            should_succeed: false,
            return_value: None,
            expected_input: None,
            call_count: std::sync::Arc::new(std::sync::Mutex::new(0)),
        }
    }

    /// Creates a mock signer that returns a specific signed transaction
    fn with_return_value(signed_tx: String) -> Self {
        Self {
            should_succeed: true,
            return_value: Some(signed_tx),
            expected_input: None,
            call_count: std::sync::Arc::new(std::sync::Mutex::new(0)),
        }
    }

    /// Creates a mock signer that expects a specific input transaction
    fn with_expected_input(expected: String) -> Self {
        Self {
            should_succeed: true,
            return_value: None,
            expected_input: Some(expected),
            call_count: std::sync::Arc::new(std::sync::Mutex::new(0)),
        }
    }

    /// Returns the number of times sign_transaction was called
    fn call_count(&self) -> usize {
        *self.call_count.lock().unwrap()
    }
}

#[async_trait]
impl Signer for MockSigner {
    async fn sign_transaction(&self, unsigned_tx: &str) -> Result<String, SignerError> {
        // Increment call count
        {
            let mut count = self.call_count.lock().unwrap();
            *count += 1;
        }

        // Check expected input if specified
        if let Some(ref expected) = self.expected_input {
            if unsigned_tx != expected {
                return Err(SignerError::InvalidTransaction(format!(
                    "Expected transaction '{}', got '{}'",
                    expected, unsigned_tx
                )));
            }
        }

        if !self.should_succeed {
            return Err(SignerError::Lwk(
                "Mock signing failure for testing".to_string(),
            ));
        }

        // Return specific value or generate a default signed transaction
        match &self.return_value {
            Some(signed_tx) => Ok(signed_tx.clone()),
            None => {
                // Generate a realistic signed transaction by appending signature data
                Ok(format!("{}deadbeefcafebabe1234567890abcdef", unsigned_tx))
            }
        }
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}
// Helper function to create mock UTXO data for testing
fn create_mock_utxos(asset_id: &str, amounts: Vec<f64>) -> Vec<Unspent> {
    amounts
        .into_iter()
        .enumerate()
        .map(|(i, amount)| Unspent {
            txid: format!("txid_{:03}", i),
            vout: i as u32,
            amount,
            asset: asset_id.to_string(),
            address: format!("address_{}", i),
            spendable: true,
            confirmations: Some(6),
            scriptpubkey: Some(format!("76a914{}88ac", "0".repeat(40))),
            redeemscript: None,
            witnessscript: None,
            amountblinder: Some(format!("{:064}", i)),
            assetblinder: Some(format!("{:064}", i + 1000)),
        })
        .collect()
}

/// Helper function to create mock RPC response for listunspent
fn create_listunspent_mock(
    server: &MockServer,
    _wallet_name: &str,
    _asset_id: &str,
    utxos: Vec<Unspent>,
) {
    use httpmock::Method::POST;

    // Specific mock for createrawtransaction - return transaction hex (must come first)
    server.mock(|when, then| {
        when.method(POST)
            .body_contains("createrawtransaction");
        then.status(200)
            .header("content-type", "application/json")
            .json_body(json!({
                "jsonrpc": "1.0",
                "id": "amp-client",
                "result": "0200000000010123456789abcdef1234567890abcdef1234567890abcdef1234567890abcdef00000000000000000002",
                "error": null
            }));
    });

    // Catch-all mock for all other RPC calls (listunspent, loadwallet, etc.)
    server.mock(|when, then| {
        when.method(POST);
        then.status(200)
            .header("content-type", "application/json")
            .json_body(json!({
                "jsonrpc": "1.0",
                "id": "amp-client",
                "result": utxos,
                "error": null
            }));
    });
}

/// Helper function to create mock RPC response for gettransaction
fn create_gettransaction_mock(
    server: &MockServer,
    txid: &str,
    confirmations: u32,
    blockheight: Option<u64>,
) {
    server.mock(|when, then| {
        when.method(POST).path("/").json_body(json!({
            "jsonrpc": "1.0",
            "id": "amp-client",
            "method": "gettransaction",
            "params": [txid, true]
        }));
        then.status(200).json_body(json!({
            "jsonrpc": "1.0",
            "id": "amp-client",
            "result": {
                "txid": txid,
                "confirmations": confirmations,
                "blockheight": blockheight,
                "hex": "020000000001..."
            },
            "error": null
        }));
    });
}

/// Helper function to create mock RPC response for createrawtransaction

#[tokio::test]
async fn test_utxo_selection_sufficient_funds_single_utxo() {
    let server = MockServer::start();
    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";

    // Create UTXOs: one large UTXO that covers the required amount
    let utxos = create_mock_utxos(asset_id, vec![150.0]);
    create_listunspent_mock(&server, "test_wallet", asset_id, utxos);

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    // Test selecting UTXOs for 100.0 + 1.0 fee = 101.0 total
    let result = rpc
        .select_utxos_for_amount("test_wallet", asset_id, 100.0, 1.0)
        .await;

    match result {
        Ok((selected_utxos, total_amount)) => {
            assert_eq!(selected_utxos.len(), 1);
            assert_eq!(total_amount, 150.0);
            assert_eq!(selected_utxos[0].amount, 150.0);
        }
        Err(e) => {
            println!("Error: {}", e);
            panic!("Test failed with error: {}", e);
        }
    }
}

#[tokio::test]
async fn test_utxo_selection_sufficient_funds_multiple_utxos() {
    let server = MockServer::start();
    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";

    // Create UTXOs: multiple smaller UTXOs that together cover the required amount
    let utxos = create_mock_utxos(asset_id, vec![50.0, 30.0, 40.0, 25.0]);
    create_listunspent_mock(&server, "test_wallet", asset_id, utxos);

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    // Test selecting UTXos for 120.0 + 1.0 fee = 121.0 total
    let result = rpc
        .select_utxos_for_amount("test_wallet", asset_id, 120.0, 1.0)
        .await;

    assert!(result.is_ok());
    let (selected_utxos, total_amount) = result.unwrap();

    // Should select largest UTXOs first: 50.0 + 40.0 + 30.0 = 120.0 (sufficient)
    // or 50.0 + 40.0 + 30.0 + 25.0 = 145.0 depending on algorithm
    assert!(selected_utxos.len() >= 3);
    assert!(total_amount >= 121.0);

    // Verify UTXOs are sorted by amount (largest first)
    for i in 1..selected_utxos.len() {
        assert!(selected_utxos[i - 1].amount >= selected_utxos[i].amount);
    }
}

#[tokio::test]
async fn test_utxo_selection_insufficient_funds() {
    let server = MockServer::start();
    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";

    // Create UTXOs: total amount is less than required
    let utxos = create_mock_utxos(asset_id, vec![10.0, 5.0, 3.0]);
    create_listunspent_mock(&server, "test_wallet", asset_id, utxos);

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    // Try to select UTXOs for 100.0 + 1.0 fee = 101.0 total, but only have 18.0
    let result = rpc
        .select_utxos_for_amount("test_wallet", asset_id, 100.0, 1.0)
        .await;

    assert!(result.is_err());
    let error = result.unwrap_err();
    println!("Actual error: {}", error);
    assert!(error.to_string().contains("Insufficient UTXOs"));
}

#[tokio::test]
async fn test_utxo_selection_no_spendable_utxos() {
    let server = MockServer::start();
    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";

    // Create UTXOs that are not spendable
    let mut utxos = create_mock_utxos(asset_id, vec![100.0, 50.0]);
    for utxo in &mut utxos {
        utxo.spendable = false;
    }
    create_listunspent_mock(&server, "test_wallet", asset_id, utxos);

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    let result = rpc
        .select_utxos_for_amount("test_wallet", asset_id, 50.0, 1.0)
        .await;

    assert!(result.is_err());
    let error = result.unwrap_err();
    assert!(error.to_string().contains("No spendable UTXOs"));
}

#[tokio::test]
async fn test_utxo_selection_exact_amount_needed() {
    let server = MockServer::start();
    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";

    // Create UTXOs that exactly match the required amount
    let utxos = create_mock_utxos(asset_id, vec![50.0, 51.0]);
    create_listunspent_mock(&server, "test_wallet", asset_id, utxos);

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    // Need exactly 101.0 (100.0 + 1.0 fee), have 51.0 + 50.0 = 101.0
    let result = rpc
        .select_utxos_for_amount("test_wallet", asset_id, 100.0, 1.0)
        .await;

    assert!(result.is_ok());
    let (selected_utxos, total_amount) = result.unwrap();
    assert_eq!(selected_utxos.len(), 2);
    assert_eq!(total_amount, 101.0);
}

#[tokio::test]
async fn test_utxo_selection_algorithm_largest_first() {
    let server = MockServer::start();
    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";

    // Create UTXOs in random order to test sorting
    let utxos = create_mock_utxos(asset_id, vec![25.0, 100.0, 10.0, 75.0, 50.0]);
    create_listunspent_mock(&server, "test_wallet", asset_id, utxos);

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    // Need 120.0 + 1.0 fee = 121.0 total
    let result = rpc
        .select_utxos_for_amount("test_wallet", asset_id, 120.0, 1.0)
        .await;

    assert!(result.is_ok());
    let (selected_utxos, total_amount) = result.unwrap();

    // Should select 100.0 + 75.0 = 175.0 (largest first algorithm)
    assert!(total_amount >= 121.0);

    // Verify first UTXO is the largest available
    assert_eq!(selected_utxos[0].amount, 100.0);

    // Verify UTXOs are in descending order by amount
    for i in 1..selected_utxos.len() {
        assert!(selected_utxos[i - 1].amount >= selected_utxos[i].amount);
    }
}

#[tokio::test]
async fn test_transaction_construction_with_mock_signer_success() {
    let server = MockServer::start();
    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";

    // Setup UTXO mock
    let utxos = create_mock_utxos(asset_id, vec![150.0]);
    create_listunspent_mock(&server, "test_wallet", asset_id, utxos);

    // Setup transaction creation mock
    let mut address_amounts = HashMap::new();
    address_amounts.insert("recipient1".to_string(), 100.0);

    let mut expected_outputs = HashMap::new();
    expected_outputs.insert("recipient1".to_string(), 100.0);
    expected_outputs.insert("address_0".to_string(), 49.0); // Change: 150 - 100 - 1 fee

    let mut expected_assets = HashMap::new();
    expected_assets.insert("recipient1".to_string(), asset_id.to_string());
    expected_assets.insert("address_0".to_string(), asset_id.to_string());

    let _expected_inputs = vec![TxInput {
        txid: "txid_000".to_string(),
        vout: 0,
        sequence: None,
    }];

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    // Test transaction construction
    let result = rpc
        .build_distribution_transaction(
            "test_wallet",
            asset_id,
            address_amounts,
            "address_0", // change address
            1.0,         // fee
        )
        .await;

    if result.is_err() {
        println!("Error: {}", result.as_ref().unwrap_err());
    }
    assert!(result.is_ok());
    let (raw_tx, selected_utxos, change_amount) = result.unwrap();

    // Verify transaction was built
    assert!(!raw_tx.is_empty());
    assert_eq!(selected_utxos.len(), 1);
    assert_eq!(change_amount, 50.0);
}

#[tokio::test]
async fn test_signer_integration_success() {
    let server = MockServer::start();
    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    let unsigned_tx = "0200000000010123456789abcdef1234567890abcdef1234567890abcdef1234567890abcdef00000000000000000002";
    let expected_signed_tx = format!("{}deadbeefcafebabe1234567890abcdef", unsigned_tx);

    let mock_signer = MockSigner::new_success();

    let result = rpc.sign_transaction(unsigned_tx, &mock_signer).await;

    assert!(result.is_ok());
    let signed_tx = result.unwrap();
    assert_eq!(signed_tx, expected_signed_tx);
    assert_eq!(mock_signer.call_count(), 1);
}

#[tokio::test]
async fn test_signer_integration_failure() {
    let server = MockServer::start();
    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    let unsigned_tx = "0200000000010123456789abcdef1234567890abcdef1234567890abcdef1234567890abcdef00000000000000000002";

    let mock_signer = MockSigner::new_failure();

    let result = rpc.sign_transaction(unsigned_tx, &mock_signer).await;

    assert!(result.is_err());
    let error = result.unwrap_err();
    assert!(error.to_string().contains("Mock signing failure"));
    assert_eq!(mock_signer.call_count(), 1);
}

#[tokio::test]
async fn test_signer_integration_with_expected_input() {
    let server = MockServer::start();
    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    let unsigned_tx = "0200000000010123456789abcdef1234567890abcdef1234567890abcdef1234567890abcdef00000000000000000002";

    let mock_signer = MockSigner::with_expected_input(unsigned_tx.to_string());

    let result = rpc.sign_transaction(unsigned_tx, &mock_signer).await;

    assert!(result.is_ok());
    assert_eq!(mock_signer.call_count(), 1);
}

#[tokio::test]
async fn test_signer_integration_with_wrong_input() {
    let server = MockServer::start();
    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    let unsigned_tx = "0200000000010123456789abcdef1234567890abcdef1234567890abcdef1234567890abcdef00000000000000000002";
    let expected_tx = "different_transaction_hex";

    let mock_signer = MockSigner::with_expected_input(expected_tx.to_string());

    let result = rpc.sign_transaction(unsigned_tx, &mock_signer).await;

    assert!(result.is_err());
    let error = result.unwrap_err();
    assert!(error.to_string().contains("Expected transaction"));
    assert_eq!(mock_signer.call_count(), 1);
}

#[tokio::test]
async fn test_signer_integration_with_custom_return_value() {
    let server = MockServer::start();
    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    let unsigned_tx = "0200000000010123456789abcdef1234567890abcdef1234567890abcdef1234567890abcdef00000000000000000002";
    let custom_signed_tx = "0200000000010123456789abcdef1234567890abcdef1234567890abcdef1234567890abcdef00000000deadbeef00000000";

    let mock_signer = MockSigner::with_return_value(custom_signed_tx.to_string());

    let result = rpc.sign_transaction(unsigned_tx, &mock_signer).await;

    if result.is_err() {
        println!("Error: {}", result.as_ref().unwrap_err());
    }
    assert!(result.is_ok());
    let signed_tx = result.unwrap();
    assert_eq!(signed_tx, custom_signed_tx);
    assert_eq!(mock_signer.call_count(), 1);
}

#[tokio::test]
async fn test_transaction_structure_validation_empty_hex() {
    let server = MockServer::start();
    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    let mock_signer = MockSigner::new_success();

    let result = rpc.sign_transaction("", &mock_signer).await;

    assert!(result.is_err());
    let error = result.unwrap_err();
    assert!(error.to_string().contains("cannot be empty"));
    assert_eq!(mock_signer.call_count(), 0); // Should not call signer for invalid input
}

#[tokio::test]
async fn test_transaction_structure_validation_odd_length_hex() {
    let server = MockServer::start();
    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    let mock_signer = MockSigner::new_success();

    let result = rpc.sign_transaction("abc", &mock_signer).await;

    assert!(result.is_err());
    let error = result.unwrap_err();
    assert!(error.to_string().contains("even length"));
    assert_eq!(mock_signer.call_count(), 0); // Should not call signer for invalid input
}

#[tokio::test]
async fn test_transaction_structure_validation_invalid_hex_characters() {
    let server = MockServer::start();
    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    let mock_signer = MockSigner::new_success();

    let result = rpc.sign_transaction("abcg", &mock_signer).await;

    assert!(result.is_err());
    let error = result.unwrap_err();
    assert!(error.to_string().contains("invalid hex characters"));
    assert_eq!(mock_signer.call_count(), 0); // Should not call signer for invalid input
}

#[tokio::test]
async fn test_liquid_specific_transaction_format() {
    let server = MockServer::start();
    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";

    // Setup UTXO mock with Liquid-specific asset ID
    let utxos = create_mock_utxos(asset_id, vec![100.0]);
    create_listunspent_mock(&server, "test_wallet", asset_id, utxos);

    // Setup transaction creation mock with Liquid-specific outputs
    let mut address_amounts = HashMap::new();
    address_amounts.insert(
        "lq1qq2xvpcvfup5j8zscjq05u2wxxjcyewk7979f9lq".to_string(),
        50.0,
    );

    let mut expected_outputs = HashMap::new();
    expected_outputs.insert(
        "lq1qq2xvpcvfup5j8zscjq05u2wxxjcyewk7979f9lq".to_string(),
        50.0,
    );
    expected_outputs.insert("address_0".to_string(), 49.0); // Change

    let mut expected_assets = HashMap::new();
    expected_assets.insert(
        "lq1qq2xvpcvfup5j8zscjq05u2wxxjcyewk7979f9lq".to_string(),
        asset_id.to_string(),
    );
    expected_assets.insert("address_0".to_string(), asset_id.to_string());

    let _expected_inputs = vec![TxInput {
        txid: "txid_000".to_string(),
        vout: 0,
        sequence: None,
    }];

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    let result = rpc
        .build_distribution_transaction(
            "test_wallet",
            asset_id,
            address_amounts,
            "address_0", // change address
            1.0,         // fee
        )
        .await;

    assert!(result.is_ok());
    let (raw_tx, selected_utxos, change_amount) = result.unwrap();

    // Verify Liquid-specific transaction structure
    assert!(!raw_tx.is_empty());
    assert!(raw_tx.starts_with("02")); // Liquid transaction version
    assert_eq!(selected_utxos.len(), 1);
    assert_eq!(selected_utxos[0].asset, asset_id); // Verify asset ID is preserved
    assert_eq!(change_amount, 50.0);
}

#[tokio::test]
async fn test_transaction_construction_with_multiple_outputs() {
    let server = MockServer::start();
    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";

    // Setup UTXO mock with sufficient funds
    let utxos = create_mock_utxos(asset_id, vec![200.0]);
    create_listunspent_mock(&server, "test_wallet", asset_id, utxos);

    // Setup transaction creation mock with multiple outputs
    let mut address_amounts = HashMap::new();
    address_amounts.insert("recipient1".to_string(), 50.0);
    address_amounts.insert("recipient2".to_string(), 75.0);

    let mut expected_outputs = HashMap::new();
    expected_outputs.insert("recipient1".to_string(), 50.0);
    expected_outputs.insert("recipient2".to_string(), 75.0);
    expected_outputs.insert("address_0".to_string(), 73.0); // Change: 200 - 50 - 75 - 2 fee

    let mut expected_assets = HashMap::new();
    expected_assets.insert("recipient1".to_string(), asset_id.to_string());
    expected_assets.insert("recipient2".to_string(), asset_id.to_string());
    expected_assets.insert("address_0".to_string(), asset_id.to_string());

    let _expected_inputs = vec![TxInput {
        txid: "txid_000".to_string(),
        vout: 0,
        sequence: None,
    }];

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    let result = rpc
        .build_distribution_transaction(
            "test_wallet",
            asset_id,
            address_amounts,
            "address_0", // change address
            2.0,         // fee
        )
        .await;

    assert!(result.is_ok());
    let (raw_tx, selected_utxos, change_amount) = result.unwrap();

    // Verify transaction with multiple outputs
    assert!(!raw_tx.is_empty());
    assert_eq!(selected_utxos.len(), 1);
    assert_eq!(change_amount, 75.0);
}

#[tokio::test]
async fn test_transaction_construction_no_change_needed() {
    let server = MockServer::start();
    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";

    // Setup UTXO mock with exact amount needed
    let utxos = create_mock_utxos(asset_id, vec![101.0]);
    create_listunspent_mock(&server, "test_wallet", asset_id, utxos);

    // Setup transaction creation mock with no change output
    let mut address_amounts = HashMap::new();
    address_amounts.insert("recipient1".to_string(), 100.0);

    let mut expected_outputs = HashMap::new();
    expected_outputs.insert("recipient1".to_string(), 100.0);
    // No change output expected

    let mut expected_assets = HashMap::new();
    expected_assets.insert("recipient1".to_string(), asset_id.to_string());

    let _expected_inputs = vec![TxInput {
        txid: "txid_000".to_string(),
        vout: 0,
        sequence: None,
    }];

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    let result = rpc
        .build_distribution_transaction(
            "test_wallet",
            asset_id,
            address_amounts,
            "address_0", // change address
            1.0,         // fee
        )
        .await;

    assert!(result.is_ok());
    let (raw_tx, selected_utxos, change_amount) = result.unwrap();

    // Verify transaction with no change
    assert!(!raw_tx.is_empty());
    assert_eq!(selected_utxos.len(), 1);
    assert_eq!(change_amount, 1.0); // Change is 101 - 100 = 1.0
}

#[tokio::test]
async fn test_transaction_construction_dust_change_handling() {
    let server = MockServer::start();
    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";

    // Setup UTXO mock with amount that would create dust change
    let utxos = create_mock_utxos(asset_id, vec![100.5]);
    create_listunspent_mock(&server, "test_wallet", asset_id, utxos);

    // Setup transaction creation mock - change amount is 0.4 which is above dust threshold
    let mut address_amounts = HashMap::new();
    address_amounts.insert("recipient1".to_string(), 100.0);

    let mut expected_outputs = HashMap::new();
    expected_outputs.insert("recipient1".to_string(), 100.0);
    expected_outputs.insert("address_0".to_string(), 0.4); // Change: 100.5 - 100.0 - 0.1 = 0.4

    let mut expected_assets = HashMap::new();
    expected_assets.insert("recipient1".to_string(), asset_id.to_string());
    expected_assets.insert("address_0".to_string(), asset_id.to_string());

    let _expected_inputs = vec![TxInput {
        txid: "txid_000".to_string(),
        vout: 0,
        sequence: None,
    }];

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    let result = rpc
        .build_distribution_transaction(
            "test_wallet",
            asset_id,
            address_amounts,
            "address_0", // change address
            0.1,         // small fee
        )
        .await;

    assert!(result.is_ok());
    let (raw_tx, selected_utxos, change_amount) = result.unwrap();

    // Verify dust change handling
    assert!(!raw_tx.is_empty());
    assert_eq!(selected_utxos.len(), 1);
    assert_eq!(change_amount, 0.5); // 100.5 - 100.0 = 0.5
}

#[tokio::test]
async fn test_transaction_construction_zero_amount_distribution() {
    let rpc = ElementsRpc::new(
        "http://localhost:18884".to_string(),
        "user".to_string(),
        "pass".to_string(),
    );

    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";
    let address_amounts = HashMap::new(); // Empty distribution

    let result = rpc
        .build_distribution_transaction(
            "test_wallet",
            asset_id,
            address_amounts,
            "change_address", // change address
            1.0,
        )
        .await;

    assert!(result.is_err());
    let error = result.unwrap_err();
    println!("Actual error: {}", error);
    assert!(error
        .to_string()
        .contains("Total distribution amount must be greater than zero"));
}

#[tokio::test]
async fn test_signer_validation_comprehensive() {
    let server = MockServer::start();
    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    // Test cases for various invalid transaction formats
    let test_cases = vec![
        ("", "cannot be empty"),
        ("abc", "even length"),
        ("abcg", "invalid hex characters"),
    ];

    for (invalid_tx, expected_error) in test_cases {
        let mock_signer = MockSigner::new_success();
        let result = rpc.sign_transaction(invalid_tx, &mock_signer).await;

        assert!(
            result.is_err(),
            "Expected error for input: '{}'",
            invalid_tx
        );
        let error = result.unwrap_err();
        assert!(
            error.to_string().contains(expected_error),
            "Expected error containing '{}', got: '{}'",
            expected_error,
            error
        );
        assert_eq!(
            mock_signer.call_count(),
            0,
            "Signer should not be called for invalid input: '{}'",
            invalid_tx
        );
    }
}

#[tokio::test]
async fn test_signer_return_value_validation() {
    let server = MockServer::start();
    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    let unsigned_tx = "0200000000010123456789abcdef1234567890abcdef1234567890abcdef1234567890abcdef00000000000000000002";

    // Test signer returning empty string
    let mock_signer = MockSigner::with_return_value("".to_string());
    let result = rpc.sign_transaction(unsigned_tx, &mock_signer).await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("cannot be empty"));

    // Test signer returning odd length hex
    let mock_signer = MockSigner::with_return_value("abc".to_string());
    let result = rpc.sign_transaction(unsigned_tx, &mock_signer).await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("even length"));

    // Test signer returning invalid hex
    let mock_signer = MockSigner::with_return_value("abcg".to_string());
    let result = rpc.sign_transaction(unsigned_tx, &mock_signer).await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("invalid hex"));

    // Test signer returning transaction that meets length requirement but is below minimum size
    let short_unsigned_tx = "abcd"; // 2 bytes when decoded
    let mock_signer = MockSigner::with_return_value("abcdef".to_string()); // 3 bytes when decoded, longer than unsigned but below 10 byte minimum
    let result = rpc.sign_transaction(short_unsigned_tx, &mock_signer).await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("minimum size"));
}

#[tokio::test]
async fn test_utxo_selection_edge_cases() {
    let server = MockServer::start();
    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";

    // Test with zero fee
    let utxos = create_mock_utxos(asset_id, vec![100.0]);
    create_listunspent_mock(&server, "test_wallet", asset_id, utxos);

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    let result = rpc
        .select_utxos_for_amount("test_wallet", asset_id, 100.0, 0.0)
        .await;
    assert!(result.is_ok());
    let (selected_utxos, total_amount) = result.unwrap();
    assert_eq!(selected_utxos.len(), 1);
    assert_eq!(total_amount, 100.0);
}

#[tokio::test]
async fn test_utxo_selection_with_confirmations_filter() {
    let server = MockServer::start();
    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";

    // Create UTXOs with different confirmation counts
    let mut utxos = create_mock_utxos(asset_id, vec![100.0, 50.0]);
    utxos[0].confirmations = Some(6); // Confirmed
    utxos[1].confirmations = Some(0); // Unconfirmed

    create_listunspent_mock(&server, "test_wallet", asset_id, utxos);

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    let result = rpc
        .select_utxos_for_amount("test_wallet", asset_id, 75.0, 1.0)
        .await;

    assert!(result.is_ok());
    let (selected_utxos, total_amount) = result.unwrap();

    // Should select confirmed UTXOs preferentially
    assert!(total_amount >= 76.0);
    for utxo in &selected_utxos {
        // All selected UTXOs should be spendable
        assert!(utxo.spendable);
    }
}

#[tokio::test]
async fn test_confirmation_polling_success_immediate() {
    let server = MockServer::start();
    let txid = "test_txid_immediate_confirmation";

    // Mock get_transaction to return transaction with sufficient confirmations immediately
    create_gettransaction_mock(&server, txid, 3, Some(12345));

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    // Test with 2 required confirmations - should succeed immediately
    let result = rpc.wait_for_confirmations(txid, Some(2), Some(1)).await;

    if result.is_err() {
        println!("Error: {:?}", result.as_ref().unwrap_err());
    }
    assert!(result.is_ok());
    let tx_detail = result.unwrap();
    assert_eq!(tx_detail.txid, txid);
    assert_eq!(tx_detail.confirmations, 3);
    assert!(tx_detail.confirmations >= 2);
}

#[tokio::test]
async fn test_confirmation_polling_success_after_wait() {
    let server = MockServer::start();
    let txid = "test_txid_delayed_confirmation";

    // Mock get_transaction to return sufficient confirmations
    create_gettransaction_mock(&server, txid, 2, Some(12345));

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    // Test with fast polling interval to speed up test
    let result = rpc
        .wait_for_confirmations_with_interval(txid, Some(2), Some(1), Some(1))
        .await;

    assert!(result.is_ok());
    let tx_detail = result.unwrap();
    assert_eq!(tx_detail.txid, txid);
    assert_eq!(tx_detail.confirmations, 2);
}

#[tokio::test]
async fn test_confirmation_polling_timeout() {
    let server = MockServer::start();
    let txid = "test_txid_timeout";

    // Mock get_transaction to always return 0 confirmations
    create_gettransaction_mock(&server, txid, 0, None);

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    // Test with very short timeout and fast polling
    let result = rpc
        .wait_for_confirmations_with_interval(txid, Some(2), Some(0), Some(1))
        .await;

    assert!(result.is_err());
    let error = result.unwrap_err();
    assert!(matches!(error, AmpError::Timeout(_)));
    assert!(error
        .to_string()
        .contains("Timeout waiting for confirmations"));
    assert!(error.to_string().contains(txid));
    assert!(error.to_string().contains("You can retry confirmation"));
}

#[tokio::test]
async fn test_confirmation_polling_rpc_errors_with_recovery() {
    let server = MockServer::start();
    let txid = "test_txid_rpc_errors";

    // Mock successful response - the polling logic handles RPC errors by continuing to poll
    create_gettransaction_mock(&server, txid, 3, Some(12345));

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    // Should succeed with sufficient confirmations
    let result = rpc
        .wait_for_confirmations_with_interval(txid, Some(2), Some(1), Some(1))
        .await;

    assert!(result.is_ok());
    let tx_detail = result.unwrap();
    assert_eq!(tx_detail.txid, txid);
    assert_eq!(tx_detail.confirmations, 3);
}

#[tokio::test]
async fn test_confirmation_polling_default_parameters() {
    let server = MockServer::start();
    let txid = "test_txid_defaults";

    // Mock get_transaction to return exactly 2 confirmations (default minimum)
    create_gettransaction_mock(&server, txid, 2, Some(12345));

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    // Test with default parameters (None values)
    let result = rpc.wait_for_confirmations(txid, None, None).await;

    assert!(result.is_ok());
    let tx_detail = result.unwrap();
    assert_eq!(tx_detail.confirmations, 2);
}

#[tokio::test]
async fn test_confirmation_polling_custom_minimum_confirmations() {
    let server = MockServer::start();
    let txid = "test_txid_custom_min";

    // Mock get_transaction to return 5 confirmations
    create_gettransaction_mock(&server, txid, 5, Some(12345));

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    // Test with custom minimum confirmations (6) - should timeout since we only have 5
    let result = rpc
        .wait_for_confirmations_with_interval(txid, Some(6), Some(0), Some(1))
        .await;

    assert!(result.is_err());
    assert!(matches!(result.unwrap_err(), AmpError::Timeout(_)));

    // Test with lower minimum confirmations (3) - should succeed
    let result = rpc.wait_for_confirmations(txid, Some(3), Some(1)).await;

    assert!(result.is_ok());
    let tx_detail = result.unwrap();
    assert_eq!(tx_detail.confirmations, 5);
    assert!(tx_detail.confirmations >= 3);
}

#[tokio::test]
async fn test_change_data_collection_success_with_multiple_outputs() {
    let server = MockServer::start();
    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";
    let txid = "test_txid_change_multiple";

    // Mock loadwallet first
    server.mock(|when, then| {
        when.method(POST).path("/").json_body(json!({
            "jsonrpc": "1.0",
            "id": "amp-client",
            "method": "loadwallet",
            "params": ["test_wallet"]
        }));
        then.status(200).json_body(json!({
            "jsonrpc": "1.0",
            "id": "amp-client",
            "result": {"name": "test_wallet", "warning": ""},
            "error": null
        }));
    });

    // Mock listunspent on wallet-specific endpoint with correct parameters
    server.mock(|when, then| {
        when.method(POST)
            .path("/wallet/test_wallet")
            .json_body(json!({
                "jsonrpc": "1.0",
                "id": "amp-client",
                "method": "listunspent",
                "params": [0, 9999999, [], true, {}]
            }));
        then.status(200).json_body(json!({
            "jsonrpc": "1.0",
            "id": "amp-client",
            "result": [
                {
                    "txid": txid,
                    "vout": 1,
                    "amount": 25.5,
                    "asset": asset_id,
                    "address": "change_address_1",
                    "spendable": true,
                    "confirmations": 3
                },
                {
                    "txid": txid,
                    "vout": 2,
                    "amount": 10.0,
                    "asset": asset_id,
                    "address": "change_address_2",
                    "spendable": true,
                    "confirmations": 3
                },
                {
                    "txid": "different_txid",
                    "vout": 0,
                    "amount": 50.0,
                    "asset": asset_id,
                    "address": "other_address",
                    "spendable": true,
                    "confirmations": 6
                }
            ],
            "error": null
        }));
    });

    let rpc = ElementsRpc::new(
        server.url("/").trim_end_matches('/').to_string(),
        "user".to_string(),
        "pass".to_string(),
    );

    let result = rpc
        .collect_change_data(asset_id, txid, &rpc, "test_wallet")
        .await;

    assert!(result.is_ok());
    let change_data = result.unwrap();

    // Should only return UTXOs from the specified transaction
    assert_eq!(change_data.len(), 2);

    // Verify all returned UTXOs are from the correct transaction
    for utxo in &change_data {
        assert_eq!(utxo.txid, txid);
        assert_eq!(utxo.asset, asset_id);
        assert!(utxo.spendable);
    }

    // Verify specific amounts
    let amounts: Vec<f64> = change_data.iter().map(|u| u.amount).collect();
    assert!(amounts.contains(&25.5));
    assert!(amounts.contains(&10.0));
}

#[tokio::test]
async fn test_change_data_collection_no_change_outputs() {
    let server = MockServer::start();
    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";
    let txid = "test_txid_no_change";

    // Mock loadwallet first
    server.mock(|when, then| {
        when.method(POST).path("/").json_body(json!({
            "jsonrpc": "1.0",
            "id": "amp-client",
            "method": "loadwallet",
            "params": ["test_wallet"]
        }));
        then.status(200).json_body(json!({
            "jsonrpc": "1.0",
            "id": "amp-client",
            "result": {"name": "test_wallet", "warning": ""},
            "error": null
        }));
    });

    // Mock listunspent on wallet-specific endpoint with correct parameters
    server.mock(|when, then| {
        when.method(POST)
            .path("/wallet/test_wallet")
            .json_body(json!({
                "jsonrpc": "1.0",
                "id": "amp-client",
                "method": "listunspent",
                "params": [0, 9999999, [], true, {}]
            }));
        then.status(200).json_body(json!({
            "jsonrpc": "1.0",
            "id": "amp-client",
            "result": [
                {
                    "txid": "different_txid_1",
                    "vout": 0,
                    "amount": 100.0,
                    "asset": asset_id,
                    "address": "other_address_1",
                    "spendable": true,
                    "confirmations": 6
                },
                {
                    "txid": "different_txid_2",
                    "vout": 1,
                    "amount": 50.0,
                    "asset": asset_id,
                    "address": "other_address_2",
                    "spendable": true,
                    "confirmations": 3
                }
            ],
            "error": null
        }));
    });

    let rpc = ElementsRpc::new(
        server.url("/").trim_end_matches('/').to_string(),
        "user".to_string(),
        "pass".to_string(),
    );

    let result = rpc
        .collect_change_data(asset_id, txid, &rpc, "test_wallet")
        .await;

    assert!(result.is_ok());
    let change_data = result.unwrap();

    // Should return empty vector when no change outputs exist
    assert_eq!(change_data.len(), 0);
}

#[tokio::test]
async fn test_change_data_collection_filters_unspendable() {
    let server = MockServer::start();
    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";
    let txid = "test_txid_unspendable";

    // Mock loadwallet first
    server.mock(|when, then| {
        when.method(POST).path("/").json_body(json!({
            "jsonrpc": "1.0",
            "id": "amp-client",
            "method": "loadwallet",
            "params": ["test_wallet"]
        }));
        then.status(200).json_body(json!({
            "jsonrpc": "1.0",
            "id": "amp-client",
            "result": {"name": "test_wallet", "warning": ""},
            "error": null
        }));
    });

    // Mock listunspent on wallet-specific endpoint with correct parameters
    server.mock(|when, then| {
        when.method(POST)
            .path("/wallet/test_wallet")
            .json_body(json!({
                "jsonrpc": "1.0",
                "id": "amp-client",
                "method": "listunspent",
                "params": [0, 9999999, [], true, {}]
            }));
        then.status(200).json_body(json!({
            "jsonrpc": "1.0",
            "id": "amp-client",
            "result": [
                {
                    "txid": txid,
                    "vout": 0,
                    "amount": 25.0,
                    "asset": asset_id,
                    "address": "spendable_address",
                    "spendable": true,
                    "confirmations": 3
                },
                {
                    "txid": txid,
                    "vout": 1,
                    "amount": 15.0,
                    "asset": asset_id,
                    "address": "unspendable_address",
                    "spendable": false,
                    "confirmations": 3
                }
            ],
            "error": null
        }));
    });

    let rpc = ElementsRpc::new(
        server.url("/").trim_end_matches('/').to_string(),
        "user".to_string(),
        "pass".to_string(),
    );

    let result = rpc
        .collect_change_data(asset_id, txid, &rpc, "test_wallet")
        .await;

    if result.is_err() {
        println!("Error: {}", result.as_ref().unwrap_err());
    }
    assert!(result.is_ok());
    let change_data = result.unwrap();

    // Should only return spendable UTXOs
    assert_eq!(change_data.len(), 1);
    assert_eq!(change_data[0].amount, 25.0);
    assert!(change_data[0].spendable);
    assert_eq!(change_data[0].address, "spendable_address");
}

#[tokio::test]
async fn test_change_data_collection_filters_wrong_asset() {
    let server = MockServer::start();
    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";
    let different_asset_id = "different_asset_id_hex_string_here_123456789abcdef";
    let txid = "test_txid_wrong_asset";

    // Mock loadwallet first
    server.mock(|when, then| {
        when.method(POST).path("/").json_body(json!({
            "jsonrpc": "1.0",
            "id": "amp-client",
            "method": "loadwallet",
            "params": ["test_wallet"]
        }));
        then.status(200).json_body(json!({
            "jsonrpc": "1.0",
            "id": "amp-client",
            "result": {"name": "test_wallet", "warning": ""},
            "error": null
        }));
    });

    // Mock listunspent on wallet-specific endpoint with correct parameters
    server.mock(|when, then| {
        when.method(POST)
            .path("/wallet/test_wallet")
            .json_body(json!({
                "jsonrpc": "1.0",
                "id": "amp-client",
                "method": "listunspent",
                "params": [0, 9999999, [], true, {}]
            }));
        then.status(200).json_body(json!({
            "jsonrpc": "1.0",
            "id": "amp-client",
            "result": [
                {
                    "txid": txid,
                    "vout": 0,
                    "amount": 25.0,
                    "asset": asset_id,
                    "address": "correct_asset_address",
                    "spendable": true,
                    "confirmations": 3
                },
                {
                    "txid": txid,
                    "vout": 1,
                    "amount": 15.0,
                    "asset": different_asset_id,
                    "address": "wrong_asset_address",
                    "spendable": true,
                    "confirmations": 3
                }
            ],
            "error": null
        }));
    });

    let rpc = ElementsRpc::new(
        server.url("/").trim_end_matches('/').to_string(),
        "user".to_string(),
        "pass".to_string(),
    );

    let result = rpc
        .collect_change_data(asset_id, txid, &rpc, "test_wallet")
        .await;

    assert!(result.is_ok());
    let change_data = result.unwrap();

    // Should only return UTXOs with the correct asset ID
    assert_eq!(change_data.len(), 1);
    assert_eq!(change_data[0].amount, 25.0);
    assert_eq!(change_data[0].asset, asset_id);
    assert_eq!(change_data[0].address, "correct_asset_address");
}

#[tokio::test]
async fn test_change_data_collection_rpc_error() {
    let server = MockServer::start();
    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";
    let txid = "test_txid_rpc_error";

    // Mock listunspent to return RPC error
    server.mock(|when, then| {
        when.method(POST).path("/").json_body(json!({
            "jsonrpc": "1.0",
            "id": "amp-client",
            "method": "listunspent",
            "params": [1, 9999999, [], true, {"asset": asset_id}]
        }));
        then.status(500).json_body(json!({
            "jsonrpc": "1.0",
            "id": "amp-client",
            "error": {
                "code": -1,
                "message": "RPC server error"
            }
        }));
    });

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    let result = rpc
        .collect_change_data(asset_id, txid, &rpc, "test_wallet")
        .await;

    assert!(result.is_err());
    let error = result.unwrap_err();
    assert!(matches!(error, AmpError::Rpc(_)));
    assert!(error
        .to_string()
        .contains("Failed to query unspent outputs"));
}

#[tokio::test]
async fn test_change_data_formatting_for_api() {
    let server = MockServer::start();
    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";
    let txid = "test_txid_formatting";

    // Mock loadwallet first
    server.mock(|when, then| {
        when.method(POST).path("/").json_body(json!({
            "jsonrpc": "1.0",
            "id": "amp-client",
            "method": "loadwallet",
            "params": ["test_wallet"]
        }));
        then.status(200).json_body(json!({
            "jsonrpc": "1.0",
            "id": "amp-client",
            "result": {"name": "test_wallet", "warning": ""},
            "error": null
        }));
    });

    // Mock listunspent on wallet-specific endpoint with correct parameters
    server.mock(|when, then| {
        when.method(POST)
            .path("/wallet/test_wallet")
            .json_body(json!({
                "jsonrpc": "1.0",
                "id": "amp-client",
                "method": "listunspent",
                "params": [0, 9999999, [], true, {}]
            }));
        then.status(200).json_body(json!({
            "jsonrpc": "1.0",
            "id": "amp-client",
            "result": [
                {
                    "txid": txid,
                    "vout": 1,
                    "amount": 42.75,
                    "asset": asset_id,
                    "address": "lq1qq2xvpcvfup5j8zscjq05u2wxxjcyewk7979f9lq",
                    "spendable": true,
                    "confirmations": 2,
                    "scriptpubkey": "76a914abcdef1234567890abcdef1234567890abcdef88ac",
                    "redeemscript": null,
                    "witnessscript": null
                }
            ],
            "error": null
        }));
    });

    let rpc = ElementsRpc::new(
        server.url("/").trim_end_matches('/').to_string(),
        "user".to_string(),
        "pass".to_string(),
    );

    let result = rpc
        .collect_change_data(asset_id, txid, &rpc, "test_wallet")
        .await;

    assert!(result.is_ok());
    let change_data = result.unwrap();

    assert_eq!(change_data.len(), 1);
    let change_utxo = &change_data[0];

    // Verify all fields are properly formatted for API submission
    assert_eq!(change_utxo.txid, txid);
    assert_eq!(change_utxo.vout, 1);
    assert_eq!(change_utxo.amount, 42.75);
    assert_eq!(change_utxo.asset, asset_id);
    assert_eq!(
        change_utxo.address,
        "lq1qq2xvpcvfup5j8zscjq05u2wxxjcyewk7979f9lq"
    );
    assert!(change_utxo.spendable);
    assert_eq!(change_utxo.confirmations, Some(2));
    assert_eq!(
        change_utxo.scriptpubkey,
        Some("76a914abcdef1234567890abcdef1234567890abcdef88ac".to_string())
    );

    // Test serialization to ensure it matches API expectations
    let serialized = serde_json::to_string(&change_data).unwrap();
    assert!(serialized.contains(&txid));
    assert!(serialized.contains("42.75"));
    assert!(serialized.contains(&asset_id));
    assert!(serialized.contains("lq1qq2xvpcvfup5j8zscjq05u2wxxjcyewk7979f9lq"));
}

#[tokio::test]
async fn test_confirmation_timeout_error_message_format() {
    let server = MockServer::start();
    let txid = "test_txid_timeout_message";

    // Mock get_transaction to always return 0 confirmations
    server.mock(|when, then| {
        when.method(POST).path("/").json_body(json!({
            "jsonrpc": "1.0",
            "id": "amp-client",
            "method": "gettransaction",
            "params": [txid]
        }));
        then.status(200).json_body(json!({
            "jsonrpc": "1.0",
            "id": "amp-client",
            "result": {
                "txid": txid,
                "confirmations": 0,
                "blockheight": null,
                "hex": "020000000001..."
            },
            "error": null
        }));
    });

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    let result = rpc
        .wait_for_confirmations_with_interval(txid, Some(2), Some(0), Some(1))
        .await;

    assert!(result.is_err());
    let error = result.unwrap_err();

    // Verify error message contains all required information
    let error_msg = error.to_string();
    assert!(error_msg.contains("Timeout waiting for confirmations"));
    assert!(error_msg.contains(txid));
    assert!(error_msg.contains("You can retry confirmation"));
    assert!(error_msg.contains("calling the confirmation API"));

    // Verify error type is correct
    assert!(matches!(error, AmpError::Timeout(_)));

    // Test retry instructions
    if let Some(instructions) = error.retry_instructions() {
        assert!(instructions.contains("transaction ID"));
        assert!(instructions.contains("manually confirm"));
    }
}

#[tokio::test]
async fn test_collect_change_data_integration() {
    let server = MockServer::start();
    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";
    let distribution_txid = "abc123def456789abc123def456789abc123def456789abc123def456789abc123de";

    // Create mock UTXOs including change outputs from the distribution transaction
    let mut all_utxos = Vec::new();

    // Add some existing UTXOs from other transactions
    all_utxos.push(Unspent {
        txid: "other_txid_123".to_string(),
        vout: 0,
        amount: 75.0,
        asset: asset_id.to_string(),
        address: "lq1qq1xvpcvfup5j8zscjq05u2wxxjcyewk7979f9lq".to_string(),
        spendable: true,
        confirmations: Some(10),
        scriptpubkey: Some("76a914abc123def456789abc123def456789abc123de88ac".to_string()),
        redeemscript: None,
        witnessscript: None,
        amountblinder: Some(
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string(),
        ),
        assetblinder: Some(
            "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb".to_string(),
        ),
    });

    // Add change outputs from the distribution transaction
    all_utxos.push(Unspent {
        txid: distribution_txid.to_string(),
        vout: 1,
        amount: 25.5,
        asset: asset_id.to_string(),
        address: "lq1qq2xvpcvfup5j8zscjq05u2wxxjcyewk7979f9lq".to_string(),
        spendable: true,
        confirmations: Some(3),
        scriptpubkey: Some("76a914def456abc123789def456abc123789def456ab88ac".to_string()),
        redeemscript: None,
        witnessscript: None,
        amountblinder: Some(
            "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc".to_string(),
        ),
        assetblinder: Some(
            "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd".to_string(),
        ),
    });

    all_utxos.push(Unspent {
        txid: distribution_txid.to_string(),
        vout: 2,
        amount: 10.0,
        asset: asset_id.to_string(),
        address: "lq1qq3xvpcvfup5j8zscjq05u2wxxjcyewk7979f9lq".to_string(),
        spendable: true,
        confirmations: Some(3),
        scriptpubkey: Some("76a914ghi789jkl012345ghi789jkl012345ghi789jk88ac".to_string()),
        redeemscript: None,
        witnessscript: None,
        amountblinder: Some(
            "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee".to_string(),
        ),
        assetblinder: Some(
            "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff".to_string(),
        ),
    });

    // Add another UTXO from a different transaction
    all_utxos.push(Unspent {
        txid: "different_txid_456".to_string(),
        vout: 0,
        amount: 50.0,
        asset: asset_id.to_string(),
        address: "lq1qq4xvpcvfup5j8zscjq05u2wxxjcyewk7979f9lq".to_string(),
        spendable: true,
        confirmations: Some(6),
        scriptpubkey: Some("76a914mno012pqr345678mno012pqr345678mno012pq88ac".to_string()),
        redeemscript: None,
        witnessscript: None,
        amountblinder: Some(
            "1010101010101010101010101010101010101010101010101010101010101010".to_string(),
        ),
        assetblinder: Some(
            "2020202020202020202020202020202020202020202020202020202020202020".to_string(),
        ),
    });

    // Create mock for listunspent RPC call
    create_listunspent_mock(&server, "test_wallet", asset_id, all_utxos);

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    // Test collecting change data for the distribution transaction
    let result = rpc
        .collect_change_data(asset_id, distribution_txid, &rpc, "test_wallet")
        .await;

    assert!(result.is_ok());
    let change_utxos = result.unwrap();

    // Should return exactly 2 change UTXOs from the distribution transaction
    assert_eq!(change_utxos.len(), 2);

    // Verify the change UTXOs are correctly filtered
    for utxo in &change_utxos {
        assert_eq!(utxo.txid, distribution_txid);
        assert_eq!(utxo.asset, asset_id);
        assert!(utxo.spendable);
    }

    // Verify specific change UTXOs
    let change_utxo_1 = change_utxos.iter().find(|u| u.vout == 1).unwrap();
    assert_eq!(change_utxo_1.amount, 25.5);
    assert_eq!(
        change_utxo_1.address,
        "lq1qq2xvpcvfup5j8zscjq05u2wxxjcyewk7979f9lq"
    );

    let change_utxo_2 = change_utxos.iter().find(|u| u.vout == 2).unwrap();
    assert_eq!(change_utxo_2.amount, 10.0);
    assert_eq!(
        change_utxo_2.address,
        "lq1qq3xvpcvfup5j8zscjq05u2wxxjcyewk7979f9lq"
    );
}

#[tokio::test]
async fn test_collect_change_data_no_change_scenario() {
    let server = MockServer::start();
    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";
    let distribution_txid = "abc123def456789abc123def456789abc123def456789abc123def456789abc123de";

    // Create mock UTXOs with no change outputs from the distribution transaction
    let all_utxos = vec![
        Unspent {
            txid: "other_txid_123".to_string(),
            vout: 0,
            amount: 75.0,
            asset: asset_id.to_string(),
            address: "lq1qq1xvpcvfup5j8zscjq05u2wxxjcyewk7979f9lq".to_string(),
            spendable: true,
            confirmations: Some(10),
            scriptpubkey: Some("76a914abc123def456789abc123def456789abc123de88ac".to_string()),
            redeemscript: None,
            witnessscript: None,
            amountblinder: Some(
                "3030303030303030303030303030303030303030303030303030303030303030".to_string(),
            ),
            assetblinder: Some(
                "4040404040404040404040404040404040404040404040404040404040404040".to_string(),
            ),
        },
        Unspent {
            txid: "different_txid_456".to_string(),
            vout: 0,
            amount: 50.0,
            asset: asset_id.to_string(),
            address: "lq1qq2xvpcvfup5j8zscjq05u2wxxjcyewk7979f9lq".to_string(),
            spendable: true,
            confirmations: Some(6),
            scriptpubkey: Some("76a914mno012pqr345678mno012pqr345678mno012pq88ac".to_string()),
            redeemscript: None,
            witnessscript: None,
            amountblinder: Some(
                "5050505050505050505050505050505050505050505050505050505050505050".to_string(),
            ),
            assetblinder: Some(
                "6060606060606060606060606060606060606060606060606060606060606060".to_string(),
            ),
        },
    ];

    // Create mock for listunspent RPC call
    create_listunspent_mock(&server, "test_wallet", asset_id, all_utxos);

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    // Test collecting change data when no change outputs exist
    let result = rpc
        .collect_change_data(asset_id, distribution_txid, &rpc, "test_wallet")
        .await;

    assert!(result.is_ok());
    let change_utxos = result.unwrap();

    // Should return empty vector when no change outputs exist
    assert_eq!(change_utxos.len(), 0);
}

#[tokio::test]
async fn test_collect_change_data_workflow_integration() {
    let server = MockServer::start();
    let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";
    let distribution_txid = "abc123def456789abc123def456789abc123def456789abc123def456789abc123de";

    // Simulate the post-confirmation scenario where we need to collect change data
    let post_confirmation_utxos = vec![
        // Change output from the distribution transaction
        Unspent {
            txid: distribution_txid.to_string(),
            vout: 2, // Change output
            amount: 48.0,
            asset: asset_id.to_string(),
            address: "change_address".to_string(),
            spendable: true,
            confirmations: Some(3),
            scriptpubkey: Some("76a914change_address_script_hash88ac".to_string()),
            redeemscript: None,
            witnessscript: None,
            amountblinder: Some(
                "7070707070707070707070707070707070707070707070707070707070707070".to_string(),
            ),
            assetblinder: Some(
                "8080808080808080808080808080808080808080808080808080808080808080".to_string(),
            ),
        },
        // Some other unrelated UTXOs
        Unspent {
            txid: "unrelated_txid".to_string(),
            vout: 0,
            amount: 25.0,
            asset: asset_id.to_string(),
            address: "other_address".to_string(),
            spendable: true,
            confirmations: Some(10),
            scriptpubkey: Some("76a914other_address_script_hash88ac".to_string()),
            redeemscript: None,
            witnessscript: None,
            amountblinder: Some(
                "9090909090909090909090909090909090909090909090909090909090909090".to_string(),
            ),
            assetblinder: Some(
                "a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0".to_string(),
            ),
        },
    ];

    // Mock the listunspent call for change data collection
    create_listunspent_mock(&server, "test_wallet", asset_id, post_confirmation_utxos);

    let rpc = ElementsRpc::new(server.url("/"), "user".to_string(), "pass".to_string());

    // Collect change data for confirmation
    let change_result = rpc
        .collect_change_data(asset_id, distribution_txid, &rpc, "test_wallet")
        .await;

    assert!(change_result.is_ok());
    let change_utxos = change_result.unwrap();

    // Should find exactly one change UTXO
    assert_eq!(change_utxos.len(), 1);
    assert_eq!(change_utxos[0].txid, distribution_txid);
    assert_eq!(change_utxos[0].vout, 2);
    assert_eq!(change_utxos[0].amount, 48.0);
    assert_eq!(change_utxos[0].address, "change_address");
    assert!(change_utxos[0].spendable);

    // This change data would then be used in the distribution confirmation API call
}