cow-bridging 0.3.0

Cross-chain bridge aggregator for the CoW Protocol SDK (Across, Bungee).
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
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
//! [`BridgingSdk`] — multi-provider cross-chain bridge aggregator.

use cow_errors::CowError;

use crate::swap_quoter::SwapQuoter;

// ── Bridging constants ──────────────────────────────────────────────────────

/// Bungee bridge backend API path segment.
pub const BUNGEE_API_PATH: &str = "/api/v1/bungee";

/// Bungee bridge manual API path segment.
pub const BUNGEE_MANUAL_API_PATH: &str = "/api/v1/bungee-manual";

/// Bungee (Socket) public backend base URL.
pub const BUNGEE_BASE_URL: &str = "https://public-backend.bungee.exchange";

/// Bungee API URL (base URL + API path).
pub const BUNGEE_API_URL: &str = "https://public-backend.bungee.exchange/api/v1/bungee";

/// Bungee manual API URL (base URL + manual API path).
pub const BUNGEE_MANUAL_API_URL: &str =
    "https://public-backend.bungee.exchange/api/v1/bungee-manual";

/// Bungee events API URL for tracking bridge transactions.
pub const BUNGEE_EVENTS_API_URL: &str = "https://microservices.socket.tech/loki";

/// Across Protocol bridge API base URL.
pub const ACROSS_API_URL: &str = "https://app.across.to/api";

/// Default bridge slippage tolerance in basis points (0.5 %).
pub const DEFAULT_BRIDGE_SLIPPAGE_BPS: u32 = 50;

/// Default gas cost for hook estimation (240 000 gas).
pub const DEFAULT_GAS_COST_FOR_HOOK_ESTIMATION: u64 = 240_000;

/// Default extra gas for hook estimation (350 000 gas).
pub const DEFAULT_EXTRA_GAS_FOR_HOOK_ESTIMATION: u64 = 350_000;

/// Default extra gas cost when creating a proxy (400 000 gas).
pub const DEFAULT_EXTRA_GAS_PROXY_CREATION: u64 = 400_000;

/// URL prefix used to identify bridge hook dapps.
pub const HOOK_DAPP_BRIDGE_PROVIDER_PREFIX: &str = "cow-sdk://bridging/providers";

/// Bungee bridge hook dapp identifier.
pub const BUNGEE_HOOK_DAPP_ID: &str = "cow-sdk://bridging/providers/bungee";

/// Across bridge hook dapp identifier.
pub const ACROSS_HOOK_DAPP_ID: &str = "cow-sdk://bridging/providers/across";

/// Near Intents bridge hook dapp identifier.
pub const NEAR_INTENTS_HOOK_DAPP_ID: &str = "cow-sdk://bridging/providers/near-intents";

/// Bungee API fallback timeout in milliseconds (5 minutes).
pub const BUNGEE_API_FALLBACK_TIMEOUT: u64 = 300_000;

use super::{
    bungee::BungeeProvider,
    provider::BridgeProvider,
    types::{BridgeError, QuoteBridgeRequest, QuoteBridgeResponse},
};

/// High-level cross-chain bridge aggregator.
///
/// Holds a list of [`BridgeProvider`] implementations and queries them
/// concurrently when fetching quotes.
///
/// # Example
///
/// ```rust,no_run
/// use cow_bridging::BridgingSdk;
///
/// let sdk = BridgingSdk::new().with_bungee("my-api-key");
/// assert_eq!(sdk.provider_count(), 1);
/// ```
#[derive(Default)]
pub struct BridgingSdk {
    providers: Vec<Box<dyn BridgeProvider>>,
}

impl std::fmt::Debug for BridgingSdk {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BridgingSdk").field("provider_count", &self.providers.len()).finish()
    }
}

impl BridgingSdk {
    /// Create an empty [`BridgingSdk`] with no providers.
    ///
    /// # Returns
    ///
    /// A new [`BridgingSdk`] instance with an empty provider list.
    ///
    /// # Example
    ///
    /// ```rust
    /// use cow_bridging::BridgingSdk;
    ///
    /// let sdk = BridgingSdk::new();
    /// assert_eq!(sdk.provider_count(), 0);
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self { providers: vec![] }
    }

    /// Add the Bungee (Socket) bridge provider using the given API key.
    ///
    /// This is a builder-style method that consumes `self` and returns the
    /// modified instance, allowing chained calls.
    ///
    /// # Arguments
    ///
    /// * `api_key` — Bungee (Socket) API key used to authenticate requests.
    ///
    /// # Returns
    ///
    /// The [`BridgingSdk`] instance with the Bungee provider appended.
    #[must_use]
    pub fn with_bungee(mut self, api_key: impl Into<String>) -> Self {
        self.providers.push(Box::new(BungeeProvider::new(api_key)));
        self
    }

    /// Register any custom [`BridgeProvider`] implementation.
    ///
    /// # Arguments
    ///
    /// * `provider` — A type implementing [`BridgeProvider`] that will be boxed and stored
    ///   alongside any existing providers.
    pub fn add_provider(&mut self, provider: impl BridgeProvider + 'static) {
        self.providers.push(Box::new(provider));
    }

    /// Number of registered providers.
    ///
    /// # Returns
    ///
    /// The count of [`BridgeProvider`] instances currently registered with
    /// this SDK.
    #[must_use]
    pub fn provider_count(&self) -> usize {
        self.providers.len()
    }

    /// Query all registered providers concurrently and return the best quote.
    ///
    /// "Best" is defined as the highest [`net_buy_amount`](QuoteBridgeResponse::net_buy_amount).
    ///
    /// # Errors
    ///
    /// - [`BridgeError::NoProviders`] if no providers support the requested route.
    /// - [`BridgeError::NoQuote`] if all providers fail or return no quote.
    pub async fn get_best_quote(
        &self,
        req: &QuoteBridgeRequest,
    ) -> Result<QuoteBridgeResponse, BridgeError> {
        let eligible: Vec<&dyn BridgeProvider> = self
            .providers
            .iter()
            .filter(|p| p.supports_route(req.sell_chain_id, req.buy_chain_id))
            .map(|p| p.as_ref())
            .collect();

        if eligible.is_empty() {
            return Err(BridgeError::NoProviders);
        }

        let futures: Vec<_> = eligible.iter().map(|p| p.get_quote(req)).collect();
        let results = futures::future::join_all(futures).await;

        let best = results
            .into_iter()
            .filter_map(|r| r.ok())
            .max_by_key(QuoteBridgeResponse::net_buy_amount);

        best.ok_or(BridgeError::NoQuote)
    }

    /// Query all registered providers concurrently and return all results.
    ///
    /// Providers that do not support the route are skipped.
    /// Both successful quotes and errors are included in the output.
    ///
    /// # Errors
    ///
    /// Individual provider failures are returned as [`CowError`] entries
    /// in the result vector rather than short-circuiting the entire call.
    pub async fn get_all_quotes(
        &self,
        req: &QuoteBridgeRequest,
    ) -> Vec<Result<QuoteBridgeResponse, CowError>> {
        let eligible: Vec<&dyn BridgeProvider> = self
            .providers
            .iter()
            .filter(|p| p.supports_route(req.sell_chain_id, req.buy_chain_id))
            .map(|p| p.as_ref())
            .collect();

        let futures: Vec<_> = eligible.iter().map(|p| p.get_quote(req)).collect();
        futures::future::join_all(futures).await
    }
}

// ── Type guard result types ──────────────────────────────────────────────────

use super::types::BridgeQuoteResults;

/// A bridge quote paired with a callback-style post function.
///
/// In the `TypeScript` SDK this includes a closure `postSwapOrderFromQuote`.
/// In Rust, the struct holds the data needed to construct the order; the
/// caller orchestrates posting via the order-book API.
#[derive(Debug, Clone)]
pub struct BridgeQuoteAndPost {
    /// Swap quote results (amounts, costs, app-data).
    pub swap: QuoteBridgeResponse,
    /// Bridge quote results.
    pub bridge: BridgeQuoteResults,
}

/// A simple quote-and-post result for same-chain swaps.
///
/// In the `TypeScript` SDK this is `QuoteAndPost` from the trading package.
/// Here it wraps the quote response; order posting is handled separately.
#[derive(Debug, Clone)]
pub struct QuoteAndPost {
    /// The quote response.
    pub quote: QuoteBridgeResponse,
}

/// Union of same-chain and cross-chain quote results.
///
/// Mirrors the `TypeScript` `CrossChainQuoteAndPost = QuoteAndPost | BridgeQuoteAndPost`.
#[derive(Debug, Clone)]
pub enum CrossChainQuoteAndPost {
    /// Same-chain swap (no bridging needed).
    SameChain(Box<QuoteAndPost>),
    /// Cross-chain swap with bridging.
    CrossChain(Box<BridgeQuoteAndPost>),
}

// ── Type guard functions ─────────────────────────────────────────────────────

/// Returns `true` if the result is a [`BridgeQuoteAndPost`] (cross-chain with
/// both swap and bridge data).
///
/// Mirrors the `TypeScript` `isBridgeQuoteAndPost` type guard.
#[must_use]
pub const fn is_bridge_quote_and_post(result: &CrossChainQuoteAndPost) -> bool {
    matches!(result, CrossChainQuoteAndPost::CrossChain(_))
}

/// Returns `true` if the result is a [`QuoteAndPost`] (same-chain swap).
///
/// Mirrors the `TypeScript` `isQuoteAndPost` type guard.
#[must_use]
pub const fn is_quote_and_post(result: &CrossChainQuoteAndPost) -> bool {
    matches!(result, CrossChainQuoteAndPost::SameChain(_))
}

/// Assert that the result is a [`BridgeQuoteAndPost`], returning a reference
/// to it or an error.
///
/// # Errors
///
/// Returns [`BridgeError::QuoteError`] if the result is not a cross-chain quote.
pub fn assert_is_bridge_quote_and_post(
    result: &CrossChainQuoteAndPost,
) -> Result<&BridgeQuoteAndPost, BridgeError> {
    match result {
        CrossChainQuoteAndPost::CrossChain(bqp) => Ok(bqp.as_ref()),
        CrossChainQuoteAndPost::SameChain(_) => {
            Err(BridgeError::QuoteError("expected BridgeQuoteAndPost, got QuoteAndPost".to_owned()))
        }
    }
}

/// Assert that the result is a [`QuoteAndPost`], returning a reference to it
/// or an error.
///
/// # Errors
///
/// Returns [`BridgeError::QuoteError`] if the result is not a same-chain quote.
pub fn assert_is_quote_and_post(
    result: &CrossChainQuoteAndPost,
) -> Result<&QuoteAndPost, BridgeError> {
    match result {
        CrossChainQuoteAndPost::SameChain(qp) => Ok(qp.as_ref()),
        CrossChainQuoteAndPost::CrossChain(_) => {
            Err(BridgeError::QuoteError("expected QuoteAndPost, got BridgeQuoteAndPost".to_owned()))
        }
    }
}

// ── Cross-chain order flow ───────────────────────────────────────────────────

use crate::{
    across::{EvmLogEntry, get_deposit_params},
    types::{BridgeHook, BridgeQuoteResult, BridgeStatus, BridgeStatusResult, CrossChainOrder},
};
use alloy_primitives::Address;

/// Parameters for [`get_cross_chain_order`].
#[derive(Debug)]
pub struct GetCrossChainOrderParams<'a> {
    /// Chain ID where the order was settled.
    pub chain_id: u64,
    /// The `CoW` Protocol order UID.
    pub order_id: String,
    /// Full app-data JSON of the order.
    pub full_app_data: Option<String>,
    /// Transaction hash of the settlement.
    pub trade_tx_hash: String,
    /// Raw log entries from the settlement transaction.
    pub logs: &'a [EvmLogEntry],
    /// Optional settlement contract address override.
    pub settlement_override: Option<Address>,
}

/// Build a [`CrossChainOrder`] from settlement transaction data.
///
/// Parses Across deposit events and `CoW` Trade events from the logs, matches
/// them by index, and constructs the bridging deposit parameters.
///
/// This is a simplified version of the `TypeScript` `getCrossChainOrder` that
/// does not call the `OrderBookApi` (the caller must provide the order data
/// and logs). For full orchestration, use the `OrderBookApi` directly.
///
/// # Errors
///
/// Returns [`BridgeError::QuoteError`] if the deposit parameters cannot be
/// extracted from the logs.
pub fn get_cross_chain_order(
    params: &GetCrossChainOrderParams<'_>,
) -> Result<CrossChainOrder, BridgeError> {
    let bridging_params = get_deposit_params(
        params.chain_id,
        &params.order_id,
        params.logs,
        params.settlement_override,
    )
    .ok_or_else(|| {
        BridgeError::QuoteError(format!(
            "bridging params cannot be derived from transaction: {}",
            params.trade_tx_hash
        ))
    })?;

    Ok(CrossChainOrder {
        chain_id: params.chain_id,
        status_result: BridgeStatusResult::new(BridgeStatus::Unknown),
        bridging_params,
        trade_tx_hash: params.trade_tx_hash.clone(),
        explorer_url: None,
    })
}

/// Context passed to [`get_bridge_signed_hook`].
///
/// Mirrors the `HookBridgeResultContext` struct of the `TypeScript`
/// SDK: the fields carry the pieces of state a [`crate::provider::HookBridgeProvider`]
/// needs to both request the hook and derive its nonce.
#[derive(Debug)]
pub struct GetBridgeSignedHookContext<'a> {
    /// Signer that will EIP-712-sign the hook bundle through `cow-shed`.
    pub signer: &'a alloy_signer_local::PrivateKeySigner,
    /// Gas-limit estimated for the bridge post-hook. Passed verbatim to
    /// [`crate::provider::HookBridgeProvider::get_signed_hook`].
    pub hook_gas_limit: u64,
    /// Source chain of the bridge — picks the right cow-shed factory /
    /// domain separator.
    pub chain_id: cow_chains::SupportedChainId,
    /// Hook validity deadline (UNIX seconds). Usually equals
    /// `order_to_sign.valid_to` from the enclosing swap quote.
    pub deadline: u64,
}

/// Output of [`get_bridge_signed_hook`].
///
/// Bundles the signed hook together with the raw bridge call and the
/// provider's original [`QuoteBridgeResponse`] so the caller can wire
/// the three into a final order.
#[derive(Debug, Clone)]
pub struct GetBridgeSignedHookOutput {
    /// Signed bridge hook ready to be attached as a post-interaction
    /// on the enclosing `CoW` order's app-data.
    pub hook: BridgeHook,
    /// Raw EVM call that the cow-shed proxy will execute.
    pub unsigned_bridge_call: cow_chains::EvmCall,
    /// The bridging quote produced upstream of the signing step.
    pub bridging_quote: QuoteBridgeResponse,
}

