hyperware_process_lib 3.0.0

A library for writing Hyperware processes in Rust.
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
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
//! ## (unfinished, unpolished and not fully tested)  EVM wallet functionality for Hyperware.
//!
//! This module provides high-level wallet functionality for Ethereum,
//! including transaction signing, contract interaction, and account management.
//! It provides a simple interface for sending ETH and interacting with ERC20,
//! ERC721, and ERC1155 tokens.
//!
//! ERC6551 + the hypermap is not supported yet.
//!

use crate::eth::{BlockNumberOrTag, EthError, Provider};
use crate::hypermap;
use crate::hypermap::{namehash, valid_fact, valid_name, valid_note};
use crate::println as kiprintln;
use crate::signer::{EncryptedSignerData, LocalSigner, Signer, SignerError, TransactionData};

use alloy::rpc::types::{
    request::TransactionRequest, Filter, FilterBlockOption, FilterSet, TransactionReceipt,
};
use alloy_primitives::TxKind;
use alloy_primitives::{Address as EthAddress, Bytes, TxHash, B256, U256};
use alloy_sol_types::{sol, SolCall};
use hex;
use serde::{Deserialize, Serialize};
use std::str::FromStr;
use thiserror::Error;

// Define UserOperation struct for ERC-4337
sol! {
    #[derive(Debug, Default, PartialEq, Eq)]
    struct UserOperation {
        address sender;
        uint256 nonce;
        bytes initCode;
        bytes callData;
        uint256 callGasLimit;
        uint256 verificationGasLimit;
        uint256 preVerificationGas;
        uint256 maxFeePerGas;
        uint256 maxPriorityFeePerGas;
        bytes paymasterAndData;
        bytes signature;
    }

    // v0.8 UserOperation struct with packed fields
    #[derive(Debug, Default, PartialEq, Eq)]
    struct PackedUserOperation {
        address sender;
        uint256 nonce;
        bytes initCode;
        bytes callData;
        bytes32 accountGasLimits;  // packed verificationGasLimit (16 bytes) and callGasLimit (16 bytes)
        uint256 preVerificationGas;
        bytes32 gasFees;  // packed maxPriorityFeePerGas (16 bytes) and maxFeePerGas (16 bytes)
        bytes paymasterAndData;
        bytes signature;
    }
}

// Define contract interfaces
pub mod contracts {
    use alloy_sol_types::sol;

    sol! {
        interface IERC20 {
            function balanceOf(address who) external view returns (uint256);
            function decimals() external view returns (uint8);
            function symbol() external view returns (string);
            function name() external view returns (string);
            function totalSupply() external view returns (uint256);
            function allowance(address owner, address spender) external view returns (uint256);
            function transfer(address to, uint256 value) external returns (bool);
            function approve(address spender, uint256 value) external returns (bool);
            function transferFrom(address from, address to, uint256 value) external returns (bool);
        }

        interface IERC721 {
            function balanceOf(address owner) external view returns (uint256);
            function ownerOf(uint256 tokenId) external view returns (address);
            function isApprovedForAll(address owner, address operator) external view returns (bool);
            function safeTransferFrom(address from, address to, uint256 tokenId) external;
            function setApprovalForAll(address operator, bool approved) external;
        }

        interface IERC1155 {
            function balanceOf(address account, uint256 id) external view returns (uint256);
            function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
            function isApprovedForAll(address account, address operator) external view returns (bool);
            function setApprovalForAll(address operator, bool approved) external;
            function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
            function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
        }

        interface IERC6551Account {
            function execute(address to, uint256 value, bytes calldata data, uint8 operation) external payable returns (bytes memory);
            function execute(address to, uint256 value, bytes calldata data, uint8 operation, uint256 txGas) external payable returns (bytes memory);
            function isValidSigner(address signer, bytes calldata data) external view returns (bytes4 magicValue);
            function token() external view returns (uint256 chainId, address tokenContract, uint256 tokenId);
            function setSignerDataKey(bytes32 signerDataKey) external;
        }

        // ERC-4337 EntryPoint Interface
        interface IEntryPoint {
            function handleOps(bytes calldata packedOps, address payable beneficiary) external;
            function getUserOpHash(bytes calldata packedUserOp) external view returns (bytes32);
            function getNonce(address sender, uint192 key) external view returns (uint256);
        }

        // ERC-4337 Account Interface
        interface IAccount {
            function validateUserOp(
                bytes calldata packedUserOp,
                bytes32 userOpHash,
                uint256 missingAccountFunds
            ) external returns (uint256 validationData);
        }

        // ERC-4337 Paymaster Interface
        interface IPaymaster {
            enum PostOpMode {
                opSucceeded,
                opReverted,
                postOpReverted
            }

            function validatePaymasterUserOp(
                bytes calldata packedUserOp,
                bytes32 userOpHash,
                uint256 maxCost
            ) external returns (bytes memory context, uint256 validationData);

            function postOp(
                PostOpMode mode,
                bytes calldata context,
                uint256 actualGasCost
            ) external;
        }
    }
}

#[derive(Debug, Error)]
pub enum WalletError {
    #[error("signing error: {0}")]
    SignerError(#[from] SignerError),

    #[error("ethereum error: {0}")]
    EthError(#[from] EthError),

    #[error("name resolution error: {0}")]
    NameResolutionError(String),

    #[error("invalid amount: {0}")]
    InvalidAmount(String),

    #[error("transaction error: {0}")]
    TransactionError(String),

    #[error("gas estimation error: {0}")]
    GasEstimationError(String),

    #[error("insufficient funds: {0}")]
    InsufficientFunds(String),

    #[error("network congestion: {0}")]
    NetworkCongestion(String),

    #[error("transaction underpriced")]
    TransactionUnderpriced,

    #[error("transaction nonce too low")]
    TransactionNonceTooLow,

    #[error("permission denied: {0}")]
    PermissionDenied(String),
}

/// Represents the storage state of a wallet's private key
#[derive(Debug, Clone)]
pub enum KeyStorage {
    /// An unencrypted wallet with a signer
    Decrypted(LocalSigner),
    Encrypted(EncryptedSignerData),
}

// Manual implementation of Serialize for KeyStorage
impl Serialize for KeyStorage {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeStruct;

        match self {
            KeyStorage::Decrypted(signer) => {
                let mut state = serializer.serialize_struct("KeyStorage", 2)?;
                state.serialize_field("type", "Decrypted")?;
                state.serialize_field("signer", signer)?;
                state.end()
            }
            KeyStorage::Encrypted(data) => {
                let mut state = serializer.serialize_struct("KeyStorage", 2)?;
                state.serialize_field("type", "Encrypted")?;
                state.serialize_field("data", data)?;
                state.end()
            }
        }
    }
}

// Manual implementation of Deserialize for KeyStorage
impl<'de> Deserialize<'de> for KeyStorage {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(tag = "type")]
        enum KeyStorageData {
            #[serde(rename = "Decrypted")]
            Decrypted { signer: LocalSigner },

            #[serde(rename = "Encrypted")]
            Encrypted { data: EncryptedSignerData },
        }

        let data = KeyStorageData::deserialize(deserializer)?;

        match data {
            KeyStorageData::Decrypted { signer } => Ok(KeyStorage::Decrypted(signer)),
            KeyStorageData::Encrypted { data } => Ok(KeyStorage::Encrypted(data)),
        }
    }
}

impl KeyStorage {
    /// Get the encrypted data if this is an encrypted key storage
    pub fn get_encrypted_data(&self) -> Option<Vec<u8>> {
        match self {
            KeyStorage::Encrypted(data) => Some(data.encrypted_data.clone()),
            KeyStorage::Decrypted(_) => None,
        }
    }

    /// Get the address associated with this wallet
    pub fn get_address(&self) -> String {
        match self {
            KeyStorage::Decrypted(signer) => signer.address().to_string(),
            KeyStorage::Encrypted(data) => data.address.clone(),
        }
    }

    /// Get the chain ID associated with this wallet
    pub fn get_chain_id(&self) -> u64 {
        match self {
            KeyStorage::Decrypted(signer) => signer.chain_id(),
            KeyStorage::Encrypted(data) => data.chain_id,
        }
    }
}

/// Represents an amount of ETH with proper formatting
#[derive(Debug, Clone)]
pub struct EthAmount {
    /// Value in wei
    wei_value: U256,
}

impl EthAmount {
    /// Create a new amount from ETH value
    pub fn from_eth(eth_value: f64) -> Self {
        // Convert ETH to wei (1 ETH = 10^18 wei)
        let wei = (eth_value * 1_000_000_000_000_000_000.0) as u128;
        Self {
            wei_value: U256::from(wei),
        }
    }

    /// Create from a string like "0.1 ETH" or "10 wei"
    pub fn from_string(amount_str: &str) -> Result<Self, WalletError> {
        let parts: Vec<&str> = amount_str.trim().split_whitespace().collect();

        if parts.is_empty() {
            return Err(WalletError::InvalidAmount(
                "Empty amount string".to_string(),
            ));
        }

        let value_str = parts[0];
        let unit = parts
            .get(1)
            .map(|s| s.to_lowercase())
            .unwrap_or_else(|| "eth".to_string());

        let value = value_str.parse::<f64>().map_err(|_| {
            WalletError::InvalidAmount(format!("Invalid numeric value: {}", value_str))
        })?;

        match unit.as_str() {
            "eth" => Ok(Self::from_eth(value)),
            "wei" => Ok(Self {
                wei_value: U256::from(value as u128),
            }),
            _ => Err(WalletError::InvalidAmount(format!(
                "Unknown unit: {}",
                unit
            ))),
        }
    }

    /// Get the value in wei
    pub fn as_wei(&self) -> U256 {
        self.wei_value
    }

    /// Get a human-readable string representation
    pub fn to_string(&self) -> String {
        // Just return the numerical value without denomination
        if self.wei_value >= U256::from(100_000_000_000_000u128) {
            // Convert to u128 first (safe since ETH total supply fits in u128) then to f64
            let wei_u128 = self.wei_value.to::<u128>();
            let eth_value = wei_u128 as f64 / 1_000_000_000_000_000_000.0;
            format!("{:.6}", eth_value)
        } else {
            format!("{}", self.wei_value)
        }
    }

    /// Get a formatted string with denomination (for display purposes)
    pub fn to_display_string(&self) -> String {
        // For values over 0.0001 ETH, show in ETH, otherwise in wei
        if self.wei_value >= U256::from(100_000_000_000_000u128) {
            // Convert to u128 first (safe since ETH total supply fits in u128) then to f64
            let wei_u128 = self.wei_value.to::<u128>();
            let eth_value = wei_u128 as f64 / 1_000_000_000_000_000_000.0;
            format!("{:.6} ETH", eth_value)
        } else {
            format!("{} wei", self.wei_value)
        }
    }
}

/// Transaction receipt returned after sending
#[derive(Debug, Clone)]
pub struct TxReceipt {
    /// Transaction hash
    pub hash: TxHash,
    /// Transaction details
    pub details: String,
}

/// Result type for Hypermap transactions
#[derive(Debug, Clone)]
pub struct HypermapTxReceipt {
    /// Transaction hash
    pub hash: TxHash,
    /// Description of the operation
    pub description: String,
}

//
// HELPER FUNCTIONS
//

/// Helper for making contract view function calls
fn call_view_function<T: SolCall>(
    contract: EthAddress,
    call: T,
    provider: &Provider,
) -> Result<T::Return, WalletError> {
    let call_data = call.abi_encode();
    let tx = TransactionRequest {
        to: Some(TxKind::Call(contract)),
        input: call_data.into(),
        ..Default::default()
    };

    let result = provider.call(tx, None)?;

    if result.is_empty() {
        return Err(WalletError::TransactionError(
            "Empty result from call".into(),
        ));
    }

    match T::abi_decode_returns(&result, true) {
        Ok(decoded) => Ok(decoded),
        Err(e) => Err(WalletError::TransactionError(format!(
            "Failed to decode result: {}",
            e
        ))),
    }
}

