cardano_serialization_lib/builders/
tx_builder.rs

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
#![allow(deprecated)]

use crate::*;

use super::*;
use crate::builders::fakes::{fake_bootstrap_witness, fake_raw_key_public, fake_raw_key_sig};
use crate::fees;
use crate::utils;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};

fn count_needed_vkeys(tx_builder: &TransactionBuilder) -> usize {
    let mut input_hashes: Ed25519KeyHashes = Ed25519KeyHashes::from(&tx_builder.inputs);
    input_hashes.extend_move(Ed25519KeyHashes::from(&tx_builder.collateral));
    input_hashes.extend_move(tx_builder.required_signers.clone());
    if let Some(mint_builder) = &tx_builder.mint {
        input_hashes.extend_move(Ed25519KeyHashes::from(&mint_builder.get_native_scripts()));
    }
    if let Some(withdrawals_builder) = &tx_builder.withdrawals {
        input_hashes.extend_move(withdrawals_builder.get_required_signers());
    }
    if let Some(certs_builder) = &tx_builder.certs {
        input_hashes.extend_move(certs_builder.get_required_signers());
    }
    if let Some(voting_builder) = &tx_builder.voting_procedures {
        input_hashes.extend_move(voting_builder.get_required_signers());
    }
    input_hashes.len()
}

// tx_body must be the result of building from tx_builder
// constructs the rest of the Transaction using fake witness data of the correct length
// for use in calculating the size of the final Transaction
pub(crate) fn fake_full_tx(
    tx_builder: &TransactionBuilder,
    body: TransactionBody,
) -> Result<Transaction, JsError> {
    let fake_sig = fake_raw_key_sig();

    // recall: this includes keys for input, certs and withdrawals
    let vkeys = match count_needed_vkeys(tx_builder) {
        0 => None,
        x => {
            let mut result = Vkeywitnesses::new();
            for i in 0..x {
                let raw_key_public = fake_raw_key_public(i as u64);
                let fake_vkey_witness = Vkeywitness::new(&Vkey::new(&raw_key_public), &fake_sig);
                result.add(&fake_vkey_witness.clone());
            }
            Some(result)
        }
    };
    let bootstraps = get_bootstraps(&tx_builder.inputs);
    let bootstrap_keys = match bootstraps.len() {
        0 => None,
        _x => {
            let mut result = BootstrapWitnesses::new();
            let mut number = 1;
            for addr in bootstraps {
                number += 1;
                // picking icarus over daedalus for fake witness generation shouldn't matter
                result.add(&fake_bootstrap_witness(number, &ByronAddress::from_bytes(addr)?));
            }
            Some(result)
        }
    };
    let (plutus_scripts, mut plutus_data, redeemers) = {
        if let Some(s) = tx_builder.get_combined_plutus_scripts() {
            let (s, d, r) = s.collect();
            (Some(s), d, Some(r))
        } else {
            (None, None, None)
        }
    };

    if let Some(extra_datums) = &tx_builder.extra_datums {
        if let Some(d) = &mut plutus_data {
            d.extend(extra_datums);
        } else {
            plutus_data = Some(extra_datums.clone());
        }
    }

    let witness_set = TransactionWitnessSet::new_with_partial_dedup(
        vkeys,
        tx_builder.get_combined_native_scripts(),
        bootstrap_keys,
        plutus_scripts,
        plutus_data,
        redeemers,
    );
    Ok(Transaction {
        body,
        witness_set,
        is_valid: true,
        auxiliary_data: tx_builder.auxiliary_data.clone(),
    })
}

fn assert_required_mint_scripts(
    mint: &Mint,
    maybe_mint_scripts: Option<&NativeScripts>,
) -> Result<(), JsError> {
    if maybe_mint_scripts.is_none_or_empty() {
        return Err(JsError::from_str(
            "Mint is present in the builder, but witness scripts are not provided!",
        ));
    }
    let mint_scripts = maybe_mint_scripts.unwrap();
    let witness_hashes: HashSet<ScriptHash> =
        mint_scripts.iter().map(|script| script.hash()).collect();
    for mint_hash in mint.keys().0.iter() {
        if !witness_hashes.contains(mint_hash) {
            return Err(JsError::from_str(&format!(
                "No witness script is found for mint policy '{:?}'! Script is required!",
                hex::encode(mint_hash.to_bytes()),
            )));
        }
    }
    Ok(())
}

fn min_fee(tx_builder: &TransactionBuilder) -> Result<Coin, JsError> {
    // Commented out for performance, `min_fee` is a critical function
    // This was mostly added here as a paranoid step anyways
    // If someone is using `set_mint` and `add_mint*` API function, everything is expected to be intact
    // TODO: figure out if assert is needed here and a better way to do it maybe only once if mint doesn't change
    // if let Some(mint) = tx_builder.mint.as_ref() {
    //     assert_required_mint_scripts(mint, tx_builder.mint_scripts.as_ref())?;
    // }
    let full_tx = fake_full_tx(tx_builder, tx_builder.build()?)?;
    let mut fee: Coin = fees::min_fee(&full_tx, &tx_builder.config.fee_algo)?;

    if let Some(ex_unit_prices) = &tx_builder.config.ex_unit_prices {
        let script_fee: Coin = fees::min_script_fee(&full_tx, &ex_unit_prices)?;
        fee = fee.checked_add(&script_fee)?;
    } else {
        if tx_builder.has_plutus_inputs() {
            return Err(JsError::from_str(
                "Plutus inputs are present but ex_unit_prices are missing in the config!",
            ));
        }
    }

    let total_ref_script_size = tx_builder.get_total_ref_scripts_size()?;
    if let Some(ref_script_coins_per_byte) = &tx_builder.config.ref_script_coins_per_byte {
        let script_ref_fee = min_ref_script_fee(total_ref_script_size, ref_script_coins_per_byte)?;
        fee = fee.checked_add(&script_ref_fee)?;
    } else {
        if total_ref_script_size > 0 {
            return Err(JsError::from_str(
                "Plutus scripts are present but ref_script_coins_per_byte are missing in the config!",
            ));
        }
    }

    Ok(fee)
}

#[wasm_bindgen]
pub enum CoinSelectionStrategyCIP2 {
    /// Performs CIP2's Largest First ada-only selection. Will error if outputs contain non-ADA assets.
    LargestFirst,
    /// Performs CIP2's Random Improve ada-only selection. Will error if outputs contain non-ADA assets.
    RandomImprove,
    /// Same as LargestFirst, but before adding ADA, will insert by largest-first for each asset type.
    LargestFirstMultiAsset,
    /// Same as RandomImprove, but before adding ADA, will insert by random-improve for each asset type.
    RandomImproveMultiAsset,
}

#[wasm_bindgen]
#[derive(Clone, Debug)]
pub struct TransactionBuilderConfig {
    pub(crate) fee_algo: fees::LinearFee,
    pub(crate) pool_deposit: Coin,  // protocol parameter
    pub(crate) key_deposit: Coin,   // protocol parameter
    pub(crate) max_value_size: u32, // protocol parameter
    pub(crate) max_tx_size: u32,    // protocol parameter
    pub(crate) data_cost: DataCost, // protocol parameter
    pub(crate) ex_unit_prices: Option<ExUnitPrices>, // protocol parameter
    pub(crate) ref_script_coins_per_byte: Option<UnitInterval>, // protocol parameter
    pub(crate) prefer_pure_change: bool,
    pub(crate) deduplicate_explicit_ref_inputs_with_regular_inputs: bool,
}

impl TransactionBuilderConfig {
    pub(crate) fn utxo_cost(&self) -> DataCost {
        self.data_cost.clone()
    }
}

#[wasm_bindgen]
#[derive(Clone, Debug)]
pub struct TransactionBuilderConfigBuilder {
    fee_algo: Option<fees::LinearFee>,
    pool_deposit: Option<Coin>,                      // protocol parameter
    key_deposit: Option<Coin>,                       // protocol parameter
    max_value_size: Option<u32>,                     // protocol parameter
    max_tx_size: Option<u32>,                        // protocol parameter
    data_cost: Option<DataCost>,                     // protocol parameter
    ex_unit_prices: Option<ExUnitPrices>,            // protocol parameter
    ref_script_coins_per_byte: Option<UnitInterval>, // protocol parameter
    prefer_pure_change: bool,
    deduplicate_explicit_ref_inputs_with_regular_inputs: bool,
}

#[wasm_bindgen]
impl TransactionBuilderConfigBuilder {
    pub fn new() -> Self {
        Self {
            fee_algo: None,
            pool_deposit: None,
            key_deposit: None,
            max_value_size: None,
            max_tx_size: None,
            data_cost: None,
            ex_unit_prices: None,
            ref_script_coins_per_byte: None,
            prefer_pure_change: false,
            deduplicate_explicit_ref_inputs_with_regular_inputs: false,
        }
    }

    pub fn fee_algo(&self, fee_algo: &fees::LinearFee) -> Self {
        let mut cfg = self.clone();
        cfg.fee_algo = Some(fee_algo.clone());
        cfg
    }

    pub fn coins_per_utxo_byte(&self, coins_per_utxo_byte: &Coin) -> Self {
        let mut cfg = self.clone();
        cfg.data_cost = Some(DataCost::new_coins_per_byte(coins_per_utxo_byte));
        cfg
    }

    pub fn ex_unit_prices(&self, ex_unit_prices: &ExUnitPrices) -> Self {
        let mut cfg = self.clone();
        cfg.ex_unit_prices = Some(ex_unit_prices.clone());
        cfg
    }

    pub fn pool_deposit(&self, pool_deposit: &BigNum) -> Self {
        let mut cfg = self.clone();
        cfg.pool_deposit = Some(pool_deposit.clone());
        cfg
    }

    pub fn key_deposit(&self, key_deposit: &BigNum) -> Self {
        let mut cfg = self.clone();
        cfg.key_deposit = Some(key_deposit.clone());
        cfg
    }

    pub fn max_value_size(&self, max_value_size: u32) -> Self {
        let mut cfg = self.clone();
        cfg.max_value_size = Some(max_value_size);
        cfg
    }

    pub fn max_tx_size(&self, max_tx_size: u32) -> Self {
        let mut cfg = self.clone();
        cfg.max_tx_size = Some(max_tx_size);
        cfg
    }

    pub fn ref_script_coins_per_byte(&self, ref_script_coins_per_byte: &UnitInterval) -> Self {
        let mut cfg = self.clone();
        cfg.ref_script_coins_per_byte = Some(ref_script_coins_per_byte.clone());
        cfg
    }

    pub fn prefer_pure_change(&self, prefer_pure_change: bool) -> Self {
        let mut cfg = self.clone();
        cfg.prefer_pure_change = prefer_pure_change;
        cfg
    }

    ///Removes a ref input (that was set via set_reference_inputs) if the ref inputs was presented in regular tx inputs
    pub fn deduplicate_explicit_ref_inputs_with_regular_inputs(&self, deduplicate_explicit_ref_inputs_with_regular_inputs: bool) -> Self {
        let mut cfg = self.clone();
        cfg.deduplicate_explicit_ref_inputs_with_regular_inputs = deduplicate_explicit_ref_inputs_with_regular_inputs;
        cfg
    }