/// Produce a signed bridge hook for a [`crate::provider::HookBridgeProvider`].
///
/// Mirrors `getBridgeSignedHook` from
/// `packages/bridging/src/BridgingSdk/getBridgeSignedHook.ts`. The
/// function:
///
/// 1. Asks the provider for a bridge quote ([`crate::provider::BridgeProvider::get_quote`]).
/// 2. Asks the provider for the unsigned EVM call that will initiate the bridge
///    ([`crate::provider::HookBridgeProvider::get_unsigned_bridge_call`]).
/// 3. Derives a deterministic hook nonce from the call data and the order's `valid_to` deadline —
///    `keccak256(abi.encodePacked(data, uint256 deadline))`. This ties the signed hook to a
///    specific combination of bridge call and order deadline.
/// 4. Delegates to [`crate::provider::HookBridgeProvider::get_signed_hook`] to produce the EIP-712
///    signed hook via `cow-shed`.
///
/// # Errors
///
/// Returns [`BridgeError::TxBuildError`] if any of the provider calls
/// fail, wrapping the underlying [`CowError`].
pub async fn get_bridge_signed_hook<P: crate::provider::HookBridgeProvider + ?Sized>(
    hook_provider: &P,
    bridge_request: &QuoteBridgeRequest,
    context: GetBridgeSignedHookContext<'_>,
) -> Result<GetBridgeSignedHookOutput, BridgeError> {
    // 1. Bridge quote from the provider.
    let bridging_quote = hook_provider
        .get_quote(bridge_request)
        .await
        .map_err(|e| BridgeError::TxBuildError(e.to_string()))?;

    // 2. Raw EVM call.
    let unsigned_bridge_call = hook_provider
        .get_unsigned_bridge_call(bridge_request, &bridging_quote)
        .await
        .map_err(|e| BridgeError::TxBuildError(e.to_string()))?;

    // 3. Derive the hook nonce.
    let nonce_hex = derive_hook_nonce(&unsigned_bridge_call.data, context.deadline);

    // 4. Sign the hook.
    let hook = hook_provider
        .get_signed_hook(
            context.chain_id,
            &unsigned_bridge_call,
            &nonce_hex,
            context.deadline,
            context.hook_gas_limit,
            context.signer,
        )
        .await
        .map_err(|e| BridgeError::TxBuildError(e.to_string()))?;

    Ok(GetBridgeSignedHookOutput { hook, unsigned_bridge_call, bridging_quote })
}

/// Derive the bridge-hook nonce as the `TypeScript` SDK does:
///
/// ```text
/// nonce = keccak256( abi.encodePacked(bytes calldata, uint256 deadline) )
/// ```
///
/// `abi.encodePacked` on `(bytes, uint256)` concatenates the raw bytes
/// of `data` with the 32-byte big-endian `deadline` — no 32-byte offset
/// prefix like the non-packed encoding would introduce.
///
/// The returned string is the `0x`-prefixed lowercase hex of the hash,
/// matching the TS `solidityKeccak256` output.
fn derive_hook_nonce(data: &[u8], deadline: u64) -> String {
    let deadline_be: [u8; 32] = alloy_primitives::U256::from(deadline).to_be_bytes();
    let mut packed = Vec::with_capacity(data.len() + 32);
    packed.extend_from_slice(data);
    packed.extend_from_slice(&deadline_be);
    let hash = alloy_primitives::keccak256(&packed);
    format!("{hash:#x}")
}

/// Parameters for [`get_quote_with_bridge`].
#[derive(Clone)]
pub struct GetQuoteWithBridgeParams {
    /// The swap-and-bridge request.
    pub swap_and_bridge_request: QuoteBridgeRequest,
    /// Slippage tolerance in basis points for the swap leg.
    pub slippage_bps: u32,
    /// Optional caller-supplied app-data metadata to merge into the
    /// auto-generated `hooks` / `bridging` metadata.
    ///
    /// Corresponds to `advanced_settings.app_data.metadata` in the
    /// `TypeScript` SDK — the load-bearing bit of the cow-sdk#852 fix.
    pub advanced_settings_metadata: Option<serde_json::Value>,
    /// Optional quote-time signer. When provided on the hook branch,
    /// [`get_quote_with_hook_bridge`] produces a **real** EIP-712 signed
    /// hook via [`get_bridge_signed_hook`] instead of the placeholder
    /// mock used for cost estimation. The receiver-account branch
    /// ignores this field.
    ///
    /// Corresponds to the `quoteSigner` parameter of the TS SDK's
    /// `getQuoteWithHookBridge`. Keep it `None` when the final signing
    /// wallet is not available yet (e.g. hardware wallet flows).
    pub quote_signer: Option<std::sync::Arc<alloy_signer_local::PrivateKeySigner>>,
    /// Hook deadline (UNIX seconds). Defaults to `u32::MAX` when `None`.
    ///
    /// Threaded into [`get_bridge_signed_hook`] so the hook nonce binds
    /// to the same validity as the enclosing order.
    pub hook_deadline: Option<u64>,
}

impl std::fmt::Debug for GetQuoteWithBridgeParams {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GetQuoteWithBridgeParams")
            .field("swap_and_bridge_request", &self.swap_and_bridge_request)
            .field("slippage_bps", &self.slippage_bps)
            .field("advanced_settings_metadata", &self.advanced_settings_metadata)
            .field("quote_signer", &self.quote_signer.is_some())
            .field("hook_deadline", &self.hook_deadline)
            .finish()
    }
}

/// Get a quote that includes bridging (cross-chain).
///
/// Dispatches to the hook-bridge or receiver-account-bridge branch based on
/// the provider's runtime type, mirroring the `TypeScript`
/// `getQuoteWithBridge` in
/// `packages/bridging/src/BridgingSdk/getQuoteWithBridge.ts`.
///
/// # Flow
///
/// 1. Reject non-sell orders (cross-chain only supports `OrderKind::Sell`).
/// 2. If the provider implements [`crate::provider::HookBridgeProvider`], delegate to
///    [`get_quote_with_hook_bridge`].
/// 3. Otherwise, if the provider implements [`crate::provider::ReceiverAccountBridgeProvider`],
///    delegate to [`get_quote_with_receiver_account_bridge`].
/// 4. Fall through to an error if the provider implements neither.
///
/// # Errors
///
/// * [`BridgeError::OnlySellOrderSupported`] when `kind != Sell`.
/// * [`BridgeError::TxBuildError`] when the provider implements neither sub-trait.
/// * Any error returned by the delegated branch.
pub async fn get_quote_with_bridge(
    params: &GetQuoteWithBridgeParams,
    provider: &dyn BridgeProvider,
    quoter: &dyn SwapQuoter,
) -> Result<BridgeQuoteAndPost, BridgeError> {
    if params.swap_and_bridge_request.kind != cow_types::OrderKind::Sell {
        return Err(BridgeError::OnlySellOrderSupported);
    }

    if let Some(hook_provider) = provider.as_hook_bridge_provider() {
        return get_quote_with_hook_bridge(hook_provider, params, quoter).await;
    }

    if let Some(receiver_provider) = provider.as_receiver_account_bridge_provider() {
        return get_quote_with_receiver_account_bridge(receiver_provider, params, quoter).await;
    }

    Err(BridgeError::TxBuildError(format!(
        "provider {name} implements neither HookBridgeProvider nor ReceiverAccountBridgeProvider",
        name = provider.info().name,
    )))
}

/// Get a quote without bridging (same-chain swap).
///
/// Delegates to the [`SwapQuoter`] — equivalent to calling `TradingSdk::get_quote_only`
/// with the bridge request fields mapped to `TradeParameters`.
///
/// Mirrors `getQuoteWithoutBridge` in the `TypeScript` SDK.
///
/// # Errors
///
/// Returns [`BridgeError::TxBuildError`] when the quoter fails.
pub async fn get_quote_without_bridge(
    request: &QuoteBridgeRequest,
    quoter: &dyn SwapQuoter,
) -> Result<QuoteAndPost, BridgeError> {
    let params = crate::swap_quoter::SwapQuoteParams {
        owner: request.account,
        chain_id: request.sell_chain_id,
        sell_token: request.sell_token,
        sell_token_decimals: request.sell_token_decimals,
        buy_token: request.buy_token,
        buy_token_decimals: request.buy_token_decimals,
        amount: request.sell_amount,
        kind: request.kind,
        slippage_bps: request.slippage_bps,
        app_data_json: None,
    };
    let outcome =
        quoter.quote_swap(params).await.map_err(|e| BridgeError::TxBuildError(e.to_string()))?;

    Ok(QuoteAndPost {
        quote: QuoteBridgeResponse {
            provider: "same-chain".to_owned(),
            sell_amount: outcome.sell_amount,
            buy_amount: outcome.buy_amount_after_slippage,
            fee_amount: outcome.fee_amount,
            estimated_secs: 0,
            bridge_hook: None,
        },
    })
}

/// Get a swap quote for an intermediate hop, as a stand-alone helper.
///
/// Builds swap parameters from the bridge request (using `buy_token` as
/// the intermediate token destination) and asks the [`SwapQuoter`] to
/// price it. Mirrors `getSwapQuote` in the `TypeScript` SDK.
///
/// # Errors
///
/// Returns [`BridgeError::TxBuildError`] when the quoter fails.
pub async fn get_swap_quote(
    request: &QuoteBridgeRequest,
    quoter: &dyn SwapQuoter,
) -> Result<QuoteBridgeResponse, BridgeError> {
    let params = crate::swap_quoter::SwapQuoteParams {
        owner: request.account,
        chain_id: request.sell_chain_id,
        sell_token: request.sell_token,
        sell_token_decimals: request.sell_token_decimals,
        buy_token: request.buy_token,
        buy_token_decimals: request.buy_token_decimals,
        amount: request.sell_amount,
        kind: request.kind,
        slippage_bps: request.slippage_bps,
        app_data_json: None,
    };
    let outcome =
        quoter.quote_swap(params).await.map_err(|e| BridgeError::TxBuildError(e.to_string()))?;

    Ok(QuoteBridgeResponse {
        provider: "swap".to_owned(),
        sell_amount: outcome.sell_amount,
        buy_amount: outcome.buy_amount_after_slippage,
        fee_amount: outcome.fee_amount,
        estimated_secs: 0,
        bridge_hook: None,
    })
}

/// Build an order from a completed bridge quote.
///
/// In the `TypeScript` SDK, this is `createPostSwapOrderFromQuote` which returns
/// a closure that re-fetches the bridge quote with the real signer, then posts
/// via `postSwapOrderFromQuoteTrading`.
///
/// # Errors
///
/// Always returns [`BridgeError::TxBuildError`] until the trading/signing SDKs
/// are ported.
pub async fn create_post_swap_order_from_quote(
    _quote: &BridgeQuoteAndPost,
) -> Result<(), BridgeError> {
    // TODO: Requires TradingSdk + OrderBookApi + signer.
    // Flow:
    //   1. Optionally re-fetch bridge quote with real signer
    //   2. Update trade parameters (receiver, appData)
    //   3. Call postSwapOrderFromQuoteTrading
    Err(BridgeError::TxBuildError(
        "create_post_swap_order_from_quote requires TradingSdk + OrderBookApi (not yet ported)"
            .to_owned(),
    ))
}

/// Quote the intermediate swap step of a cross-chain bridge flow.
///
/// Given a bridge request and a [`BridgeProvider`], this:
/// 1. Asks the provider for candidate intermediate tokens
///    ([`BridgeProvider::get_intermediate_tokens`]).
/// 2. Picks the best candidate via [`crate::utils::determine_intermediate_token`].
/// 3. Asks the [`SwapQuoter`] to price the swap from the sell token to the intermediate token.
/// 4. Merges any caller-supplied `app_data.metadata` with the auto-generated `hooks` / `bridging`
///    metadata — the cow-sdk#852 fix: caller-provided partner / UTM metadata must survive the
///    intermediate quote instead of being overwritten.
/// 5. Returns a [`QuoteBridgeResponse`] whose `buy_amount` is the swap's `afterSlippage.buyAmount`
///    — the amount handed off to the bridge.
///
/// # Arguments
///
/// * `request` — the top-level bridge quote request.
/// * `provider` — the [`BridgeProvider`] that will route the bridge step.
/// * `quoter` — a [`SwapQuoter`] that can price the intermediate swap (typically a wrapper around
///   `cow_trading::TradingSdk::get_quote_only`).
/// * `advanced_settings_metadata` — optional caller-supplied app-data metadata JSON. When `Some`,
///   its keys are merged with the auto-generated `hooks` / `bridging` entries (see cow-sdk#852).
///
/// # Errors
///
/// * [`BridgeError::NoIntermediateTokens`] if the provider returns an empty candidate list.
/// * [`BridgeError::TxBuildError`] if the swap quote fails, wrapping the underlying [`CowError`].
pub async fn get_intermediate_swap_result(
    request: &QuoteBridgeRequest,
    provider: &dyn crate::provider::BridgeProvider,
    quoter: &dyn SwapQuoter,
    advanced_settings_metadata: Option<&serde_json::Value>,
) -> Result<QuoteBridgeResponse, BridgeError> {
    use crate::utils::determine_intermediate_token;

    // 1. Ask the provider for candidates.
    let candidates = provider
        .get_intermediate_tokens(request)
        .await
        .map_err(|e| BridgeError::TxBuildError(e.to_string()))?;

    if candidates.is_empty() {
        return Err(BridgeError::NoIntermediateTokens);
    }

    // 2. Pick the best candidate.
    let candidate_addrs: Vec<alloy_primitives::Address> =
        candidates.iter().map(|t| t.address).collect();
    let intermediate = determine_intermediate_token(
        request.sell_chain_id,
        request.sell_token,
        &candidate_addrs,
        &foldhash::HashSet::default(),
        false,
    )?;
    let intermediate_info =
        candidates.iter().find(|t| t.address == intermediate).cloned().ok_or_else(|| {
            BridgeError::TxBuildError("intermediate token not in candidates".into())
        })?;

    // 3. Build the app-data JSON with caller metadata preserved (#852 fix).
    let app_data_json = build_intermediate_app_data_json(advanced_settings_metadata, provider);

    // 4. Quote the swap.
    let params = crate::swap_quoter::SwapQuoteParams {
        owner: request.account,
        chain_id: request.sell_chain_id,
        sell_token: request.sell_token,
        sell_token_decimals: request.sell_token_decimals,
        buy_token: intermediate_info.address,
        buy_token_decimals: intermediate_info.decimals,
        amount: request.sell_amount,
        kind: request.kind,
        slippage_bps: request.slippage_bps,
        app_data_json: Some(app_data_json),
    };
    let outcome =
        quoter.quote_swap(params).await.map_err(|e| BridgeError::TxBuildError(e.to_string()))?;

    // 5. Wrap the outcome in a QuoteBridgeResponse.
    Ok(QuoteBridgeResponse {
        provider: provider.info().name.clone(),
        sell_amount: outcome.sell_amount,
        buy_amount: outcome.buy_amount_after_slippage,
        fee_amount: outcome.fee_amount,
        estimated_secs: 0,
        bridge_hook: None,
    })
}