/// Calculate gas parameters based on network type
fn calculate_gas_params(provider: &Provider, chain_id: u64) -> Result<(u128, u128), WalletError> {
    match chain_id {
        1 => {
            // Mainnet: 50% buffer and 1.5 gwei priority fee
            let latest_block = provider
                .get_block_by_number(BlockNumberOrTag::Latest, false)?
                .ok_or_else(|| {
                    WalletError::TransactionError("Failed to get latest block".into())
                })?;

            let base_fee = latest_block
                .header
                .inner
                .base_fee_per_gas
                .ok_or_else(|| WalletError::TransactionError("No base fee in block".into()))?
                as u128;

            Ok((base_fee + (base_fee / 2), 1_500_000_000u128))
        }
        8453 => {
            // Base
            let latest_block = provider
                .get_block_by_number(BlockNumberOrTag::Latest, false)?
                .ok_or_else(|| {
                    WalletError::TransactionError("Failed to get latest block".into())
                })?;

            let base_fee = latest_block
                .header
                .inner
                .base_fee_per_gas
                .ok_or_else(|| WalletError::TransactionError("No base fee in block".into()))?
                as u128;

            let max_fee = base_fee + (base_fee / 3);

            let min_priority_fee = 100_000u128;

            let max_priority_fee = max_fee / 2;

            let priority_fee = std::cmp::max(
                min_priority_fee,
                std::cmp::min(base_fee / 10, max_priority_fee),
            );

            Ok((max_fee, priority_fee))
        }
        10 => {
            // Optimism: 25% buffer and 0.3 gwei priority fee
            let latest_block = provider
                .get_block_by_number(BlockNumberOrTag::Latest, false)?
                .ok_or_else(|| {
                    WalletError::TransactionError("Failed to get latest block".into())
                })?;

            let base_fee = latest_block
                .header
                .inner
                .base_fee_per_gas
                .ok_or_else(|| WalletError::TransactionError("No base fee in block".into()))?
                as u128;

            Ok((base_fee + (base_fee / 4), 300_000_000u128))
        }
        31337 | 1337 => {
            // Test networks
            Ok((2_000_000_000, 100_000_000))
        }
        _ => {
            // Default: 30% buffer
            let base_fee = provider.get_gas_price()?.to::<u128>();
            let adjusted_fee = (base_fee * 130) / 100;
            Ok((adjusted_fee, adjusted_fee / 10))
        }
    }
}

/// Prepare and send a transaction with common parameters
fn prepare_and_send_tx<S: Signer, F>(
    to: EthAddress,
    call_data: Vec<u8>,
    value: U256,
    provider: &Provider,
    signer: &S,
    gas_limit: Option<u64>,
    format_receipt: F,
) -> Result<TxReceipt, WalletError>
where
    F: FnOnce(TxHash) -> String,
{
    // Get the current nonce for the signer's address
    let signer_address = signer.address();
    let nonce = provider
        .get_transaction_count(signer_address, None)?
        .to::<u64>();

    // Calculate gas parameters based on chain ID
    let (gas_price, priority_fee) = calculate_gas_params(provider, signer.chain_id())?;

    // Use provided gas limit or estimate it with 20% buffer
    let gas_limit = match gas_limit {
        Some(limit) => limit,
        None => {
            let tx_req = TransactionRequest {
                from: Some(signer_address),
                to: Some(TxKind::Call(to)),
                input: call_data.clone().into(),
                ..Default::default()
            };

            match provider.estimate_gas(tx_req, None) {
                Ok(gas) => {
                    let limit = (gas.to::<u64>() * 120) / 100; // Add 20% buffer
                    limit
                }
                Err(_) => {
                    100_000 // Default value if estimation fails
                }
            }
        }
    };

    // Prepare transaction data
    let tx_data = TransactionData {
        to,
        value,
        data: Some(call_data),
        nonce,
        gas_limit,
        gas_price,
        max_priority_fee: Some(priority_fee),
        chain_id: signer.chain_id(),
    };

    // Sign and send transaction
    let signed_tx = signer.sign_transaction(&tx_data)?;

    let tx_hash = provider.send_raw_transaction(signed_tx.into())?;

    kiprintln!("PL:: Transaction sent with hash: {}", tx_hash);

    // Return the receipt with formatted details
    Ok(TxReceipt {
        hash: tx_hash,
        details: format_receipt(tx_hash),
    })
}

/// Helper for creating Hypermap transaction operations
fn create_hypermap_tx<S: Signer, F>(
    parent_entry: &str,
    hypermap_call_data: Bytes,
    description_fn: F,
    provider: Provider,
    signer: &S,
) -> Result<HypermapTxReceipt, WalletError>
where
    F: FnOnce() -> String,
{
    // Get the parent TBA address and verify ownership
    let hypermap = provider.hypermap();
    let parent_hash_str = namehash(parent_entry);
    let (tba, owner, _) = hypermap.get_hash(&parent_hash_str)?;

    // Check that the signer is the owner of the parent entry
    let signer_address = signer.address();
    if signer_address != owner {
        return Err(WalletError::PermissionDenied(format!(
            "Signer address {} does not own the entry {}",
            signer_address, parent_entry
        )));
    }

    // Create the ERC-6551 execute call
    let execute_call = contracts::IERC6551Account::execute_0Call {
        to: *hypermap.address(),
        value: U256::ZERO,
        data: hypermap_call_data,
        operation: 0, // CALL operation
    };

    // Format receipt message
    let description = description_fn();
    let format_receipt = move |_| description.clone();

    // For ERC-6551 operations we need a higher gas limit
    let gas_limit = Some(600_000);

    // Send the transaction
    let receipt = prepare_and_send_tx(
        tba,
        execute_call.abi_encode(),
        U256::ZERO,
        &provider,
        signer,
        gas_limit,
        format_receipt,
    )?;

    // Convert to Hypermap receipt
    Ok(HypermapTxReceipt {
        hash: receipt.hash,
        description: receipt.details,
    })
}

//
// NAME RESOLUTION
//

// Resolve a .hypr/.os/future tlzs names to an Ethereum address using Hypermap
pub fn resolve_name(name: &str, chain_id: u64) -> Result<EthAddress, WalletError> {
    // If it's already an address, just parse it
    if name.starts_with("0x") && name.len() == 42 {
        return EthAddress::from_str(name).map_err(|_| {
            WalletError::NameResolutionError(format!("Invalid address format: {}", name))
        });
    }

    // hardcoded to .hypr for now
    let formatted_name = if !name.contains('.') {
        format!("{}.hypr", name)
    } else {
        name.to_string()
    };

    // Use hypermap resolution
    let hypermap = hypermap::Hypermap::default(chain_id);
    match hypermap.get(&formatted_name) {
        Ok((_tba, owner, _)) => Ok(owner),
        Err(e) => Err(WalletError::NameResolutionError(format!(
            "Failed to resolve name '{}': {}",
            name, e
        ))),
    }
}

/// Resolve a token symbol to its contract address on the specified chain
pub fn resolve_token_symbol(token: &str, chain_id: u64) -> Result<EthAddress, WalletError> {
    // If it's already an address, just parse it
    if token.starts_with("0x") && token.len() == 42 {
        return EthAddress::from_str(token).map_err(|_| {
            WalletError::NameResolutionError(format!("Invalid address format: {}", token))
        });
    }

    // Convert to uppercase for case-insensitive comparison
    let token_upper = token.to_uppercase();

    // Map of known token addresses by chain ID and symbol
    match chain_id {
        1 => { // Ethereum Mainnet
            match token_upper.as_str() {
                "USDC" => EthAddress::from_str("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48")
                    .map_err(|_| WalletError::NameResolutionError("Invalid USDC address format".to_string())),
                "USDT" => EthAddress::from_str("0xdAC17F958D2ee523a2206206994597C13D831ec7")
                    .map_err(|_| WalletError::NameResolutionError("Invalid USDT address format".to_string())),
                "DAI" => EthAddress::from_str("0x6B175474E89094C44Da98b954EedeAC495271d0F")
                    .map_err(|_| WalletError::NameResolutionError("Invalid DAI address format".to_string())),
                "WETH" => EthAddress::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2")
                    .map_err(|_| WalletError::NameResolutionError("Invalid WETH address format".to_string())),
                "WBTC" => EthAddress::from_str("0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599")
                    .map_err(|_| WalletError::NameResolutionError("Invalid WBTC address format".to_string())),
                _ => Err(WalletError::NameResolutionError(
                    format!("Token '{}' not recognized on chain ID {}", token, chain_id)
                )),
            }
        },
        8453 => { // Base
            match token_upper.as_str() {
                "USDC" => EthAddress::from_str("0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913")
                    .map_err(|_| WalletError::NameResolutionError("Invalid USDC address format".to_string())),
                "DAI" => EthAddress::from_str("0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb")
                    .map_err(|_| WalletError::NameResolutionError("Invalid DAI address format".to_string())),
                "WETH" => EthAddress::from_str("0x4200000000000000000000000000000000000006")
                    .map_err(|_| WalletError::NameResolutionError("Invalid WETH address format".to_string())),
                _ => Err(WalletError::NameResolutionError(
                    format!("Token '{}' not recognized on chain ID {}", token, chain_id)
                )),
            }
        },
        10 => { // Optimism
            match token_upper.as_str() {
                "USDC" => EthAddress::from_str("0x7F5c764cBc14f9669B88837ca1490cCa17c31607")
                    .map_err(|_| WalletError::NameResolutionError("Invalid USDC address format".to_string())),
                "DAI" => EthAddress::from_str("0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1")
                    .map_err(|_| WalletError::NameResolutionError("Invalid DAI address format".to_string())),
                "WETH" => EthAddress::from_str("0x4200000000000000000000000000000000000006")
                    .map_err(|_| WalletError::NameResolutionError("Invalid WETH address format".to_string())),
                _ => Err(WalletError::NameResolutionError(
                    format!("Token '{}' not recognized on chain ID {}", token, chain_id)
                )),
            }
        },
        137 => { // Polygon
            match token_upper.as_str() {
                "USDC" => EthAddress::from_str("0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174")
                    .map_err(|_| WalletError::NameResolutionError("Invalid USDC address format".to_string())),
                "USDT" => EthAddress::from_str("0xc2132D05D31c914a87C6611C10748AEb04B58e8F")
                    .map_err(|_| WalletError::NameResolutionError("Invalid USDT address format".to_string())),
                "DAI" => EthAddress::from_str("0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063")
                    .map_err(|_| WalletError::NameResolutionError("Invalid DAI address format".to_string())),
                "WETH" => EthAddress::from_str("0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619")
                    .map_err(|_| WalletError::NameResolutionError("Invalid WETH address format".to_string())),
                "WMATIC" => EthAddress::from_str("0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270")
                    .map_err(|_| WalletError::NameResolutionError("Invalid WMATIC address format".to_string())),
                _ => Err(WalletError::NameResolutionError(
                    format!("Token '{}' not recognized on chain ID {}", token, chain_id)
                )),
            }
        },
        42161 => { // Arbitrum
            match token_upper.as_str() {
                "USDC" => EthAddress::from_str("0xFF970A61A04b1cA14834A43f5dE4533eBDDB5CC8")
                    .map_err(|_| WalletError::NameResolutionError("Invalid USDC address format".to_string())),
                "USDT" => EthAddress::from_str("0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9")
                    .map_err(|_| WalletError::NameResolutionError("Invalid USDT address format".to_string())),
                "DAI" => EthAddress::from_str("0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1")
                    .map_err(|_| WalletError::NameResolutionError("Invalid DAI address format".to_string())),
                "WETH" => EthAddress::from_str("0x82aF49447D8a07e3bd95BD0d56f35241523fBab1")
                    .map_err(|_| WalletError::NameResolutionError("Invalid WETH address format".to_string())),
                _ => Err(WalletError::NameResolutionError(
                    format!("Token '{}' not recognized on chain ID {}", token, chain_id)
                )),
            }
        },
        11155111 => { // Sepolia Testnet
            match token_upper.as_str() {
                // Common tokens on Sepolia testnet
                "USDC" => EthAddress::from_str("0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238")
                    .map_err(|_| WalletError::NameResolutionError("Invalid USDC address format".to_string())),
                "USDT" => EthAddress::from_str("0x8267cF9254734C6Eb452a7bb9AAF97B392258b21")
                    .map_err(|_| WalletError::NameResolutionError("Invalid USDT address format".to_string())),
                "DAI" => EthAddress::from_str("0x3e622317f8C93f7328350cF0B56d9eD4C620C5d6")
                    .map_err(|_| WalletError::NameResolutionError("Invalid DAI address format".to_string())),
                "WETH" => EthAddress::from_str("0x7b79995e5f793A07Bc00c21412e50Ecae098E7f9")
                    .map_err(|_| WalletError::NameResolutionError("Invalid WETH address format".to_string())),
                _ => Err(WalletError::NameResolutionError(
                    format!("Token '{}' not recognized on Sepolia testnet. Please use a contract address.", token)
                )),
            }
        },
        // Test networks
        31337 | 1337 => {
            return Err(WalletError::NameResolutionError(
                format!("Token symbol resolution not supported on test networks. Please use the full contract address.")
            ));
        },
        _ => {
            return Err(WalletError::NameResolutionError(
                format!("Token symbol resolution not supported for chain ID {}", chain_id)
            ));
        }
    }
    .map_err(|e| match e {
        WalletError::NameResolutionError(msg) => WalletError::NameResolutionError(msg),
        _ => WalletError::NameResolutionError(
            format!("Invalid address format for token '{}' on chain ID {}", token, chain_id)
        ),
    })
}