    pub fn build(&self) -> Result<TransactionBuilderConfig, JsError> {
        let cfg: Self = self.clone();
        Ok(TransactionBuilderConfig {
            fee_algo: cfg
                .fee_algo
                .ok_or(JsError::from_str("uninitialized field: fee_algo"))?,
            pool_deposit: cfg
                .pool_deposit
                .ok_or(JsError::from_str("uninitialized field: pool_deposit"))?,
            key_deposit: cfg
                .key_deposit
                .ok_or(JsError::from_str("uninitialized field: key_deposit"))?,
            max_value_size: cfg
                .max_value_size
                .ok_or(JsError::from_str("uninitialized field: max_value_size"))?,
            max_tx_size: cfg
                .max_tx_size
                .ok_or(JsError::from_str("uninitialized field: max_tx_size"))?,
            data_cost: cfg.data_cost.ok_or(JsError::from_str(
                "uninitialized field: coins_per_utxo_byte or coins_per_utxo_word",
            ))?,
            ex_unit_prices: cfg.ex_unit_prices,
            ref_script_coins_per_byte: cfg.ref_script_coins_per_byte,
            prefer_pure_change: cfg.prefer_pure_change,
            deduplicate_explicit_ref_inputs_with_regular_inputs: cfg.deduplicate_explicit_ref_inputs_with_regular_inputs,
        })
    }
}

#[wasm_bindgen]
#[derive(Clone, Debug)]
pub struct ChangeConfig {
    address: Address,
    plutus_data: Option<OutputDatum>,
    script_ref: Option<ScriptRef>,
}

#[wasm_bindgen]
impl ChangeConfig {
    pub fn new(address: &Address) -> Self {
        Self {
            address: address.clone(),
            plutus_data: None,
            script_ref: None,
        }
    }

    pub fn change_address(&self, address: &Address) -> Self {
        let mut c_cfg = self.clone();
        c_cfg.address = address.clone();
        c_cfg
    }

    pub fn change_plutus_data(&self, plutus_data: &OutputDatum) -> Self {
        let mut c_cfg = self.clone();
        c_cfg.plutus_data = Some(plutus_data.clone());
        c_cfg
    }

    pub fn change_script_ref(&self, script_ref: &ScriptRef) -> Self {
        let mut c_cfg = self.clone();
        c_cfg.script_ref = Some(script_ref.clone());
        c_cfg
    }
}

#[wasm_bindgen]
#[derive(Clone, Debug)]
pub struct TransactionBuilder {
    pub(crate) config: TransactionBuilderConfig,
    pub(crate) inputs: TxInputsBuilder,
    pub(crate) collateral: TxInputsBuilder,
    pub(crate) outputs: TransactionOutputs,
    pub(crate) fee: Option<Coin>,
    pub(crate) ttl: Option<SlotBigNum>, // absolute slot number
    pub(crate) certs: Option<CertificatesBuilder>,
    pub(crate) withdrawals: Option<WithdrawalsBuilder>,
    pub(crate) auxiliary_data: Option<AuxiliaryData>,
    pub(crate) validity_start_interval: Option<SlotBigNum>,
    pub(crate) mint: Option<MintBuilder>,
    pub(crate) script_data_hash: Option<ScriptDataHash>,
    pub(crate) required_signers: Ed25519KeyHashes,
    pub(crate) collateral_return: Option<TransactionOutput>,
    pub(crate) total_collateral: Option<Coin>,
    pub(crate) reference_inputs: HashMap<TransactionInput, usize>,
    pub(crate) extra_datums: Option<PlutusList>,
    pub(crate) voting_procedures: Option<VotingBuilder>,
    pub(crate) voting_proposals: Option<VotingProposalBuilder>,
    pub(crate) current_treasury_value: Option<Coin>,
    pub(crate) donation: Option<Coin>,
}

#[wasm_bindgen]
impl TransactionBuilder {
    /// This automatically selects and adds inputs from {inputs} consisting of just enough to cover
    /// the outputs that have already been added.
    /// This should be called after adding all certs/outputs/etc and will be an error otherwise.
    /// Uses CIP2: https://github.com/cardano-foundation/CIPs/blob/master/CIP-0002/CIP-0002.md
    /// Adding a change output must be called after via TransactionBuilder::add_change_if_needed()
    /// This function, diverging from CIP2, takes into account fees and will attempt to add additional
    /// inputs to cover the minimum fees. This does not, however, set the txbuilder's fee.
    pub fn add_inputs_from(
        &mut self,
        inputs: &TransactionUnspentOutputs,
        strategy: CoinSelectionStrategyCIP2,
    ) -> Result<(), JsError> {
        let mut available_inputs: Vec<&TransactionUnspentOutput> = inputs.0.iter().collect();
        let have_no_inputs_in_tx = !self.inputs.has_inputs();
        let mut input_total = self.get_total_input()?;
        let mut output_total = self
            .get_total_output()?
            .checked_add(&Value::new(&self.min_fee()?))?;

        if (input_total.coin >= output_total.coin) && have_no_inputs_in_tx {
            if available_inputs.is_empty() {
                return Err(JsError::from_str("No inputs to add. Transaction should have at least one input"));
            }

            //just add first input, to cover needs of one input
            let input = available_inputs.pop().unwrap();
            self.add_regular_input(
                &input.output.address,
                &input.input,
                &input.output.amount,
            )?;
            input_total = input_total.checked_add(&input.output.amount)?;
        }

        match strategy {
            CoinSelectionStrategyCIP2::LargestFirst => {
                if self
                    .outputs
                    .0
                    .iter()
                    .any(|output| output.amount.multiasset.is_some())
                {
                    return Err(JsError::from_str("Multiasset values not supported by LargestFirst. Please use LargestFirstMultiAsset"));
                }
                self.cip2_largest_first_by(
                    &available_inputs,
                    &mut (0..available_inputs.len()).collect(),
                    &mut input_total,
                    &mut output_total,
                    |value| Some(value.coin),
                )?;
            }
            CoinSelectionStrategyCIP2::RandomImprove => {
                if self
                    .outputs
                    .0
                    .iter()
                    .any(|output| output.amount.multiasset.is_some())
                {
                    return Err(JsError::from_str("Multiasset values not supported by RandomImprove. Please use RandomImproveMultiAsset"));
                }
                use rand::Rng;
                let mut rng = rand::thread_rng();
                let mut available_indices =
                    (0..available_inputs.len()).collect::<BTreeSet<usize>>();
                self.cip2_random_improve_by(
                    &available_inputs,
                    &mut available_indices,
                    &mut input_total,
                    &mut output_total,
                    |value| Some(value.coin),
                    &mut rng,
                    true,
                )?;
                // Phase 3: add extra inputs needed for fees (not covered by CIP-2)
                // We do this at the end because this new inputs won't be associated with
                // a specific output, so the improvement algorithm we do above does not apply here.
                while input_total.coin < output_total.coin {
                    if available_indices.is_empty() {
                        return Err(JsError::from_str("UTxO Balance Insufficient[x]"));
                    }
                    let i = *available_indices
                        .iter()
                        .nth(rng.gen_range(0..available_indices.len()))
                        .unwrap();
                    available_indices.remove(&i);
                    let input = &available_inputs[i];
                    let input_fee = self.fee_for_input(
                        &input.output.address,
                        &input.input,
                        &input.output.amount,
                    )?;
                    self.add_regular_input(
                        &input.output.address,
                        &input.input,
                        &input.output.amount,
                    )?;
                    input_total = input_total.checked_add(&input.output.amount)?;
                    output_total = output_total.checked_add(&Value::new(&input_fee))?;
                }
            }
            CoinSelectionStrategyCIP2::LargestFirstMultiAsset => {
                // indices into {available_inputs} for inputs that contain {policy_id}:{asset_name}
                let mut available_indices = (0..available_inputs.len()).collect::<Vec<usize>>();
                // run largest-fist by each asset type
                if let Some(ma) = output_total.multiasset.clone() {
                    for (policy_id, assets) in ma.0.iter() {
                        for (asset_name, _) in assets.0.iter() {
                            self.cip2_largest_first_by(
                                &available_inputs,
                                &mut available_indices,
                                &mut input_total,
                                &mut output_total,
                                |value| value.multiasset.as_ref()?.get(policy_id)?.get(asset_name),
                            )?;
                        }
                    }
                }
                // add in remaining ADA
                self.cip2_largest_first_by(
                    &available_inputs,
                    &mut available_indices,
                    &mut input_total,
                    &mut output_total,
                    |value| Some(value.coin),
                )?;
            }
            CoinSelectionStrategyCIP2::RandomImproveMultiAsset => {
                use rand::Rng;
                let mut rng = rand::thread_rng();
                let mut available_indices =
                    (0..available_inputs.len()).collect::<BTreeSet<usize>>();
                // run random-improve by each asset type
                if let Some(ma) = output_total.multiasset.clone() {
                    for (policy_id, assets) in ma.0.iter() {
                        for (asset_name, _) in assets.0.iter() {
                            self.cip2_random_improve_by(
                                &available_inputs,
                                &mut available_indices,
                                &mut input_total,
                                &mut output_total,
                                |value| value.multiasset.as_ref()?.get(policy_id)?.get(asset_name),
                                &mut rng,
                                false,
                            )?;
                        }
                    }
                }
                // add in remaining ADA
                self.cip2_random_improve_by(
                    &available_inputs,
                    &mut available_indices,
                    &mut input_total,
                    &mut output_total,
                    |value| Some(value.coin),
                    &mut rng,
                    false,
                )?;
                // Phase 3: add extra inputs needed for fees (not covered by CIP-2)
                // We do this at the end because this new inputs won't be associated with
                // a specific output, so the improvement algorithm we do above does not apply here.
                while input_total.coin < output_total.coin {
                    if available_indices.is_empty() {
                        return Err(JsError::from_str("UTxO Balance Insufficient[x]"));
                    }
                    let i = *available_indices
                        .iter()
                        .nth(rng.gen_range(0..available_indices.len()))
                        .unwrap();
                    available_indices.remove(&i);
                    let input = &available_inputs[i];
                    let input_fee = self.fee_for_input(
                        &input.output.address,
                        &input.input,
                        &input.output.amount,
                    )?;
                    self.add_regular_input(
                        &input.output.address,
                        &input.input,
                        &input.output.amount,
                    )?;
                    input_total = input_total.checked_add(&input.output.amount)?;
                    output_total = output_total.checked_add(&Value::new(&input_fee))?;
                }
            }
        }

        Ok(())
    }