/// Build the `appData` JSON for the intermediate swap, preserving
/// caller-supplied metadata.
///
/// Implements the cow-sdk#852 fix: when `advanced_settings.app_data.metadata`
/// exists, its keys are spread into the final metadata object *before*
/// the auto-generated `hooks` and `bridging` entries. This matches the
/// `TypeScript` flow:
///
/// ```text
/// appData.metadata = {
///     ...advanced_settings?.app_data?.metadata,
///     hooks,
///     bridging: { providerId: provider.info.dappId },
/// }
/// ```
///
/// The return value is a stringified JSON document ready to be passed
/// through a [`SwapQuoter`].
fn build_intermediate_app_data_json(
    caller_metadata: Option<&serde_json::Value>,
    provider: &dyn crate::provider::BridgeProvider,
) -> String {
    let mut metadata = caller_metadata.and_then(|v| v.as_object().cloned()).unwrap_or_default();

    // Overwrite with auto-generated fields — they are the load-bearing
    // bits for the on-chain bridge flow.
    metadata.insert(
        "bridging".to_owned(),
        serde_json::json!({ "providerId": provider.info().dapp_id }),
    );
    // Hooks are populated by the orchestration layer in PR #7 once the
    // real post-hook is known; for now carry an empty hooks entry so
    // the shape mirrors the TS output.
    if !metadata.contains_key("hooks") {
        metadata.insert("hooks".to_owned(), serde_json::json!({ "post": [] }));
    }

    let doc = serde_json::json!({
        "version": "1.4.0",
        "appCode": "CoW Bridging",
        "metadata": metadata,
    });
    serde_json::to_string(&doc).unwrap_or_else(|_| "{}".to_owned())
}

// ── Timeout ─────────────────────────────────────────────────────────────────

/// Create a bridge request timeout future.
///
/// Returns a future that resolves to a [`BridgeError::Timeout`] after
/// `timeout_ms` milliseconds. This is the Rust equivalent of the `TypeScript`
/// `createBridgeRequestTimeoutPromise(timeoutMs, prefix)`.
///
/// # Example
///
/// ```rust,no_run
/// use cow_bridging::sdk::create_bridge_request_timeout;
///
/// # async fn example() {
/// let timeout = create_bridge_request_timeout(20_000, "Across");
/// // Use with tokio::select! or futures::select! to race against a real request
/// # }
/// ```
#[cfg(feature = "native")]
pub async fn create_bridge_request_timeout(timeout_ms: u64, prefix: &str) -> BridgeError {
    tokio::time::sleep(std::time::Duration::from_millis(timeout_ms)).await;
    BridgeError::ApiError(format!("{prefix} timeout after {timeout_ms}ms"))
}

// ── Strategy factory ────────────────────────────────────────────────────────

/// Strategy variant for quote retrieval.
///
/// Mirrors the `TypeScript` `createStrategies` factory which returns
/// `SingleQuoteStrategy`, `MultiQuoteStrategy`, and `BestQuoteStrategy`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuoteStrategy {
    /// Query a single provider (or fall back to a direct swap for same-chain).
    Single,
    /// Query all providers and return all results.
    Multi,
    /// Query all providers and return the best quote.
    Best,
}

impl QuoteStrategy {
    /// Return the strategy name.
    ///
    /// # Returns
    ///
    /// A static string label for this strategy variant:
    /// `"SingleQuoteStrategy"`, `"MultiQuoteStrategy"`, or `"BestQuoteStrategy"`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use cow_bridging::sdk::QuoteStrategy;
    ///
    /// assert_eq!(QuoteStrategy::Best.name(), "BestQuoteStrategy");
    /// ```
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Single => "SingleQuoteStrategy",
            Self::Multi => "MultiQuoteStrategy",
            Self::Best => "BestQuoteStrategy",
        }
    }
}

/// Create all available quote strategies.
///
/// Returns the three strategy variants (Single, Multi, Best). In the
/// `TypeScript` SDK each is a class instance backed by an optional
/// `intermediateTokensCache`; in Rust the strategies are simple enum
/// variants and caching is handled by the caller.
///
/// Mirrors `createStrategies(cache)` from `strategies/createStrategies.ts`.
#[must_use]
pub const fn create_strategies() -> [QuoteStrategy; 3] {
    [QuoteStrategy::Single, QuoteStrategy::Multi, QuoteStrategy::Best]
}

// ── Provider quote execution ────────────────────────────────────────────────

use super::types::MultiQuoteResult;

/// Default total timeout for multi-provider quotes (40 seconds).
pub const DEFAULT_TOTAL_TIMEOUT_MS: u64 = 40_000;

/// Default per-provider timeout (20 seconds).
pub const DEFAULT_PROVIDER_TIMEOUT_MS: u64 = 20_000;

/// Execute quotes across providers concurrently with a global timeout.
///
/// Spawns one future per provider, races them against a global timeout, and
/// returns whatever results completed. Providers that did not respond in time
/// get a timeout error in the results vector.
///
/// Mirrors `executeProviderQuotes` from `BridgingSdk/utils.ts`.
///
/// # Errors
///
/// Does not return an error itself — individual provider errors are captured
/// in the returned [`MultiQuoteResult`] entries.
#[cfg(feature = "native")]
pub async fn execute_provider_quotes(
    sdk: &BridgingSdk,
    request: &QuoteBridgeRequest,
    timeout_ms: u64,
) -> Vec<MultiQuoteResult> {
    use futures::future::join_all;

    let futs: Vec<_> = sdk
        .providers
        .iter()
        .map(|p| {
            let name = p.name().to_owned();
            async move {
                let result = p.get_quote(request).await;
                match result {
                    Ok(quote) => MultiQuoteResult {
                        provider_dapp_id: name,
                        quote: Some(crate::types::BridgeQuoteAmountsAndCosts {
                            before_fee: crate::types::BridgeAmounts {
                                sell_amount: quote.sell_amount,
                                buy_amount: quote.buy_amount,
                            },
                            after_fee: crate::types::BridgeAmounts {
                                sell_amount: quote.sell_amount,
                                buy_amount: quote.buy_amount.saturating_sub(quote.fee_amount),
                            },
                            after_slippage: crate::types::BridgeAmounts {
                                sell_amount: quote.sell_amount,
                                buy_amount: quote.buy_amount.saturating_sub(quote.fee_amount),
                            },
                            costs: crate::types::BridgeCosts {
                                bridging_fee: crate::types::BridgingFee {
                                    fee_bps: 0,
                                    amount_in_sell_currency: quote.fee_amount,
                                    amount_in_buy_currency: quote.fee_amount,
                                },
                            },
                            slippage_bps: request.slippage_bps,
                        }),
                        error: None,
                    },
                    Err(e) => MultiQuoteResult {
                        provider_dapp_id: name,
                        quote: None,
                        error: Some(e.to_string()),
                    },
                }
            }
        })
        .collect();

    // Race all futures against a global timeout
    let fetched_results =
        tokio::time::timeout(std::time::Duration::from_millis(timeout_ms), join_all(futs)).await;

    match fetched_results {
        Ok(results) => results,
        Err(_timeout) => {
            // Return timeout errors for all providers
            sdk.providers
                .iter()
                .map(|p| MultiQuoteResult {
                    provider_dapp_id: p.name().to_owned(),
                    quote: None,
                    error: Some(format!("Multi-quote timeout after {timeout_ms}ms")),
                })
                .collect()
        }
    }
}

/// Fetch a multi-quote from providers with timeout.
///
/// Executes quotes across the SDK's providers concurrently and returns all
/// results (including errors). Results are sorted by buy amount descending.
///
/// Mirrors `fetchMultiQuote` from `strategies/utils.ts` and the
/// `MultiQuoteStrategy.execute` method.
///
/// # Errors
///
/// Individual provider errors are captured in the results vector.
#[cfg(feature = "native")]
pub async fn fetch_multi_quote(
    sdk: &BridgingSdk,
    request: &QuoteBridgeRequest,
    timeout_ms: Option<u64>,
) -> Vec<MultiQuoteResult> {
    let timeout = timeout_ms.map_or(DEFAULT_TOTAL_TIMEOUT_MS, |v| v);
    let mut results = execute_provider_quotes(sdk, request, timeout).await;

    // Fill timeout results
    let dapp_ids: Vec<String> = sdk.providers.iter().map(|p| p.name().to_owned()).collect();
    crate::utils::fill_timeout_results(&mut results, &dapp_ids);

    // Sort by buy amount after slippage (best first)
    results.sort_by(|a, b| {
        let a_amount =
            a.quote.as_ref().map_or(alloy_primitives::U256::ZERO, |q| q.after_slippage.buy_amount);
        let b_amount =
            b.quote.as_ref().map_or(alloy_primitives::U256::ZERO, |q| q.after_slippage.buy_amount);
        b_amount.cmp(&a_amount)
    });

    results
}

// ── Cache key ───────────────────────────────────────────────────────────────

/// Compute a cache key for a bridge request.
///
/// Produces a deterministic string key from the request's chain IDs and
/// token addresses, suitable for use as a hash-map key.
///
/// Mirrors `getCacheKey` from `BridgingSdk/utils.ts` (which delegates to
/// `hashQuote`).
///
/// # Returns
///
/// A string in the format `"{sell_chain}-{buy_chain}-{sell_token}-{buy_token}"`
/// where token addresses are hex-encoded with a `0x` prefix.
#[must_use]
pub fn get_cache_key(request: &QuoteBridgeRequest) -> String {
    format!(
        "{}-{}-{:#x}-{:#x}",
        request.sell_chain_id, request.buy_chain_id, request.sell_token, request.buy_token,
    )
}

// ── Safe callback invocation ────────────────────────────────────────────────

/// Safely invoke a "best quote" callback, catching panics.
///
/// Mirrors `safeCallBestQuoteCallback` from `BridgingSdk/utils.ts`.
/// If the callback panics, the panic is caught and logged via
/// [`tracing::warn!`]; it does not propagate.
///
/// # Arguments
///
/// * `callback` — An optional closure to invoke with the best quote result. If `None`, this
///   function is a no-op.
/// * `result` — The [`MultiQuoteResult`] to pass to the callback.
pub fn safe_call_best_quote_callback<F: FnOnce(&MultiQuoteResult)>(
    callback: Option<F>,
    result: &MultiQuoteResult,
) {
    if let Some(cb) = callback {
        let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            cb(result);
        }));
        if let Err(e) = outcome {
            tracing::warn!("Error in best-quote callback: {:?}", e);
        }
    }
}

/// Safely invoke a "progressive quote" callback, catching panics.
///
/// Mirrors `safeCallProgressiveCallback` from `BridgingSdk/utils.ts`.
/// If the callback panics, the panic is caught and logged via
/// [`tracing::warn!`]; it does not propagate.
///
/// # Arguments
///
/// * `callback` — An optional closure to invoke with the progressive quote result. If `None`, this
///   function is a no-op.
/// * `result` — The [`MultiQuoteResult`] to pass to the callback.
pub fn safe_call_progressive_callback<F: FnOnce(&MultiQuoteResult)>(
    callback: Option<F>,
    result: &MultiQuoteResult,
) {
    if let Some(cb) = callback {
        let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            cb(result);
        }));
        if let Err(e) = outcome {
            tracing::warn!("Error in progressive-quote callback: {:?}", e);
        }
    }
}

// ── Hook-based and receiver-account bridge quote ────────────────────────────

/// Orchestrate a cross-chain quote for a hook-based bridge (Across, Bungee, …).
///
/// Mirrors `getQuoteWithHookBridge` from
/// `packages/bridging/src/BridgingSdk/getQuoteWithBridge.ts:209-312`.
///
/// # Flow
///
/// 1. Estimate gas for the bridge post-hook
///    ([`crate::provider::HookBridgeProvider::get_gas_limit_estimation_for_hook`]).
/// 2. Quote the intermediate swap via [`get_intermediate_swap_result`] (app-data carries a
///    cost-estimation mock hook so the swap quote sees realistic gas).
/// 3. Either:
///    - **With a signer** (`params.quote_signer.is_some()`): call [`get_bridge_signed_hook`] to
///      fetch the bridge quote, unsigned call, derive the hook nonce, and produce a real EIP-712
///      signed hook via `cow-shed`.
///    - **Without a signer**: fetch [`BridgeProvider::get_quote`] +
///      [`crate::provider::HookBridgeProvider::get_unsigned_bridge_call`] and package with a
///      placeholder mock hook — the real hook is signed later during the post flow.
/// 4. Package the result in a [`BridgeQuoteAndPost`] whose `bridge.bridge_call_details` carries the
///    unsigned call and either the real or mock pre-authorized hook.
///
/// # Errors
///
/// Returns [`BridgeError::TxBuildError`] if any downstream quoter / provider call fails.
pub async fn get_quote_with_hook_bridge(
    hook_provider: &dyn crate::provider::HookBridgeProvider,
    params: &GetQuoteWithBridgeParams,
    quoter: &dyn SwapQuoter,
) -> Result<BridgeQuoteAndPost, BridgeError> {
    // 1. Gas limit estimation for the post-hook (real value used by the mock hook so that the
    //    intermediate swap sees realistic gas).
    let hook_gas_limit = hook_provider
        .get_gas_limit_estimation_for_hook(
            true,
            Some(DEFAULT_EXTRA_GAS_FOR_HOOK_ESTIMATION),
            Some(DEFAULT_EXTRA_GAS_PROXY_CREATION),
        )
        .await
        .map_err(|e| BridgeError::TxBuildError(e.to_string()))?;

    // 2. Intermediate swap result (reuses PR #6 implementation).
    let swap = get_intermediate_swap_result(
        &params.swap_and_bridge_request,
        hook_provider,
        quoter,
        params.advanced_settings_metadata.as_ref(),
    )
    .await?;

    // 3. Produce the bridge-call details — signed or mock depending on whether a `quote_signer` is
    //    available.
    let (unsigned_bridge_call, bridge_response, pre_authorized_bridging_hook) =
        if let Some(signer) = &params.quote_signer {
            let chain_id = cow_chains::SupportedChainId::try_from(
                params.swap_and_bridge_request.sell_chain_id,
            )
            .map_err(|e| {
                BridgeError::TxBuildError(format!(
                    "unsupported sell_chain_id {} for hook signing: {e}",
                    params.swap_and_bridge_request.sell_chain_id,
                ))
            })?;
            let deadline = params.hook_deadline.unwrap_or_else(|| u64::from(u32::MAX));
            let ctx = GetBridgeSignedHookContext {
                signer: signer.as_ref(),
                hook_gas_limit,
                chain_id,
                deadline,
            };
            let out =
                get_bridge_signed_hook(hook_provider, &params.swap_and_bridge_request, ctx).await?;
            (out.unsigned_bridge_call, out.bridging_quote, out.hook)
        } else {
            let bridge_response = hook_provider
                .get_quote(&params.swap_and_bridge_request)
                .await
                .map_err(|e| BridgeError::TxBuildError(e.to_string()))?;
            let unsigned_call = hook_provider
                .get_unsigned_bridge_call(&params.swap_and_bridge_request, &bridge_response)
                .await
                .map_err(|e| BridgeError::TxBuildError(e.to_string()))?;
            let mock_post_hook = crate::utils::hook_mock_for_cost_estimation(hook_gas_limit);
            let hook = BridgeHook {
                post_hook: mock_post_hook,
                recipient: format!("{:#x}", params.swap_and_bridge_request.account),
            };
            (unsigned_call, bridge_response, hook)
        };

    // 4. Assemble the BridgeQuoteResult + BridgeCallDetails.
    let quote = minimal_bridge_quote_result(&params.swap_and_bridge_request, &bridge_response);

    Ok(BridgeQuoteAndPost {
        swap,
        bridge: crate::types::BridgeQuoteResults {
            provider_info: hook_provider.info().clone(),
            quote,
            bridge_call_details: Some(crate::types::BridgeCallDetails {
                unsigned_bridge_call,
                pre_authorized_bridging_hook,
            }),
            bridge_receiver_override: None,
        },
    })
}