//
// ETHEREUM FUNCTIONS
//

/// Send ETH to an address or name
pub fn send_eth<S: Signer>(
    to: &str,
    amount: EthAmount,
    provider: Provider,
    signer: &S,
) -> Result<TxReceipt, WalletError> {
    // Resolve the name to an address
    let to_address = resolve_name(to, signer.chain_id())?;

    // Standard gas limit for ETH transfer is always 21000
    let gas_limit = Some(21000);

    // Format receipt message
    let amount_str = amount.to_string();
    let format_receipt = move |_tx_hash| format!("Sent {} to {}", amount_str, to);

    // For ETH transfers, we have no call data
    let empty_call_data = vec![];

    // Use the helper function to prepare and send the transaction
    prepare_and_send_tx(
        to_address,
        empty_call_data,
        amount.as_wei(),
        &provider,
        signer,
        gas_limit,
        format_receipt,
    )
}

/// Get the ETH balance for an address or name
pub fn get_eth_balance(
    address_or_name: &str,
    chain_id: u64,
    provider: Provider,
) -> Result<EthAmount, WalletError> {
    // Resolve name to address
    let address = resolve_name(address_or_name, chain_id)?;

    // Query balance
    let balance = provider.get_balance(address, None)?;

    // Return formatted amount
    Ok(EthAmount { wei_value: balance })
}

/// Wait for a transaction to be confirmed
pub fn wait_for_transaction(
    tx_hash: TxHash,
    provider: Provider,
    confirmations: u64,
    timeout_secs: u64,
) -> Result<TransactionReceipt, WalletError> {
    let start_time = std::time::Instant::now();
    let timeout = std::time::Duration::from_secs(timeout_secs);

    loop {
        // Check if we've exceeded the timeout
        if start_time.elapsed() > timeout {
            return Err(WalletError::TransactionError(format!(
                "Transaction confirmation timeout after {} seconds",
                timeout_secs
            )));
        }

        // Try to get the receipt
        if let Ok(Some(receipt)) = provider.get_transaction_receipt(tx_hash) {
            // Check if we have enough confirmations
            let latest_block = provider.get_block_number()?;
            let receipt_block = receipt.block_number.unwrap_or(0) as u64;

            if latest_block >= receipt_block + confirmations {
                return Ok(receipt);
            }
        }

        // Wait a bit before checking again
        std::thread::sleep(std::time::Duration::from_secs(2));
    }
}

//
// ERC-20 TOKEN FUNCTIONS
//

/// Get the ERC20 token balance of an address or name
/// Returns the balance in token units (adjusted for decimals)
pub fn erc20_balance_of(
    token_address: &str,
    owner_address: &str,
    provider: &Provider,
) -> Result<f64, WalletError> {
    // First try to resolve the token as a symbol
    let token = match resolve_token_symbol(token_address, provider.chain_id) {
        Ok(addr) => addr,
        Err(_) => resolve_name(token_address, provider.chain_id)?, // Fall back to regular name resolution
    };

    let owner = resolve_name(owner_address, provider.chain_id)?;

    let call = contracts::IERC20::balanceOfCall { who: owner };
    let balance = call_view_function(token, call, provider)?;

    let decimals = erc20_decimals(token_address, provider)?;
    let balance_float = balance._0.to::<u128>() as f64 / 10f64.powi(decimals as i32);

    Ok(balance_float)
}

/// Get the number of decimals for an ERC20 token
pub fn erc20_decimals(token_address: &str, provider: &Provider) -> Result<u8, WalletError> {
    let token = match resolve_token_symbol(token_address, provider.chain_id) {
        Ok(addr) => addr,
        Err(_) => resolve_name(token_address, provider.chain_id)?,
    };

    let call = contracts::IERC20::decimalsCall {};
    let decimals = call_view_function(token, call, provider)?;
    Ok(decimals._0)
}

/// Get the token symbol for an ERC20 token
pub fn erc20_symbol(token_address: &str, provider: &Provider) -> Result<String, WalletError> {
    let token = match resolve_token_symbol(token_address, provider.chain_id) {
        Ok(addr) => addr,
        Err(_) => resolve_name(token_address, provider.chain_id)?,
    };

    let call = contracts::IERC20::symbolCall {};
    let symbol = call_view_function(token, call, provider)?;
    Ok(symbol._0)
}

/// Get the token name for an ERC20 token
pub fn erc20_name(token_address: &str, provider: &Provider) -> Result<String, WalletError> {
    let token = match resolve_token_symbol(token_address, provider.chain_id) {
        Ok(addr) => addr,
        Err(_) => resolve_name(token_address, provider.chain_id)?,
    };

    let call = contracts::IERC20::nameCall {};
    let name = call_view_function(token, call, provider)?;
    Ok(name._0)
}

/// Get the total supply of an ERC20 token
pub fn erc20_total_supply(token_address: &str, provider: &Provider) -> Result<U256, WalletError> {
    let token = match resolve_token_symbol(token_address, provider.chain_id) {
        Ok(addr) => addr,
        Err(_) => resolve_name(token_address, provider.chain_id)?,
    };

    let call = contracts::IERC20::totalSupplyCall {};
    let total_supply = call_view_function(token, call, provider)?;
    Ok(total_supply._0)
}

/// Get the allowance for an ERC20 token
pub fn erc20_allowance(
    token_address: &str,
    owner_address: &str,
    spender_address: &str,
    provider: &Provider,
) -> Result<U256, WalletError> {
    let token = match resolve_token_symbol(token_address, provider.chain_id) {
        Ok(addr) => addr,
        Err(_) => resolve_name(token_address, provider.chain_id)?,
    };

    let owner = resolve_name(owner_address, provider.chain_id)?;
    let spender = resolve_name(spender_address, provider.chain_id)?;

    let call = contracts::IERC20::allowanceCall { owner, spender };
    let allowance = call_view_function(token, call, provider)?;
    Ok(allowance._0)
}

/// Transfer ERC20 tokens to an address or name
pub fn erc20_transfer<S: Signer>(
    token_address: &str,
    to_address: &str,
    amount: U256,
    provider: &Provider,
    signer: &S,
) -> Result<TxReceipt, WalletError> {
    kiprintln!(
        "PL:: Transferring {} tokens to {} on {}",
        amount,
        to_address,
        provider.chain_id
    );

    // Resolve token address (could be a symbol like "USDC")
    let token = match resolve_token_symbol(token_address, provider.chain_id) {
        Ok(addr) => addr,
        Err(_) => resolve_name(token_address, provider.chain_id)?,
    };

    kiprintln!("PL:: Resolved token address: {}", token);

    // Resolve recipient address
    let to = resolve_name(to_address, provider.chain_id)?;
    kiprintln!("PL:: Resolved recipient address: {}", to);

    // Create the call
    let call = contracts::IERC20::transferCall { to, value: amount };
    let call_data = call.abi_encode();

    // Get token details for receipt formatting
    let token_symbol =
        erc20_symbol(token_address, provider).unwrap_or_else(|_| "tokens".to_string());
    let token_decimals = erc20_decimals(token_address, provider).unwrap_or(18);

    // Format receipt message
    let format_receipt = move |_| {
        let amount_float = amount.to::<u128>() as f64 / 10f64.powi(token_decimals as i32);
        format!(
            "Transferred {:.6} {} to {}",
            amount_float, token_symbol, to_address
        )
    };

    // Prepare and send transaction
    prepare_and_send_tx(
        token,
        call_data,
        U256::ZERO,
        provider,
        signer,
        Some(100_000), // Default gas limit for ERC20 transfers
        format_receipt,
    )
}

/// Approve an address to spend ERC20 tokens
pub fn erc20_approve<S: Signer>(
    token_address: &str,
    spender_address: &str,
    amount: U256,
    provider: &Provider,
    signer: &S,
) -> Result<TxReceipt, WalletError> {
    // Resolve addresses
    let token = resolve_name(token_address, provider.chain_id)?;
    let spender = resolve_name(spender_address, provider.chain_id)?;

    // Create the call
    let call = contracts::IERC20::approveCall {
        spender,
        value: amount,
    };
    let call_data = call.abi_encode();

    // Get token details for receipt formatting
    let token_symbol =
        erc20_symbol(token_address, provider).unwrap_or_else(|_| "tokens".to_string());
    let token_decimals = erc20_decimals(token_address, provider).unwrap_or(18);

    // Format receipt message
    let format_receipt = move |_| {
        let amount_float = amount.to::<u128>() as f64 / 10f64.powi(token_decimals as i32);
        format!(
            "Approved {:.6} {} to be spent by {}",
            amount_float, token_symbol, spender_address
        )
    };

    // Prepare and send transaction
    prepare_and_send_tx(
        token,
        call_data,
        U256::ZERO,
        provider,
        signer,
        Some(60_000), // Default gas limit for approvals
        format_receipt,
    )
}

/// Transfer ERC20 tokens from one address to another (requires approval)
pub fn erc20_transfer_from<S: Signer>(
    token_address: &str,
    from_address: &str,
    to_address: &str,
    amount: U256,
    provider: &Provider,
    signer: &S,
) -> Result<TxReceipt, WalletError> {
    // Resolve addresses
    let token = resolve_name(token_address, provider.chain_id)?;
    let from = resolve_name(from_address, provider.chain_id)?;
    let to = resolve_name(to_address, provider.chain_id)?;

    // Create the call
    let call = contracts::IERC20::transferFromCall {
        from,
        to,
        value: amount,
    };
    let call_data = call.abi_encode();

    // Get token details for receipt formatting
    let token_symbol =
        erc20_symbol(token_address, provider).unwrap_or_else(|_| "tokens".to_string());
    let token_decimals = erc20_decimals(token_address, provider).unwrap_or(18);

    // Format receipt message
    let format_receipt = move |_| {
        let amount_float = amount.to::<u128>() as f64 / 10f64.powi(token_decimals as i32);
        format!(
            "Transferred {:.6} {} from {} to {}",
            amount_float, token_symbol, from_address, to_address
        )
    };

    // Prepare and send transaction
    prepare_and_send_tx(
        token,
        call_data,
        U256::ZERO,
        provider,
        signer,
        Some(100_000), // Default gas limit
        format_receipt,
    )
}