    fn cip2_largest_first_by<F>(
        &mut self,
        available_inputs: &Vec<&TransactionUnspentOutput>,
        available_indices: &mut Vec<usize>,
        input_total: &mut Value,
        output_total: &mut Value,
        by: F,
    ) -> Result<(), JsError>
    where
        F: Fn(&Value) -> Option<BigNum>,
    {
        let mut relevant_indices = available_indices.clone();
        relevant_indices.retain(|i| by(&available_inputs[*i].output.amount).is_some());
        // ordered in ascending order by predicate {by}
        relevant_indices
            .sort_by_key(|i| by(&available_inputs[*i].output.amount).expect("filtered above"));

        // iterate in decreasing order for predicate {by}
        for i in relevant_indices.iter().rev() {
            if by(input_total).unwrap_or(BigNum::zero())
                >= by(output_total).expect("do not call on asset types that aren't in the output")
            {
                break;
            }
            let input = &available_inputs[*i];
            // differing from CIP2, we include the needed fees in the targets instead of just output values
            let input_fee =
                self.fee_for_input(&input.output.address, &input.input, &input.output.amount)?;
            self.add_regular_input(&input.output.address, &input.input, &input.output.amount)?;
            *input_total = input_total.checked_add(&input.output.amount)?;
            *output_total = output_total.checked_add(&Value::new(&input_fee))?;
            available_indices.swap_remove(available_indices.iter().position(|j| i == j).unwrap());
        }

        if by(input_total).unwrap_or(BigNum::zero())
            < by(output_total).expect("do not call on asset types that aren't in the output")
        {
            return Err(JsError::from_str("UTxO Balance Insufficient"));
        }

        Ok(())
    }

    fn cip2_random_improve_by<F>(
        &mut self,
        available_inputs: &Vec<&TransactionUnspentOutput>,
        available_indices: &mut BTreeSet<usize>,
        input_total: &mut Value,
        output_total: &mut Value,
        by: F,
        rng: &mut rand::rngs::ThreadRng,
        pure_ada: bool,
    ) -> Result<(), JsError>
    where
        F: Fn(&Value) -> Option<BigNum>,
    {
        use rand::Rng;
        // Phase 1: Random Selection
        let mut relevant_indices = available_indices
            .iter()
            .filter(|i| by(&available_inputs[**i].output.amount).is_some())
            .cloned()
            .collect::<Vec<usize>>();
        let mut associated_indices: BTreeMap<TransactionOutput, Vec<usize>> = BTreeMap::new();
        let mut outputs = self
            .outputs
            .0
            .iter()
            .filter(|output| by(&output.amount).is_some())
            .cloned()
            .collect::<Vec<TransactionOutput>>();
        outputs.sort_by_key(|output| by(&output.amount).expect("filtered above"));
        let mut available_coins = by(input_total).unwrap_or(BigNum::zero());
        for output in outputs.iter().rev() {
            // TODO: how should we adapt this to inputs being associated when running for other assets?
            // if we do these two phases for each asset and don't take into account the other runs for other assets
            // then we over-add (and potentially fail if we don't have plenty of inputs)
            // On the other hand, the improvement phase it difficult to determine if a change is an improvement
            // if we're trying to improve for multiple assets at a time without knowing how important each input is
            // e.g. maybe we have lots of asset A but not much of B
            // For now I will just have this be entirely separarte per-asset but we might want to in a later commit
            // consider the improvements separately and have it take some kind of dot product / distance for assets
            // during the improvement phase and have the improvement phase target multiple asset types at once.
            // One issue with that is how to scale in between differnet assets. We could maybe normalize them by
            // dividing each asset type by the sum of the required asset type in all outputs.
            // Another possibility for adapting this to multiasstes is when associating an input x for asset type a
            // we try and subtract all other assets b != a from the outputs we're trying to cover.
            // It might make sense to diverge further and not consider it per-output and to instead just match against
            // the sum of all outputs as one single value.
            let mut added = available_coins.clone();
            let needed = by(&output.amount).unwrap();
            while added < needed {
                if relevant_indices.is_empty() {
                    return Err(JsError::from_str("UTxO Balance Insufficient"));
                }
                let random_index = rng.gen_range(0..relevant_indices.len());
                let i = relevant_indices.swap_remove(random_index);
                available_indices.remove(&i);
                let input = &available_inputs[i];
                added = added.checked_add(
                    &by(&input.output.amount)
                        .expect("do not call on asset types that aren't in the output"),
                )?;
                associated_indices
                    .entry(output.clone())
                    .or_default()
                    .push(i);
            }
            available_coins = added.checked_sub(&needed)?;
        }
        if !relevant_indices.is_empty() && pure_ada {
            // Phase 2: Improvement
            for output in outputs.iter_mut() {
                let associated = associated_indices.get_mut(output);
                if let Some(associated) = associated {
                    for i in associated.iter_mut() {
                        let random_index = rng.gen_range(0..relevant_indices.len());
                        let j: &mut usize = relevant_indices.get_mut(random_index).unwrap();
                        let input = &available_inputs[*i];
                        let new_input = &available_inputs[*j];
                        let cur: u64 = (&by(&input.output.amount).unwrap_or(BigNum::zero())).into();
                        let new: u64 = (&by(&new_input.output.amount).unwrap_or(BigNum::zero())).into();
                        let min: u64 = (&by(&output.amount).unwrap_or(BigNum::zero())).into();
                        let ideal = 2 * min;
                        let max = 3 * min;
                        let move_closer =
                            (ideal as i128 - new as i128).abs() < (ideal as i128 - cur as i128).abs();
                        let not_exceed_max = new < max;
                        if move_closer && not_exceed_max {
                            std::mem::swap(i, j);
                            available_indices.insert(*i);
                            available_indices.remove(j);
                        }
                    }
                }
            }
        }

        // after finalizing the improvement we need to actually add these results to the builder
        for output in outputs.iter() {
            if let Some(associated) = associated_indices.get(output) {
                for i in associated.iter() {
                    let input = &available_inputs[*i];
                    let input_fee = self.fee_for_input(
                        &input.output.address,
                        &input.input,
                        &input.output.amount,
                    )?;
                    self.add_regular_input(
                        &input.output.address,
                        &input.input,
                        &input.output.amount,
                    )?;
                    *input_total = input_total.checked_add(&input.output.amount)?;
                    *output_total = output_total.checked_add(&Value::new(&input_fee))?;
                }
            }
        }

        Ok(())
    }

    pub fn set_inputs(&mut self, inputs: &TxInputsBuilder) {
        self.inputs = inputs.clone();
    }

    pub fn set_collateral(&mut self, collateral: &TxInputsBuilder) {
        self.collateral = collateral.clone();
    }

    pub fn set_collateral_return(&mut self, collateral_return: &TransactionOutput) {
        self.collateral_return = Some(collateral_return.clone());
    }

    pub fn remove_collateral_return(&mut self) {
        self.collateral_return = None;
    }

    /// This function will set the collateral-return value and then auto-calculate and assign
    /// the total collateral coin value. Will raise an error in case no collateral inputs are set
    /// or in case the total collateral value will have any assets in it except coin.
    pub fn set_collateral_return_and_total(
        &mut self,
        collateral_return: &TransactionOutput,
    ) -> Result<(), JsError> {
        let collateral = &self.collateral;
        if collateral.len() == 0 {
            return Err(JsError::from_str(
                "Cannot calculate total collateral value when collateral inputs are missing",
            ));
        }
        let col_input_value: Value = collateral.total_value()?;
        let total_col: Value = col_input_value.checked_sub(&collateral_return.amount())?;
        if total_col.multiasset.is_some() {
            return Err(JsError::from_str(
                "Total collateral value cannot contain assets!",
            ));
        }

        let min_ada = min_ada_for_output(&collateral_return, &self.config.utxo_cost())?;
        if min_ada > collateral_return.amount.coin {
            return Err(JsError::from_str(&format!(
                "Not enough coin to make return on the collateral value!\
                 Increase amount of return coins. \
                 Min ada for return {}, but was {}",
                min_ada, collateral_return.amount.coin
            )));
        }

        self.set_collateral_return(collateral_return);
        self.total_collateral = Some(total_col.coin);
        Ok(())
    }

    pub fn set_total_collateral(&mut self, total_collateral: &Coin) {
        self.total_collateral = Some(total_collateral.clone());
    }

    pub fn remove_total_collateral(&mut self) {
        self.total_collateral = None;
    }

    /// This function will set the total-collateral coin and then auto-calculate and assign
    /// the collateral return value. Will raise an error in case no collateral inputs are set.
    /// The specified address will be the received of the collateral return
    pub fn set_total_collateral_and_return(
        &mut self,
        total_collateral: &Coin,
        return_address: &Address,
    ) -> Result<(), JsError> {
        let collateral = &self.collateral;
        if collateral.len() == 0 {
            return Err(JsError::from_str(
                "Cannot calculate collateral return when collateral inputs are missing",
            ));
        }
        let col_input_value: Value = collateral.total_value()?;
        let col_return: Value = col_input_value.checked_sub(&Value::new(&total_collateral))?;
        if col_return.multiasset.is_some() || col_return.coin > BigNum::zero() {
            let return_output = TransactionOutput::new(return_address, &col_return);
            let min_ada = min_ada_for_output(&return_output, &self.config.utxo_cost())?;
            if min_ada > col_return.coin {
                return Err(JsError::from_str(&format!(
                    "Not enough coin to make return on the collateral value!\
                 Decrease the total collateral value or add more collateral inputs. \
                 Min ada for return {}, but was {}",
                    min_ada, col_return.coin
                )));
            }
            self.collateral_return = Some(return_output);
        }
        self.set_total_collateral(total_collateral);

        Ok(())
    }

    pub fn add_reference_input(&mut self, reference_input: &TransactionInput) {
        self.reference_inputs.insert(reference_input.clone(), 0);
    }

    pub fn add_script_reference_input(
        &mut self,
        reference_input: &TransactionInput,
        script_size: usize,
    ) {
        self.reference_inputs
            .insert(reference_input.clone(), script_size);
    }

    /// We have to know what kind of inputs these are to know what kind of mock witnesses to create since
    /// 1) mock witnesses have different lengths depending on the type which changes the expecting fee
    /// 2) Witnesses are a set so we need to get rid of duplicates to avoid over-estimating the fee
    #[deprecated(since = "10.2.0", note = "Use `.set_inputs`")]
    pub fn add_key_input(
        &mut self,
        hash: &Ed25519KeyHash,
        input: &TransactionInput,
        amount: &Value,
    ) {
        self.inputs.add_key_input(hash, input, amount);
    }

    /// This method will add the input to the builder and also register the required native script witness
    #[deprecated(since = "10.2.0", note = "Use `.set_inputs`")]
    pub fn add_native_script_input(
        &mut self,
        script: &NativeScript,
        input: &TransactionInput,
        amount: &Value,
    ) {
        self.inputs.add_native_script_input(
            &NativeScriptSource::new(script),
            input,
            amount);
    }

    /// This method will add the input to the builder and also register the required plutus witness
    #[deprecated(since = "10.2.0", note = "Use `.set_inputs`")]
    pub fn add_plutus_script_input(
        &mut self,
        witness: &PlutusWitness,
        input: &TransactionInput,
        amount: &Value,
    ) {
        self.inputs.add_plutus_script_input(witness, input, amount);
    }

    #[deprecated(since = "10.2.0", note = "Use `.set_inputs`")]
    pub fn add_bootstrap_input(
        &mut self,
        hash: &ByronAddress,
        input: &TransactionInput,
        amount: &Value,
    ) {
        self.inputs.add_bootstrap_input(hash, input, amount);
    }