/// Orchestrate a cross-chain quote for a receiver-account-based bridge (NEAR Intents, …).
///
/// Mirrors `getQuoteWithReceiverAccountBridge` from
/// `packages/bridging/src/BridgingSdk/getQuoteWithBridge.ts:145-207`.
///
/// # Flow
///
/// 1. Quote the intermediate swap via [`get_intermediate_swap_result`] (no hook injection — the
///    bridge is triggered by the deposit itself, not a post-hook).
/// 2. Ask the provider for a bridge quote ([`BridgeProvider::get_quote`]).
/// 3. Ask the provider for the deposit-address override
///    ([`crate::provider::ReceiverAccountBridgeProvider::get_bridge_receiver_override`]).
/// 4. Package the result in a [`BridgeQuoteAndPost`] where `bridge.bridge_receiver_override` holds
///    the deposit address and `bridge.bridge_call_details` is `None`.
///
/// # Errors
///
/// Returns [`BridgeError::TxBuildError`] if any downstream quoter / provider call fails.
pub async fn get_quote_with_receiver_account_bridge(
    receiver_provider: &dyn crate::provider::ReceiverAccountBridgeProvider,
    params: &GetQuoteWithBridgeParams,
    quoter: &dyn SwapQuoter,
) -> Result<BridgeQuoteAndPost, BridgeError> {
    // 1. Intermediate swap result — no hook; just the metadata fix (#852).
    let swap = get_intermediate_swap_result(
        &params.swap_and_bridge_request,
        receiver_provider,
        quoter,
        params.advanced_settings_metadata.as_ref(),
    )
    .await?;

    // 2. Bridge quote.
    let bridge_response = receiver_provider
        .get_quote(&params.swap_and_bridge_request)
        .await
        .map_err(|e| BridgeError::TxBuildError(e.to_string()))?;

    // 3. Deposit-address override.
    let receiver_override = receiver_provider
        .get_bridge_receiver_override(&params.swap_and_bridge_request, &bridge_response)
        .await
        .map_err(|e| BridgeError::TxBuildError(e.to_string()))?;

    let quote = minimal_bridge_quote_result(&params.swap_and_bridge_request, &bridge_response);

    Ok(BridgeQuoteAndPost {
        swap,
        bridge: crate::types::BridgeQuoteResults {
            provider_info: receiver_provider.info().clone(),
            quote,
            bridge_call_details: None,
            bridge_receiver_override: Some(receiver_override),
        },
    })
}

/// Build a minimal [`crate::types::BridgeQuoteResult`] from a provider's
/// [`QuoteBridgeResponse`].
///
/// The orchestration layer doesn't have access to the richer
/// provider-specific conversion (`to_bridge_quote_result` for Across,
/// `bungee_to_bridge_quote_result` for Bungee) because those take
/// provider-specific API responses as input. We rebuild the minimal
/// `BridgeQuoteResult` from the `QuoteBridgeResponse` alone so the
/// orchestrator can wrap the result in a [`BridgeQuoteAndPost`].
///
/// The simplification is intentional: `BridgeQuoteResult` holds more
/// granular fee breakdown than `QuoteBridgeResponse` does, so a subset
/// of fields end up defaulted.
fn minimal_bridge_quote_result(
    request: &QuoteBridgeRequest,
    response: &QuoteBridgeResponse,
) -> crate::types::BridgeQuoteResult {
    use crate::types::{
        BridgeAmounts, BridgeCosts, BridgeFees, BridgeLimits, BridgeQuoteAmountsAndCosts,
        BridgingFee,
    };

    let fee = response.fee_amount;
    let before_fee_buy = response.buy_amount.saturating_add(fee);

    BridgeQuoteResult {
        id: None,
        signature: None,
        attestation_signature: None,
        quote_body: None,
        is_sell: request.kind == cow_types::OrderKind::Sell,
        amounts_and_costs: BridgeQuoteAmountsAndCosts {
            before_fee: BridgeAmounts {
                sell_amount: response.sell_amount,
                buy_amount: before_fee_buy,
            },
            after_fee: BridgeAmounts {
                sell_amount: response.sell_amount,
                buy_amount: response.buy_amount,
            },
            after_slippage: BridgeAmounts {
                sell_amount: response.sell_amount,
                buy_amount: response.buy_amount,
            },
            costs: BridgeCosts {
                bridging_fee: BridgingFee {
                    fee_bps: 0,
                    amount_in_sell_currency: fee,
                    amount_in_buy_currency: fee,
                },
            },
            slippage_bps: request.slippage_bps,
        },
        expected_fill_time_seconds: Some(response.estimated_secs),
        quote_timestamp: 0,
        fees: BridgeFees { bridge_fee: fee, destination_gas_fee: alloy_primitives::U256::ZERO },
        limits: BridgeLimits {
            min_deposit: alloy_primitives::U256::ZERO,
            max_deposit: alloy_primitives::U256::MAX,
        },
    }
}

// ── Test utilities ──────────────────────────────────────────────────────────

#[cfg(test)]
pub mod test_helpers {
    //! Test helper utilities ported from the `TypeScript` bridging test package.
    //!
    //! Mirrors:
    //! - `expectToEqual` from `test/utils.ts`
    //! - `getMockSigner` / `getPk` / `getWallet` / `getRpcProvider` from `test/getWallet.ts`

    use alloy_primitives::Address;
    use alloy_signer_local::PrivateKeySigner;

    /// A well-known test private key (DO NOT use in production).
    ///
    /// This is the standard Hardhat account #0 key.
    pub const TEST_PRIVATE_KEY: &str =
        "ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";

    /// Return the test private key hex string.
    ///
    /// Mirrors `getPk()` from the `TypeScript` test utilities.
    #[must_use]
    pub fn get_pk() -> &'static str {
        TEST_PRIVATE_KEY
    }

    /// Create a [`PrivateKeySigner`] from the test private key.
    ///
    /// Mirrors `getMockSigner()` / `getWallet()` from the `TypeScript` test utilities.
    #[must_use]
    pub fn get_mock_signer() -> PrivateKeySigner {
        TEST_PRIVATE_KEY.parse::<PrivateKeySigner>().expect("valid test key")
    }

    /// Alias for [`get_mock_signer`].
    #[must_use]
    pub fn get_wallet() -> PrivateKeySigner {
        get_mock_signer()
    }

    /// Return a test RPC URL.
    ///
    /// Mirrors `getRpcProvider()` from the `TypeScript` test utilities.
    /// Returns the default Ethereum mainnet public RPC endpoint.
    #[must_use]
    pub fn get_rpc_provider() -> &'static str {
        "https://eth.llamarpc.com"
    }

    /// Assert that two serializable values produce the same JSON string.
    ///
    /// Mirrors `expectToEqual(a, b)` from the `TypeScript` test utilities,
    /// which compares `JSON.stringify(a, jsonWithBigintReplacer)` outputs.
    ///
    /// # Panics
    ///
    /// Panics if the serialised forms differ.
    pub fn expect_to_equal<T: serde::Serialize>(actual: &T, expected: &T) {
        let actual_json = serde_json::to_string_pretty(actual).expect("failed to serialise actual");
        let expected_json =
            serde_json::to_string_pretty(expected).expect("failed to serialise expected");
        assert_eq!(actual_json, expected_json);
    }

    /// Return the address corresponding to the test private key.
    #[must_use]
    pub fn test_address() -> Address {
        get_mock_signer().address()
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        #[test]
        fn mock_signer_has_expected_address() {
            let signer = get_mock_signer();
            // Hardhat account #0
            let expected: Address = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266".parse().unwrap();
            assert_eq!(signer.address(), expected);
        }

        #[test]
        fn expect_to_equal_passes_for_equal_values() {
            expect_to_equal(&42u64, &42u64);
        }

        #[test]
        #[should_panic]
        fn expect_to_equal_panics_for_different_values() {
            expect_to_equal(&42u64, &43u64);
        }

        #[test]
        fn get_pk_returns_key() {
            assert_eq!(get_pk().len(), 64);
        }

        #[test]
        fn get_rpc_provider_returns_url() {
            assert!(get_rpc_provider().starts_with("https://"));
        }
    }
}

#[cfg(test)]
#[allow(clippy::tests_outside_test_module, reason = "inner module pattern")]
mod intermediate_swap_tests {
    use alloy_primitives::{B256, U256};
    use cow_types::OrderKind;

    use super::*;
    use crate::{
        provider::{
            BridgeNetworkInfo, BridgeStatusFuture, BridgingParamsFuture, BuyTokensFuture,
            IntermediateTokensFuture, NetworksFuture, QuoteFuture,
        },
        swap_quoter::{QuoteSwapFuture, SwapQuoteOutcome, SwapQuoteParams},
        types::{
            BridgeProviderInfo, BridgeProviderType, BuyTokensParams, GetProviderBuyTokens,
            IntermediateTokenInfo,
        },
    };

    fn dummy_info(name: &str) -> BridgeProviderInfo {
        BridgeProviderInfo {
            name: name.to_owned(),
            logo_url: String::new(),
            dapp_id: format!("cow-sdk://bridging/providers/{name}"),
            website: String::new(),
            provider_type: BridgeProviderType::HookBridgeProvider,
        }
    }

    struct FixedProvider {
        info: BridgeProviderInfo,
        tokens: Vec<IntermediateTokenInfo>,
    }