//
// ERC-721 NFT FUNCTIONS
//

/// Get the NFT balance of an address
pub fn erc721_balance_of(
    token_address: &str,
    owner_address: &str,
    provider: &Provider,
) -> Result<U256, WalletError> {
    let token = resolve_name(token_address, provider.chain_id)?;
    let owner = resolve_name(owner_address, provider.chain_id)?;

    let call = contracts::IERC721::balanceOfCall { owner };
    let balance = call_view_function(token, call, provider)?;
    Ok(balance._0)
}

/// Get the owner of an NFT token
pub fn erc721_owner_of(
    token_address: &str,
    token_id: U256,
    provider: &Provider,
) -> Result<EthAddress, WalletError> {
    let token = resolve_name(token_address, provider.chain_id)?;
    let call = contracts::IERC721::ownerOfCall { tokenId: token_id };
    let owner = call_view_function(token, call, provider)?;
    Ok(owner._0)
}

/// Check if an operator is approved for all NFTs of an owner
pub fn erc721_is_approved_for_all(
    token_address: &str,
    owner_address: &str,
    operator_address: &str,
    provider: &Provider,
) -> Result<bool, WalletError> {
    let token = resolve_name(token_address, provider.chain_id)?;
    let owner = resolve_name(owner_address, provider.chain_id)?;
    let operator = resolve_name(operator_address, provider.chain_id)?;

    let call = contracts::IERC721::isApprovedForAllCall { owner, operator };
    let is_approved = call_view_function(token, call, provider)?;
    Ok(is_approved._0)
}

/// Safely transfer an NFT
pub fn erc721_safe_transfer_from<S: Signer>(
    token_address: &str,
    from_address: &str,
    to_address: &str,
    token_id: U256,
    provider: &Provider,
    signer: &S,
) -> Result<TxReceipt, WalletError> {
    // Resolve addresses
    let token = resolve_name(token_address, provider.chain_id)?;
    let from = resolve_name(from_address, provider.chain_id)?;
    let to = resolve_name(to_address, provider.chain_id)?;

    // Create the call
    let call = contracts::IERC721::safeTransferFromCall {
        from,
        to,
        tokenId: token_id,
    };
    let call_data = call.abi_encode();

    // Format receipt message
    let format_receipt = move |_| {
        format!(
            "Safely transferred NFT ID {} from {} to {}",
            token_id, from_address, to_address
        )
    };

    // Prepare and send transaction
    prepare_and_send_tx(
        token,
        call_data,
        U256::ZERO,
        provider,
        signer,
        Some(200_000), // Higher gas limit for NFT transfers
        format_receipt,
    )
}

/// Set approval for all tokens to an operator
pub fn erc721_set_approval_for_all<S: Signer>(
    token_address: &str,
    operator_address: &str,
    approved: bool,
    provider: &Provider,
    signer: &S,
) -> Result<TxReceipt, WalletError> {
    // Resolve addresses
    let token = resolve_name(token_address, provider.chain_id)?;
    let operator = resolve_name(operator_address, provider.chain_id)?;

    // Create the call
    let call = contracts::IERC721::setApprovalForAllCall { operator, approved };
    let call_data = call.abi_encode();

    // Format receipt message
    let format_receipt = move |_| {
        format!(
            "{} operator {} to manage all of your NFTs in contract {}",
            if approved {
                "Approved"
            } else {
                "Revoked approval for"
            },
            operator_address,
            token_address
        )
    };

    // Prepare and send transaction
    prepare_and_send_tx(
        token,
        call_data,
        U256::ZERO,
        provider,
        signer,
        Some(60_000), // Default gas limit for approvals
        format_receipt,
    )
}

//
// ERC-1155 MULTI-TOKEN FUNCTIONS
//

/// Get the balance of a specific token ID for an account
pub fn erc1155_balance_of(
    token_address: &str,
    account_address: &str,
    token_id: U256,
    provider: &Provider,
) -> Result<U256, WalletError> {
    let token = resolve_name(token_address, provider.chain_id)?;
    let account = resolve_name(account_address, provider.chain_id)?;

    let call = contracts::IERC1155::balanceOfCall {
        account,
        id: token_id,
    };
    let balance = call_view_function(token, call, provider)?;
    Ok(balance._0)
}

/// Get balances for multiple accounts and token IDs
pub fn erc1155_balance_of_batch(
    token_address: &str,
    account_addresses: Vec<&str>,
    token_ids: Vec<U256>,
    provider: &Provider,
) -> Result<Vec<U256>, WalletError> {
    // Check that arrays are same length
    if account_addresses.len() != token_ids.len() {
        return Err(WalletError::TransactionError(
            "Arrays of accounts and token IDs must have the same length".into(),
        ));
    }

    // Resolve token address
    let token = resolve_name(token_address, provider.chain_id)?;

    // Resolve all account addresses
    let mut accounts = Vec::with_capacity(account_addresses.len());
    for addr in account_addresses {
        accounts.push(resolve_name(addr, provider.chain_id)?);
    }

    let call = contracts::IERC1155::balanceOfBatchCall {
        accounts,
        ids: token_ids,
    };
    let balances = call_view_function(token, call, provider)?;
    Ok(balances._0)
}

/// Check if an operator is approved for all tokens of an account
pub fn erc1155_is_approved_for_all(
    token_address: &str,
    account_address: &str,
    operator_address: &str,
    provider: &Provider,
) -> Result<bool, WalletError> {
    let token = resolve_name(token_address, provider.chain_id)?;
    let account = resolve_name(account_address, provider.chain_id)?;
    let operator = resolve_name(operator_address, provider.chain_id)?;

    let call = contracts::IERC1155::isApprovedForAllCall { account, operator };
    let is_approved = call_view_function(token, call, provider)?;
    Ok(is_approved._0)
}

/// Set approval for all tokens to an operator
pub fn erc1155_set_approval_for_all<S: Signer>(
    token_address: &str,
    operator_address: &str,
    approved: bool,
    provider: &Provider,
    signer: &S,
) -> Result<TxReceipt, WalletError> {
    // Resolve addresses
    let token = resolve_name(token_address, provider.chain_id)?;
    let operator = resolve_name(operator_address, provider.chain_id)?;

    // Create the call
    let call = contracts::IERC1155::setApprovalForAllCall { operator, approved };
    let call_data = call.abi_encode();

    // Format receipt message
    let format_receipt = move |_| {
        format!(
            "{} operator {} to manage all of your ERC1155 tokens in contract {}",
            if approved {
                "Approved"
            } else {
                "Revoked approval for"
            },
            operator_address,
            token_address
        )
    };

    // Prepare and send transaction
    prepare_and_send_tx(
        token,
        call_data,
        U256::ZERO,
        provider,
        signer,
        Some(60_000), // Default gas limit for approvals
        format_receipt,
    )
}

/// Transfer a single ERC1155 token
pub fn erc1155_safe_transfer_from<S: Signer>(
    token_address: &str,
    from_address: &str,
    to_address: &str,
    token_id: U256,
    amount: U256,
    data: Vec<u8>,
    provider: &Provider,
    signer: &S,
) -> Result<TxReceipt, WalletError> {
    // Resolve addresses
    let token = resolve_name(token_address, provider.chain_id)?;
    let from = resolve_name(from_address, provider.chain_id)?;
    let to = resolve_name(to_address, provider.chain_id)?;

    // Create the call
    let call = contracts::IERC1155::safeTransferFromCall {
        from,
        to,
        id: token_id,
        amount,
        data: Bytes::from(data),
    };
    let call_data = call.abi_encode();

    // Format receipt message
    let format_receipt = move |_| {
        format!(
            "Transferred {} of token ID {} from {} to {}",
            amount, token_id, from_address, to_address
        )
    };

    // Prepare and send transaction
    prepare_and_send_tx(
        token,
        call_data,
        U256::ZERO,
        provider,
        signer,
        Some(150_000), // Default gas limit for ERC1155 transfers
        format_receipt,
    )
}

/// Batch transfer multiple ERC1155 tokens
pub fn erc1155_safe_batch_transfer_from<S: Signer>(
    token_address: &str,
    from_address: &str,
    to_address: &str,
    token_ids: Vec<U256>,
    amounts: Vec<U256>,
    data: Vec<u8>,
    provider: &Provider,
    signer: &S,
) -> Result<TxReceipt, WalletError> {
    // Check that arrays are same length
    if token_ids.len() != amounts.len() {
        return Err(WalletError::TransactionError(
            "Arrays of token IDs and amounts must have the same length".into(),
        ));
    }

    // Resolve addresses
    let token = resolve_name(token_address, provider.chain_id)?;
    let from = resolve_name(from_address, provider.chain_id)?;
    let to = resolve_name(to_address, provider.chain_id)?;

    // Create the call
    let call = contracts::IERC1155::safeBatchTransferFromCall {
        from,
        to,
        ids: token_ids.clone(),
        amounts: amounts.clone(),
        data: Bytes::from(data),
    };
    let call_data = call.abi_encode();

    // For batch transfers, gas estimation is tricky - use a formula that scales with token count
    let token_count = token_ids.len();
    // Base gas (200,000) + extra per token (50,000 each)
    let default_gas = Some(200_000 + (token_count as u64 * 50_000));

    // Format receipt message
    let format_receipt = move |_| {
        format!(
            "Batch transferred {} token types from {} to {}",
            token_count, from_address, to_address
        )
    };

    // Prepare and send transaction
    prepare_and_send_tx(
        token,
        call_data,
        U256::ZERO,
        provider,
        signer,
        default_gas,
        format_receipt,
    )
}

//
// HYPERMAP FUNCTIONS
//

/// Create a note (mutable data) on a Hypermap namespace entry
pub fn create_note<S: Signer>(
    parent_entry: &str,
    note_key: &str,
    data: Vec<u8>,
    provider: Provider,
    signer: &S,
) -> Result<HypermapTxReceipt, WalletError> {
    // Verify the note key is valid
    if !valid_note(note_key) {
        return Err(WalletError::NameResolutionError(
            format!("Invalid note key '{}'. Must start with '~' and contain only lowercase letters, numbers, and hyphens", note_key)
        ));
    }

    // Create the note function call data
    let note_function = hypermap::contract::noteCall {
        note: Bytes::from(note_key.as_bytes().to_vec()),
        data: Bytes::from(data),
    };

    // Create the hypermap transaction
    create_hypermap_tx(
        parent_entry,
        Bytes::from(note_function.abi_encode()),
        || format!("Created note '{}' on '{}'", note_key, parent_entry),
        provider,
        signer,
    )
}

/// Create a fact (immutable data) on a Hypermap namespace entry
pub fn create_fact<S: Signer>(
    parent_entry: &str,
    fact_key: &str,
    data: Vec<u8>,
    provider: Provider,
    signer: &S,
) -> Result<HypermapTxReceipt, WalletError> {
    // Verify the fact key is valid
    if !valid_fact(fact_key) {
        return Err(WalletError::NameResolutionError(
            format!("Invalid fact key '{}'. Must start with '!' and contain only lowercase letters, numbers, and hyphens", fact_key)
        ));
    }

    // Create the fact function call data
    let fact_function = hypermap::contract::factCall {
        fact: Bytes::from(fact_key.as_bytes().to_vec()),
        data: Bytes::from(data),
    };

    // Create the hypermap transaction
    create_hypermap_tx(
        parent_entry,
        Bytes::from(fact_function.abi_encode()),
        || format!("Created fact '{}' on '{}'", fact_key, parent_entry),
        provider,
        signer,
    )
}