    /// This function is replace for previous one add_input.
    /// The functions adds a non script input, if it is a script input it returns an error.
    /// To add script input you need to use add_native_script_input or add_plutus_script_input.
    /// Also we recommend to use TxInputsBuilder and .set_inputs, because all add_*_input functions might be removed from transaction builder.
    #[deprecated(since = "12.0.0", note = "Use `.set_inputs`")]
    pub fn add_regular_input(
        &mut self,
        address: &Address,
        input: &TransactionInput,
        amount: &Value,
    ) -> Result<(), JsError> {
        self.inputs.add_regular_input(address, input, amount)
    }

    // This method should be used after outputs of the transaction is defined.
    // It will attempt utxo selection initially then add change, if adding change fails
    // then it will attempt to use up the rest of the available inputs, attempting to add change
    // after every extra input.
    pub fn add_inputs_from_and_change(
        &mut self,
        inputs: &TransactionUnspentOutputs,
        strategy: CoinSelectionStrategyCIP2,
        change_config: &ChangeConfig,
    ) -> Result<bool, JsError> {
        self.add_inputs_from(inputs, strategy)?;
        if self.fee.is_some() {
            return Err(JsError::from_str(
                "Cannot calculate change if fee was explicitly specified",
            ))
        }
        let mut add_change_result = self
            .add_change_if_needed_with_optional_script_and_datum(
                &change_config.address,
                change_config
                    .plutus_data
                    .clone()
                    .map_or(None, |od| Some(od.0)),
                change_config.script_ref.clone(),
            );
        match add_change_result {
            Ok(v) => Ok(v),
            Err(e) => {
                let mut unused_inputs = TransactionUnspentOutputs::new();
                for input in inputs.into_iter() {
                    if self
                        .inputs
                        .inputs()
                        .into_iter()
                        .all(|used_input| input.input() != *used_input)
                    {
                        unused_inputs.add(input)
                    }
                }
                unused_inputs.0.sort_by_key(|input| {
                    input
                        .clone()
                        .output
                        .amount
                        .multiasset
                        .map_or(0, |ma| ma.len())
                });
                unused_inputs.0.reverse();
                while unused_inputs.0.len() > 0 {
                    let last_input = unused_inputs.0.pop();
                    match last_input {
                        Some(input) => {
                            self.add_regular_input(
                                &input.output().address(),
                                &input.input(),
                                &input.output().amount(),
                            )?;
                            add_change_result = self
                                .add_change_if_needed_with_optional_script_and_datum(
                                    &change_config.address,
                                    change_config
                                        .plutus_data
                                        .clone()
                                        .map_or(None, |od| Some(od.0)),
                                    change_config.script_ref.clone(),
                                );
                            if let Ok(value) = add_change_result {
                                return Ok(value);
                            }
                        }
                        None => {
                            return Err(JsError::from_str(
                                "Unable to balance tx with available inputs",
                            ))
                        }
                    }
                }
                Err(e)
            }
        }
    }

    // This method should be used after outputs of the transaction is defined.
    // It will attempt to fill the required values using the inputs given.
    // After which, it will attempt to set a collateral return output.
    pub fn add_inputs_from_and_change_with_collateral_return(
        &mut self,
        inputs: &TransactionUnspentOutputs,
        strategy: CoinSelectionStrategyCIP2,
        change_config: &ChangeConfig,
        collateral_percentage: &BigNum,
    ) -> Result<(), JsError> {
        let mut total_collateral = Value::zero();
        for collateral_input in self.collateral.iter() {
            total_collateral = total_collateral.checked_add(&collateral_input.amount)?;
        }

        //set fake max total collateral and return
        self.set_total_collateral(&total_collateral.coin());
        self.set_collateral_return(&TransactionOutput::new(
            &change_config.address,
            &total_collateral,
        ));

        let add_change_result = self.add_inputs_from_and_change(inputs, strategy, change_config);

        self.remove_collateral_return();
        self.remove_total_collateral();

        //check if adding inputs and change was successful
        add_change_result?;

        let fee = self.get_fee_if_set().ok_or(JsError::from_str(
            "Cannot calculate collateral return if fee was not set",
        ))?;

        let collateral_required = fee
            .checked_mul(&collateral_percentage)?
            .div_floor(&BigNum(100))
            .checked_add(&BigNum::one())?;
        let set_collateral_result =
            self.set_total_collateral_and_return(&collateral_required, &change_config.address);

        if let Err(e) = set_collateral_result {
            self.remove_collateral_return();
            self.remove_total_collateral();
            return Err(e);
        }

        Ok(())
    }

    /// Returns a copy of the current script input witness scripts in the builder
    #[deprecated(since = "10.2.0", note = "Use `.set_inputs`")]
    pub fn get_native_input_scripts(&self) -> Option<NativeScripts> {
        self.inputs.get_native_input_scripts()
    }

    /// Returns a copy of the current plutus input witness scripts in the builder.
    /// NOTE: each plutus witness will be cloned with a specific corresponding input index
    #[deprecated(since = "10.2.0", note = "Use `.set_inputs`")]
    pub fn get_plutus_input_scripts(&self) -> Option<PlutusWitnesses> {
        self.inputs.get_plutus_input_scripts()
    }

    /// calculates how much the fee would increase if you added a given output
    pub fn fee_for_input(
        &self,
        address: &Address,
        input: &TransactionInput,
        amount: &Value,
    ) -> Result<Coin, JsError> {
        let mut self_copy = self.clone();

        // we need some value for these for it to be a a valid transaction
        // but since we're only calculating the difference between the fee of two transactions
        // it doesn't matter what these are set as, since it cancels out
        self_copy.set_fee(&BigNum::zero());

        let fee_before = min_fee(&self_copy)?;

        self_copy.add_regular_input(&address, &input, &amount)?;
        let fee_after = min_fee(&self_copy)?;
        fee_after.checked_sub(&fee_before)
    }

    /// Add explicit output via a TransactionOutput object
    pub fn add_output(&mut self, output: &TransactionOutput) -> Result<(), JsError> {
        let value_size = output.amount.to_bytes().len();
        if value_size > self.config.max_value_size as usize {
            return Err(JsError::from_str(&format!(
                "Maximum value size of {} exceeded. Found: {}",
                self.config.max_value_size, value_size
            )));
        }
        let min_ada = min_ada_for_output(&output, &self.config.utxo_cost())?;
        if output.amount().coin() < min_ada {
            Err(JsError::from_str(&format!(
                "Value {} less than the minimum UTXO value {}",
                output.amount().coin(),
                min_ada
            )))
        } else {
            self.outputs.add(output);
            Ok(())
        }
    }

    /// calculates how much the fee would increase if you added a given output
    pub fn fee_for_output(&self, output: &TransactionOutput) -> Result<Coin, JsError> {
        let mut self_copy = self.clone();

        // we need some value for these for it to be a a valid transaction
        // but since we're only calculating the different between the fee of two transactions
        // it doesn't matter what these are set as, since it cancels out
        self_copy.set_fee(&BigNum::zero());

        let fee_before = min_fee(&self_copy)?;

        self_copy.add_output(&output)?;
        let fee_after = min_fee(&self_copy)?;
        fee_after.checked_sub(&fee_before)
    }

    pub fn set_fee(&mut self, fee: &Coin) {
        self.fee = Some(fee.clone())
    }