    impl BridgeProvider for FixedProvider {
        fn info(&self) -> &BridgeProviderInfo {
            &self.info
        }
        fn supports_route(&self, _s: u64, _b: u64) -> bool {
            true
        }
        fn get_networks<'a>(&'a self) -> NetworksFuture<'a> {
            Box::pin(async { Ok(Vec::<BridgeNetworkInfo>::new()) })
        }
        fn get_buy_tokens<'a>(&'a self, _p: BuyTokensParams) -> BuyTokensFuture<'a> {
            let info = self.info.clone();
            Box::pin(
                async move { Ok(GetProviderBuyTokens { provider_info: info, tokens: vec![] }) },
            )
        }
        fn get_intermediate_tokens<'a>(
            &'a self,
            _req: &'a QuoteBridgeRequest,
        ) -> IntermediateTokensFuture<'a> {
            let tokens = self.tokens.clone();
            Box::pin(async move { Ok(tokens) })
        }
        fn get_quote<'a>(&'a self, _req: &'a QuoteBridgeRequest) -> QuoteFuture<'a> {
            Box::pin(async {
                Ok(QuoteBridgeResponse {
                    provider: "fixed".into(),
                    sell_amount: U256::ZERO,
                    buy_amount: U256::ZERO,
                    fee_amount: U256::ZERO,
                    estimated_secs: 0,
                    bridge_hook: None,
                })
            })
        }
        fn get_bridging_params<'a>(
            &'a self,
            _c: u64,
            _o: &'a cow_orderbook::types::Order,
            _t: B256,
            _s: Option<Address>,
        ) -> BridgingParamsFuture<'a> {
            Box::pin(async { Ok(None) })
        }
        fn get_explorer_url(&self, _id: &str) -> String {
            String::new()
        }
        fn get_status<'a>(&'a self, _id: &'a str, _c: u64) -> BridgeStatusFuture<'a> {
            Box::pin(async {
                Ok(BridgeStatusResult {
                    status: BridgeStatus::Unknown,
                    fill_time_in_seconds: None,
                    deposit_tx_hash: None,
                    fill_tx_hash: None,
                })
            })
        }
    }

    struct CapturingQuoter {
        captured: std::sync::OnceLock<SwapQuoteParams>,
        outcome: SwapQuoteOutcome,
    }

    impl SwapQuoter for CapturingQuoter {
        fn quote_swap<'a>(&'a self, params: SwapQuoteParams) -> QuoteSwapFuture<'a> {
            self.captured.set(params).ok();
            let outcome = self.outcome.clone();
            Box::pin(async move { Ok(outcome) })
        }
    }

    fn usdc_token() -> IntermediateTokenInfo {
        IntermediateTokenInfo {
            chain_id: 1,
            address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48".parse().unwrap(),
            decimals: 6,
            symbol: "USDC".into(),
            name: "USD Coin".into(),
            logo_url: None,
        }
    }

    fn sample_request() -> QuoteBridgeRequest {
        QuoteBridgeRequest {
            sell_chain_id: 1,
            buy_chain_id: 42_161,
            sell_token: Address::repeat_byte(0x11),
            sell_token_decimals: 18,
            buy_token: Address::repeat_byte(0x22),
            buy_token_decimals: 6,
            sell_amount: U256::from(1_000_000u64),
            account: Address::repeat_byte(0x33),
            owner: None,
            receiver: None,
            bridge_recipient: None,
            slippage_bps: 50,
            bridge_slippage_bps: None,
            kind: OrderKind::Sell,
        }
    }

    fn default_outcome() -> SwapQuoteOutcome {
        SwapQuoteOutcome {
            sell_amount: U256::from(1_000_000u64),
            buy_amount_after_slippage: U256::from(999_500u64),
            fee_amount: U256::from(500u64),
            valid_to: 9_999_999,
            app_data_hex: "0xabc".into(),
            full_app_data: "{\"version\":\"1.4.0\"}".into(),
        }
    }

    #[tokio::test]
    async fn errors_when_provider_has_no_candidates() {
        let provider = FixedProvider { info: dummy_info("p"), tokens: vec![] };
        let quoter =
            CapturingQuoter { captured: std::sync::OnceLock::new(), outcome: default_outcome() };
        let err = get_intermediate_swap_result(&sample_request(), &provider, &quoter, None)
            .await
            .unwrap_err();
        assert!(matches!(err, BridgeError::NoIntermediateTokens));
    }

    #[tokio::test]
    async fn picks_first_candidate_and_returns_wrapped_outcome() {
        let provider = FixedProvider { info: dummy_info("p"), tokens: vec![usdc_token()] };
        let quoter =
            CapturingQuoter { captured: std::sync::OnceLock::new(), outcome: default_outcome() };
        let resp = get_intermediate_swap_result(&sample_request(), &provider, &quoter, None)
            .await
            .unwrap();
        assert_eq!(resp.provider, "p");
        assert_eq!(resp.buy_amount, U256::from(999_500u64));
        assert_eq!(resp.fee_amount, U256::from(500u64));
    }

    #[tokio::test]
    async fn threads_intermediate_token_to_quoter() {
        let provider = FixedProvider { info: dummy_info("p"), tokens: vec![usdc_token()] };
        let quoter =
            CapturingQuoter { captured: std::sync::OnceLock::new(), outcome: default_outcome() };
        get_intermediate_swap_result(&sample_request(), &provider, &quoter, None).await.unwrap();
        let captured = quoter.captured.get().cloned().expect("quoter called");
        assert_eq!(captured.buy_token, usdc_token().address);
        assert_eq!(captured.buy_token_decimals, 6);
        assert_eq!(captured.chain_id, 1);
    }

    // ── cow-sdk#852 metadata preservation ────────────────────────────────

    #[tokio::test]
    async fn fix_852_preserves_caller_metadata() {
        let provider = FixedProvider { info: dummy_info("cow-prov"), tokens: vec![usdc_token()] };
        let quoter =
            CapturingQuoter { captured: std::sync::OnceLock::new(), outcome: default_outcome() };
        let caller_meta = serde_json::json!({
            "partnerFee":   { "bps": 25, "recipient": "0xpartner" },
            "utm":          { "utmSource": "cow-widget" },
            "orderClass":   { "orderClass": "market" }
        });

        get_intermediate_swap_result(&sample_request(), &provider, &quoter, Some(&caller_meta))
            .await
            .unwrap();

        let captured = quoter.captured.get().cloned().expect("quoter called");
        let app_data_json = captured.app_data_json.expect("app_data threaded through");
        let parsed: serde_json::Value = serde_json::from_str(&app_data_json).unwrap();
        let metadata = parsed.get("metadata").expect("metadata key present");

        // Caller metadata survived.
        assert_eq!(
            metadata.get("partnerFee").and_then(|v| v.get("bps")).and_then(|v| v.as_u64()),
            Some(25)
        );
        assert_eq!(
            metadata.get("utm").and_then(|v| v.get("utmSource")).and_then(|v| v.as_str()),
            Some("cow-widget")
        );
        assert_eq!(
            metadata.get("orderClass").and_then(|v| v.get("orderClass")).and_then(|v| v.as_str()),
            Some("market")
        );

        // Auto-generated bridging entry present.
        assert_eq!(
            metadata.get("bridging").and_then(|v| v.get("providerId")).and_then(|v| v.as_str()),
            Some("cow-sdk://bridging/providers/cow-prov")
        );

        // Hooks default to an empty post list if the caller didn't supply any.
        assert!(metadata.get("hooks").is_some());
    }

    #[tokio::test]
    async fn bridging_entry_overwrites_caller_attempt_to_inject_its_own() {
        let provider = FixedProvider { info: dummy_info("cow-prov"), tokens: vec![usdc_token()] };
        let quoter =
            CapturingQuoter { captured: std::sync::OnceLock::new(), outcome: default_outcome() };
        // Caller tries to inject a different providerId — the auto-generated
        // one must win because that's what the on-chain hook encodes.
        let caller_meta = serde_json::json!({
            "bridging": { "providerId": "caller-spoofed" },
        });

        get_intermediate_swap_result(&sample_request(), &provider, &quoter, Some(&caller_meta))
            .await
            .unwrap();
        let captured = quoter.captured.get().cloned().unwrap();
        let parsed: serde_json::Value =
            serde_json::from_str(&captured.app_data_json.unwrap()).unwrap();
        assert_eq!(
            parsed.pointer("/metadata/bridging/providerId").and_then(|v| v.as_str()),
            Some("cow-sdk://bridging/providers/cow-prov")
        );
    }

    // ── Error-path coverage ─────────────────────────────────────────────

    #[tokio::test]
    async fn propagates_quoter_error_as_tx_build_error() {
        struct FailingQuoter;
        impl SwapQuoter for FailingQuoter {
            fn quote_swap<'a>(&'a self, _p: SwapQuoteParams) -> QuoteSwapFuture<'a> {
                Box::pin(async {
                    Err(cow_errors::CowError::Api { status: 500, body: "orderbook down".into() })
                })
            }
        }
        let provider = FixedProvider { info: dummy_info("p"), tokens: vec![usdc_token()] };
        let err = get_intermediate_swap_result(&sample_request(), &provider, &FailingQuoter, None)
            .await
            .unwrap_err();
        let msg = if let BridgeError::TxBuildError(s) = err {
            s
        } else {
            panic!("expected TxBuildError, got {err:?}")
        };
        assert!(msg.contains("500"));
        assert!(msg.contains("orderbook down"));
    }

    #[tokio::test]
    async fn errors_when_all_candidates_are_the_sell_token() {
        // `determine_intermediate_token` filters candidates equal to the
        // sell token when `allow_intermediate_eq_sell = false`. With ≥ 2
        // candidates all equal to the sell token the filter empties and
        // the function must surface `NoIntermediateTokens`.
        let req = sample_request();
        let same = |chain| IntermediateTokenInfo {
            chain_id: chain,
            address: req.sell_token,
            decimals: 18,
            symbol: "SELL".into(),
            name: "Sell Token".into(),
            logo_url: None,
        };
        struct Never;
        impl SwapQuoter for Never {
            fn quote_swap<'a>(&'a self, _p: SwapQuoteParams) -> QuoteSwapFuture<'a> {
                Box::pin(async { panic!("quoter should not be called") })
            }
        }
        let provider = FixedProvider {
            info: dummy_info("p"),
            tokens: vec![same(req.sell_chain_id), same(req.sell_chain_id)],
        };
        let err = get_intermediate_swap_result(&req, &provider, &Never, None).await.unwrap_err();
        assert!(matches!(err, BridgeError::NoIntermediateTokens));
    }

    #[tokio::test]
    async fn provider_info_name_is_threaded_into_response() {
        let provider = FixedProvider { info: dummy_info("zany"), tokens: vec![usdc_token()] };
        let quoter =
            CapturingQuoter { captured: std::sync::OnceLock::new(), outcome: default_outcome() };
        let resp = get_intermediate_swap_result(&sample_request(), &provider, &quoter, None)
            .await
            .unwrap();
        assert_eq!(resp.provider, "zany");
    }

    #[tokio::test]
    async fn non_object_caller_metadata_is_ignored_gracefully() {
        let provider = FixedProvider { info: dummy_info("p"), tokens: vec![usdc_token()] };
        let quoter =
            CapturingQuoter { captured: std::sync::OnceLock::new(), outcome: default_outcome() };
        // A JSON scalar is not a metadata object — the function must
        // tolerate it without panicking and still inject the bridging entry.
        let bogus = serde_json::json!("not-an-object");
        get_intermediate_swap_result(&sample_request(), &provider, &quoter, Some(&bogus))
            .await
            .unwrap();
        let captured = quoter.captured.get().cloned().unwrap();
        let parsed: serde_json::Value =
            serde_json::from_str(&captured.app_data_json.unwrap()).unwrap();
        assert!(parsed.pointer("/metadata/bridging/providerId").is_some());
    }

    #[tokio::test]
    async fn caller_hooks_entry_is_preserved_when_present() {
        // If the caller already supplied a hooks entry, we must not clobber
        // it with the empty default — some flows pre-populate `hooks.pre`.
        let provider = FixedProvider { info: dummy_info("p"), tokens: vec![usdc_token()] };
        let quoter =
            CapturingQuoter { captured: std::sync::OnceLock::new(), outcome: default_outcome() };
        let caller_meta = serde_json::json!({
            "hooks": { "pre": [{ "target": "0xabc", "callData": "0x", "gasLimit": "100000" }], "post": [] },
        });
        get_intermediate_swap_result(&sample_request(), &provider, &quoter, Some(&caller_meta))
            .await
            .unwrap();
        let captured = quoter.captured.get().cloned().unwrap();
        let parsed: serde_json::Value =
            serde_json::from_str(&captured.app_data_json.unwrap()).unwrap();
        let pre = parsed
            .pointer("/metadata/hooks/pre")
            .and_then(|v| v.as_array())
            .expect("pre array present");
        assert_eq!(pre.len(), 1);
    }

    #[tokio::test]
    async fn fixed_provider_surface_is_callable_for_coverage() {
        // Exercise every `FixedProvider` trait method once — otherwise the
        // trait-impl rows stay uncovered because `get_intermediate_swap_result`
        // only calls `info()` + `get_intermediate_tokens()`.
        use alloy_primitives::{Address, B256};
        let p = FixedProvider { info: dummy_info("surface"), tokens: vec![usdc_token()] };
        assert!(p.supports_route(1, 10));
        assert!(p.get_networks().await.unwrap().is_empty());
        let toks = p
            .get_buy_tokens(BuyTokensParams {
                sell_chain_id: 1,
                buy_chain_id: 10,
                sell_token_address: None,
            })
            .await
            .unwrap();
        assert!(toks.tokens.is_empty());
        assert_eq!(p.get_quote(&sample_request()).await.unwrap().provider, "fixed");
        let order = cow_orderbook::api::mock_get_order(&format!("0x{}", "aa".repeat(56)));
        assert!(p.get_bridging_params(1, &order, B256::ZERO, None).await.unwrap().is_none());
        assert!(p.get_explorer_url("x").is_empty());
        assert_eq!(p.get_status("x", 1).await.unwrap().status, BridgeStatus::Unknown);
        // `Address` is imported to silence the unused-import lint if the
        // local scope ever loses its reference.
        let _ = Address::ZERO;
    }

    #[tokio::test]
    async fn no_caller_metadata_still_produces_bridging_entry() {
        let provider = FixedProvider { info: dummy_info("cow-prov"), tokens: vec![usdc_token()] };
        let quoter =
            CapturingQuoter { captured: std::sync::OnceLock::new(), outcome: default_outcome() };
        get_intermediate_swap_result(&sample_request(), &provider, &quoter, None).await.unwrap();
        let captured = quoter.captured.get().cloned().unwrap();
        let parsed: serde_json::Value =
            serde_json::from_str(&captured.app_data_json.unwrap()).unwrap();
        assert!(parsed.pointer("/metadata/bridging/providerId").is_some());
        assert!(parsed.pointer("/metadata/hooks").is_some());
    }
}

// ── Orchestration tests (PR #7) ──────────────────────────────────────────────

#[cfg(test)]
#[allow(clippy::tests_outside_test_module, reason = "inner module pattern")]
mod orchestration_tests {
    use alloy_primitives::{B256, U256};
    use cow_chains::EvmCall;
    use cow_types::OrderKind;

    use super::*;
    use crate::{
        provider::{
            BridgeNetworkInfo, BridgeStatusFuture, BridgingParamsFuture, BuyTokensFuture,
            GasEstimationFuture, HookBridgeProvider, IntermediateTokensFuture, NetworksFuture,
            QuoteFuture, ReceiverAccountBridgeProvider, ReceiverOverrideFuture, SignedHookFuture,
            UnsignedCallFuture,
        },
        swap_quoter::{QuoteSwapFuture, SwapQuoteOutcome, SwapQuoteParams},
        types::{
            BridgeProviderInfo, BridgeProviderType, BuyTokensParams, GetProviderBuyTokens,
            IntermediateTokenInfo,
        },
    };

    fn hook_info() -> BridgeProviderInfo {
        BridgeProviderInfo {
            name: "mock-hook".into(),
            logo_url: String::new(),
            dapp_id: "cow-sdk://bridging/providers/mock-hook".into(),
            website: String::new(),
            provider_type: BridgeProviderType::HookBridgeProvider,
        }
    }

    fn receiver_info() -> BridgeProviderInfo {
        BridgeProviderInfo {
            name: "mock-receiver".into(),
            logo_url: String::new(),
            dapp_id: "cow-sdk://bridging/providers/mock-receiver".into(),
            website: String::new(),
            provider_type: BridgeProviderType::ReceiverAccountBridgeProvider,
        }
    }

    fn usdc() -> IntermediateTokenInfo {
        IntermediateTokenInfo {
            chain_id: 1,
            address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48".parse().unwrap(),
            decimals: 6,
            symbol: "USDC".into(),
            name: "USD Coin".into(),
            logo_url: None,
        }
    }

    fn sample_request(kind: OrderKind) -> QuoteBridgeRequest {
        QuoteBridgeRequest {
            sell_chain_id: 1,
            buy_chain_id: 42_161,
            sell_token: Address::repeat_byte(0x11),
            sell_token_decimals: 18,
            buy_token: Address::repeat_byte(0x22),
            buy_token_decimals: 6,
            sell_amount: U256::from(1_000_000u64),
            account: Address::repeat_byte(0x33),
            owner: None,
            receiver: None,
            bridge_recipient: None,
            slippage_bps: 50,
            bridge_slippage_bps: None,
            kind,
        }
    }

    fn sample_outcome() -> SwapQuoteOutcome {
        SwapQuoteOutcome {
            sell_amount: U256::from(1_000_000u64),
            buy_amount_after_slippage: U256::from(999_500u64),
            fee_amount: U256::from(500u64),
            valid_to: 9_999_999,
            app_data_hex: "0xabc".into(),
            full_app_data: "{}".into(),
        }
    }

    fn sample_bridge_response(provider_name: &str) -> QuoteBridgeResponse {
        QuoteBridgeResponse {
            provider: provider_name.to_owned(),
            sell_amount: U256::from(999_500u64),
            buy_amount: U256::from(998_000u64),
            fee_amount: U256::from(1_500u64),
            estimated_secs: 42,
            bridge_hook: None,
        }
    }