/// Mint a new namespace entry under a parent entry
pub fn mint_entry<S: Signer>(
    parent_entry: &str,
    label: &str,
    recipient: &str,
    implementation: &str,
    provider: Provider,
    signer: &S,
) -> Result<HypermapTxReceipt, WalletError> {
    // Verify the label is valid
    if !valid_name(label) {
        return Err(WalletError::NameResolutionError(format!(
            "Invalid label '{}'. Must contain only lowercase letters, numbers, and hyphens",
            label
        )));
    }

    // Resolve addresses
    let recipient_address = resolve_name(recipient, provider.chain_id)?;
    let implementation_address = resolve_name(implementation, provider.chain_id)?;

    // Create the mint function call data
    let mint_function = hypermap::contract::mintCall {
        who: recipient_address,
        label: Bytes::from(label.as_bytes().to_vec()),
        initialization: Bytes::default(), // No initialization data
        erc721Data: Bytes::default(),     // No ERC721 data
        implementation: implementation_address,
    };

    // Create the hypermap transaction
    create_hypermap_tx(
        parent_entry,
        Bytes::from(mint_function.abi_encode()),
        || format!("Minted new entry '{}' under '{}'", label, parent_entry),
        provider,
        signer,
    )
}

/// Set the gene for a namespace entry
pub fn set_gene<S: Signer>(
    entry: &str,
    gene_implementation: &str,
    provider: Provider,
    signer: &S,
) -> Result<HypermapTxReceipt, WalletError> {
    // Resolve gene implementation address
    let gene_address = resolve_name(gene_implementation, provider.chain_id)?;

    // Create the gene function call data
    let gene_function = hypermap::contract::geneCall {
        _gene: gene_address,
    };

    // Create the hypermap transaction
    create_hypermap_tx(
        entry,
        Bytes::from(gene_function.abi_encode()),
        || format!("Set gene for '{}' to '{}'", entry, gene_implementation),
        provider,
        signer,
    )
}

//
// TOKEN BOUND ACCOUNT (ERC-6551) FUNCTIONS
//

/// Executes a call through a Token Bound Account (TBA) using a specific signer.
/// This function is designed for scenarios where the signer might be an authorized delegate
/// (e.g., via Hypermap notes like ~access-list) rather than the direct owner of the underlying NFT.
/// The TBA's own `execute` implementation is responsible for verifying the signer's authorization.
pub fn execute_via_tba_with_signer<S: Signer>(
    tba_address_or_name: &str,
    hot_wallet_signer: &S,
    target_address_or_name: &str,
    call_data: Vec<u8>,
    value: U256,
    provider: &Provider,
    operation: Option<u8>,
) -> Result<TxReceipt, WalletError> {
    // Resolve addresses
    let tba = resolve_name(tba_address_or_name, provider.chain_id)?;
    let target = resolve_name(target_address_or_name, provider.chain_id)?;
    let op = operation.unwrap_or(0); // Default to CALL operation

    kiprintln!(
        "PL:: Executing via TBA {} (signer: {}) -> Target {} (Op: {}, Value: {})",
        tba,
        hot_wallet_signer.address(),
        target,
        op,
        value
    );

    // Create the outer execute call (with txGas) directed at the TBA
    // Use the _1 suffix for the second defined execute function (5 args)
    let internal_gas_limit = U256::from(500_000); // Explicitly set gas for the internal call
    let execute_call = contracts::IERC6551Account::execute_1Call {
        // <-- Using _1 suffix now
        to: target,
        value, // This value is sent from the TBA to the target
        data: Bytes::from(call_data),
        operation: op,
        txGas: internal_gas_limit, // Provide gas for the internal call
    };
    let execute_call_data = execute_call.abi_encode();

    // Format receipt message
    let format_receipt = move |_| {
        format!(
            "Execute via TBA {} to target {} (Signer: {}, Internal Gas: {})", // Updated log
            tba_address_or_name,
            target_address_or_name,
            hot_wallet_signer.address(),
            internal_gas_limit // Log internal gas
        )
    };

    // Prepare and send the transaction *to* the TBA, signed by the hot_wallet_signer.
    // The `value` field in the *outer* transaction is U256::ZERO because the ETH transfer
    // happens *inside* the TBA's execution context, funded by the TBA itself.
    // prepare_and_send_tx will handle gas estimation for the outer transaction.
    prepare_and_send_tx(
        tba,               // Transaction is sent TO the TBA address
        execute_call_data, // Data is the ABI-encoded `execute` call with internal gas limit
        U256::ZERO,        // Outer transaction sends no ETH directly to the TBA
        provider,
        hot_wallet_signer, // Signed by the provided (potentially delegated) signer
        None,              // Let prepare_and_send_tx estimate outer gas limit
        format_receipt,
    )
}

/// Executes a call through a Token Bound Account (TBA)
/// Assumes the provided signer is the owner/controller authorized by the standard ERC6551 implementation.
pub fn tba_execute<S: Signer>(
    tba_address: &str,
    target_address: &str,
    call_data: Vec<u8>,
    value: U256,
    operation: u8, // 0 for CALL, 1 for DELEGATECALL, etc.
    provider: &Provider,
    signer: &S,
) -> Result<TxReceipt, WalletError> {
    // Resolve addresses
    let tba = resolve_name(tba_address, provider.chain_id)?;
    let target = resolve_name(target_address, provider.chain_id)?;

    // Create the execute call
    let execute_call = contracts::IERC6551Account::execute_0Call {
        to: target,
        value,
        data: Bytes::from(call_data),
        operation,
    };

    // Format receipt message
    let format_receipt = move |_| {
        format!(
            "Executed call via TBA {} to target {}",
            tba_address, target_address
        )
    };

    // Prepare and send the transaction - Use a higher default gas limit for TBA executions
    prepare_and_send_tx(
        tba,
        execute_call.abi_encode(),
        value, // Pass the value intended for the target call
        provider,
        signer,
        Some(500_000), // Higher gas limit for potential complex TBA logic + target call
        format_receipt,
    )
}

/// Checks if an address is a valid signer for a given TBA.
/// This checks against the standard ERC-6551 `isValidSigner` which returns a magic value.
pub fn tba_is_valid_signer(
    tba_address: &str,
    signer_address: &str,
    provider: &Provider,
) -> Result<bool, WalletError> {
    // Resolve addresses
    let tba = resolve_name(tba_address, provider.chain_id)?;
    let signer_addr = resolve_name(signer_address, provider.chain_id)?;

    // Create the isValidSigner call
    let call = contracts::IERC6551Account::isValidSignerCall {
        signer: signer_addr,
        data: Bytes::default(), // No extra data needed for standard check
    };
    let call_data = call.abi_encode();

    // Perform the raw eth_call
    let tx = TransactionRequest {
        to: Some(TxKind::Call(tba)),
        input: call_data.into(),
        ..Default::default()
    };
    let result_bytes = provider.call(tx, None)?;

    // Expected magic value for valid signer (IERC6551Account.isValidSigner.selector)
    const ERC6551_IS_VALID_SIGNER: [u8; 4] = [0x52, 0x3e, 0x32, 0x60];

    // Check if the returned bytes match the magic value
    Ok(result_bytes.len() >= 4 && result_bytes[..4] == ERC6551_IS_VALID_SIGNER)
}

/// Retrieves the token information (chainId, contract address, tokenId) associated with a TBA.
pub fn tba_get_token_info(
    tba_address: &str,
    provider: &Provider,
) -> Result<(u64, EthAddress, U256), WalletError> {
    // Resolve TBA address
    let tba = resolve_name(tba_address, provider.chain_id)?;

    // Create the token() call
    let call = contracts::IERC6551Account::tokenCall {};

    // Use the view function helper
    let result = call_view_function(tba, call, provider)?;

    // Use named fields from the generated struct
    let chain_id_u256 = result.chainId;
    let token_contract = result.tokenContract;
    let token_id = result.tokenId;

    // Convert chainId U256 to u64 (potential truncation, but unlikely for real chain IDs)
    let chain_id = chain_id_u256.to::<u64>();

    Ok((chain_id, token_contract, token_id))
}

/// Sets the signer data key for a HypermapSignerAccount TBA.
/// This links the TBA's alternative signer validation mechanism to a specific Hypermap note hash.
pub fn tba_set_signer_data_key<S: Signer>(
    tba_address: &str,
    data_key_hash: B256, // Use B256 for bytes32
    provider: &Provider,
    signer: &S, // Must be called by the current owner/controller of the TBA
) -> Result<TxReceipt, WalletError> {
    // Resolve TBA address
    let tba = resolve_name(tba_address, provider.chain_id)?;

    // Create the setSignerDataKey call
    let set_key_call = contracts::IERC6551Account::setSignerDataKeyCall {
        signerDataKey: data_key_hash,
    };

    // Format receipt message
    let format_receipt = move |_| {
        format!(
            "Set signer data key for TBA {} to hash {}",
            tba_address, data_key_hash
        )
    };

    // Prepare and send the transaction
    prepare_and_send_tx(
        tba,
        set_key_call.abi_encode(),
        U256::ZERO,
        provider,
        signer,
        Some(100_000), // Gas limit for a simple storage set
        format_receipt,
    )
}

//
// HYPERMAP + TBA HELPER FUNCTIONS
//

/// Creates a note (~allowed-signer) on a Hypermap entry containing an alternative signer's address,
/// and then configures the entry's TBA to use this note for alternative signature validation.
/// Requires the signature of the *owner* of the Hypermap entry.
pub fn setup_alternative_signer<S: Signer>(
    entry_name: &str,               // e.g., "username.hypr"
    alt_signer_address: EthAddress, // The address allowed to sign alternatively
    provider: &Provider,
    owner_signer: &S, // Signer holding the key that owns 'entry_name'
) -> Result<TxReceipt, WalletError> {
    // 1. Calculate the Hypermap entry hash
    let entry_hash = hypermap::namehash(entry_name);

    // 2. Get the TBA associated with this entry and verify ownership
    let hypermap_contract = provider.hypermap();
    let (tba, owner, _) = hypermap_contract.get_hash(&entry_hash)?;

    // 3. Check if the provided signer is the owner
    if owner_signer.address() != owner {
        return Err(WalletError::PermissionDenied(format!(
            "Signer {} does not own the entry {}",
            owner_signer.address(),
            entry_name
        )));
    }

    // 4. Define the note key for the allowed signer
    let note_key = "~allowed-signer";

    // 5. Create the note in Hypermap storing the alternative signer's address
    // This requires a transaction signed by the owner_signer, executed via the parent TBA (owner's TBA)
    kiprintln!(
        "PL:: Creating note '{}' on '{}' with data {}",
        note_key,
        entry_name,
        alt_signer_address
    );
    let create_note_receipt = create_note(
        entry_name,
        note_key,
        alt_signer_address.to_vec(), // Store address as bytes
        provider.clone(),
        owner_signer,
    )?;
    kiprintln!(
        "PL:: Create note transaction sent: {}",
        create_note_receipt.hash
    );
    // Note: We might want to wait for this tx to confirm before proceeding

    // 6. Calculate the namehash of the specific note
    // Combine note key and entry name, then hash
    let note_full_name = format!("{}.{}", note_key, entry_name);
    let note_hash_str = hypermap::namehash(&note_full_name);
    // Convert the String hash to B256
    let note_hash = B256::from_str(&note_hash_str.trim_start_matches("0x"))
        .map_err(|_| WalletError::TransactionError("Failed to parse note hash string".into()))?;

    kiprintln!(
        "PL:: Calculated note hash for '{}': {}",
        note_full_name,
        note_hash
    );

    // 7. Set this note hash as the signer data key in the TBA
    // This also requires a transaction signed by the owner_signer, sent directly to the TBA
    kiprintln!(
        "PL:: Setting signer data key on TBA {} to note hash {}",
        tba,
        note_hash
    );
    let set_key_receipt = tba_set_signer_data_key(
        &tba.to_string(), // Use the TBA address resolved earlier
        note_hash,
        provider,
        owner_signer, // Owner signer makes this call directly to the TBA
    )?;
    kiprintln!(
        "PL:: Set signer data key transaction sent: {}",
        set_key_receipt.hash
    );

    // Return the receipt of the *second* transaction (setting the key)
    // Ideally, we'd return both or confirm the first one succeeded.
    Ok(TxReceipt {
        hash: set_key_receipt.hash,
        details: format!(
            "Set up alternative signer {} for entry {} (Note Tx: {}, SetKey Tx: {})",
            alt_signer_address, entry_name, create_note_receipt.hash, set_key_receipt.hash
        ),
    })
}