    /// !!! DEPRECATED !!!
    /// Set ttl value.
    #[deprecated(
        since = "10.1.0",
        note = "Underlying value capacity of ttl (BigNum u64) bigger then Slot32. Use set_ttl_bignum instead."
    )]
    pub fn set_ttl(&mut self, ttl: Slot32) {
        self.ttl = Some(ttl.into())
    }

    pub fn set_ttl_bignum(&mut self, ttl: &SlotBigNum) {
        self.ttl = Some(ttl.clone())
    }

    pub fn remove_ttl(&mut self) {
        self.ttl = None;
    }

    /// !!! DEPRECATED !!!
    /// Uses outdated slot number format.
    #[deprecated(
        since = "10.1.0",
        note = "Underlying value capacity of validity_start_interval (BigNum u64) bigger then Slot32. Use set_validity_start_interval_bignum instead."
    )]
    pub fn set_validity_start_interval(&mut self, validity_start_interval: Slot32) {
        self.validity_start_interval = Some(validity_start_interval.into())
    }

    pub fn set_validity_start_interval_bignum(&mut self, validity_start_interval: SlotBigNum) {
        self.validity_start_interval = Some(validity_start_interval.clone())
    }

    pub fn remove_validity_start_interval(&mut self) {
        self.validity_start_interval = None;
    }

    /// !!! DEPRECATED !!!
    /// Can emit error if add a cert with script credential.
    /// Use set_certs_builder instead.
    #[deprecated(
        since = "11.4.1",
        note = "Can emit an error if you add a cert with script credential. Use set_certs_builder instead."
    )]
    pub fn set_certs(&mut self, certs: &Certificates) -> Result<(), JsError> {
        let mut builder = CertificatesBuilder::new();
        for cert in &certs.certs {
            builder.add(cert)?;
        }

        self.certs = Some(builder);

        Ok(())
    }

    pub fn remove_certs(&mut self) {
        self.certs = None;
    }

    pub fn set_certs_builder(&mut self, certs: &CertificatesBuilder) {
        self.certs = Some(certs.clone());
    }

    /// !!! DEPRECATED !!!
    /// Can emit error if add a withdrawal with script credential.
    /// Use set_withdrawals_builder instead.
    #[deprecated(
        since = "11.4.1",
        note = "Can emit an error if you add a withdrawal with script credential. Use set_withdrawals_builder instead."
    )]
    pub fn set_withdrawals(&mut self, withdrawals: &Withdrawals) -> Result<(), JsError> {
        let mut withdrawals_builder = WithdrawalsBuilder::new();
        for (withdrawal, coin) in &withdrawals.0 {
            withdrawals_builder.add(&withdrawal, &coin)?;
        }

        self.withdrawals = Some(withdrawals_builder);

        Ok(())
    }

    pub fn set_withdrawals_builder(&mut self, withdrawals: &WithdrawalsBuilder) {
        self.withdrawals = Some(withdrawals.clone());
    }

    pub fn set_voting_builder(&mut self, voting_builder: &VotingBuilder) {
        self.voting_procedures = Some(voting_builder.clone());
    }

    pub fn set_voting_proposal_builder(&mut self, voting_proposal_builder: &VotingProposalBuilder) {
        self.voting_proposals = Some(voting_proposal_builder.clone());
    }

    pub fn remove_withdrawals(&mut self) {
        self.withdrawals = None;
    }

    pub fn get_auxiliary_data(&self) -> Option<AuxiliaryData> {
        self.auxiliary_data.clone()
    }

    /// Set explicit auxiliary data via an AuxiliaryData object
    /// It might contain some metadata plus native or Plutus scripts
    pub fn set_auxiliary_data(&mut self, auxiliary_data: &AuxiliaryData) {
        self.auxiliary_data = Some(auxiliary_data.clone())
    }

    pub fn remove_auxiliary_data(&mut self) {
        self.auxiliary_data = None;
    }

    /// Set metadata using a GeneralTransactionMetadata object
    /// It will be set to the existing or new auxiliary data in this builder
    pub fn set_metadata(&mut self, metadata: &GeneralTransactionMetadata) {
        let mut aux = self
            .auxiliary_data
            .as_ref()
            .cloned()
            .unwrap_or(AuxiliaryData::new());
        aux.set_metadata(metadata);
        self.set_auxiliary_data(&aux);
    }

    /// Add a single metadatum using TransactionMetadatumLabel and TransactionMetadatum objects
    /// It will be securely added to existing or new metadata in this builder
    pub fn add_metadatum(&mut self, key: &TransactionMetadatumLabel, val: &TransactionMetadatum) {
        let mut metadata = self
            .auxiliary_data
            .as_ref()
            .map(|aux| aux.metadata().as_ref().cloned())
            .unwrap_or(None)
            .unwrap_or(GeneralTransactionMetadata::new());
        metadata.insert(key, val);
        self.set_metadata(&metadata);
    }

    /// Add a single JSON metadatum using a TransactionMetadatumLabel and a String
    /// It will be securely added to existing or new metadata in this builder
    pub fn add_json_metadatum(
        &mut self,
        key: &TransactionMetadatumLabel,
        val: String,
    ) -> Result<(), JsError> {
        self.add_json_metadatum_with_schema(key, val, MetadataJsonSchema::NoConversions)
    }

    /// Add a single JSON metadatum using a TransactionMetadatumLabel, a String, and a MetadataJsonSchema object
    /// It will be securely added to existing or new metadata in this builder
    pub fn add_json_metadatum_with_schema(
        &mut self,
        key: &TransactionMetadatumLabel,
        val: String,
        schema: MetadataJsonSchema,
    ) -> Result<(), JsError> {
        let metadatum = encode_json_str_to_metadatum(val, schema)?;
        self.add_metadatum(key, &metadatum);
        Ok(())
    }

    pub fn set_mint_builder(&mut self, mint_builder: &MintBuilder) {
        self.mint = Some(mint_builder.clone());
    }

    pub fn remove_mint_builder(&mut self) {
        self.mint = None;
    }

    pub fn get_mint_builder(&self) -> Option<MintBuilder> {
        self.mint.clone()
    }

    /// !!! DEPRECATED !!!
    /// Mints are defining by MintBuilder now.
    /// Use `.set_mint_builder()` and `MintBuilder` instead.
    #[deprecated(
        since = "11.2.0",
        note = "Mints are defining by MintBuilder now. Use `.set_mint_builder()` and `MintBuilder` instead."
    )]
    /// Set explicit Mint object and the required witnesses to this builder
    /// it will replace any previously existing mint and mint scripts
    /// NOTE! Error will be returned in case a mint policy does not have a matching script
    pub fn set_mint(&mut self, mint: &Mint, mint_scripts: &NativeScripts) -> Result<(), JsError> {
        assert_required_mint_scripts(mint, Some(mint_scripts))?;
        let mut scripts_policies = HashMap::new();
        for scipt in mint_scripts {
            scripts_policies.insert(scipt.hash(), scipt.clone());
        }

        let mut mint_builder = MintBuilder::new();

        for (policy_id, asset_map) in &mint.0 {
            for (asset_name, amount) in &asset_map.0 {
                if let Some(script) = scripts_policies.get(policy_id) {
                    let native_script_source = NativeScriptSource::new(script);
                    let mint_witness = MintWitness::new_native_script(&native_script_source);
                    mint_builder.set_asset(&mint_witness, asset_name, amount)?;
                } else {
                    return Err(JsError::from_str(
                        "Mint policy does not have a matching script",
                    ));
                }
            }
        }
        self.mint = Some(mint_builder);
        Ok(())
    }

    /// !!! DEPRECATED !!!
    /// Mints are defining by MintBuilder now.
    /// Use `.get_mint_builder()` and `.build()` instead.
    #[deprecated(
        since = "11.2.0",
        note = "Mints are defining by MintBuilder now. Use `.get_mint_builder()` and `.build()` instead."
    )]
    /// Returns a copy of the current mint state in the builder
    pub fn get_mint(&self) -> Option<Mint> {
        match &self.mint {
            Some(mint) => Some(mint.build().expect("MintBuilder is invalid")),
            None => None,
        }
    }

    /// Returns a copy of the current mint witness scripts in the builder
    pub fn get_mint_scripts(&self) -> Option<NativeScripts> {
        match &self.mint {
            Some(mint) => Some(mint.get_native_scripts()),
            None => None,
        }
    }

    /// !!! DEPRECATED !!!
    /// Mints are defining by MintBuilder now.
    /// Use `.set_mint_builder()` and `MintBuilder` instead.
    #[deprecated(
        since = "11.2.0",
        note = "Mints are defining by MintBuilder now. Use `.set_mint_builder()` and `MintBuilder` instead."
    )]
    /// Add a mint entry to this builder using a PolicyID and MintAssets object
    /// It will be securely added to existing or new Mint in this builder
    /// It will replace any existing mint assets with the same PolicyID
    pub fn set_mint_asset(&mut self, policy_script: &NativeScript, mint_assets: &MintAssets) -> Result<(), JsError> {
        let native_script_source = NativeScriptSource::new(policy_script);
        let mint_witness = MintWitness::new_native_script(&native_script_source);
        if let Some(mint) = &mut self.mint {
            for (asset, amount) in mint_assets.0.iter() {
                mint.set_asset(&mint_witness, asset, amount)?;
            }
        } else {
            let mut mint = MintBuilder::new();
            for (asset, amount) in mint_assets.0.iter() {
                mint.set_asset(&mint_witness, asset, amount)?;
            }
            self.mint = Some(mint);
        }
        Ok(())
    }

    /// !!! DEPRECATED !!!
    /// Mints are defining by MintBuilder now.
    /// Use `.set_mint_builder()` and `MintBuilder` instead.
    #[deprecated(
        since = "11.2.0",
        note = "Mints are defining by MintBuilder now. Use `.set_mint_builder()` and `MintBuilder` instead."
    )]
    /// Add a mint entry to this builder using a PolicyID, AssetName, and Int object for amount
    /// It will be securely added to existing or new Mint in this builder
    /// It will replace any previous existing amount same PolicyID and AssetName
    pub fn add_mint_asset(
        &mut self,
        policy_script: &NativeScript,
        asset_name: &AssetName,
        amount: &Int,
    ) -> Result<(), JsError> {
        let native_script_source = NativeScriptSource::new(policy_script);
        let mint_witness = MintWitness::new_native_script(&native_script_source);
        if let Some(mint) = &mut self.mint {
            mint.add_asset(&mint_witness, asset_name, &amount)?;
        } else {
            let mut mint = MintBuilder::new();
            mint.add_asset(&mint_witness, asset_name, &amount)?;
            self.mint = Some(mint);
        }
        Ok(())
    }

    /// Add a mint entry together with an output to this builder
    /// Using a PolicyID, AssetName, Int for amount, Address, and Coin (BigNum) objects
    /// The asset will be securely added to existing or new Mint in this builder
    /// A new output will be added with the specified Address, the Coin value, and the minted asset
    pub fn add_mint_asset_and_output(
        &mut self,
        policy_script: &NativeScript,
        asset_name: &AssetName,
        amount: &Int,
        output_builder: &TransactionOutputAmountBuilder,
        output_coin: &Coin,
    ) -> Result<(), JsError> {
        if !amount.is_positive() {
            return Err(JsError::from_str("Output value must be positive!"));
        }
        let policy_id: PolicyID = policy_script.hash();
        self.add_mint_asset(policy_script, asset_name, amount)?;
        let multiasset =
            Mint::new_from_entry(&policy_id, &MintAssets::new_from_entry(asset_name, amount)?)
                .as_positive_multiasset();

        self.add_output(
            &output_builder
                .with_coin_and_asset(&output_coin, &multiasset)
                .build()?,
        )
    }

    /// Add a mint entry together with an output to this builder
    /// Using a PolicyID, AssetName, Int for amount, and Address objects
    /// The asset will be securely added to existing or new Mint in this builder
    /// A new output will be added with the specified Address and the minted asset
    /// The output will be set to contain the minimum required amount of Coin
    pub fn add_mint_asset_and_output_min_required_coin(
        &mut self,
        policy_script: &NativeScript,
        asset_name: &AssetName,
        amount: &Int,
        output_builder: &TransactionOutputAmountBuilder,
    ) -> Result<(), JsError> {
        if !amount.is_positive() {
            return Err(JsError::from_str("Output value must be positive!"));
        }
        let policy_id: PolicyID = policy_script.hash();
        self.add_mint_asset(policy_script, asset_name, amount)?;
        let multiasset =
            Mint::new_from_entry(&policy_id, &MintAssets::new_from_entry(asset_name, amount)?)
                .as_positive_multiasset();

        self.add_output(
            &output_builder
                .with_asset_and_min_required_coin_by_utxo_cost(
                    &multiasset,
                    &self.config.utxo_cost(),
                )?
                .build()?,
        )
    }

    pub fn add_extra_witness_datum(&mut self, datum: &PlutusData) {
        if let Some(extra_datums) = &mut self.extra_datums {
            extra_datums.add(datum);
        } else {
            let mut extra_datums = PlutusList::new();
            extra_datums.add(datum);
            self.extra_datums = Some(extra_datums);
        }
    }

    pub fn get_extra_witness_datums(&self) -> Option<PlutusList> {
        self.extra_datums.clone()
    }

    pub fn set_donation(&mut self, donation: &Coin) {
        self.donation = Some(donation.clone());
    }

    pub fn get_donation(&self) -> Option<Coin> {
        self.donation.clone()
    }

    pub fn set_current_treasury_value(
        &mut self,
        current_treasury_value: &Coin,
    ) -> Result<(), JsError> {
        if current_treasury_value == &Coin::zero() {
            return Err(JsError::from_str("Current treasury value cannot be zero!"));
        }
        self.current_treasury_value = Some(current_treasury_value.clone());
        Ok(())
    }

    pub fn get_current_treasury_value(&self) -> Option<Coin> {
        self.current_treasury_value.clone()
    }

    pub fn new(cfg: &TransactionBuilderConfig) -> Self {
        Self {
            config: cfg.clone(),
            inputs: TxInputsBuilder::new(),
            collateral: TxInputsBuilder::new(),
            outputs: TransactionOutputs::new(),
            fee: None,
            ttl: None,
            certs: None,
            withdrawals: None,
            auxiliary_data: None,
            validity_start_interval: None,
            mint: None,
            script_data_hash: None,
            required_signers: Ed25519KeyHashes::new(),
            collateral_return: None,
            total_collateral: None,
            reference_inputs: HashMap::new(),
            extra_datums: None,
            voting_procedures: None,
            voting_proposals: None,
            donation: None,
            current_treasury_value: None,
        }
    }

    pub fn get_reference_inputs(&self) -> TransactionInputs {
        let mut inputs: HashSet<TransactionInput> = HashSet::new();

        let mut add_ref_inputs_set = |ref_inputs: TransactionInputs| {
            for input in &ref_inputs {
                if !self.inputs.has_input(&input) {
                    inputs.insert(input.clone());
                }
            }
        };

        add_ref_inputs_set(self.inputs.get_ref_inputs());

        if let Some(mint) = &self.mint {
            add_ref_inputs_set(mint.get_ref_inputs());
        }

        if let Some(withdrawals) = &self.withdrawals {
            add_ref_inputs_set(withdrawals.get_ref_inputs());
        }

        if let Some(certs) = &self.certs {
            add_ref_inputs_set(certs.get_ref_inputs());
        }

        if let Some(voting_procedures) = &self.voting_procedures {
            add_ref_inputs_set(voting_procedures.get_ref_inputs());
        }

        if let Some(voting_proposals) = &self.voting_proposals {
            add_ref_inputs_set(voting_proposals.get_ref_inputs());
        }

        if self.config.deduplicate_explicit_ref_inputs_with_regular_inputs {
            add_ref_inputs_set(TransactionInputs::from_vec(
                self.reference_inputs.keys().cloned().collect())
            )
        } else {
            for input in self.reference_inputs.keys().cloned() {
                inputs.insert(input);
            }
        }

        let vec_inputs = inputs.into_iter().collect();
        TransactionInputs::from_vec(vec_inputs)
    }

    fn validate_inputs_intersection(&self) -> Result<(), JsError> {
        let ref_inputs = self.get_reference_inputs();
        for input in &ref_inputs {
            if self.inputs.has_input(input) {
                return Err(JsError::from_str(&format!(
                    "The reference input {:?} is also present in the regular transaction inputs set. \
    It's not allowed to have the same inputs in both the transaction's inputs set and the reference inputs set. \
    You can use the `deduplicate_explicit_ref_inputs_with_regular_inputs` parameter in the `TransactionConfigBuilder` \
    to enforce the removal of duplicate reference inputs."
                    , input)));
            }
        }
        Ok(())
    }

    fn get_total_ref_scripts_size(&self) -> Result<usize, JsError> {
        let mut sizes_map = HashMap::new();
        fn add_to_map<'a>(
            item: (&'a TransactionInput, usize),
            sizes_map: &mut HashMap<&'a TransactionInput, usize>,
        ) -> Result<(), JsError> {
            if sizes_map.entry(item.0).or_insert(item.1) != &item.1 {
                Err(JsError::from_str(&format!(
                    "Different script sizes for the same ref input {}",
                    item.0
                )))
            } else {
                Ok(())
            }
        }

        for item in self.inputs.get_script_ref_inputs_with_size() {
            add_to_map(item, &mut sizes_map)?
        }

        for (tx_in, size) in &self.reference_inputs {
            add_to_map((tx_in, *size), &mut sizes_map)?
        }

        if let Some(mint) = &self.mint {
            for item in mint.get_script_ref_inputs_with_size() {
                add_to_map(item, &mut sizes_map)?
            }
        }

        if let Some(withdrawals) = &self.withdrawals {
            for item in withdrawals.get_script_ref_inputs_with_size() {
                add_to_map(item, &mut sizes_map)?
            }
        }

        if let Some(certs) = &self.certs {
            for item in certs.get_script_ref_inputs_with_size() {
                add_to_map(item, &mut sizes_map)?
            }
        }

        if let Some(voting_procedures) = &self.voting_procedures {
            for item in voting_procedures.get_script_ref_inputs_with_size() {
                add_to_map(item, &mut sizes_map)?
            }
        }

        if let Some(voting_proposals) = &self.voting_proposals {
            for item in voting_proposals.get_script_ref_inputs_with_size() {
                add_to_map(item, &mut sizes_map)?
            }
        }

        Ok(sizes_map.values().sum())
    }

    /// does not include refunds or withdrawals
    pub fn get_explicit_input(&self) -> Result<Value, JsError> {
        self.inputs
            .iter()
            .try_fold(Value::zero(), |acc, ref tx_builder_input| {
                acc.checked_add(&tx_builder_input.amount)
            })
    }

    /// withdrawals and refunds
    pub fn get_implicit_input(&self) -> Result<Value, JsError> {
        let mut implicit_input = Value::zero();
        if let Some(withdrawals) = &self.withdrawals {
            implicit_input = implicit_input.checked_add(&withdrawals.get_total_withdrawals()?)?;
        }
        if let Some(refunds) = &self.certs {
            implicit_input = implicit_input.checked_add(
                &refunds
                    .get_certificates_refund(&self.config.pool_deposit, &self.config.key_deposit)?,
            )?;
        }

        Ok(implicit_input)
    }

    /// Returns mint as tuple of (mint_value, burn_value) or two zero values
    fn get_mint_as_values(&self) -> (Value, Value) {
        self.mint
            .as_ref()
            .map(|m| {
                let mint = m.build_unchecked();
                (
                    Value::new_from_assets(&mint.as_positive_multiasset()),
                    Value::new_from_assets(&mint.as_negative_multiasset()),
                )
            })
            .unwrap_or((Value::zero(), Value::zero()))
    }

    /// Return explicit input plus implicit input plus mint
    pub fn get_total_input(&self) -> Result<Value, JsError> {
        let (mint_value, _) = self.get_mint_as_values();
        self.get_explicit_input()?
            .checked_add(&self.get_implicit_input()?)?
            .checked_add(&mint_value)
    }

    /// Return explicit output plus deposit plus burn
    pub fn get_total_output(&self) -> Result<Value, JsError> {
        let (_, burn_value) = self.get_mint_as_values();
        let mut total = self
            .get_explicit_output()?
            .checked_add(&Value::new(&self.get_deposit()?))?
            .checked_add(&burn_value)?;
        if let Some(donation) = &self.donation {
            total = total.checked_add(&Value::new(donation))?;
        }
        Ok(total)
    }

    /// does not include fee
    pub fn get_explicit_output(&self) -> Result<Value, JsError> {
        self.outputs
            .0
            .iter()
            .try_fold(Value::new(&BigNum::zero()), |acc, ref output| {
                acc.checked_add(&output.amount())
            })
    }

    pub fn get_deposit(&self) -> Result<Coin, JsError> {
        let mut total_deposit = Coin::zero();
        if let Some(certs) = &self.certs {
            total_deposit =
                total_deposit.checked_add(&certs.get_certificates_deposit(
                    &self.config.pool_deposit,
                    &self.config.key_deposit,
                )?)?;
        }

        if let Some(voting_proposal_builder) = &self.voting_proposals {
            total_deposit =
                total_deposit.checked_add(&voting_proposal_builder.get_total_deposit()?)?;
        }

        Ok(total_deposit)
    }

    pub fn get_fee_if_set(&self) -> Option<Coin> {
        self.fee.clone()
    }

    /// Warning: this function will mutate the /fee/ field
    /// Make sure to call this function last after setting all other tx-body properties
    /// Editing inputs, outputs, mint, etc. after change been calculated
    /// might cause a mismatch in calculated fee versus the required fee
    pub fn add_change_if_needed(&mut self, address: &Address) -> Result<bool, JsError> {
        self.add_change_if_needed_with_optional_script_and_datum(address, None, None)
    }

    pub fn add_change_if_needed_with_datum(
        &mut self,
        address: &Address,
        plutus_data: &OutputDatum,
    ) -> Result<bool, JsError> {
        self.add_change_if_needed_with_optional_script_and_datum(
            address,
            Some(plutus_data.0.clone()),
            None,
        )
    }

    fn add_change_if_needed_with_optional_script_and_datum(
        &mut self,
        address: &Address,
        plutus_data: Option<DataOption>,
        script_ref: Option<ScriptRef>,
    ) -> Result<bool, JsError> {
        let fee = match &self.fee {
            None => self.min_fee(),
            // generating the change output involves changing the fee
            Some(_x) => {
                return Err(JsError::from_str(
                    "Cannot calculate change if fee was explicitly specified",
                ))
            }
        }?;

        let input_total = self.get_total_input()?;
        let output_total = self.get_total_output()?;

        let shortage = get_input_shortage(&input_total, &output_total, &fee)?;
        if let Some(shortage) = shortage {
            return Err(JsError::from_str(&format!(
                "Insufficient input in transaction. {}",
                shortage
            )));
        }

        use std::cmp::Ordering;
        match &input_total.partial_cmp(&output_total.checked_add(&Value::new(&fee))?) {
            Some(Ordering::Equal) => {
                // recall: min_fee assumed the fee was the maximum possible so we definitely have enough input to cover whatever fee it ends up being
                self.set_fee(&input_total.checked_sub(&output_total)?.coin());
                Ok(false)
            }
            Some(Ordering::Less) => Err(JsError::from_str("Insufficient input in transaction")),
            Some(Ordering::Greater) => {
                fn has_assets(ma: Option<MultiAsset>) -> bool {
                    ma.map(|assets| assets.len() > 0).unwrap_or(false)
                }
                let change_estimator = input_total.checked_sub(&output_total)?;
                if has_assets(change_estimator.multiasset()) {
                    fn will_adding_asset_make_output_overflow(
                        output: &TransactionOutput,
                        current_assets: &Assets,
                        asset_to_add: (PolicyID, AssetName, BigNum),
                        max_value_size: u32,
                        data_cost: &DataCost,
                    ) -> Result<bool, JsError> {
                        let (policy, asset_name, value) = asset_to_add;
                        let mut current_assets_clone = current_assets.clone();
                        current_assets_clone.insert(&asset_name, &value);
                        let mut amount_clone = output.amount.clone();
                        let mut val = Value::new(&Coin::zero());
                        let mut ma = MultiAsset::new();

                        ma.insert(&policy, &current_assets_clone);
                        val.set_multiasset(&ma);
                        amount_clone = amount_clone.checked_add(&val)?;

                        // calculate minADA for more precise max value size
                        let mut calc = MinOutputAdaCalculator::new_empty(data_cost)?;
                        calc.set_amount(&val);
                        let min_ada = calc.calculate_ada()?;
                        amount_clone.set_coin(&min_ada);

                        Ok(amount_clone.to_bytes().len() > max_value_size as usize)
                    }
                    fn pack_nfts_for_change(
                        max_value_size: u32,
                        data_cost: &DataCost,
                        change_address: &Address,
                        change_estimator: &Value,
                        plutus_data: &Option<DataOption>,
                        script_ref: &Option<ScriptRef>,
                    ) -> Result<Vec<MultiAsset>, JsError> {
                        // we insert the entire available ADA temporarily here since that could potentially impact the size
                        // as it could be 1, 2 3 or 4 bytes for Coin.
                        let mut change_assets: Vec<MultiAsset> = Vec::new();

                        let mut base_coin = Value::new(&change_estimator.coin());
                        base_coin.set_multiasset(&MultiAsset::new());
                        let mut output = TransactionOutput {
                            address: change_address.clone(),
                            amount: base_coin.clone(),
                            plutus_data: plutus_data.clone(),
                            script_ref: script_ref.clone(),
                            serialization_format: None,
                        };
                        // If this becomes slow on large TXs we can optimize it like the following
                        // to avoid cloning + reserializing the entire output.
                        // This would probably be more relevant if we use a smarter packing algorithm
                        // which might need to compare more size differences than greedy
                        //let mut bytes_used = output.to_bytes().len();

                        // a greedy packing is done here to avoid an exponential bin-packing
                        // which in most cases likely shouldn't be the difference between
                        // having an extra change output or not unless there are gigantic
                        // differences in NFT policy sizes
                        for (policy, assets) in change_estimator.multiasset().unwrap().0.iter() {
                            // for simplicity we also don't split assets within a single policy since
                            // you would need to have a very high amoun of assets (which add 1-36 bytes each)
                            // in a single policy to make a difference. In the future if this becomes an issue
                            // we can change that here.

                            // this is the other part of the optimization but we need to take into account
                            // the difference between CBOR encoding which can change which happens in two places:
                            // a) length within assets of one policy id
                            // b) length of the entire multiasset
                            // so for simplicity we will just do it the safe, naive way unless
                            // performance becomes an issue.
                            //let extra_bytes = policy.to_bytes().len() + assets.to_bytes().len() + 2 + cbor_len_diff;
                            //if bytes_used + extra_bytes <= max_value_size as usize {
                            let mut old_amount = output.amount.clone();
                            let mut val = Value::new(&Coin::zero());
                            let mut next_nft = MultiAsset::new();

                            let asset_names = assets.keys();
                            let mut rebuilt_assets = Assets::new();
                            for n in 0..asset_names.len() {
                                let asset_name = asset_names.get(n);
                                let value = assets.get(&asset_name).unwrap();

                                if will_adding_asset_make_output_overflow(
                                    &output,
                                    &rebuilt_assets,
                                    (policy.clone(), asset_name.clone(), value),
                                    max_value_size,
                                    data_cost,
                                )? {
                                    // if we got here, this means we will run into a overflow error,
                                    // so we want to split into multiple outputs, for that we...

                                    // 1. insert the current assets as they are, as this won't overflow
                                    next_nft.insert(policy, &rebuilt_assets);
                                    val.set_multiasset(&next_nft);
                                    output.amount = output.amount.checked_add(&val)?;
                                    change_assets.push(output.amount.multiasset().unwrap());

                                    // 2. create a new output with the base coin value as zero
                                    base_coin = Value::new(&Coin::zero());
                                    base_coin.set_multiasset(&MultiAsset::new());
                                    output = TransactionOutput {
                                        address: change_address.clone(),
                                        amount: base_coin.clone(),
                                        plutus_data: plutus_data.clone(),
                                        script_ref: script_ref.clone(),
                                        serialization_format: None,
                                    };

                                    // 3. continue building the new output from the asset we stopped
                                    old_amount = output.amount.clone();
                                    val = Value::new(&Coin::zero());
                                    next_nft = MultiAsset::new();

                                    rebuilt_assets = Assets::new();
                                }

                                rebuilt_assets.insert(&asset_name, &value);
                            }

                            next_nft.insert(policy, &rebuilt_assets);
                            val.set_multiasset(&next_nft);
                            output.amount = output.amount.checked_add(&val)?;

                            // calculate minADA for more precise max value size
                            let mut amount_clone = output.amount.clone();
                            let mut calc = MinOutputAdaCalculator::new_empty(data_cost)?;
                            calc.set_amount(&val);
                            let min_ada = calc.calculate_ada()?;
                            amount_clone.set_coin(&min_ada);

                            if amount_clone.to_bytes().len() > max_value_size as usize {
                                output.amount = old_amount;
                                break;
                            }
                        }
                        change_assets.push(output.amount.multiasset().unwrap());
                        Ok(change_assets)
                    }
                    let mut change_left = input_total.checked_sub(&output_total)?;
                    let mut new_fee = fee.clone();
                    // we might need multiple change outputs for cases where the change has many asset types
                    // which surpass the max UTXO size limit
                    let utxo_cost = self.config.utxo_cost();
                    let mut calc = MinOutputAdaCalculator::new_empty(&utxo_cost)?;
                    if let Some(data) = &plutus_data {
                        match data {
                            DataOption::DataHash(data_hash) => calc.set_data_hash(data_hash),
                            DataOption::Data(datum) => calc.set_plutus_data(datum),
                        };
                    }
                    if let Some(script_ref) = &script_ref {
                        calc.set_script_ref(script_ref);
                    }
                    let minimum_utxo_val = calc.calculate_ada()?;
                    while let Some(Ordering::Greater) = change_left
                        .multiasset
                        .as_ref()
                        .map_or_else(|| None, |ma| ma.partial_cmp(&MultiAsset::new()))
                    {
                        let nft_changes = pack_nfts_for_change(
                            self.config.max_value_size,
                            &utxo_cost,
                            address,
                            &change_left,
                            &plutus_data.clone(),
                            &script_ref.clone(),
                        )?;
                        if nft_changes.len() == 0 {
                            // this likely should never happen
                            return Err(JsError::from_str("NFTs too large for change output"));
                        }
                        // we only add the minimum needed (for now) to cover this output
                        let mut change_value = Value::new(&Coin::zero());
                        for nft_change in nft_changes.iter() {
                            change_value.set_multiasset(&nft_change);
                            let mut calc = MinOutputAdaCalculator::new_empty(&utxo_cost)?;
                            //TODO add precise calculation
                            let mut fake_change = change_value.clone();
                            fake_change.set_coin(&change_left.coin);
                            calc.set_amount(&fake_change);
                            if let Some(data) = &plutus_data {
                                match data {
                                    DataOption::DataHash(data_hash) => {
                                        calc.set_data_hash(data_hash)
                                    }
                                    DataOption::Data(datum) => calc.set_plutus_data(datum),
                                };
                            }
                            if let Some(script_ref) = &script_ref {
                                calc.set_script_ref(script_ref);
                            }
                            let min_ada = calc.calculate_ada()?;
                            change_value.set_coin(&min_ada);
                            let change_output = TransactionOutput {
                                address: address.clone(),
                                amount: change_value.clone(),
                                plutus_data: plutus_data.clone(),
                                script_ref: script_ref.clone(),
                                serialization_format: None,
                            };

                            // increase fee
                            let fee_for_change = self.fee_for_output(&change_output)?;
                            new_fee = new_fee.checked_add(&fee_for_change)?;
                            if change_left.coin() < min_ada.checked_add(&new_fee)? {
                                return Err(JsError::from_str("Not enough ADA leftover to include non-ADA assets in a change address"));
                            }
                            change_left = change_left.checked_sub(&change_value)?;
                            self.add_output(&change_output)?;
                        }
                    }
                    change_left = change_left.checked_sub(&Value::new(&new_fee))?;
                    // add potentially a separate pure ADA change output
                    let left_above_minimum = change_left.coin.compare(&minimum_utxo_val) > 0;
                    if self.config.prefer_pure_change && left_above_minimum {
                        let pure_output = TransactionOutput {
                            address: address.clone(),
                            amount: change_left.clone(),
                            plutus_data: plutus_data.clone(),
                            script_ref: script_ref.clone(),
                            serialization_format: None,
                        };
                        let additional_fee = self.fee_for_output(&pure_output)?;
                        let potential_pure_value =
                            change_left.checked_sub(&Value::new(&additional_fee))?;
                        let potential_pure_above_minimum =
                            potential_pure_value.coin.compare(&minimum_utxo_val) > 0;
                        if potential_pure_above_minimum {
                            new_fee = new_fee.checked_add(&additional_fee)?;
                            change_left = Value::zero();
                            self.add_output(&TransactionOutput {
                                address: address.clone(),
                                amount: potential_pure_value.clone(),
                                plutus_data: plutus_data.clone(),
                                script_ref: script_ref.clone(),
                                serialization_format: None,
                            })?;
                        }
                    }
                    self.set_fee(&new_fee);
                    // add in the rest of the ADA
                    if !change_left.is_zero() {
                        self.outputs.0.last_mut().unwrap().amount = self
                            .outputs
                            .0
                            .last()
                            .unwrap()
                            .amount
                            .checked_add(&change_left)?;
                    }
                    Ok(true)
                } else {
                    let mut calc = MinOutputAdaCalculator::new_empty(&self.config.utxo_cost())?;
                    calc.set_amount(&change_estimator);
                    if let Some(data) = &plutus_data {
                        match data {
                            DataOption::DataHash(data_hash) => calc.set_data_hash(data_hash),
                            DataOption::Data(datum) => calc.set_plutus_data(datum),
                        };
                    }
                    if let Some(script_ref) = &script_ref {
                        calc.set_script_ref(script_ref);
                    }
                    let min_ada = calc.calculate_ada()?;

                    // no-asset case so we have no problem burning the rest if there is no other option
                    fn burn_extra(
                        builder: &mut TransactionBuilder,
                        burn_amount: &BigNum,
                    ) -> Result<bool, JsError> {
                        // recall: min_fee assumed the fee was the maximum possible so we definitely have enough input to cover whatever fee it ends up being
                        builder.set_fee(burn_amount);
                        Ok(false) // not enough input to covert the extra fee from adding an output so we just burn whatever is left
                    }
                    match change_estimator.coin() >= min_ada {
                        false => burn_extra(self, &change_estimator.coin()),
                        true => {
                            // check how much the fee would increase if we added a change output
                            let fee_for_change = self.fee_for_output(&TransactionOutput {
                                address: address.clone(),
                                amount: change_estimator.clone(),
                                plutus_data: plutus_data.clone(),
                                script_ref: script_ref.clone(),
                                serialization_format: None,
                            })?;

                            let new_fee = fee.checked_add(&fee_for_change)?;
                            match change_estimator.coin()
                                >= min_ada.checked_add(&Value::new(&new_fee).coin())?
                            {
                                false => burn_extra(self, &change_estimator.coin()),
                                true => {
                                    // recall: min_fee assumed the fee was the maximum possible so we definitely have enough input to cover whatever fee it ends up being
                                    self.set_fee(&new_fee);

                                    self.add_output(&TransactionOutput {
                                        address: address.clone(),
                                        amount: change_estimator
                                            .checked_sub(&Value::new(&new_fee.clone()))?,
                                        plutus_data: plutus_data.clone(),
                                        script_ref: script_ref.clone(),
                                        serialization_format: None,
                                    })?;

                                    Ok(true)
                                }
                            }
                        }
                    }
                }
            }
            None => Err(JsError::from_str(
                "missing input or output for some native asset",
            )),
        }
    }

    /// This method will calculate the script hash data
    /// using the plutus datums and redeemers already present in the builder
    /// along with the provided cost model, and will register the calculated value
    /// in the builder to be used when building the tx body.
    /// In case there are no plutus input witnesses present - nothing will change
    /// You can set specific hash value using `.set_script_data_hash`
    /// NOTE: this function will check which language versions are used in the present scripts
    /// and will assert and require for a corresponding cost-model to be present in the passed map.
    /// Only the cost-models for the present language versions will be used in the hash calculation.
    pub fn calc_script_data_hash(&mut self, cost_models: &Costmdls) -> Result<(), JsError> {
        let mut used_langs = BTreeSet::new();
        let mut retained_cost_models = Costmdls::new();
        let mut plutus_witnesses = PlutusWitnesses::new();
        if let Some(mut inputs_plutus) = self.inputs.get_plutus_input_scripts() {
            used_langs.append(&mut self.inputs.get_used_plutus_lang_versions());
            plutus_witnesses.0.append(&mut inputs_plutus.0)
        }
        if let Some(mut collateral_plutus) = self.collateral.get_plutus_input_scripts() {
            used_langs.append(&mut self.collateral.get_used_plutus_lang_versions());
            plutus_witnesses.0.append(&mut collateral_plutus.0)
        }
        if let Some(mint_builder) = &self.mint {
            used_langs.append(&mut mint_builder.get_used_plutus_lang_versions());
            plutus_witnesses
                .0
                .append(&mut mint_builder.get_plutus_witnesses().0)
        }
        if let Some(certs_builder) = &self.certs {
            used_langs.append(&mut certs_builder.get_used_plutus_lang_versions());
            plutus_witnesses
                .0
                .append(&mut certs_builder.get_plutus_witnesses().0)
        }
        if let Some(withdrawals_builder) = &self.withdrawals {
            used_langs.append(&mut withdrawals_builder.get_used_plutus_lang_versions());
            plutus_witnesses
                .0
                .append(&mut withdrawals_builder.get_plutus_witnesses().0)
        }
        if let Some(voting_builder) = &self.voting_procedures {
            used_langs.append(&mut voting_builder.get_used_plutus_lang_versions());
            plutus_witnesses
                .0
                .append(&mut voting_builder.get_plutus_witnesses().0)
        }

        if let Some(voting_proposal_builder) = &self.voting_proposals {
            used_langs.append(&mut voting_proposal_builder.get_used_plutus_lang_versions());
            plutus_witnesses
                .0
                .append(&mut voting_proposal_builder.get_plutus_witnesses().0)
        }

        let (_scripts, mut datums, redeemers) = plutus_witnesses.collect();
        for lang in used_langs {
            match cost_models.get(&lang) {
                Some(cost) => {
                    retained_cost_models.insert(&lang, &cost);
                }
                _ => {
                    return Err(JsError::from_str(&format!(
                        "Missing cost model for language version: {:?}",
                        lang
                    )))
                }
            }
        }

        if let Some(extra_datum) = &self.extra_datums {
            if datums.is_none() {
                datums = Some(PlutusList::new());
            }

            for datum in extra_datum {
                if let Some(datums) = &mut datums {
                    datums.add(datum);
                }
            }
        }

        if datums.is_some() || redeemers.len() > 0 || retained_cost_models.len() > 0 {
            self.script_data_hash =
                Some(hash_script_data(&redeemers, &retained_cost_models, datums));
        }

        Ok(())
    }

    /// Sets the specified hash value.
    /// Alternatively you can use `.calc_script_data_hash` to calculate the hash automatically.
    /// Or use `.remove_script_data_hash` to delete the previously set value
    pub fn set_script_data_hash(&mut self, hash: &ScriptDataHash) {
        self.script_data_hash = Some(hash.clone());
    }

    /// Deletes any previously set plutus data hash value.
    /// Use `.set_script_data_hash` or `.calc_script_data_hash` to set it.
    pub fn remove_script_data_hash(&mut self) {
        self.script_data_hash = None;
    }

    pub fn add_required_signer(&mut self, key: &Ed25519KeyHash) {
        self.required_signers.add(key);
    }

    fn build_and_size(&self) -> Result<(TransactionBody, usize), JsError> {
        let fee = self
            .fee
            .ok_or_else(|| JsError::from_str("Fee not specified"))?;

        let built = TransactionBody {
            inputs: self.inputs.inputs(),
            outputs: self.outputs.clone(),
            fee,
            ttl: self.ttl,
            certs: self.certs.as_ref().map(|x| x.build()),
            withdrawals: self.withdrawals.as_ref().map(|x| x.build()),
            update: None,
            auxiliary_data_hash: self
                .auxiliary_data
                .as_ref()
                .map(|x| utils::hash_auxiliary_data(x)),
            validity_start_interval: self.validity_start_interval,
            mint: self.mint.as_ref()
                .map(|x| x.build())
                .transpose()?,
            script_data_hash: self.script_data_hash.clone(),
            collateral: self.collateral.inputs_option(),
            required_signers: self.required_signers.to_option(),
            network_id: None,
            collateral_return: self.collateral_return.clone(),
            total_collateral: self.total_collateral.clone(),
            reference_inputs: self.get_reference_inputs().to_option(),
            voting_procedures: self.voting_procedures.as_ref().map(|x| x.build()),
            voting_proposals: self.voting_proposals.as_ref().map(|x| x.build()),
            donation: self.donation.clone(),
            current_treasury_value: self.current_treasury_value.clone(),
        };
        // we must build a tx with fake data (of correct size) to check the final Transaction size
        let full_tx = fake_full_tx(self, built)?;
        let full_tx_size = full_tx.to_bytes().len();
        return Ok((full_tx.body, full_tx_size));
    }

    pub fn full_size(&self) -> Result<usize, JsError> {
        return self.build_and_size().map(|r| r.1);
    }

    pub fn output_sizes(&self) -> Vec<usize> {
        return self.outputs.0.iter().map(|o| o.to_bytes().len()).collect();
    }

    /// Returns object the body of the new transaction
    /// Auxiliary data itself is not included
    /// You can use `get_auxiliary_data` or `build_tx`
    pub fn build(&self) -> Result<TransactionBody, JsError> {
        let (body, full_tx_size) = self.build_and_size()?;
        if full_tx_size > self.config.max_tx_size as usize {
            Err(JsError::from_str(&format!(
                "Maximum transaction size of {} exceeded. Found: {}",
                self.config.max_tx_size, full_tx_size
            )))
        } else {
            Ok(body)
        }
    }

    fn get_combined_native_scripts(&self) -> Option<NativeScripts> {
        let mut ns = NativeScripts::new();
        if let Some(input_scripts) = self.inputs.get_native_input_scripts() {
            input_scripts.iter().for_each(|s| {
                ns.add(s);
            });
        }
        if let Some(input_scripts) = self.collateral.get_native_input_scripts() {
            input_scripts.iter().for_each(|s| {
                ns.add(s);
            });
        }
        if let Some(mint_builder) = &self.mint {
            mint_builder.get_native_scripts().iter().for_each(|s| {
                ns.add(s);
            });
        }
        if let Some(certificates_builder) = &self.certs {
            certificates_builder
                .get_native_scripts()
                .iter()
                .for_each(|s| {
                    ns.add(s);
                });
        }
        if let Some(withdrawals_builder) = &self.withdrawals {
            withdrawals_builder
                .get_native_scripts()
                .iter()
                .for_each(|s| {
                    ns.add(s);
                });
        }
        if let Some(voting_builder) = &self.voting_procedures {
            voting_builder.get_native_scripts().iter().for_each(|s| {
                ns.add(s);
            });
        }

        if ns.len() > 0 {
            Some(ns)
        } else {
            None
        }
    }

    fn get_combined_plutus_scripts(&self) -> Option<PlutusWitnesses> {
        let mut res = PlutusWitnesses::new();
        if let Some(scripts) = self.inputs.get_plutus_input_scripts() {
            scripts.0.iter().for_each(|s| {
                res.add(s);
            })
        }
        if let Some(scripts) = self.collateral.get_plutus_input_scripts() {
            scripts.0.iter().for_each(|s| {
                res.add(s);
            })
        }
        if let Some(mint_builder) = &self.mint {
            mint_builder.get_plutus_witnesses().0.iter().for_each(|s| {
                res.add(s);
            })
        }
        if let Some(certificates_builder) = &self.certs {
            certificates_builder
                .get_plutus_witnesses()
                .0
                .iter()
                .for_each(|s| {
                    res.add(s);
                })
        }
        if let Some(withdrawals_builder) = &self.withdrawals {
            withdrawals_builder
                .get_plutus_witnesses()
                .0
                .iter()
                .for_each(|s| {
                    res.add(s);
                })
        }
        if let Some(voting_builder) = &self.voting_procedures {
            voting_builder
                .get_plutus_witnesses()
                .0
                .iter()
                .for_each(|s| {
                    res.add(s);
                })
        }
        if let Some(voting_proposal_builder) = &self.voting_proposals {
            voting_proposal_builder
                .get_plutus_witnesses()
                .0
                .iter()
                .for_each(|s| {
                    res.add(s);
                })
        }
        if res.len() > 0 {
            Some(res)
        } else {
            None
        }
    }

    // This function should be producing the total witness-set
    // that is created by the tx-builder itself,
    // before the transaction is getting signed by the actual wallet.
    // E.g. scripts or something else that has been used during the tx preparation
    pub(crate) fn get_witness_set(&self) -> TransactionWitnessSet {
        let mut wit = TransactionWitnessSet::new();
        if let Some(scripts) = self.get_combined_native_scripts() {
            wit.set_native_scripts(&scripts);
        }
        let mut all_datums = None;
        if let Some(pw) = self.get_combined_plutus_scripts() {
            let (scripts, datums, redeemers) = pw.collect();
            wit.set_plutus_scripts(&scripts);
            all_datums = datums;
            wit.set_redeemers(&redeemers);
        }

        if let Some(extra_datum) = &self.extra_datums {
            if all_datums.is_none() {
                all_datums = Some(PlutusList::new());
            }

            for datum in extra_datum {
                if let Some(datums) = &mut all_datums {
                    datums.add(datum);
                }
            }
        }

        if let Some(datums) = &all_datums {
            wit.set_plutus_data(datums);
        }

        wit
    }

    fn has_plutus_inputs(&self) -> bool {
        if self.inputs.has_plutus_scripts() {
            return true;
        }
        if self.mint.as_ref().map_or(false, |m| m.has_plutus_scripts()) {
            return true;
        }
        if self
            .certs
            .as_ref()
            .map_or(false, |c| c.has_plutus_scripts())
        {
            return true;
        }
        if self
            .withdrawals
            .as_ref()
            .map_or(false, |w| w.has_plutus_scripts())
        {
            return true;
        }
        if self
            .voting_procedures
            .as_ref()
            .map_or(false, |w| w.has_plutus_scripts())
        {
            return true;
        }
        if self
            .voting_proposals
            .as_ref()
            .map_or(false, |w| w.has_plutus_scripts())
        {
            return true;
        }

        return false;
    }

    /// Returns full Transaction object with the body and the auxiliary data
    /// NOTE: witness_set will contain all mint_scripts if any been added or set
    /// NOTE: is_valid set to true
    /// NOTE: Will fail in case there are any script inputs added with no corresponding witness
    pub fn build_tx(&self) -> Result<Transaction, JsError> {
        if self.has_plutus_inputs() {
            if self.script_data_hash.is_none() {
                return Err(JsError::from_str(
                    "Plutus inputs are present, but script data hash is not specified",
                ));
            }
            if self.collateral.len() == 0 {
                return Err(JsError::from_str(
                    "Plutus inputs are present, but no collateral inputs are added",
                ));
            }
        }
        self.validate_inputs_intersection()?;
        self.build_tx_unsafe()
    }

    /// Similar to `.build_tx()` but will NOT fail in case there are missing script witnesses
    pub fn build_tx_unsafe(&self) -> Result<Transaction, JsError> {
        Ok(Transaction {
            body: self.build()?,
            witness_set: self.get_witness_set(),
            is_valid: true,
            auxiliary_data: self.auxiliary_data.clone(),
        })
    }

    /// warning: sum of all parts of a transaction must equal 0. You cannot just set the fee to the min value and forget about it
    /// warning: min_fee may be slightly larger than the actual minimum fee (ex: a few lovelaces)
    /// this is done to simplify the library code, but can be fixed later
    pub fn min_fee(&self) -> Result<Coin, JsError> {
        let mut self_copy = self.clone();
        self_copy.set_fee(&(0x1_00_00_00_00u64).into());
        min_fee(&self_copy)
    }
}