    // ── Mock providers ───────────────────────────────────────────────────

    /// A hook provider wired to return fixed bridge + unsigned-call data.
    struct MockHookProvider {
        info: BridgeProviderInfo,
        tokens: Vec<IntermediateTokenInfo>,
        bridge_response: QuoteBridgeResponse,
        unsigned_call: EvmCall,
        gas_limit: u64,
    }

    impl BridgeProvider for MockHookProvider {
        fn info(&self) -> &BridgeProviderInfo {
            &self.info
        }
        fn supports_route(&self, _s: u64, _b: u64) -> bool {
            true
        }
        fn get_networks<'a>(&'a self) -> NetworksFuture<'a> {
            Box::pin(async { Ok(Vec::<BridgeNetworkInfo>::new()) })
        }
        fn get_buy_tokens<'a>(&'a self, _p: BuyTokensParams) -> BuyTokensFuture<'a> {
            let info = self.info.clone();
            Box::pin(
                async move { Ok(GetProviderBuyTokens { provider_info: info, tokens: vec![] }) },
            )
        }
        fn get_intermediate_tokens<'a>(
            &'a self,
            _req: &'a QuoteBridgeRequest,
        ) -> IntermediateTokensFuture<'a> {
            let tokens = self.tokens.clone();
            Box::pin(async move { Ok(tokens) })
        }
        fn get_quote<'a>(&'a self, _req: &'a QuoteBridgeRequest) -> QuoteFuture<'a> {
            let response = self.bridge_response.clone();
            Box::pin(async move { Ok(response) })
        }
        fn get_bridging_params<'a>(
            &'a self,
            _c: u64,
            _o: &'a cow_orderbook::types::Order,
            _t: B256,
            _s: Option<Address>,
        ) -> BridgingParamsFuture<'a> {
            Box::pin(async { Ok(None) })
        }
        fn get_explorer_url(&self, _id: &str) -> String {
            String::new()
        }
        fn get_status<'a>(&'a self, _id: &'a str, _c: u64) -> BridgeStatusFuture<'a> {
            Box::pin(async {
                Ok(BridgeStatusResult {
                    status: BridgeStatus::Unknown,
                    fill_time_in_seconds: None,
                    deposit_tx_hash: None,
                    fill_tx_hash: None,
                })
            })
        }
        fn as_hook_bridge_provider(&self) -> Option<&dyn HookBridgeProvider> {
            Some(self)
        }
    }

    impl HookBridgeProvider for MockHookProvider {
        fn get_unsigned_bridge_call<'a>(
            &'a self,
            _req: &'a QuoteBridgeRequest,
            _quote: &'a QuoteBridgeResponse,
        ) -> UnsignedCallFuture<'a> {
            let call = self.unsigned_call.clone();
            Box::pin(async move { Ok(call) })
        }
        fn get_gas_limit_estimation_for_hook<'a>(
            &'a self,
            _proxy_deployed: bool,
            _extra_gas: Option<u64>,
            _extra_gas_proxy_creation: Option<u64>,
        ) -> GasEstimationFuture<'a> {
            let gas = self.gas_limit;
            Box::pin(async move { Ok(gas) })
        }
        fn get_signed_hook<'a>(
            &'a self,
            _chain_id: cow_chains::SupportedChainId,
            _unsigned_call: &'a EvmCall,
            _nonce: &'a str,
            _deadline: u64,
            _gas: u64,
            _signer: &'a alloy_signer_local::PrivateKeySigner,
        ) -> SignedHookFuture<'a> {
            Box::pin(async {
                Err(cow_errors::CowError::Signing("not needed in PR #7 tests".into()))
            })
        }
    }

    /// A receiver-account provider wired to return a fixed deposit address.
    struct MockReceiverProvider {
        info: BridgeProviderInfo,
        tokens: Vec<IntermediateTokenInfo>,
        bridge_response: QuoteBridgeResponse,
        deposit_address: String,
    }

    impl BridgeProvider for MockReceiverProvider {
        fn info(&self) -> &BridgeProviderInfo {
            &self.info
        }
        fn supports_route(&self, _s: u64, _b: u64) -> bool {
            true
        }
        fn get_networks<'a>(&'a self) -> NetworksFuture<'a> {
            Box::pin(async { Ok(Vec::<BridgeNetworkInfo>::new()) })
        }
        fn get_buy_tokens<'a>(&'a self, _p: BuyTokensParams) -> BuyTokensFuture<'a> {
            let info = self.info.clone();
            Box::pin(
                async move { Ok(GetProviderBuyTokens { provider_info: info, tokens: vec![] }) },
            )
        }
        fn get_intermediate_tokens<'a>(
            &'a self,
            _req: &'a QuoteBridgeRequest,
        ) -> IntermediateTokensFuture<'a> {
            let tokens = self.tokens.clone();
            Box::pin(async move { Ok(tokens) })
        }
        fn get_quote<'a>(&'a self, _req: &'a QuoteBridgeRequest) -> QuoteFuture<'a> {
            let response = self.bridge_response.clone();
            Box::pin(async move { Ok(response) })
        }
        fn get_bridging_params<'a>(
            &'a self,
            _c: u64,
            _o: &'a cow_orderbook::types::Order,
            _t: B256,
            _s: Option<Address>,
        ) -> BridgingParamsFuture<'a> {
            Box::pin(async { Ok(None) })
        }
        fn get_explorer_url(&self, _id: &str) -> String {
            String::new()
        }
        fn get_status<'a>(&'a self, _id: &'a str, _c: u64) -> BridgeStatusFuture<'a> {
            Box::pin(async {
                Ok(BridgeStatusResult {
                    status: BridgeStatus::Unknown,
                    fill_time_in_seconds: None,
                    deposit_tx_hash: None,
                    fill_tx_hash: None,
                })
            })
        }
        fn as_receiver_account_bridge_provider(
            &self,
        ) -> Option<&dyn ReceiverAccountBridgeProvider> {
            Some(self)
        }
    }

    impl ReceiverAccountBridgeProvider for MockReceiverProvider {
        fn get_bridge_receiver_override<'a>(
            &'a self,
            _quote_request: &'a QuoteBridgeRequest,
            _quote_result: &'a QuoteBridgeResponse,
        ) -> ReceiverOverrideFuture<'a> {
            let addr = self.deposit_address.clone();
            Box::pin(async move { Ok(addr) })
        }
    }

    /// A provider that implements neither sub-trait.
    struct MockUnknownProvider {
        info: BridgeProviderInfo,
    }

    impl BridgeProvider for MockUnknownProvider {
        fn info(&self) -> &BridgeProviderInfo {
            &self.info
        }
        fn supports_route(&self, _s: u64, _b: u64) -> bool {
            true
        }
        fn get_networks<'a>(&'a self) -> NetworksFuture<'a> {
            Box::pin(async { Ok(Vec::<BridgeNetworkInfo>::new()) })
        }
        fn get_buy_tokens<'a>(&'a self, _p: BuyTokensParams) -> BuyTokensFuture<'a> {
            let info = self.info.clone();
            Box::pin(
                async move { Ok(GetProviderBuyTokens { provider_info: info, tokens: vec![] }) },
            )
        }
        fn get_intermediate_tokens<'a>(
            &'a self,
            _req: &'a QuoteBridgeRequest,
        ) -> IntermediateTokensFuture<'a> {
            Box::pin(async { Ok(Vec::<IntermediateTokenInfo>::new()) })
        }
        fn get_quote<'a>(&'a self, _req: &'a QuoteBridgeRequest) -> QuoteFuture<'a> {
            Box::pin(async { Ok(sample_bridge_response("unknown")) })
        }
        fn get_bridging_params<'a>(
            &'a self,
            _c: u64,
            _o: &'a cow_orderbook::types::Order,
            _t: B256,
            _s: Option<Address>,
        ) -> BridgingParamsFuture<'a> {
            Box::pin(async { Ok(None) })
        }
        fn get_explorer_url(&self, _id: &str) -> String {
            String::new()
        }
        fn get_status<'a>(&'a self, _id: &'a str, _c: u64) -> BridgeStatusFuture<'a> {
            Box::pin(async {
                Ok(BridgeStatusResult {
                    status: BridgeStatus::Unknown,
                    fill_time_in_seconds: None,
                    deposit_tx_hash: None,
                    fill_tx_hash: None,
                })
            })
        }
    }

    struct FixedQuoter {
        outcome: SwapQuoteOutcome,
        captured: std::sync::OnceLock<SwapQuoteParams>,
    }

    impl SwapQuoter for FixedQuoter {
        fn quote_swap<'a>(&'a self, params: SwapQuoteParams) -> QuoteSwapFuture<'a> {
            self.captured.set(params).ok();
            let outcome = self.outcome.clone();
            Box::pin(async move { Ok(outcome) })
        }
    }

    fn build_unsigned_call() -> EvmCall {
        EvmCall { to: Address::repeat_byte(0xAC), data: vec![0xde, 0xad], value: U256::ZERO }
    }

    fn hook_params_with_metadata(metadata: Option<serde_json::Value>) -> GetQuoteWithBridgeParams {
        GetQuoteWithBridgeParams {
            swap_and_bridge_request: sample_request(OrderKind::Sell),
            slippage_bps: 50,
            advanced_settings_metadata: metadata,
            quote_signer: None,
            hook_deadline: None,
        }
    }

    // ── Dispatcher tests ─────────────────────────────────────────────────

    #[tokio::test]
    async fn get_quote_with_bridge_rejects_buy_orders() {
        let provider = MockHookProvider {
            info: hook_info(),
            tokens: vec![usdc()],
            bridge_response: sample_bridge_response("mock-hook"),
            unsigned_call: build_unsigned_call(),
            gas_limit: 500_000,
        };
        let quoter =
            FixedQuoter { outcome: sample_outcome(), captured: std::sync::OnceLock::new() };
        let params = GetQuoteWithBridgeParams {
            swap_and_bridge_request: sample_request(OrderKind::Buy),
            slippage_bps: 50,
            advanced_settings_metadata: None,
            quote_signer: None,
            hook_deadline: None,
        };
        let err = get_quote_with_bridge(&params, &provider, &quoter).await.unwrap_err();
        assert!(matches!(err, BridgeError::OnlySellOrderSupported));
    }

    #[tokio::test]
    async fn get_quote_with_bridge_dispatches_to_hook_branch() {
        let provider = MockHookProvider {
            info: hook_info(),
            tokens: vec![usdc()],
            bridge_response: sample_bridge_response("mock-hook"),
            unsigned_call: build_unsigned_call(),
            gas_limit: 500_000,
        };
        let quoter =
            FixedQuoter { outcome: sample_outcome(), captured: std::sync::OnceLock::new() };
        let result = get_quote_with_bridge(&hook_params_with_metadata(None), &provider, &quoter)
            .await
            .unwrap();
        // Hook branch populates bridge_call_details, leaves override empty.
        assert!(result.bridge.bridge_call_details.is_some());
        assert!(result.bridge.bridge_receiver_override.is_none());
        assert_eq!(result.bridge.provider_info.name, "mock-hook");
    }

    #[tokio::test]
    async fn get_quote_with_bridge_dispatches_to_receiver_branch() {
        let provider = MockReceiverProvider {
            info: receiver_info(),
            tokens: vec![usdc()],
            bridge_response: sample_bridge_response("mock-receiver"),
            deposit_address: "0xDEA00DEA00DEA00DEA00DEA00DEA00DEA00DEA000".into(),
        };
        let quoter =
            FixedQuoter { outcome: sample_outcome(), captured: std::sync::OnceLock::new() };
        let result = get_quote_with_bridge(&hook_params_with_metadata(None), &provider, &quoter)
            .await
            .unwrap();
        // Receiver branch populates receiver_override, leaves call_details empty.
        assert!(result.bridge.bridge_call_details.is_none());
        assert_eq!(
            result.bridge.bridge_receiver_override.as_deref(),
            Some("0xDEA00DEA00DEA00DEA00DEA00DEA00DEA00DEA000"),
        );
    }

    #[tokio::test]
    async fn get_quote_with_bridge_errors_on_unknown_provider_kind() {
        let provider = MockUnknownProvider { info: hook_info() };
        let quoter =
            FixedQuoter { outcome: sample_outcome(), captured: std::sync::OnceLock::new() };
        let err = get_quote_with_bridge(&hook_params_with_metadata(None), &provider, &quoter)
            .await
            .unwrap_err();
        if let BridgeError::TxBuildError(msg) = err {
            assert!(msg.contains("implements neither"));
        } else {
            panic!("expected TxBuildError, got {err:?}");
        }
    }

    // ── Metadata preservation (#852 at orchestration level) ──────────────

    #[tokio::test]
    async fn hook_branch_preserves_caller_metadata_on_intermediate_swap() {
        let provider = MockHookProvider {
            info: hook_info(),
            tokens: vec![usdc()],
            bridge_response: sample_bridge_response("mock-hook"),
            unsigned_call: build_unsigned_call(),
            gas_limit: 500_000,
        };
        let quoter =
            FixedQuoter { outcome: sample_outcome(), captured: std::sync::OnceLock::new() };
        let caller_meta = serde_json::json!({
            "partnerFee": { "bps": 25, "recipient": "0xpartner" },
        });
        let params = hook_params_with_metadata(Some(caller_meta));

        get_quote_with_bridge(&params, &provider, &quoter).await.unwrap();

        let captured = quoter.captured.get().cloned().expect("quoter called");
        let app_data: serde_json::Value =
            serde_json::from_str(&captured.app_data_json.unwrap()).unwrap();
        assert_eq!(app_data.pointer("/metadata/partnerFee/bps").and_then(|v| v.as_u64()), Some(25),);
        assert_eq!(
            app_data.pointer("/metadata/bridging/providerId").and_then(|v| v.as_str()),
            Some("cow-sdk://bridging/providers/mock-hook"),
        );
    }

    // ── Simple flows ─────────────────────────────────────────────────────

    #[tokio::test]
    async fn get_quote_without_bridge_calls_quoter_with_full_request() {
        let outcome = sample_outcome();
        let quoter = FixedQuoter { outcome: outcome.clone(), captured: std::sync::OnceLock::new() };
        let result =
            get_quote_without_bridge(&sample_request(OrderKind::Sell), &quoter).await.unwrap();
        assert_eq!(result.quote.sell_amount, outcome.sell_amount);
        assert_eq!(result.quote.buy_amount, outcome.buy_amount_after_slippage);
        assert_eq!(result.quote.fee_amount, outcome.fee_amount);
        assert_eq!(result.quote.provider, "same-chain");

        let captured = quoter.captured.get().cloned().unwrap();
        // `get_quote_without_bridge` maps the *final* buy token directly —
        // no intermediate-token substitution.
        assert_eq!(captured.buy_token, sample_request(OrderKind::Sell).buy_token);
    }

    #[tokio::test]
    async fn get_swap_quote_returns_provider_agnostic_response() {
        let outcome = sample_outcome();
        let quoter = FixedQuoter { outcome: outcome.clone(), captured: std::sync::OnceLock::new() };
        let resp = get_swap_quote(&sample_request(OrderKind::Sell), &quoter).await.unwrap();
        assert_eq!(resp.provider, "swap");
        assert_eq!(resp.buy_amount, outcome.buy_amount_after_slippage);
    }

    #[tokio::test]
    async fn get_quote_without_bridge_propagates_quoter_error() {
        struct Failing;
        impl SwapQuoter for Failing {
            fn quote_swap<'a>(&'a self, _p: SwapQuoteParams) -> QuoteSwapFuture<'a> {
                Box::pin(async {
                    Err(cow_errors::CowError::Api { status: 502, body: "upstream".into() })
                })
            }
        }
        let err =
            get_quote_without_bridge(&sample_request(OrderKind::Sell), &Failing).await.unwrap_err();
        assert!(matches!(err, BridgeError::TxBuildError(_)));
    }

    #[tokio::test]
    async fn get_swap_quote_propagates_quoter_error() {
        struct Failing;
        impl SwapQuoter for Failing {
            fn quote_swap<'a>(&'a self, _p: SwapQuoteParams) -> QuoteSwapFuture<'a> {
                Box::pin(async {
                    Err(cow_errors::CowError::Api { status: 500, body: "boom".into() })
                })
            }
        }
        let err = get_swap_quote(&sample_request(OrderKind::Sell), &Failing).await.unwrap_err();
        assert!(matches!(err, BridgeError::TxBuildError(_)));
    }

    // ── Hook branch error paths ──────────────────────────────────────────

    #[tokio::test]
    async fn hook_branch_propagates_gas_estimation_error() {
        /// Hook provider whose gas estimation fails.
        struct FailingGasProvider {
            info: BridgeProviderInfo,
            tokens: Vec<IntermediateTokenInfo>,
        }
        impl BridgeProvider for FailingGasProvider {
            fn info(&self) -> &BridgeProviderInfo {
                &self.info
            }
            fn supports_route(&self, _s: u64, _b: u64) -> bool {
                true
            }
            fn get_networks<'a>(&'a self) -> NetworksFuture<'a> {
                Box::pin(async { Ok(Vec::<BridgeNetworkInfo>::new()) })
            }
            fn get_buy_tokens<'a>(&'a self, _p: BuyTokensParams) -> BuyTokensFuture<'a> {
                let info = self.info.clone();
                Box::pin(
                    async move { Ok(GetProviderBuyTokens { provider_info: info, tokens: vec![] }) },
                )
            }
            fn get_intermediate_tokens<'a>(
                &'a self,
                _req: &'a QuoteBridgeRequest,
            ) -> IntermediateTokensFuture<'a> {
                let tokens = self.tokens.clone();
                Box::pin(async move { Ok(tokens) })
            }
            fn get_quote<'a>(&'a self, _req: &'a QuoteBridgeRequest) -> QuoteFuture<'a> {
                Box::pin(async { Ok(sample_bridge_response("hook-failing-gas")) })
            }
            fn get_bridging_params<'a>(
                &'a self,
                _c: u64,
                _o: &'a cow_orderbook::types::Order,
                _t: B256,
                _s: Option<Address>,
            ) -> BridgingParamsFuture<'a> {
                Box::pin(async { Ok(None) })
            }
            fn get_explorer_url(&self, _id: &str) -> String {
                String::new()
            }
            fn get_status<'a>(&'a self, _id: &'a str, _c: u64) -> BridgeStatusFuture<'a> {
                Box::pin(async {
                    Ok(BridgeStatusResult {
                        status: BridgeStatus::Unknown,
                        fill_time_in_seconds: None,
                        deposit_tx_hash: None,
                        fill_tx_hash: None,
                    })
                })
            }
            fn as_hook_bridge_provider(&self) -> Option<&dyn HookBridgeProvider> {
                Some(self)
            }
        }
        impl HookBridgeProvider for FailingGasProvider {
            fn get_unsigned_bridge_call<'a>(
                &'a self,
                _req: &'a QuoteBridgeRequest,
                _quote: &'a QuoteBridgeResponse,
            ) -> UnsignedCallFuture<'a> {
                Box::pin(async {
                    Err(cow_errors::CowError::Api { status: 0, body: "not called".into() })
                })
            }
            fn get_gas_limit_estimation_for_hook<'a>(
                &'a self,
                _proxy_deployed: bool,
                _extra_gas: Option<u64>,
                _extra_gas_proxy_creation: Option<u64>,
            ) -> GasEstimationFuture<'a> {
                Box::pin(async {
                    Err(cow_errors::CowError::Api { status: 500, body: "gas oracle down".into() })
                })
            }
            fn get_signed_hook<'a>(
                &'a self,
                _chain_id: cow_chains::SupportedChainId,
                _unsigned_call: &'a EvmCall,
                _nonce: &'a str,
                _deadline: u64,
                _gas: u64,
                _signer: &'a alloy_signer_local::PrivateKeySigner,
            ) -> SignedHookFuture<'a> {
                Box::pin(async { Err(cow_errors::CowError::Signing("n/a".into())) })
            }
        }

        let provider = FailingGasProvider { info: hook_info(), tokens: vec![usdc()] };
        let quoter =
            FixedQuoter { outcome: sample_outcome(), captured: std::sync::OnceLock::new() };
        let err = get_quote_with_bridge(&hook_params_with_metadata(None), &provider, &quoter)
            .await
            .unwrap_err();
        if let BridgeError::TxBuildError(msg) = err {
            assert!(msg.contains("gas oracle down"), "unexpected msg: {msg}");
        } else {
            panic!("expected TxBuildError, got {err:?}");
        }
    }

    #[tokio::test]
    async fn hook_branch_propagates_unsigned_call_error() {
        /// Hook provider whose `get_unsigned_bridge_call` fails.
        struct FailingUnsignedCall {
            info: BridgeProviderInfo,
            tokens: Vec<IntermediateTokenInfo>,
        }
        impl BridgeProvider for FailingUnsignedCall {
            fn info(&self) -> &BridgeProviderInfo {
                &self.info
            }
            fn supports_route(&self, _s: u64, _b: u64) -> bool {
                true
            }
            fn get_networks<'a>(&'a self) -> NetworksFuture<'a> {
                Box::pin(async { Ok(Vec::<BridgeNetworkInfo>::new()) })
            }
            fn get_buy_tokens<'a>(&'a self, _p: BuyTokensParams) -> BuyTokensFuture<'a> {
                let info = self.info.clone();
                Box::pin(
                    async move { Ok(GetProviderBuyTokens { provider_info: info, tokens: vec![] }) },
                )
            }
            fn get_intermediate_tokens<'a>(
                &'a self,
                _req: &'a QuoteBridgeRequest,
            ) -> IntermediateTokensFuture<'a> {
                let tokens = self.tokens.clone();
                Box::pin(async move { Ok(tokens) })
            }
            fn get_quote<'a>(&'a self, _req: &'a QuoteBridgeRequest) -> QuoteFuture<'a> {
                Box::pin(async { Ok(sample_bridge_response("hook-bad-calldata")) })
            }
            fn get_bridging_params<'a>(
                &'a self,
                _c: u64,
                _o: &'a cow_orderbook::types::Order,
                _t: B256,
                _s: Option<Address>,
            ) -> BridgingParamsFuture<'a> {
                Box::pin(async { Ok(None) })
            }
            fn get_explorer_url(&self, _id: &str) -> String {
                String::new()
            }
            fn get_status<'a>(&'a self, _id: &'a str, _c: u64) -> BridgeStatusFuture<'a> {
                Box::pin(async {
                    Ok(BridgeStatusResult {
                        status: BridgeStatus::Unknown,
                        fill_time_in_seconds: None,
                        deposit_tx_hash: None,
                        fill_tx_hash: None,
                    })
                })
            }
            fn as_hook_bridge_provider(&self) -> Option<&dyn HookBridgeProvider> {
                Some(self)
            }
        }
        impl HookBridgeProvider for FailingUnsignedCall {
            fn get_unsigned_bridge_call<'a>(
                &'a self,
                _req: &'a QuoteBridgeRequest,
                _quote: &'a QuoteBridgeResponse,
            ) -> UnsignedCallFuture<'a> {
                Box::pin(async {
                    Err(cow_errors::CowError::Api { status: 0, body: "bad calldata".into() })
                })
            }
            fn get_gas_limit_estimation_for_hook<'a>(
                &'a self,
                _proxy_deployed: bool,
                _extra_gas: Option<u64>,
                _extra_gas_proxy_creation: Option<u64>,
            ) -> GasEstimationFuture<'a> {
                Box::pin(async move { Ok(500_000u64) })
            }
            fn get_signed_hook<'a>(
                &'a self,
                _chain_id: cow_chains::SupportedChainId,
                _unsigned_call: &'a EvmCall,
                _nonce: &'a str,
                _deadline: u64,
                _gas: u64,
                _signer: &'a alloy_signer_local::PrivateKeySigner,
            ) -> SignedHookFuture<'a> {
                Box::pin(async { Err(cow_errors::CowError::Signing("n/a".into())) })
            }
        }

        let provider = FailingUnsignedCall { info: hook_info(), tokens: vec![usdc()] };
        let quoter =
            FixedQuoter { outcome: sample_outcome(), captured: std::sync::OnceLock::new() };
        let err = get_quote_with_bridge(&hook_params_with_metadata(None), &provider, &quoter)
            .await
            .unwrap_err();
        if let BridgeError::TxBuildError(msg) = err {
            assert!(msg.contains("bad calldata"), "unexpected msg: {msg}");
        } else {
            panic!("expected TxBuildError, got {err:?}");
        }
    }

    // ── Receiver branch error paths ──────────────────────────────────────

    #[tokio::test]
    async fn receiver_branch_propagates_override_error() {
        /// Receiver-account provider whose `get_bridge_receiver_override` fails.
        struct FailingReceiverOverride {
            info: BridgeProviderInfo,
            tokens: Vec<IntermediateTokenInfo>,
        }
        impl BridgeProvider for FailingReceiverOverride {
            fn info(&self) -> &BridgeProviderInfo {
                &self.info
            }
            fn supports_route(&self, _s: u64, _b: u64) -> bool {
                true
            }
            fn get_networks<'a>(&'a self) -> NetworksFuture<'a> {
                Box::pin(async { Ok(Vec::<BridgeNetworkInfo>::new()) })
            }
            fn get_buy_tokens<'a>(&'a self, _p: BuyTokensParams) -> BuyTokensFuture<'a> {
                let info = self.info.clone();
                Box::pin(
                    async move { Ok(GetProviderBuyTokens { provider_info: info, tokens: vec![] }) },
                )
            }
            fn get_intermediate_tokens<'a>(
                &'a self,
                _req: &'a QuoteBridgeRequest,
            ) -> IntermediateTokensFuture<'a> {
                let tokens = self.tokens.clone();
                Box::pin(async move { Ok(tokens) })
            }
            fn get_quote<'a>(&'a self, _req: &'a QuoteBridgeRequest) -> QuoteFuture<'a> {
                Box::pin(async { Ok(sample_bridge_response("receiver-failing-override")) })
            }
            fn get_bridging_params<'a>(
                &'a self,
                _c: u64,
                _o: &'a cow_orderbook::types::Order,
                _t: B256,
                _s: Option<Address>,
            ) -> BridgingParamsFuture<'a> {
                Box::pin(async { Ok(None) })
            }
            fn get_explorer_url(&self, _id: &str) -> String {
                String::new()
            }
            fn get_status<'a>(&'a self, _id: &'a str, _c: u64) -> BridgeStatusFuture<'a> {
                Box::pin(async {
                    Ok(BridgeStatusResult {
                        status: BridgeStatus::Unknown,
                        fill_time_in_seconds: None,
                        deposit_tx_hash: None,
                        fill_tx_hash: None,
                    })
                })
            }
            fn as_receiver_account_bridge_provider(
                &self,
            ) -> Option<&dyn ReceiverAccountBridgeProvider> {
                Some(self)
            }
        }
        impl ReceiverAccountBridgeProvider for FailingReceiverOverride {
            fn get_bridge_receiver_override<'a>(
                &'a self,
                _quote_request: &'a QuoteBridgeRequest,
                _quote_result: &'a QuoteBridgeResponse,
            ) -> ReceiverOverrideFuture<'a> {
                Box::pin(async {
                    Err(cow_errors::CowError::Api {
                        status: 0,
                        body: "no deposit addr available".into(),
                    })
                })
            }
        }

        let provider = FailingReceiverOverride { info: receiver_info(), tokens: vec![usdc()] };
        let quoter =
            FixedQuoter { outcome: sample_outcome(), captured: std::sync::OnceLock::new() };
        let err = get_quote_with_bridge(&hook_params_with_metadata(None), &provider, &quoter)
            .await
            .unwrap_err();
        if let BridgeError::TxBuildError(msg) = err {
            assert!(msg.contains("no deposit addr available"), "unexpected msg: {msg}");
        } else {
            panic!("expected TxBuildError, got {err:?}");
        }
    }

    // ── Hook branch — shape checks ────────────────────────────────────────

    #[tokio::test]
    async fn hook_branch_bridge_call_details_carry_unsigned_call_bytes() {
        let provider = MockHookProvider {
            info: hook_info(),
            tokens: vec![usdc()],
            bridge_response: sample_bridge_response("mock-hook"),
            unsigned_call: build_unsigned_call(),
            gas_limit: 500_000,
        };
        let quoter =
            FixedQuoter { outcome: sample_outcome(), captured: std::sync::OnceLock::new() };
        let result =
            get_quote_with_hook_bridge(&provider, &hook_params_with_metadata(None), &quoter)
                .await
                .unwrap();
        let details =
            result.bridge.bridge_call_details.expect("hook branch populates call_details");
        assert_eq!(details.unsigned_bridge_call.data, vec![0xde, 0xad]);
        assert_eq!(details.unsigned_bridge_call.to, Address::repeat_byte(0xAC),);
        // The pre-authorized hook uses the mocked post-hook (PR #7 leaves
        // the real signing for PR #8).
        assert_eq!(details.pre_authorized_bridging_hook.post_hook.gas_limit, "500000",);
    }

    // ── Receiver branch — shape checks ───────────────────────────────────

    #[tokio::test]
    async fn receiver_branch_sets_override_and_clears_call_details() {
        let provider = MockReceiverProvider {
            info: receiver_info(),
            tokens: vec![usdc()],
            bridge_response: sample_bridge_response("mock-receiver"),
            deposit_address: "TOPsolanaDepositAddrXXXXXXXXXXXXXXXXXXXXXXX".into(),
        };
        let quoter =
            FixedQuoter { outcome: sample_outcome(), captured: std::sync::OnceLock::new() };
        let result = get_quote_with_receiver_account_bridge(
            &provider,
            &hook_params_with_metadata(None),
            &quoter,
        )
        .await
        .unwrap();
        assert!(result.bridge.bridge_call_details.is_none());
        assert_eq!(
            result.bridge.bridge_receiver_override.as_deref(),
            Some("TOPsolanaDepositAddrXXXXXXXXXXXXXXXXXXXXXXX"),
        );
    }

    // ── minimal_bridge_quote_result ──────────────────────────────────────

    #[test]
    fn minimal_bridge_quote_result_wraps_response_amounts() {
        let req = sample_request(OrderKind::Sell);
        let resp = sample_bridge_response("arb");
        let quote = minimal_bridge_quote_result(&req, &resp);
        assert!(quote.is_sell);
        assert_eq!(quote.amounts_and_costs.after_fee.buy_amount, resp.buy_amount);
        // before_fee.buy_amount must equal buy_amount + fee.
        assert_eq!(
            quote.amounts_and_costs.before_fee.buy_amount,
            resp.buy_amount.saturating_add(resp.fee_amount),
        );
        assert_eq!(quote.fees.bridge_fee, resp.fee_amount);
        assert_eq!(quote.expected_fill_time_seconds, Some(resp.estimated_secs));
    }

    #[test]
    fn minimal_bridge_quote_result_flags_buy_orders_as_non_sell() {
        let req = sample_request(OrderKind::Buy);
        let resp = sample_bridge_response("arb");
        let quote = minimal_bridge_quote_result(&req, &resp);
        assert!(!quote.is_sell);
    }

    // ── get_bridge_signed_hook ───────────────────────────────────────────

    /// Hook provider that captures calls to `get_signed_hook` so the
    /// test can inspect the derived nonce / deadline / gas limit.
    struct SigningCaptureProvider {
        info: BridgeProviderInfo,
        tokens: Vec<IntermediateTokenInfo>,
        bridge_response: QuoteBridgeResponse,
        unsigned_call: EvmCall,
        captured_nonce: std::sync::OnceLock<String>,
        captured_deadline: std::sync::OnceLock<u64>,
        captured_gas: std::sync::OnceLock<u64>,
    }

    impl BridgeProvider for SigningCaptureProvider {
        fn info(&self) -> &BridgeProviderInfo {
            &self.info
        }
        fn supports_route(&self, _s: u64, _b: u64) -> bool {
            true
        }
        fn get_networks<'a>(&'a self) -> NetworksFuture<'a> {
            Box::pin(async { Ok(Vec::<BridgeNetworkInfo>::new()) })
        }
        fn get_buy_tokens<'a>(&'a self, _p: BuyTokensParams) -> BuyTokensFuture<'a> {
            let info = self.info.clone();
            Box::pin(
                async move { Ok(GetProviderBuyTokens { provider_info: info, tokens: vec![] }) },
            )
        }
        fn get_intermediate_tokens<'a>(
            &'a self,
            _req: &'a QuoteBridgeRequest,
        ) -> IntermediateTokensFuture<'a> {
            let tokens = self.tokens.clone();
            Box::pin(async move { Ok(tokens) })
        }
        fn get_quote<'a>(&'a self, _req: &'a QuoteBridgeRequest) -> QuoteFuture<'a> {
            let resp = self.bridge_response.clone();
            Box::pin(async move { Ok(resp) })
        }
        fn get_bridging_params<'a>(
            &'a self,
            _c: u64,
            _o: &'a cow_orderbook::types::Order,
            _t: B256,
            _s: Option<Address>,
        ) -> BridgingParamsFuture<'a> {
            Box::pin(async { Ok(None) })
        }
        fn get_explorer_url(&self, _id: &str) -> String {
            String::new()
        }
        fn get_status<'a>(&'a self, _id: &'a str, _c: u64) -> BridgeStatusFuture<'a> {
            Box::pin(async {
                Ok(BridgeStatusResult {
                    status: BridgeStatus::Unknown,
                    fill_time_in_seconds: None,
                    deposit_tx_hash: None,
                    fill_tx_hash: None,
                })
            })
        }
        fn as_hook_bridge_provider(&self) -> Option<&dyn HookBridgeProvider> {
            Some(self)
        }
    }

    impl HookBridgeProvider for SigningCaptureProvider {
        fn get_unsigned_bridge_call<'a>(
            &'a self,
            _req: &'a QuoteBridgeRequest,
            _quote: &'a QuoteBridgeResponse,
        ) -> UnsignedCallFuture<'a> {
            let call = self.unsigned_call.clone();
            Box::pin(async move { Ok(call) })
        }
        fn get_gas_limit_estimation_for_hook<'a>(
            &'a self,
            _proxy_deployed: bool,
            _extra_gas: Option<u64>,
            _extra_gas_proxy_creation: Option<u64>,
        ) -> GasEstimationFuture<'a> {
            Box::pin(async move { Ok(500_000u64) })
        }
        fn get_signed_hook<'a>(
            &'a self,
            _chain_id: cow_chains::SupportedChainId,
            _unsigned_call: &'a EvmCall,
            nonce: &'a str,
            deadline: u64,
            hook_gas_limit: u64,
            _signer: &'a alloy_signer_local::PrivateKeySigner,
        ) -> SignedHookFuture<'a> {
            self.captured_nonce.set(nonce.to_owned()).ok();
            self.captured_deadline.set(deadline).ok();
            self.captured_gas.set(hook_gas_limit).ok();
            Box::pin(async {
                Ok(BridgeHook {
                    post_hook: crate::utils::hook_mock_for_cost_estimation(500_000),
                    recipient: "0x0000000000000000000000000000000000000001".into(),
                })
            })
        }
    }

    fn make_signer() -> alloy_signer_local::PrivateKeySigner {
        use std::str::FromStr;
        alloy_signer_local::PrivateKeySigner::from_str(
            "ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80",
        )
        .unwrap()
    }

    #[tokio::test]
    async fn get_bridge_signed_hook_threads_context_into_provider() {
        let provider = SigningCaptureProvider {
            info: hook_info(),
            tokens: vec![usdc()],
            bridge_response: sample_bridge_response("sig-capture"),
            unsigned_call: build_unsigned_call(),
            captured_nonce: std::sync::OnceLock::new(),
            captured_deadline: std::sync::OnceLock::new(),
            captured_gas: std::sync::OnceLock::new(),
        };
        let signer = make_signer();
        let ctx = GetBridgeSignedHookContext {
            signer: &signer,
            hook_gas_limit: 123_456,
            chain_id: cow_chains::SupportedChainId::Mainnet,
            deadline: 9_999_999,
        };
        let out =
            get_bridge_signed_hook(&provider, &sample_request(OrderKind::Sell), ctx).await.unwrap();
        // Gas + deadline must match what we threaded in.
        assert_eq!(*provider.captured_gas.get().unwrap(), 123_456);
        assert_eq!(*provider.captured_deadline.get().unwrap(), 9_999_999);
        // The nonce is keccak256(data || deadline_be) — deterministic.
        let expected = derive_hook_nonce(&out.unsigned_bridge_call.data, 9_999_999);
        assert_eq!(provider.captured_nonce.get().unwrap(), &expected);
        assert_eq!(out.bridging_quote.provider, "sig-capture");
    }

    #[test]
    fn derive_hook_nonce_is_deterministic() {
        let data = vec![0xde, 0xad, 0xbe, 0xef];
        let a = derive_hook_nonce(&data, 42);
        let b = derive_hook_nonce(&data, 42);
        assert_eq!(a, b);
        assert!(a.starts_with("0x"));
        assert_eq!(a.len(), 2 + 64); // "0x" + 32 bytes hex
    }

    #[test]
    fn derive_hook_nonce_changes_with_deadline() {
        let data = vec![0x01, 0x02];
        let a = derive_hook_nonce(&data, 42);
        let b = derive_hook_nonce(&data, 43);
        assert_ne!(a, b);
    }

    #[test]
    fn derive_hook_nonce_changes_with_data() {
        let a = derive_hook_nonce(&[0x01], 42);
        let b = derive_hook_nonce(&[0x02], 42);
        assert_ne!(a, b);
    }

    #[tokio::test]
    async fn get_bridge_signed_hook_propagates_quote_error() {
        /// Provider whose `get_quote` fails.
        struct QuoteFailing {
            info: BridgeProviderInfo,
        }
        impl BridgeProvider for QuoteFailing {
            fn info(&self) -> &BridgeProviderInfo {
                &self.info
            }
            fn supports_route(&self, _s: u64, _b: u64) -> bool {
                true
            }
            fn get_networks<'a>(&'a self) -> NetworksFuture<'a> {
                Box::pin(async { Ok(Vec::new()) })
            }
            fn get_buy_tokens<'a>(&'a self, _p: BuyTokensParams) -> BuyTokensFuture<'a> {
                let info = self.info.clone();
                Box::pin(
                    async move { Ok(GetProviderBuyTokens { provider_info: info, tokens: vec![] }) },
                )
            }
            fn get_intermediate_tokens<'a>(
                &'a self,
                _req: &'a QuoteBridgeRequest,
            ) -> IntermediateTokensFuture<'a> {
                Box::pin(async { Ok(Vec::new()) })
            }
            fn get_quote<'a>(&'a self, _req: &'a QuoteBridgeRequest) -> QuoteFuture<'a> {
                Box::pin(async {
                    Err(cow_errors::CowError::Api { status: 500, body: "nope".into() })
                })
            }
            fn get_bridging_params<'a>(
                &'a self,
                _c: u64,
                _o: &'a cow_orderbook::types::Order,
                _t: B256,
                _s: Option<Address>,
            ) -> BridgingParamsFuture<'a> {
                Box::pin(async { Ok(None) })
            }
            fn get_explorer_url(&self, _id: &str) -> String {
                String::new()
            }
            fn get_status<'a>(&'a self, _id: &'a str, _c: u64) -> BridgeStatusFuture<'a> {
                Box::pin(async {
                    Ok(BridgeStatusResult {
                        status: BridgeStatus::Unknown,
                        fill_time_in_seconds: None,
                        deposit_tx_hash: None,
                        fill_tx_hash: None,
                    })
                })
            }
            fn as_hook_bridge_provider(&self) -> Option<&dyn HookBridgeProvider> {
                Some(self)
            }
        }
        impl HookBridgeProvider for QuoteFailing {
            fn get_unsigned_bridge_call<'a>(
                &'a self,
                _req: &'a QuoteBridgeRequest,
                _quote: &'a QuoteBridgeResponse,
            ) -> UnsignedCallFuture<'a> {
                Box::pin(async { Err(cow_errors::CowError::Signing("n/a".into())) })
            }
            fn get_gas_limit_estimation_for_hook<'a>(
                &'a self,
                _proxy_deployed: bool,
                _extra_gas: Option<u64>,
                _extra_gas_proxy_creation: Option<u64>,
            ) -> GasEstimationFuture<'a> {
                Box::pin(async move { Ok(500_000u64) })
            }
            fn get_signed_hook<'a>(
                &'a self,
                _chain_id: cow_chains::SupportedChainId,
                _unsigned_call: &'a EvmCall,
                _nonce: &'a str,
                _deadline: u64,
                _gas: u64,
                _signer: &'a alloy_signer_local::PrivateKeySigner,
            ) -> SignedHookFuture<'a> {
                Box::pin(async { Err(cow_errors::CowError::Signing("n/a".into())) })
            }
        }

        let provider = QuoteFailing { info: hook_info() };
        let signer = make_signer();
        let err = get_bridge_signed_hook(
            &provider,
            &sample_request(OrderKind::Sell),
            GetBridgeSignedHookContext {
                signer: &signer,
                hook_gas_limit: 1_000,
                chain_id: cow_chains::SupportedChainId::Mainnet,
                deadline: 1_234,
            },
        )
        .await
        .unwrap_err();
        if let BridgeError::TxBuildError(msg) = err {
            assert!(msg.contains("nope"), "unexpected: {msg}");
        } else {
            panic!("expected TxBuildError, got {err:?}");
        }
    }

    // ── get_quote_with_hook_bridge with signer ───────────────────────────

    #[tokio::test]
    async fn hook_branch_produces_real_hook_when_signer_provided() {
        let provider = SigningCaptureProvider {
            info: hook_info(),
            tokens: vec![usdc()],
            bridge_response: sample_bridge_response("with-signer"),
            unsigned_call: build_unsigned_call(),
            captured_nonce: std::sync::OnceLock::new(),
            captured_deadline: std::sync::OnceLock::new(),
            captured_gas: std::sync::OnceLock::new(),
        };
        let quoter =
            FixedQuoter { outcome: sample_outcome(), captured: std::sync::OnceLock::new() };
        let signer = std::sync::Arc::new(make_signer());
        let params = GetQuoteWithBridgeParams {
            swap_and_bridge_request: sample_request(OrderKind::Sell),
            slippage_bps: 50,
            advanced_settings_metadata: None,
            quote_signer: Some(std::sync::Arc::clone(&signer)),
            hook_deadline: Some(5_000_000),
        };

        get_quote_with_hook_bridge(&provider, &params, &quoter).await.unwrap();

        // The signer path must have threaded the caller's deadline
        // into get_signed_hook.
        assert_eq!(*provider.captured_deadline.get().unwrap(), 5_000_000);
    }

    #[tokio::test]
    async fn hook_branch_defaults_deadline_to_u32_max_when_unset() {
        let provider = SigningCaptureProvider {
            info: hook_info(),
            tokens: vec![usdc()],
            bridge_response: sample_bridge_response("default-deadline"),
            unsigned_call: build_unsigned_call(),
            captured_nonce: std::sync::OnceLock::new(),
            captured_deadline: std::sync::OnceLock::new(),
            captured_gas: std::sync::OnceLock::new(),
        };
        let quoter =
            FixedQuoter { outcome: sample_outcome(), captured: std::sync::OnceLock::new() };
        let signer = std::sync::Arc::new(make_signer());
        let params = GetQuoteWithBridgeParams {
            swap_and_bridge_request: sample_request(OrderKind::Sell),
            slippage_bps: 50,
            advanced_settings_metadata: None,
            quote_signer: Some(std::sync::Arc::clone(&signer)),
            hook_deadline: None,
        };

        get_quote_with_hook_bridge(&provider, &params, &quoter).await.unwrap();
        assert_eq!(*provider.captured_deadline.get().unwrap(), u64::from(u32::MAX));
    }
}