/// Retrieves the alternative signer address stored in the '~allowed-signer' note
/// associated with a given Hypermap entry.
pub fn get_alternative_signer(
    entry_name: &str,
    provider: &Provider,
) -> Result<Option<EthAddress>, WalletError> {
    // 1. Calculate the Hypermap entry hash
    let _entry_hash = hypermap::namehash(entry_name);

    // 2. Define the note key
    let note_key = "~allowed-signer";

    // 3. Calculate the specific note hash
    let hypermap_contract = provider.hypermap();
    let note_full_name = format!("{}.{}", note_key, entry_name);
    let note_hash = hypermap::namehash(&note_full_name);

    // 4. Get the data stored at this specific note hash from Hypermap
    match hypermap_contract.get_hash(&note_hash) {
        Ok((_tba, _owner, data_option)) => {
            // Handle the Option<Bytes>
            match data_option {
                Some(data_bytes) => {
                    // 5. If data is present and exactly 20 bytes long, parse it as an address
                    if data_bytes.len() == 20 {
                        Ok(Some(EthAddress::from_slice(data_bytes.as_ref())))
                    } else {
                        // Data exists but is the wrong length - use TransactionError
                        Err(WalletError::TransactionError(format!(
                            "Data at note hash {} for entry {} has incorrect length ({}) for an address",
                            note_hash,
                            entry_name,
                            data_bytes.len()
                        )))
                    }
                }
                None => {
                    // Note exists (or get_hash succeeded) but has no data
                    Ok(None)
                }
            }
        }
        Err(EthError::RpcError(msg)) => {
            // Convert potential JSON error message to string for checking
            let msg_str = msg.to_string();
            if msg_str.contains("Execution reverted") || msg_str.contains("invalid opcode") {
                // This likely means the note hash doesn't exist or isn't registered
                Ok(None)
            } else {
                // Propagate other RPC errors
                Err(WalletError::EthError(EthError::RpcError(msg)))
            }
        }
        Err(e) => Err(WalletError::EthError(e)), // Propagate other errors
    }
}

// TODO: TEST
// ... existing test section ...

/// Transaction details in a more user-friendly format
#[derive(Debug, Clone)]
pub struct TransactionDetails {
    pub hash: TxHash,
    pub from: EthAddress,
    pub to: Option<EthAddress>,
    pub value: EthAmount,
    pub block_number: Option<u64>,
    pub timestamp: Option<u64>,
    pub gas_used: Option<u64>,
    pub gas_price: Option<U256>,
    pub success: Option<bool>,
    pub direction: TransactionDirection,
}

/// Direction of the transaction relative to the address
#[derive(Debug, Clone, PartialEq)]
pub enum TransactionDirection {
    Incoming,
    Outgoing,
    SelfTransfer,
}

/// Get transactions for an address - simplified version that works with Alloy
pub fn get_address_transactions(
    address_or_name: &str,
    provider: &Provider,
    max_blocks_back: Option<u64>,
) -> Result<Vec<TransactionDetails>, WalletError> {
    let target_address = resolve_name(address_or_name, provider.chain_id)?;

    // Get block range
    let latest_block = provider.get_block_number()?;
    let blocks_back = max_blocks_back.unwrap_or(1000);
    let start_block = if latest_block > blocks_back {
        latest_block - blocks_back
    } else {
        0
    };

    // Create filter to find logs involving our address
    let filter = Filter {
        block_option: FilterBlockOption::Range {
            from_block: Some(start_block.into()),
            to_block: Some(latest_block.into()),
        },
        address: FilterSet::from(vec![target_address]),
        topics: Default::default(),
    };

    // Get logs matching our filter
    let logs = provider.get_logs(&filter)?;
    kiprintln!(
        "Found {} logs involving address {}",
        logs.len(),
        target_address
    );

    // Extract unique transaction hashes
    let mut tx_hashes = Vec::new();
    for log in logs {
        if let Some(hash) = log.transaction_hash {
            if !tx_hashes.contains(&hash) {
                tx_hashes.push(hash);
            }
        }
    }

    // Create transaction details objects for each tx hash
    let mut transactions = Vec::new();

    for tx_hash in tx_hashes {
        // For each transaction, create a basic TransactionDetails object
        // with just the transaction hash and basic direction
        let mut tx_detail = TransactionDetails {
            hash: tx_hash,
            from: EthAddress::default(), // We'll update this if we can get the transaction
            to: None,
            value: EthAmount {
                wei_value: U256::ZERO,
            },
            block_number: None,
            timestamp: None,
            gas_used: None,
            gas_price: None,
            success: None,
            direction: TransactionDirection::Incoming, // Default, will update if needed
        };

        // Try to get transaction receipt for more details
        if let Ok(Some(receipt)) = provider.get_transaction_receipt(tx_hash) {
            // Update from receipt fields that we know exist
            tx_detail.block_number = receipt.block_number;

            // Get transaction success status if available
            let status = receipt.status();
            if status {
                tx_detail.success = Some(true);
            } else {
                tx_detail.success = Some(false);
            }

            // Try to get original transaction for more details
            if let Ok(Some(tx)) = provider.get_transaction_by_hash(tx_hash) {
                // Update from transaction fields
                tx_detail.from = tx.from;

                // Set direction based on compared addresses
                if tx.from == target_address {
                    tx_detail.direction = TransactionDirection::Outgoing;
                } else {
                    tx_detail.direction = TransactionDirection::Incoming;
                }

                // Try to get block timestamp if we have block number
                if let Some(block_num) = tx_detail.block_number {
                    if let Ok(Some(block)) =
                        provider.get_block_by_number(BlockNumberOrTag::Number(block_num), false)
                    {
                        // Block header timestamp is a u64, not an Option
                        tx_detail.timestamp = Some(block.header.timestamp);
                    }
                }
            }
        }

        transactions.push(tx_detail);
    }

    // Sort by block number (descending)
    transactions.sort_by(|a, b| match (b.block_number, a.block_number) {
        (Some(b_num), Some(a_num)) => b_num.cmp(&a_num),
        (Some(_), None) => std::cmp::Ordering::Less,
        (None, Some(_)) => std::cmp::Ordering::Greater,
        (None, None) => std::cmp::Ordering::Equal,
    });

    Ok(transactions)
}

/// Format transaction details for display
pub fn format_transaction_details(tx: &TransactionDetails) -> String {
    // Symbol to represent transaction direction
    let direction_symbol = match tx.direction {
        TransactionDirection::Incoming => "",
        TransactionDirection::Outgoing => "",
        TransactionDirection::SelfTransfer => "",
    };

    // Transaction status
    let status = match tx.success {
        Some(true) => "Succeeded",
        Some(false) => "Failed",
        None => "Unknown",
    };

    // Format value
    let value = tx.value.to_string();

    // Format timestamp without external dependencies
    let timestamp = match tx.timestamp {
        Some(ts) => format_timestamp(ts),
        None => "Pending".to_string(),
    };

    // Format to and from addresses
    let from_addr = format!(
        "{:.8}...{}",
        tx.from.to_string()[0..10].to_string(),
        tx.from.to_string()[34..].to_string()
    );

    let to_addr = tx.to.map_or("Contract Creation".to_string(), |addr| {
        format!(
            "{:.8}...{}",
            addr.to_string()[0..10].to_string(),
            addr.to_string()[34..].to_string()
        )
    });

    // Format final output
    format!(
        "TX: {} [{}]\n   {} {} {}\n   Block: {}, Status: {}, Value: {}, Time: {}",
        tx.hash,
        status,
        from_addr,
        direction_symbol,
        to_addr,
        tx.block_number
            .map_or("Pending".to_string(), |b| b.to_string()),
        status,
        value,
        timestamp
    )
}
/// Format a Unix timestamp without external dependencies
fn format_timestamp(timestamp: u64) -> String {
    // Simple timestamp formatting
    // We'll use a very basic approach that doesn't rely on date/time libraries

    // Convert to seconds, minutes, hours, days since epoch
    let secs = timestamp % 60;
    let mins = (timestamp / 60) % 60;
    let hours = (timestamp / 3600) % 24;
    let days_since_epoch = timestamp / 86400;

    // Very rough estimation - doesn't account for leap years properly
    let years_since_epoch = days_since_epoch / 365;
    let days_this_year = days_since_epoch % 365;

    // Rough month calculation
    let month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    let mut month = 0;
    let mut day = days_this_year as u32;

    // Adjust for leap years in a very rough way
    let is_leap_year = (1970 + years_since_epoch as u32) % 4 == 0;
    let month_days = if is_leap_year {
        let mut md = month_days.to_vec();
        md[1] = 29; // February has 29 days in leap years
        md
    } else {
        month_days.to_vec()
    };

    // Find month and day
    for (i, &days_in_month) in month_days.iter().enumerate() {
        if day < days_in_month {
            month = i;
            break;
        }
        day -= days_in_month;
    }

    // Adjust to 1-based
    day += 1;
    month += 1;

    // Format the date
    format!(
        "{:04}-{:02}-{:02} {:02}:{:02}:{:02}",
        1970 + years_since_epoch,
        month,
        day,
        hours,
        mins,
        secs
    )
}

// New structured type to hold all ERC20 token information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenDetails {
    pub address: String,
    pub symbol: String,
    pub name: String,
    pub decimals: u8,
    pub total_supply: String,
    pub balance: String,
    pub formatted_balance: String,
}

/// Get all relevant details for an ERC20 token in one call
/// This consolidates multiple calls into a single function for frontend use
pub fn get_token_details(
    token_address: &str,
    wallet_address: &str,
    provider: &Provider,
) -> Result<TokenDetails, WalletError> {
    // First resolve the token address (could be a symbol or address)
    let token = match resolve_token_symbol(token_address, provider.chain_id) {
        Ok(addr) => addr,
        Err(_) => resolve_name(token_address, provider.chain_id)?,
    };

    // Get basic token information
    let token_str = token.to_string();
    let symbol = erc20_symbol(token_address, provider)?;
    let name = erc20_name(token_address, provider)?;
    let decimals = erc20_decimals(token_address, provider)?;

    // Get total supply
    let total_supply = erc20_total_supply(token_address, provider)?;
    let total_supply_float = total_supply.to::<u128>() as f64 / 10f64.powi(decimals as i32);
    let formatted_total_supply = format!("{:.2}", total_supply_float);

    // Get balance if wallet address is provided
    let (balance, formatted_balance) = if !wallet_address.is_empty() {
        let balance = erc20_balance_of(token_address, wallet_address, provider)?;
        (balance.to_string(), format!("{:.6}", balance))
    } else {
        ("0".to_string(), "0.000000".to_string())
    };

    Ok(TokenDetails {
        address: token_str,
        symbol,
        name,
        decimals,
        total_supply: formatted_total_supply,
        balance,
        formatted_balance,
    })
}

//
// CALLDATA CREATION HELPERS
//

/// Creates the ABI-encoded calldata for an ERC20 `transfer` call.
///
/// # Arguments
/// * `recipient` - The address to transfer tokens to.
/// * `amount` - The amount of tokens to transfer (in the token's smallest unit, e.g., wei for ETH-like).
///
/// # Returns
/// A `Vec<u8>` containing the ABI-encoded calldata.
pub fn create_erc20_transfer_calldata(recipient: EthAddress, amount: U256) -> Vec<u8> {
    let call = contracts::IERC20::transferCall {
        to: recipient,
        value: amount,
    };
    call.abi_encode()
}

/// Creates the ABI-encoded calldata for a Hypermap `note` call.
/// Performs validation on the note key format.
///
/// # Arguments
/// * `note_key` - The note key (e.g., "~my-note"). Must start with '~'.
/// * `data` - The byte data to store in the note.
///
/// # Returns
/// A `Result<Vec<u8>, WalletError>` containing the ABI-encoded calldata on success,
/// or a `WalletError::NameResolutionError` if the note key format is invalid.
pub fn create_hypermap_note_calldata(
    note_key: &str,
    data: Vec<u8>,
) -> Result<Vec<u8>, WalletError> {
    // Validate the note key format
    if !hypermap::valid_note(note_key) {
        return Err(WalletError::NameResolutionError(format!(
            "Invalid note key format: '{}'. Must start with '~' and follow naming rules.",
            note_key
        )));
    }

    let call = hypermap::contract::noteCall {
        note: Bytes::from(note_key.as_bytes().to_vec()),
        data: Bytes::from(data),
    };
    Ok(call.abi_encode())
}

/// UserOperation builder for ERC-4337
#[derive(Debug, Clone)]
pub struct UserOperationBuilder {
    pub sender: EthAddress,
    pub nonce: U256,
    pub init_code: Vec<u8>,
    pub call_data: Vec<u8>,
    pub call_gas_limit: U256,
    pub verification_gas_limit: U256,
    pub pre_verification_gas: U256,
    pub max_fee_per_gas: U256,
    pub max_priority_fee_per_gas: U256,
    pub paymaster_and_data: Vec<u8>,
    pub chain_id: u64,
}

impl UserOperationBuilder {
    /// Create a new UserOperationBuilder with defaults
    pub fn new(sender: EthAddress, chain_id: u64) -> Self {
        Self {
            sender,
            nonce: U256::ZERO,
            init_code: Vec::new(),
            call_data: Vec::new(),
            call_gas_limit: U256::from(80_000), // Reduced from 100k
            verification_gas_limit: U256::from(100_000), // Reduced from 150k
            pre_verification_gas: U256::from(50_000), // Increased from 21k for L2
            // Set reasonable gas prices for Base chain
            max_fee_per_gas: U256::from(1_000_000_000), // 1 gwei
            max_priority_fee_per_gas: U256::from(1_000_000_000), // 1 gwei
            paymaster_and_data: Vec::new(),
            chain_id,
        }
    }

    /// Build and sign the UserOperation
    pub fn build_and_sign<S: Signer>(
        self,
        entry_point: EthAddress,
        signer: &S,
    ) -> Result<PackedUserOperation, WalletError> {
        // Create the v0.8 PackedUserOperation struct
        let mut packed_op = build_packed_user_operation(&self);

        // Get the UserOp hash for signing
        let user_op_hash = self.get_user_op_hash_v08(&packed_op, entry_point, self.chain_id);

        // Log the hash before signing
        kiprintln!(
            "PL:: UserOperation hash to sign: 0x{}",
            hex::encode(&user_op_hash)
        );
        kiprintln!("PL:: Entry point: {}", entry_point);
        kiprintln!("PL:: Chain ID: {}", self.chain_id);

        // Sign the hash
        let signature = signer.sign_message(&user_op_hash)?;

        // Set the signature
        packed_op.signature = Bytes::from(signature);

        Ok(packed_op)
    }

    /// Calculate the UserOp hash according to ERC-4337 spec
    fn _get_user_op_hash(
        &self,
        user_op: &UserOperation,
        entry_point: EthAddress,
        chain_id: u64,
    ) -> Vec<u8> {
        use sha3::{Digest, Keccak256};

        // Pack the UserOp for hashing (without signature)
        let packed = self._pack_user_op_for_hash(user_op);
        let user_op_hash = Keccak256::digest(&packed);

        // Create the final hash with entry point and chain ID
        let mut hasher = Keccak256::new();
        hasher.update(user_op_hash);
        hasher.update(entry_point.as_slice());
        hasher.update(&chain_id.to_be_bytes());

        hasher.finalize().to_vec()
    }

    /// Calculate the UserOp hash for v0.8 according to ERC-4337 spec
    fn get_user_op_hash_v08(
        &self,
        user_op: &PackedUserOperation,
        entry_point: EthAddress,
        chain_id: u64,
    ) -> Vec<u8> {
        use sha3::{Digest, Keccak256};

        // Pack the UserOp for hashing (without signature)
        let packed = self.pack_user_op_for_hash_v08(user_op);
        let user_op_hash = Keccak256::digest(&packed);

        // Create the final hash with entry point and chain ID
        let mut hasher = Keccak256::new();
        hasher.update(user_op_hash);
        hasher.update(entry_point.as_slice());
        hasher.update(&chain_id.to_be_bytes());

        hasher.finalize().to_vec()
    }

    /// Pack UserOp fields for hashing (ERC-4337 specification)
    fn _pack_user_op_for_hash(&self, user_op: &UserOperation) -> Vec<u8> {
        use sha3::{Digest, Keccak256};

        let mut packed = Vec::new();

        // Pack all fields except signature
        packed.extend_from_slice(user_op.sender.as_slice());
        packed.extend_from_slice(&user_op.nonce.to_be_bytes::<32>());

        // For initCode and paymasterAndData, we hash them if non-empty
        if !user_op.initCode.is_empty() {
            let hash = Keccak256::digest(&user_op.initCode);
            packed.extend_from_slice(&hash);
        } else {
            packed.extend_from_slice(&[0u8; 32]);
        }

        if !user_op.callData.is_empty() {
            let hash = Keccak256::digest(&user_op.callData);
            packed.extend_from_slice(&hash);
        } else {
            packed.extend_from_slice(&[0u8; 32]);
        }

        packed.extend_from_slice(&user_op.callGasLimit.to_be_bytes::<32>());
        packed.extend_from_slice(&user_op.verificationGasLimit.to_be_bytes::<32>());
        packed.extend_from_slice(&user_op.preVerificationGas.to_be_bytes::<32>());
        packed.extend_from_slice(&user_op.maxFeePerGas.to_be_bytes::<32>());
        packed.extend_from_slice(&user_op.maxPriorityFeePerGas.to_be_bytes::<32>());

        if !user_op.paymasterAndData.is_empty() {
            let hash = Keccak256::digest(&user_op.paymasterAndData);
            packed.extend_from_slice(&hash);
        } else {
            packed.extend_from_slice(&[0u8; 32]);
        }

        packed
    }

    /// Pack UserOp fields for hashing v0.8 (ERC-4337 specification)
    fn pack_user_op_for_hash_v08(&self, user_op: &PackedUserOperation) -> Vec<u8> {
        use sha3::{Digest, Keccak256};

        let mut packed = Vec::new();

        // Pack all fields except signature
        packed.extend_from_slice(user_op.sender.as_slice());
        packed.extend_from_slice(&user_op.nonce.to_be_bytes::<32>());

        // For initCode and paymasterAndData, we hash them if non-empty
        if !user_op.initCode.is_empty() {
            let hash = Keccak256::digest(&user_op.initCode);
            packed.extend_from_slice(&hash);
        } else {
            packed.extend_from_slice(&[0u8; 32]);
        }

        if !user_op.callData.is_empty() {
            let hash = Keccak256::digest(&user_op.callData);
            packed.extend_from_slice(&hash);
        } else {
            packed.extend_from_slice(&[0u8; 32]);
        }

        // Pack the packed fields directly (accountGasLimits and gasFees)
        packed.extend_from_slice(&user_op.accountGasLimits.0);
        packed.extend_from_slice(&user_op.preVerificationGas.to_be_bytes::<32>());
        packed.extend_from_slice(&user_op.gasFees.0);

        if !user_op.paymasterAndData.is_empty() {
            let hash = Keccak256::digest(&user_op.paymasterAndData);
            packed.extend_from_slice(&hash);
        } else {
            packed.extend_from_slice(&[0u8; 32]);
        }

        packed
    }

    /// Set paymaster and paymaster data with EIP-2612 permit signature
    pub fn paymaster_with_permit<S: Signer>(
        &mut self,
        paymaster: EthAddress,
        _token_address: EthAddress,
        _max_cost: U256,
        _tba_address: EthAddress,
        _signer: &S,
        _provider: &Provider,
    ) -> Result<(), WalletError> {
        // Use simple Circle format - no permit signature needed
        // The TBA has already approved the paymaster to spend USDC
        let paymaster_data = encode_circle_paymaster_data(
            paymaster, 500_000, // Default verification gas limit
            300_000, // Default call gas limit
        );

        // Set the combined paymaster and data
        self.paymaster_and_data = paymaster_data;

        Ok(())
    }
}

/// Helper to create calldata for TBA execute through UserOp
pub fn create_tba_userop_calldata(
    target: EthAddress,
    value: U256,
    data: Vec<u8>,
    operation: u8,
) -> Vec<u8> {
    // Use existing IERC6551Account interface
    let call = contracts::IERC6551Account::execute_0Call {
        to: target,
        value,
        data: Bytes::from(data),
        operation,
    };
    call.abi_encode()
}

/// Pack two 16-byte values into a single bytes32 for v0.8 UserOperation
fn pack_gas_values(high: U256, low: U256) -> B256 {
    let mut packed = [0u8; 32];
    // Take the lower 16 bytes of each value
    let high_bytes = high.to_be_bytes::<32>();
    let low_bytes = low.to_be_bytes::<32>();

    // Pack high value in first 16 bytes
    packed[0..16].copy_from_slice(&high_bytes[16..32]);
    // Pack low value in last 16 bytes
    packed[16..32].copy_from_slice(&low_bytes[16..32]);

    B256::from(packed)
}

/// Build a v0.8 PackedUserOperation from the builder values
pub fn build_packed_user_operation(builder: &UserOperationBuilder) -> PackedUserOperation {
    // Pack gas limits: verificationGasLimit (high) and callGasLimit (low)
    let account_gas_limits =
        pack_gas_values(builder.verification_gas_limit, builder.call_gas_limit);

    // Pack gas fees: maxPriorityFeePerGas (high) and maxFeePerGas (low)
    let gas_fees = pack_gas_values(builder.max_priority_fee_per_gas, builder.max_fee_per_gas);

    PackedUserOperation {
        sender: builder.sender,
        nonce: builder.nonce,
        initCode: Bytes::from(builder.init_code.clone()),
        callData: Bytes::from(builder.call_data.clone()),
        accountGasLimits: account_gas_limits,
        preVerificationGas: builder.pre_verification_gas,
        gasFees: gas_fees,
        paymasterAndData: Bytes::from(builder.paymaster_and_data.clone()),
        signature: Bytes::default(),
    }
}

/// Get the ERC-4337 EntryPoint address for a given chain
pub fn get_entry_point_address(chain_id: u64) -> Option<EthAddress> {
    match chain_id {
        // v0.8.0 EntryPoint is deployed at this address on Base and other chains
        8453 => {
            // Base - use v0.8 EntryPoint
            EthAddress::from_str("0x4337084D9E255Ff0702461CF8895CE9E3b5Ff108").ok()
        }
        // v0.6.0 EntryPoint for other chains (keeping for compatibility)
        1 | 10 | 137 | 42161 => {
            EthAddress::from_str("0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789").ok()
        }
        // Sepolia testnet
        11155111 => EthAddress::from_str("0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789").ok(),
        _ => None,
    }
}

/// Known paymaster addresses by chain
pub fn get_known_paymaster(chain_id: u64) -> Option<EthAddress> {
    match chain_id {
        8453 => {
            // Base
            // Circle's USDC paymaster on Base
            EthAddress::from_str("0x0578cFB241215b77442a541325d6A4E6dFE700Ec").ok()
        }
        _ => None,
    }
}

/// Structure for EIP-2612 permit data
#[derive(Debug, Clone)]
pub struct PermitData {
    pub owner: EthAddress,
    pub spender: EthAddress,
    pub value: U256,
    pub nonce: U256,
    pub deadline: U256,
}

/// Generate EIP-2612 permit signature for USDC
pub fn generate_eip2612_permit_signature<S: Signer>(
    permit_data: &PermitData,
    token_address: EthAddress,
    chain_id: u64,
    signer: &S,
) -> Result<Vec<u8>, WalletError> {
    use sha3::{Digest, Keccak256};

    // EIP-712 Domain Separator
    // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")
    let domain_type_hash = Keccak256::digest(
        b"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)",
    );

    // USDC uses "USD Coin" and version "2"
    let name_hash = Keccak256::digest(b"USD Coin");
    let version_hash = Keccak256::digest(b"2");

    // Build domain separator
    let mut domain_data = Vec::new();
    domain_data.extend_from_slice(&domain_type_hash);
    domain_data.extend_from_slice(&name_hash);
    domain_data.extend_from_slice(&version_hash);
    domain_data.extend_from_slice(&U256::from(chain_id).to_be_bytes::<32>());
    domain_data.extend_from_slice(token_address.as_slice());
    let domain_separator = Keccak256::digest(&domain_data);

    // Permit type hash
    // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
    let permit_type_hash = Keccak256::digest(
        b"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)",
    );

    // Build permit struct hash
    let mut permit_data_encoded = Vec::new();
    permit_data_encoded.extend_from_slice(&permit_type_hash);
    permit_data_encoded.extend_from_slice(permit_data.owner.as_slice());
    permit_data_encoded.extend_from_slice(permit_data.spender.as_slice());
    permit_data_encoded.extend_from_slice(&permit_data.value.to_be_bytes::<32>());
    permit_data_encoded.extend_from_slice(&permit_data.nonce.to_be_bytes::<32>());
    permit_data_encoded.extend_from_slice(&permit_data.deadline.to_be_bytes::<32>());
    let permit_struct_hash = Keccak256::digest(&permit_data_encoded);

    // Build final message hash for EIP-712
    let mut message = Vec::new();
    message.push(0x19);
    message.push(0x01);
    message.extend_from_slice(&domain_separator);
    message.extend_from_slice(&permit_struct_hash);
    let message_hash = Keccak256::digest(&message);

    // Sign the hash (raw signature without prefix)
    // Use sign_hash for EIP-712, not sign_message which adds prefix
    let signature = signer.sign_hash(&message_hash)?;

    Ok(signature)
}

/// Get the current permit nonce for an address from USDC contract
pub fn get_usdc_permit_nonce(
    token_address: &str,
    owner: EthAddress,
    provider: &Provider,
) -> Result<U256, WalletError> {
    // USDC has a nonces(address) function
    // Function selector: 0x7ecebe00
    let mut call_data = Vec::new();
    call_data.extend_from_slice(&hex::decode("7ecebe00").unwrap());
    call_data.extend_from_slice(&[0u8; 12]); // Pad address to 32 bytes
    call_data.extend_from_slice(owner.as_slice());

    let token = resolve_name(token_address, provider.chain_id)?;

    // Create a transaction request for the call
    let tx = TransactionRequest {
        to: Some(TxKind::Call(token)),
        input: call_data.into(),
        ..Default::default()
    };

    // Make the call
    let result = provider.call(tx, None)?;

    // Parse the result as U256
    if result.len() >= 32 {
        Ok(U256::from_be_slice(&result[..32]))
    } else {
        Err(WalletError::TransactionError(
            "Invalid nonce response".to_string(),
        ))
    }
}

/// Encode paymaster data for USDC payment with EIP-2612 permit signature
/// DEPRECATED - We don't use permit signatures anymore, only simple format
/*
pub fn encode_usdc_paymaster_data_with_signer<S: Signer>(
    paymaster: EthAddress,
    token_address: EthAddress,
    max_cost: U256,
    tba_address: EthAddress,
    signer: &S,
    provider: &Provider,
) -> Result<Vec<u8>, WalletError> {
    // Start with paymaster address (20 bytes)
    let mut data = Vec::new();
    data.extend_from_slice(paymaster.as_slice());

    // Add paymaster-specific data for Circle's TokenPaymaster v0.8
    // Format: encodePacked([uint8, address, uint256, bytes])
    // - uint8: mode (0 for permit mode)
    // - address: USDC token address
    // - uint256: permit amount
    // - bytes: permit signature

    // Mode byte (0 for permit mode)
    data.push(0u8);

    // Token address (USDC)
    data.extend_from_slice(token_address.as_slice());

    // Permit amount - use max_cost which should cover gas
    data.extend_from_slice(&max_cost.to_be_bytes::<32>());

    // Get current nonce for the TBA from USDC contract
    let nonce = get_usdc_permit_nonce(&token_address.to_string(), tba_address, provider)?;

    // Generate permit data
    let deadline = U256::from(u64::MAX); // Max deadline
    let permit_data = PermitData {
        owner: tba_address,
        spender: paymaster,
        value: max_cost,
        nonce,
        deadline,
    };

    // Generate the actual permit signature
    let chain_id = provider.chain_id;
    let permit_signature =
        generate_eip2612_permit_signature(&permit_data, token_address, chain_id, signer)?;

    // Add the real permit signature
    data.extend_from_slice(&permit_signature);

    Ok(data)
}
*/

/// Encode paymaster data for USDC payment (keeping old function for compatibility)
/// This version uses a dummy signature and will fail with AA33
pub fn encode_usdc_paymaster_data(
    paymaster: EthAddress,
    _token_address: EthAddress,
    _max_cost: U256,
) -> Vec<u8> {
    // Use the new Circle format with default gas limits
    encode_circle_paymaster_data(paymaster, 500_000, 300_000)
}

/// Encode paymaster data for Circle's USDC paymaster
/// Format: abi.encode(address paymaster, uint256 verificationGasLimit, uint256 callGasLimit)
/// Returns the complete ABI encoding that the paymaster expects to receive
pub fn encode_circle_paymaster_data(
    paymaster: EthAddress,
    verification_gas_limit: u128,
    call_gas_limit: u128,
) -> Vec<u8> {
    let mut data = Vec::new();

    // ABI encoding includes the paymaster address as the first parameter
    // This matches the developer's example:
    // encode(["address", "uint256", "uint256"], ['0x0578cFB241215b77442a541325d6A4E6dFE700Ec', 500000, 300000])

    // First parameter: paymaster address as uint256 (padded to 32 bytes)
    let mut padded_address = vec![0u8; 12]; // 12 zero bytes for padding
    padded_address.extend_from_slice(paymaster.as_slice()); // 20 bytes of address
    data.extend_from_slice(&padded_address);

    // Second parameter: verification gas limit as uint256 (32 bytes)
    let verification_gas_u256 = U256::from(verification_gas_limit);
    data.extend_from_slice(&verification_gas_u256.to_be_bytes::<32>());

    // Third parameter: call gas limit as uint256 (32 bytes)
    let call_gas_u256 = U256::from(call_gas_limit);
    data.extend_from_slice(&call_gas_u256.to_be_bytes::<32>());

    // Total: 96 bytes (32 + 32 + 32)
    // This is the complete ABI encoding the paymaster expects
    data
}

/// Creates the ABI-encoded calldata for an ERC20 `permit` call.
/// This is used when the TBA needs to call permit on-chain (since TBAs can't sign off-chain)
///
/// # Arguments
/// * `owner` - The address that owns the tokens (the TBA in this case)
/// * `spender` - The address to grant allowance to (e.g., the paymaster)
/// * `value` - The amount of tokens to approve
/// * `deadline` - The deadline timestamp for the permit
///
/// # Returns
/// A `Vec<u8>` containing the ABI-encoded calldata for the permit function
pub fn create_erc20_permit_calldata(
    owner: EthAddress,
    spender: EthAddress,
    value: U256,
    deadline: U256,
) -> Vec<u8> {
    // For on-chain permit calls by the TBA, we don't need nonce, v, r, s
    // The TBA will call permit() directly as the owner
    // This creates calldata for: permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
    // But for TBA on-chain calls, v=0, r=0, s=0 works because the TBA IS the owner

    use alloy_sol_types::SolCall;

    // Define the permit function call
    // Note: Using the standard ERC20Permit interface
    sol! {
        function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s);
    }

    let call = permitCall {
        owner,
        spender,
        value,
        deadline,
        v: 0, // Dummy values for on-chain call
        r: B256::ZERO,
        s: B256::ZERO,
    };

    call.abi_encode()
}

/// Creates a multicall calldata that combines permit + another operation
/// This is useful for TBAs to approve and use tokens in a single transaction
pub fn create_multicall_permit_and_execute(
    _token_address: EthAddress,
    permit_spender: EthAddress,
    permit_amount: U256,
    permit_deadline: U256,
    _execute_target: EthAddress,
    _execute_calldata: Vec<u8>,
    _execute_value: U256,
) -> Vec<u8> {
    // Create permit calldata
    let permit_calldata = create_erc20_permit_calldata(
        EthAddress::ZERO, // Will be replaced by TBA address when executed
        permit_spender,
        permit_amount,
        permit_deadline,
    );

    // For TBA execute, we need to create two execute calls:
    // 1. Execute permit on token contract
    // 2. Execute the actual operation

    // This would need to be wrapped in a multicall or batch execute
    // The exact implementation depends on the TBA's interface

    // For now, return just the permit calldata
    // In practice, this would be combined with the execute calldata
    permit_calldata
}

// Encode paymaster data for USDC payment with on-chain permit (for TBAs)
// This version doesn't include a permit signature since TBAs will call permit on-chain
// DEPRECATED - We only use the simple Circle format now
/*
pub fn encode_usdc_paymaster_data_for_tba(
    paymaster: EthAddress,
    token_address: EthAddress,
    max_cost: U256,
) -> Vec<u8> {
    // Start with paymaster address (20 bytes)
    let mut data = Vec::new();
    data.extend_from_slice(paymaster.as_slice());

    // Add paymaster-specific data for Circle's TokenPaymaster v0.8
    // For TBAs, we might need a different mode or the paymaster needs to support on-chain permits

    // Mode byte (1 for on-chain approval mode, if supported)
    // Note: This depends on Circle's paymaster implementation
    // Mode 0 = permit signature mode (for EOAs)
    // Mode 1 = assume pre-existing approval (for smart contracts)
    data.push(1u8);

    // Token address (USDC)
    data.extend_from_slice(token_address.as_slice());

    // Max cost amount
    data.extend_from_slice(&max_cost.to_be_bytes::<32>());

    // No signature needed for on-chain approval mode

    data
}
*/