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
#![cfg(feature = "std")]

use std::{
    collections::HashMap,
    fmt::{Debug, Formatter},
    iter::repeat,
};

use async_trait::async_trait;
use fuel_asm::{op, GTFArgs, RegId};
use fuel_crypto::{Hasher, Message as CryptoMessage, Signature};
use fuel_tx::{
    field::{Outputs, Policies as PoliciesField, ScriptGasLimit, Witnesses},
    policies::{Policies, PolicyType},
    Chargeable, ConsensusParameters, Create, Input as FuelInput, Output, Script, StorageSlot,
    Transaction as FuelTransaction, TransactionFee, TxPointer, UniqueIdentifier, Upgrade, Upload,
    UploadBody, Witness,
};
pub use fuel_tx::{UpgradePurpose, UploadSubsection};
use fuel_types::{bytes::padded_len_usize, Bytes32, Salt};
use itertools::Itertools;
use script_tx_estimator::ScriptTxEstimator;

use crate::{
    constants::{SIGNATURE_WITNESS_SIZE, WORD_SIZE},
    traits::Signer,
    types::{
        bech32::Bech32Address,
        coin::Coin,
        coin_type::CoinType,
        errors::{error, error_transaction, Result},
        input::Input,
        message::Message,
        transaction::{
            CreateTransaction, EstimablePredicates, ScriptTransaction, Transaction, TxPolicies,
            UpgradeTransaction, UploadTransaction,
        },
        Address, AssetId, ContractId, DryRunner,
    },
    utils::{calculate_witnesses_size, sealed},
};

mod blob;
mod script_tx_estimator;

pub use blob::*;

const GAS_ESTIMATION_BLOCK_HORIZON: u32 = 1;

#[derive(Debug, Clone, Default)]
struct UnresolvedWitnessIndexes {
    owner_to_idx_offset: HashMap<Bech32Address, u64>,
}

#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait BuildableTransaction: sealed::Sealed {
    type TxType: Transaction;
    type Strategy;

    fn with_build_strategy(self, strategy: Self::Strategy) -> Self;
    async fn build(self, provider: impl DryRunner) -> Result<Self::TxType>;
}

impl sealed::Sealed for ScriptTransactionBuilder {}

#[derive(Debug, Clone, Default)]
pub enum ScriptBuildStrategy {
    /// Transaction is estimated and signatures are automatically added.
    #[default]
    Complete,
    /// Transaction is estimated but no signatures are added.
    /// Building without signatures will set the witness indexes of signed coins in the
    /// order as they appear in the inputs. Multiple coins with the same owner will have
    /// the same witness index. Make sure you sign the built transaction in the expected order.
    NoSignatures,
    /// No estimation is done and no signatures are added. Fake coins are added if no spendable inputs
    /// are present. Meant only for transactions that are to be dry-run with validations off.
    /// Useful for reading state with unfunded accounts.
    StateReadOnly,
}

#[derive(Debug, Clone, Default)]
pub enum Strategy {
    /// Transaction is estimated and signatures are automatically added.
    #[default]
    Complete,
    /// Transaction is estimated but no signatures are added.
    /// Building without signatures will set the witness indexes of signed coins in the
    /// order as they appear in the inputs. Multiple coins with the same owner will have
    /// the same witness index. Make sure you sign the built transaction in the expected order.
    NoSignatures,
}

#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl BuildableTransaction for ScriptTransactionBuilder {
    type TxType = ScriptTransaction;
    type Strategy = ScriptBuildStrategy;

    fn with_build_strategy(mut self, strategy: Self::Strategy) -> Self {
        self.build_strategy = strategy;
        self
    }

    async fn build(self, provider: impl DryRunner) -> Result<Self::TxType> {
        self.build(provider).await
    }
}

impl sealed::Sealed for CreateTransactionBuilder {}

#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl BuildableTransaction for CreateTransactionBuilder {
    type TxType = CreateTransaction;
    type Strategy = Strategy;

    fn with_build_strategy(mut self, strategy: Self::Strategy) -> Self {
        self.build_strategy = strategy;
        self
    }

    async fn build(self, provider: impl DryRunner) -> Result<Self::TxType> {
        self.build(provider).await
    }
}

impl sealed::Sealed for UploadTransactionBuilder {}

#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl BuildableTransaction for UploadTransactionBuilder {
    type TxType = UploadTransaction;
    type Strategy = Strategy;

    fn with_build_strategy(mut self, strategy: Self::Strategy) -> Self {
        self.build_strategy = strategy;
        self
    }

    async fn build(self, provider: impl DryRunner) -> Result<Self::TxType> {
        self.build(provider).await
    }
}

impl sealed::Sealed for UpgradeTransactionBuilder {}

#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl BuildableTransaction for UpgradeTransactionBuilder {
    type TxType = UpgradeTransaction;
    type Strategy = Strategy;

    fn with_build_strategy(mut self, strategy: Self::Strategy) -> Self {
        self.build_strategy = strategy;
        self
    }

    async fn build(self, provider: impl DryRunner) -> Result<Self::TxType> {
        self.build(provider).await
    }
}

#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait TransactionBuilder: BuildableTransaction + Send + sealed::Sealed {
    type TxType: Transaction;

    fn add_signer(&mut self, signer: impl Signer + Send + Sync) -> Result<&mut Self>;
    async fn estimate_max_fee(&self, provider: impl DryRunner) -> Result<u64>;
    fn with_tx_policies(self, tx_policies: TxPolicies) -> Self;
    fn with_inputs(self, inputs: Vec<Input>) -> Self;
    fn with_outputs(self, outputs: Vec<Output>) -> Self;
    fn with_witnesses(self, witnesses: Vec<Witness>) -> Self;
    fn inputs(&self) -> &Vec<Input>;
    fn inputs_mut(&mut self) -> &mut Vec<Input>;
    fn outputs(&self) -> &Vec<Output>;
    fn outputs_mut(&mut self) -> &mut Vec<Output>;
    fn witnesses(&self) -> &Vec<Witness>;
    fn witnesses_mut(&mut self) -> &mut Vec<Witness>;
    fn with_estimation_horizon(self, block_horizon: u32) -> Self;
}

macro_rules! impl_tx_builder_trait {
    ($ty: ty, $tx_ty: ident) => {
        #[cfg_attr(not(target_arch = "wasm32"), async_trait)]
        impl $crate::types::transaction_builders::TransactionBuilder for $ty {
            type TxType = $tx_ty;

            fn add_signer(&mut self, signer: impl Signer + Send + Sync) -> Result<&mut Self> {
                let address = signer.address();
                if self
                    .unresolved_witness_indexes
                    .owner_to_idx_offset
                    .contains_key(address)
                {
                    return Err(error_transaction!(
                        Builder,
                        "already added `Signer` with address: `{address}`"
                    ));
                }

                let index_offset = self.unresolved_signers.len() as u64;
                self.unresolved_witness_indexes
                    .owner_to_idx_offset
                    .insert(address.clone(), index_offset);
                self.unresolved_signers.push(Box::new(signer));

                Ok(self)
            }

            async fn estimate_max_fee(&self, provider: impl DryRunner) -> Result<u64> {
                let mut fee_estimation_tb = self
                    .clone_without_signers()
                    .with_build_strategy(Self::Strategy::NoSignatures);

                // Add a temporary witness for every `Signer` to include them in the fee
                // estimation.
                let witness: Witness = Signature::default().as_ref().into();
                fee_estimation_tb
                    .witnesses_mut()
                    .extend(repeat(witness).take(self.unresolved_signers.len()));

                let mut tx = $crate::types::transaction_builders::BuildableTransaction::build(
                    fee_estimation_tb,
                    &provider,
                )
                .await?;

                if tx.is_using_predicates() {
                    tx.estimate_predicates(&provider, None).await?;
                }

                let consensus_parameters = provider.consensus_parameters();

                let gas_price = provider
                    .estimate_gas_price(self.gas_price_estimation_block_horizon)
                    .await?;

                $crate::types::transaction_builders::estimate_max_fee_w_tolerance(
                    tx.tx,
                    self.max_fee_estimation_tolerance,
                    gas_price,
                    consensus_parameters,
                )
            }

            fn with_tx_policies(mut self, tx_policies: TxPolicies) -> Self {
                self.tx_policies = tx_policies;

                self
            }

            fn with_inputs(mut self, inputs: Vec<Input>) -> Self {
                self.inputs = inputs;
                self
            }

            fn with_outputs(mut self, outputs: Vec<Output>) -> Self {
                self.outputs = outputs;
                self
            }

            fn with_witnesses(mut self, witnesses: Vec<Witness>) -> Self {
                self.witnesses = witnesses;
                self
            }

            fn inputs(&self) -> &Vec<Input> {
                self.inputs.as_ref()
            }

            fn inputs_mut(&mut self) -> &mut Vec<Input> {
                &mut self.inputs
            }

            fn outputs(&self) -> &Vec<Output> {
                self.outputs.as_ref()
            }

            fn outputs_mut(&mut self) -> &mut Vec<Output> {
                &mut self.outputs
            }

            fn witnesses(&self) -> &Vec<Witness> {
                self.witnesses.as_ref()
            }

            fn witnesses_mut(&mut self) -> &mut Vec<Witness> {
                &mut self.witnesses
            }

            fn with_estimation_horizon(mut self, block_horizon: u32) -> Self {
                self.gas_price_estimation_block_horizon = block_horizon;

                self
            }
        }

        impl $ty {
            fn set_witness_indexes(&mut self) {
                use $crate::types::transaction_builders::TransactionBuilder;
                self.unresolved_witness_indexes.owner_to_idx_offset = self
                    .inputs()
                    .iter()
                    .filter_map(|input| match input {
                        Input::ResourceSigned { resource } => Some(resource.owner()),
                        _ => None,
                    })
                    .unique()
                    .cloned()
                    .enumerate()
                    .map(|(idx, owner)| (owner, idx as u64))
                    .collect();
            }

            fn generate_fuel_policies(&self) -> Result<Policies> {
                let witness_limit = match self.tx_policies.witness_limit() {
                    Some(limit) => limit,
                    None => self.calculate_witnesses_size()?,
                };
                let mut policies = Policies::default().with_witness_limit(witness_limit);

                // `MaxFee` set to `tip` or `0` for `dry_run`
                policies.set(PolicyType::MaxFee, self.tx_policies.tip().or(Some(0)));
                policies.set(PolicyType::Maturity, self.tx_policies.maturity());
                policies.set(PolicyType::Tip, self.tx_policies.tip());

                Ok(policies)
            }

            fn is_using_predicates(&self) -> bool {
                use $crate::types::transaction_builders::TransactionBuilder;
                self.inputs()
                    .iter()
                    .any(|input| matches!(input, Input::ResourcePredicate { .. }))
            }

            fn num_witnesses(&self) -> Result<u16> {
                use $crate::types::transaction_builders::TransactionBuilder;
                let num_witnesses = self.witnesses().len();

                if num_witnesses + self.unresolved_signers.len() > u16::MAX as usize {
                    return Err(error_transaction!(
                        Builder,
                        "tx exceeds maximum number of witnesses"
                    ));
                }

                Ok(num_witnesses as u16)
            }

            fn calculate_witnesses_size(&self) -> Result<u64> {
                let witnesses_size = calculate_witnesses_size(&self.witnesses);
                let signature_size = SIGNATURE_WITNESS_SIZE
                    * self.unresolved_witness_indexes.owner_to_idx_offset.len();

                let padded_len = padded_len_usize(witnesses_size + signature_size)
                    .ok_or_else(|| error!(Other, "witnesses size overflow"))?;
                Ok(padded_len as u64)
            }

            async fn set_max_fee_policy<T: Clone + PoliciesField + Chargeable + Into<$tx_ty>>(
                tx: &mut T,
                provider: impl DryRunner,
                block_horizon: u32,
                is_using_predicates: bool,
                max_fee_estimation_tolerance: f32,
            ) -> Result<()> {
                let mut wrapper_tx: $tx_ty = tx.clone().into();

                if is_using_predicates {
                    wrapper_tx.estimate_predicates(&provider, None).await?;
                }

                let gas_price = provider.estimate_gas_price(block_horizon).await?;
                let consensus_parameters = provider.consensus_parameters();

                let max_fee = $crate::types::transaction_builders::estimate_max_fee_w_tolerance(
                    wrapper_tx.tx,
                    max_fee_estimation_tolerance,
                    gas_price,
                    consensus_parameters,
                )?;

                tx.policies_mut().set(PolicyType::MaxFee, Some(max_fee));

                Ok(())
            }
        }
    };
}

pub(crate) use impl_tx_builder_trait;

pub(crate) fn estimate_max_fee_w_tolerance<T: Chargeable>(
    tx: T,
    tolerance: f32,
    gas_price: u64,
    consensus_parameters: &ConsensusParameters,
) -> Result<u64> {
    let gas_costs = &consensus_parameters.gas_costs();

    let fee_params = consensus_parameters.fee_params();

    let tx_fee = TransactionFee::checked_from_tx(gas_costs, fee_params, &tx, gas_price).ok_or(
        error_transaction!(
            Builder,
            "error calculating `TransactionFee` in `TransactionBuilder`"
        ),
    )?;

    let max_fee_w_tolerance = tx_fee.max_fee() as f64 * (1.0 + f64::from(tolerance));

    Ok(max_fee_w_tolerance as u64)
}

impl Debug for dyn Signer + Send + Sync {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Signer")
            .field("address", &self.address())
            .finish()
    }
}

/// Controls the SDK behavior regarding variable transaction outputs.
///
/// # Warning
///
/// Estimation of variable outputs is performed by saturating the transaction with variable outputs
/// and counting the number of outputs used. This process can be particularly unreliable in cases
/// where the script introspects the number of variable outputs and adjusts its logic accordingly.
/// The script could theoretically mint outputs until all variable outputs are utilized.
///
/// In such scenarios, estimation of necessary variable outputs becomes nearly impossible.
///
/// It is advised to avoid relying on automatic estimation of variable outputs if the script
/// contains logic that dynamically adjusts based on the number of outputs.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum VariableOutputPolicy {
    /// Perform a dry run of the transaction estimating the minimum number of variable outputs to
    /// add.
    EstimateMinimum,
    /// Add exactly these many variable outputs to the transaction.
    Exactly(usize),
}

impl Default for VariableOutputPolicy {
    fn default() -> Self {
        Self::Exactly(0)
    }
}

#[derive(Debug)]
pub struct ScriptTransactionBuilder {
    pub script: Vec<u8>,
    pub script_data: Vec<u8>,
    pub inputs: Vec<Input>,
    pub outputs: Vec<Output>,
    pub witnesses: Vec<Witness>,
    pub tx_policies: TxPolicies,
    pub gas_estimation_tolerance: f32,
    pub max_fee_estimation_tolerance: f32,
    pub gas_price_estimation_block_horizon: u32,
    pub variable_output_policy: VariableOutputPolicy,
    pub build_strategy: ScriptBuildStrategy,
    unresolved_witness_indexes: UnresolvedWitnessIndexes,
    unresolved_signers: Vec<Box<dyn Signer + Send + Sync>>,
}

impl Default for ScriptTransactionBuilder {
    fn default() -> Self {
        Self {
            script: Default::default(),
            script_data: Default::default(),
            inputs: Default::default(),
            outputs: Default::default(),
            witnesses: Default::default(),
            tx_policies: Default::default(),
            gas_estimation_tolerance: Default::default(),
            max_fee_estimation_tolerance: Default::default(),
            gas_price_estimation_block_horizon: GAS_ESTIMATION_BLOCK_HORIZON,
            variable_output_policy: Default::default(),
            build_strategy: Default::default(),
            unresolved_witness_indexes: Default::default(),
            unresolved_signers: Default::default(),
        }
    }
}

pub struct CreateTransactionBuilder {
    pub bytecode_length: u64,
    pub bytecode_witness_index: u16,
    pub storage_slots: Vec<StorageSlot>,
    pub inputs: Vec<Input>,
    pub outputs: Vec<Output>,
    pub witnesses: Vec<Witness>,
    pub tx_policies: TxPolicies,
    pub salt: Salt,
    pub gas_price_estimation_block_horizon: u32,
    pub max_fee_estimation_tolerance: f32,
    pub build_strategy: Strategy,
    unresolved_witness_indexes: UnresolvedWitnessIndexes,
    unresolved_signers: Vec<Box<dyn Signer + Send + Sync>>,
}

impl Default for CreateTransactionBuilder {
    fn default() -> Self {
        Self {
            bytecode_length: Default::default(),
            bytecode_witness_index: Default::default(),
            storage_slots: Default::default(),
            inputs: Default::default(),
            outputs: Default::default(),
            witnesses: Default::default(),
            tx_policies: Default::default(),
            salt: Default::default(),
            gas_price_estimation_block_horizon: GAS_ESTIMATION_BLOCK_HORIZON,
            max_fee_estimation_tolerance: Default::default(),
            build_strategy: Default::default(),
            unresolved_witness_indexes: Default::default(),
            unresolved_signers: Default::default(),
        }
    }
}

pub struct UploadTransactionBuilder {
    /// The root of the Merkle tree is created over the bytecode.
    pub root: Bytes32,
    /// The witness index of the subsection of the bytecode.
    pub witness_index: u16,
    /// The index of the subsection of the bytecode.
    pub subsection_index: u16,
    /// The total number of subsections on which bytecode was divided.
    pub subsections_number: u16,
    /// The proof set helps to verify the connection of the subsection to the `root`.
    pub proof_set: Vec<Bytes32>,
    pub inputs: Vec<Input>,
    pub outputs: Vec<Output>,
    pub witnesses: Vec<Witness>,
    pub tx_policies: TxPolicies,
    pub gas_price_estimation_block_horizon: u32,
    pub max_fee_estimation_tolerance: f32,
    pub build_strategy: Strategy,
    unresolved_witness_indexes: UnresolvedWitnessIndexes,
    unresolved_signers: Vec<Box<dyn Signer + Send + Sync>>,
}

impl Default for UploadTransactionBuilder {
    fn default() -> Self {
        Self {
            root: Default::default(),
            witness_index: Default::default(),
            subsection_index: Default::default(),
            subsections_number: Default::default(),
            proof_set: Default::default(),
            inputs: Default::default(),
            outputs: Default::default(),
            witnesses: Default::default(),
            tx_policies: Default::default(),
            gas_price_estimation_block_horizon: GAS_ESTIMATION_BLOCK_HORIZON,
            max_fee_estimation_tolerance: Default::default(),
            build_strategy: Default::default(),
            unresolved_witness_indexes: Default::default(),
            unresolved_signers: Default::default(),
        }
    }
}

pub struct UpgradeTransactionBuilder {
    /// The purpose of the upgrade.
    pub purpose: UpgradePurpose,
    pub inputs: Vec<Input>,
    pub outputs: Vec<Output>,
    pub witnesses: Vec<Witness>,
    pub tx_policies: TxPolicies,
    pub gas_price_estimation_block_horizon: u32,
    pub max_fee_estimation_tolerance: f32,
    pub build_strategy: Strategy,
    unresolved_witness_indexes: UnresolvedWitnessIndexes,
    unresolved_signers: Vec<Box<dyn Signer + Send + Sync>>,
}

impl Default for UpgradeTransactionBuilder {
    fn default() -> Self {
        Self {
            purpose: UpgradePurpose::StateTransition {
                root: Default::default(),
            },
            inputs: Default::default(),
            outputs: Default::default(),
            witnesses: Default::default(),
            tx_policies: Default::default(),
            gas_price_estimation_block_horizon: GAS_ESTIMATION_BLOCK_HORIZON,
            unresolved_witness_indexes: Default::default(),
            unresolved_signers: Default::default(),
            max_fee_estimation_tolerance: Default::default(),
            build_strategy: Default::default(),
        }
    }
}

impl_tx_builder_trait!(ScriptTransactionBuilder, ScriptTransaction);
impl_tx_builder_trait!(CreateTransactionBuilder, CreateTransaction);
impl_tx_builder_trait!(UploadTransactionBuilder, UploadTransaction);
impl_tx_builder_trait!(UpgradeTransactionBuilder, UpgradeTransaction);

impl ScriptTransactionBuilder {
    async fn build(mut self, provider: impl DryRunner) -> Result<ScriptTransaction> {
        let is_using_predicates = self.is_using_predicates();

        let tx = match self.build_strategy {
            ScriptBuildStrategy::Complete => self.resolve_fuel_tx(&provider).await?,
            ScriptBuildStrategy::NoSignatures => {
                self.set_witness_indexes();
                self.unresolved_signers = Default::default();

                self.resolve_fuel_tx(&provider).await?
            }
            ScriptBuildStrategy::StateReadOnly => {
                self.resolve_fuel_tx_for_state_reading(provider).await?
            }
        };

        Ok(ScriptTransaction {
            is_using_predicates,
            tx,
        })
    }

    async fn resolve_fuel_tx(self, dry_runner: impl DryRunner) -> Result<Script> {
        let predefined_witnesses = self.witnesses.clone();
        let mut script_tx_estimator = self.script_tx_estimator(predefined_witnesses, &dry_runner);

        let mut tx = FuelTransaction::script(
            0, // default value - will be overwritten
            self.script.clone(),
            self.script_data.clone(),
            self.generate_fuel_policies()?,
            resolve_fuel_inputs(
                self.inputs.clone(),
                self.num_witnesses()?,
                &self.unresolved_witness_indexes,
            )?,
            self.outputs.clone(),
            vec![],
        );

        self.add_variable_outputs(&mut script_tx_estimator, &mut tx)
            .await?;

        // should come after variable outputs because it can then reuse the dry run made for variable outputs
        self.set_script_gas_limit(&mut script_tx_estimator, &mut tx)
            .await?;

        if let Some(max_fee) = self.tx_policies.max_fee() {
            tx.policies_mut().set(PolicyType::MaxFee, Some(max_fee));
        } else {
            Self::set_max_fee_policy(
                &mut tx,
                &dry_runner,
                self.gas_price_estimation_block_horizon,
                self.is_using_predicates(),
                self.max_fee_estimation_tolerance,
            )
            .await?;
        }

        self.set_witnesses(&mut tx, dry_runner).await?;

        Ok(tx)
    }

    async fn resolve_fuel_tx_for_state_reading(self, dry_runner: impl DryRunner) -> Result<Script> {
        let predefined_witnesses = self.witnesses.clone();
        let mut script_tx_estimator = self.script_tx_estimator(predefined_witnesses, &dry_runner);

        let mut tx = FuelTransaction::script(
            0, // default value - will be overwritten
            self.script.clone(),
            self.script_data.clone(),
            self.generate_fuel_policies()?,
            resolve_fuel_inputs(
                self.inputs.clone(),
                self.num_witnesses()?,
                &self.unresolved_witness_indexes,
            )?,
            self.outputs.clone(),
            vec![],
        );

        let should_saturate_variable_outputs =
            if let VariableOutputPolicy::Exactly(n) = self.variable_output_policy {
                add_variable_outputs(&mut tx, n);
                false
            } else {
                true
            };

        if let Some(max_fee) = self.tx_policies.max_fee() {
            tx.policies_mut().set(PolicyType::MaxFee, Some(max_fee));
        } else {
            Self::set_max_fee_policy(
                &mut tx,
                &dry_runner,
                self.gas_price_estimation_block_horizon,
                self.is_using_predicates(),
                self.max_fee_estimation_tolerance,
            )
            .await?;
        }

        script_tx_estimator.prepare_for_estimation(&mut tx, should_saturate_variable_outputs);

        Ok(tx)
    }

    async fn set_witnesses(self, tx: &mut fuel_tx::Script, provider: impl DryRunner) -> Result<()> {
        let missing_witnesses = generate_missing_witnesses(
            tx.id(&provider.consensus_parameters().chain_id()),
            &self.unresolved_signers,
        )
        .await?;
        *tx.witnesses_mut() = [self.witnesses, missing_witnesses].concat();
        Ok(())
    }

    async fn set_script_gas_limit(
        &self,
        dry_runner: &mut ScriptTxEstimator<&impl DryRunner>,
        tx: &mut fuel_tx::Script,
    ) -> Result<()> {
        let has_no_code = self.script.is_empty();
        let script_gas_limit = if let Some(gas_limit) = self.tx_policies.script_gas_limit() {
            // Use the user defined value even if it makes the transaction revert.
            gas_limit
        } else if has_no_code {
            0
        } else {
            let dry_run = if let Some(dry_run) = dry_runner.last_dry_run() {
                // Even if the last dry run included variable outputs they only affect the transaction fee,
                // the script's gas usage remains unchanged. By opting into variable output estimation, the user
                // acknowledges the issues with tx introspection and asserts that there is no introspective logic
                // based on the number of variable outputs.
                //
                // Therefore, we can trust the gas usage from the last dry run and reuse it, avoiding the need
                // for an additional dry run.
                dry_run
            } else {
                dry_runner.run(tx.clone(), false).await?
            };
            dry_run.gas_with_tolerance(self.gas_estimation_tolerance)
        };

        *tx.script_gas_limit_mut() = script_gas_limit;
        Ok(())
    }

    fn script_tx_estimator<D>(
        &self,
        predefined_witnesses: Vec<Witness>,
        dry_runner: D,
    ) -> ScriptTxEstimator<D>
    where
        D: DryRunner,
    {
        let num_unresolved_witnesses = self.unresolved_witness_indexes.owner_to_idx_offset.len();
        ScriptTxEstimator::new(dry_runner, predefined_witnesses, num_unresolved_witnesses)
    }

    async fn add_variable_outputs(
        &self,
        dry_runner: &mut ScriptTxEstimator<&impl DryRunner>,
        tx: &mut fuel_tx::Script,
    ) -> Result<()> {
        let variable_outputs = match self.variable_output_policy {
            VariableOutputPolicy::Exactly(num) => num,
            VariableOutputPolicy::EstimateMinimum => {
                dry_runner.run(tx.clone(), true).await?.variable_outputs
            }
        };
        add_variable_outputs(tx, variable_outputs);

        Ok(())
    }

    pub fn with_variable_output_policy(mut self, variable_outputs: VariableOutputPolicy) -> Self {
        self.variable_output_policy = variable_outputs;
        self
    }

    pub fn with_script(mut self, script: Vec<u8>) -> Self {
        self.script = script;
        self
    }

    pub fn with_script_data(mut self, script_data: Vec<u8>) -> Self {
        self.script_data = script_data;
        self
    }

    pub fn with_gas_estimation_tolerance(mut self, tolerance: f32) -> Self {
        self.gas_estimation_tolerance = tolerance;
        self
    }

    pub fn with_max_fee_estimation_tolerance(mut self, max_fee_estimation_tolerance: f32) -> Self {
        self.max_fee_estimation_tolerance = max_fee_estimation_tolerance;
        self
    }

    pub fn prepare_transfer(
        inputs: Vec<Input>,
        outputs: Vec<Output>,
        tx_policies: TxPolicies,
    ) -> Self {
        ScriptTransactionBuilder::default()
            .with_inputs(inputs)
            .with_outputs(outputs)
            .with_tx_policies(tx_policies)
    }

    /// Craft a transaction used to transfer funds to a contract.
    pub fn prepare_contract_transfer(
        to: ContractId,
        amount: u64,
        asset_id: AssetId,
        inputs: Vec<Input>,
        outputs: Vec<Output>,
        tx_policies: TxPolicies,
    ) -> Self {
        let script_data: Vec<u8> = [
            to.to_vec(),
            amount.to_be_bytes().to_vec(),
            asset_id.to_vec(),
        ]
        .into_iter()
        .flatten()
        .collect();

        // This script loads:
        //  - a pointer to the contract id,
        //  - the actual amount
        //  - a pointer to the asset id
        // into the registers 0x10, 0x12, 0x13
        // and calls the TR instruction
        let script = vec![
            op::gtf(0x10, 0x00, GTFArgs::ScriptData.into()),
            op::addi(0x11, 0x10, ContractId::LEN as u16),
            op::lw(0x12, 0x11, 0),
            op::addi(0x13, 0x11, WORD_SIZE as u16),
            op::tr(0x10, 0x12, 0x13),
            op::ret(RegId::ONE),
        ]
        .into_iter()
        .collect();

        ScriptTransactionBuilder::default()
            .with_script(script)
            .with_script_data(script_data)
            .with_inputs(inputs)
            .with_outputs(outputs)
            .with_tx_policies(tx_policies)
    }

    /// Craft a transaction used to transfer funds to the base chain.
    pub fn prepare_message_to_output(
        to: Address,
        amount: u64,
        inputs: Vec<Input>,
        tx_policies: TxPolicies,
        base_asset_id: AssetId,
    ) -> Self {
        let script_data: Vec<u8> = [to.to_vec(), amount.to_be_bytes().to_vec()]
            .into_iter()
            .flatten()
            .collect();

        // This script loads:
        //  - a pointer to the recipient address,
        //  - the amount
        // into the registers 0x10, 0x11
        // and calls the SMO instruction
        let script: Vec<u8> = vec![
            op::gtf(0x10, 0x00, GTFArgs::ScriptData.into()),
            op::addi(0x11, 0x10, Bytes32::LEN as u16),
            op::lw(0x11, 0x11, 0),
            op::smo(0x10, 0x00, 0x00, 0x11),
            op::ret(RegId::ONE),
        ]
        .into_iter()
        .collect();

        let outputs = vec![Output::change(to, 0, base_asset_id)];

        ScriptTransactionBuilder::default()
            .with_tx_policies(tx_policies)
            .with_script(script)
            .with_script_data(script_data)
            .with_inputs(inputs)
            .with_outputs(outputs)
    }

    fn clone_without_signers(&self) -> Self {
        Self {
            script: self.script.clone(),
            script_data: self.script_data.clone(),
            inputs: self.inputs.clone(),
            outputs: self.outputs.clone(),
            witnesses: self.witnesses.clone(),
            tx_policies: self.tx_policies,
            gas_estimation_tolerance: self.gas_estimation_tolerance,
            unresolved_witness_indexes: self.unresolved_witness_indexes.clone(),
            unresolved_signers: Default::default(),
            gas_price_estimation_block_horizon: self.gas_price_estimation_block_horizon,
            variable_output_policy: self.variable_output_policy,
            max_fee_estimation_tolerance: self.max_fee_estimation_tolerance,
            build_strategy: self.build_strategy.clone(),
        }
    }
}

fn add_variable_outputs(tx: &mut fuel_tx::Script, variable_outputs: usize) {
    tx.outputs_mut().extend(
        repeat(Output::Variable {
            amount: 0,
            to: Address::zeroed(),
            asset_id: AssetId::zeroed(),
        })
        .take(variable_outputs),
    );
}

impl CreateTransactionBuilder {
    pub async fn build(mut self, provider: impl DryRunner) -> Result<CreateTransaction> {
        let is_using_predicates = self.is_using_predicates();

        let tx = match self.build_strategy {
            Strategy::Complete => self.resolve_fuel_tx(&provider).await?,
            Strategy::NoSignatures => {
                self.set_witness_indexes();
                self.unresolved_signers = Default::default();
                self.resolve_fuel_tx(&provider).await?
            }
        };

        Ok(CreateTransaction {
            is_using_predicates,
            tx,
        })
    }

    async fn resolve_fuel_tx(self, provider: impl DryRunner) -> Result<Create> {
        let chain_id = provider.consensus_parameters().chain_id();
        let num_witnesses = self.num_witnesses()?;
        let policies = self.generate_fuel_policies()?;
        let is_using_predicates = self.is_using_predicates();

        let mut tx = FuelTransaction::create(
            self.bytecode_witness_index,
            policies,
            self.salt,
            self.storage_slots,
            resolve_fuel_inputs(self.inputs, num_witnesses, &self.unresolved_witness_indexes)?,
            self.outputs,
            self.witnesses,
        );

        if let Some(max_fee) = self.tx_policies.max_fee() {
            tx.policies_mut().set(PolicyType::MaxFee, Some(max_fee));
        } else {
            Self::set_max_fee_policy(
                &mut tx,
                &provider,
                self.gas_price_estimation_block_horizon,
                is_using_predicates,
                self.max_fee_estimation_tolerance,
            )
            .await?;
        }

        let missing_witnesses =
            generate_missing_witnesses(tx.id(&chain_id), &self.unresolved_signers).await?;
        tx.witnesses_mut().extend(missing_witnesses);

        Ok(tx)
    }

    pub fn with_bytecode_length(mut self, bytecode_length: u64) -> Self {
        self.bytecode_length = bytecode_length;
        self
    }

    pub fn with_bytecode_witness_index(mut self, bytecode_witness_index: u16) -> Self {
        self.bytecode_witness_index = bytecode_witness_index;
        self
    }

    pub fn with_storage_slots(mut self, mut storage_slots: Vec<StorageSlot>) -> Self {
        // Storage slots have to be sorted otherwise we'd get a `TransactionCreateStorageSlotOrder`
        // error.
        storage_slots.sort();
        self.storage_slots = storage_slots;
        self
    }

    pub fn with_salt(mut self, salt: impl Into<Salt>) -> Self {
        self.salt = salt.into();
        self
    }

    pub fn with_max_fee_estimation_tolerance(mut self, max_fee_estimation_tolerance: f32) -> Self {
        self.max_fee_estimation_tolerance = max_fee_estimation_tolerance;
        self
    }

    pub fn prepare_contract_deployment(
        binary: Vec<u8>,
        contract_id: ContractId,
        state_root: Bytes32,
        salt: Salt,
        storage_slots: Vec<StorageSlot>,
        tx_policies: TxPolicies,
    ) -> Self {
        let bytecode_witness_index = 0;
        let outputs = vec![Output::contract_created(contract_id, state_root)];
        let witnesses = vec![binary.into()];

        CreateTransactionBuilder::default()
            .with_tx_policies(tx_policies)
            .with_bytecode_witness_index(bytecode_witness_index)
            .with_salt(salt)
            .with_storage_slots(storage_slots)
            .with_outputs(outputs)
            .with_witnesses(witnesses)
    }

    fn clone_without_signers(&self) -> Self {
        Self {
            bytecode_length: self.bytecode_length,
            bytecode_witness_index: self.bytecode_witness_index,
            storage_slots: self.storage_slots.clone(),
            inputs: self.inputs.clone(),
            outputs: self.outputs.clone(),
            witnesses: self.witnesses.clone(),
            tx_policies: self.tx_policies,
            salt: self.salt,
            unresolved_witness_indexes: self.unresolved_witness_indexes.clone(),
            unresolved_signers: Default::default(),
            gas_price_estimation_block_horizon: self.gas_price_estimation_block_horizon,
            max_fee_estimation_tolerance: self.max_fee_estimation_tolerance,
            build_strategy: self.build_strategy.clone(),
        }
    }
}

impl UploadTransactionBuilder {
    pub async fn build(mut self, provider: impl DryRunner) -> Result<UploadTransaction> {
        let is_using_predicates = self.is_using_predicates();

        let tx = match self.build_strategy {
            Strategy::Complete => self.resolve_fuel_tx(&provider).await?,
            Strategy::NoSignatures => {
                self.set_witness_indexes();
                self.unresolved_signers = Default::default();
                self.resolve_fuel_tx(&provider).await?
            }
        };

        Ok(UploadTransaction {
            is_using_predicates,
            tx,
        })
    }

    async fn resolve_fuel_tx(self, provider: impl DryRunner) -> Result<Upload> {
        let chain_id = provider.consensus_parameters().chain_id();
        let num_witnesses = self.num_witnesses()?;
        let policies = self.generate_fuel_policies()?;
        let is_using_predicates = self.is_using_predicates();

        let mut tx = FuelTransaction::upload(
            UploadBody {
                root: self.root,
                witness_index: self.witness_index,
                subsection_index: self.subsection_index,
                subsections_number: self.subsections_number,
                proof_set: self.proof_set,
            },
            policies,
            resolve_fuel_inputs(self.inputs, num_witnesses, &self.unresolved_witness_indexes)?,
            self.outputs,
            self.witnesses,
        );

        if let Some(max_fee) = self.tx_policies.max_fee() {
            tx.policies_mut().set(PolicyType::MaxFee, Some(max_fee));
        } else {
            Self::set_max_fee_policy(
                &mut tx,
                &provider,
                self.gas_price_estimation_block_horizon,
                is_using_predicates,
                self.max_fee_estimation_tolerance,
            )
            .await?;
        }

        let missing_witnesses =
            generate_missing_witnesses(tx.id(&chain_id), &self.unresolved_signers).await?;
        tx.witnesses_mut().extend(missing_witnesses);

        Ok(tx)
    }

    pub fn with_root(mut self, root: Bytes32) -> Self {
        self.root = root;
        self
    }

    pub fn with_witness_index(mut self, witness_index: u16) -> Self {
        self.witness_index = witness_index;
        self
    }

    pub fn with_subsection_index(mut self, subsection_index: u16) -> Self {
        self.subsection_index = subsection_index;
        self
    }

    pub fn with_subsections_number(mut self, subsections_number: u16) -> Self {
        self.subsections_number = subsections_number;
        self
    }

    pub fn with_proof_set(mut self, proof_set: Vec<Bytes32>) -> Self {
        self.proof_set = proof_set;
        self
    }

    pub fn with_max_fee_estimation_tolerance(mut self, max_fee_estimation_tolerance: f32) -> Self {
        self.max_fee_estimation_tolerance = max_fee_estimation_tolerance;
        self
    }

    pub fn prepare_subsection_upload(
        subsection: UploadSubsection,
        tx_policies: TxPolicies,
    ) -> Self {
        let subsection_witness_index = 0;
        let outputs = vec![];
        let UploadSubsection {
            root,
            subsection,
            subsection_index,
            subsections_number,
            proof_set,
        } = subsection;
        let witnesses = vec![subsection.into()];

        Self::default()
            .with_tx_policies(tx_policies)
            .with_root(root)
            .with_witness_index(subsection_witness_index)
            .with_subsection_index(subsection_index)
            .with_subsections_number(subsections_number)
            .with_proof_set(proof_set)
            .with_outputs(outputs)
            .with_witnesses(witnesses)
    }

    fn clone_without_signers(&self) -> Self {
        Self {
            root: self.root,
            witness_index: self.witness_index,
            subsection_index: self.subsection_index,
            subsections_number: self.subsections_number,
            inputs: self.inputs.clone(),
            outputs: self.outputs.clone(),
            witnesses: self.witnesses.clone(),
            tx_policies: self.tx_policies,
            unresolved_witness_indexes: self.unresolved_witness_indexes.clone(),
            unresolved_signers: Default::default(),
            gas_price_estimation_block_horizon: self.gas_price_estimation_block_horizon,
            proof_set: vec![],
            max_fee_estimation_tolerance: self.max_fee_estimation_tolerance,
            build_strategy: self.build_strategy.clone(),
        }
    }
}

impl UpgradeTransactionBuilder {
    pub async fn build(mut self, provider: impl DryRunner) -> Result<UpgradeTransaction> {
        let is_using_predicates = self.is_using_predicates();
        let tx = match self.build_strategy {
            Strategy::Complete => self.resolve_fuel_tx(&provider).await?,
            Strategy::NoSignatures => {
                self.set_witness_indexes();
                self.unresolved_signers = Default::default();
                self.resolve_fuel_tx(&provider).await?
            }
        };
        Ok(UpgradeTransaction {
            is_using_predicates,
            tx,
        })
    }

    async fn resolve_fuel_tx(self, provider: impl DryRunner) -> Result<Upgrade> {
        let chain_id = provider.consensus_parameters().chain_id();
        let num_witnesses = self.num_witnesses()?;
        let policies = self.generate_fuel_policies()?;
        let is_using_predicates = self.is_using_predicates();

        let mut tx = FuelTransaction::upgrade(
            self.purpose,
            policies,
            resolve_fuel_inputs(self.inputs, num_witnesses, &self.unresolved_witness_indexes)?,
            self.outputs,
            self.witnesses,
        );

        if let Some(max_fee) = self.tx_policies.max_fee() {
            tx.policies_mut().set(PolicyType::MaxFee, Some(max_fee));
        } else {
            Self::set_max_fee_policy(
                &mut tx,
                &provider,
                self.gas_price_estimation_block_horizon,
                is_using_predicates,
                self.max_fee_estimation_tolerance,
            )
            .await?;
        }

        let missing_witnesses =
            generate_missing_witnesses(tx.id(&chain_id), &self.unresolved_signers).await?;
        tx.witnesses_mut().extend(missing_witnesses);

        Ok(tx)
    }

    pub fn with_purpose(mut self, upgrade_purpose: UpgradePurpose) -> Self {
        self.purpose = upgrade_purpose;
        self
    }

    pub fn with_max_fee_estimation_tolerance(mut self, max_fee_estimation_tolerance: f32) -> Self {
        self.max_fee_estimation_tolerance = max_fee_estimation_tolerance;
        self
    }

    pub fn prepare_state_transition_upgrade(root: Bytes32, tx_policies: TxPolicies) -> Self {
        Self::default()
            .with_tx_policies(tx_policies)
            .with_purpose(UpgradePurpose::StateTransition { root })
    }

    pub fn prepare_consensus_parameters_upgrade(
        consensus_parameters: &ConsensusParameters,
        tx_policies: TxPolicies,
    ) -> Self {
        let serialized_consensus_parameters = postcard::to_allocvec(consensus_parameters)
            .expect("Impossible to fail unless there is not enough memory");
        let checksum = Hasher::hash(&serialized_consensus_parameters);
        let witness_index = 0;
        let outputs = vec![];
        let witnesses = vec![serialized_consensus_parameters.into()];

        Self::default()
            .with_tx_policies(tx_policies)
            .with_purpose(UpgradePurpose::ConsensusParameters {
                witness_index,
                checksum,
            })
            .with_outputs(outputs)
            .with_witnesses(witnesses)
    }

    fn clone_without_signers(&self) -> Self {
        Self {
            purpose: self.purpose,
            inputs: self.inputs.clone(),
            outputs: self.outputs.clone(),
            witnesses: self.witnesses.clone(),
            tx_policies: self.tx_policies,
            unresolved_witness_indexes: self.unresolved_witness_indexes.clone(),
            unresolved_signers: Default::default(),
            gas_price_estimation_block_horizon: self.gas_price_estimation_block_horizon,
            max_fee_estimation_tolerance: self.max_fee_estimation_tolerance,
            build_strategy: self.build_strategy.clone(),
        }
    }
}

/// Resolve SDK Inputs to fuel_tx Inputs. This function will calculate the right
/// data offsets for predicates and set witness indexes for signed coins.
fn resolve_fuel_inputs(
    inputs: Vec<Input>,
    num_witnesses: u16,
    unresolved_witness_indexes: &UnresolvedWitnessIndexes,
) -> Result<Vec<FuelInput>> {
    inputs
        .into_iter()
        .map(|input| match input {
            Input::ResourceSigned { resource } => {
                resolve_signed_resource(resource, num_witnesses, unresolved_witness_indexes)
            }
            Input::ResourcePredicate {
                resource,
                code,
                data,
            } => Ok(resolve_predicate_resource(resource, code, data)),
            Input::Contract {
                utxo_id,
                balance_root,
                state_root,
                tx_pointer,
                contract_id,
            } => Ok(FuelInput::contract(
                utxo_id,
                balance_root,
                state_root,
                tx_pointer,
                contract_id,
            )),
        })
        .collect()
}

fn resolve_signed_resource(
    resource: CoinType,
    num_witnesses: u16,
    unresolved_witness_indexes: &UnresolvedWitnessIndexes,
) -> Result<FuelInput> {
    match resource {
        CoinType::Coin(coin) => {
            let owner = &coin.owner;

            unresolved_witness_indexes
                .owner_to_idx_offset
                .get(owner)
                .ok_or(error_transaction!(
                    Builder,
                    "signature missing for coin with owner: `{owner:?}`"
                ))
                .map(|witness_idx_offset| {
                    create_coin_input(coin, num_witnesses + *witness_idx_offset as u16)
                })
        }
        CoinType::Message(message) => {
            let recipient = &message.recipient;

            unresolved_witness_indexes
                .owner_to_idx_offset
                .get(recipient)
                .ok_or(error_transaction!(
                    Builder,
                    "signature missing for message with recipient: `{recipient:?}`"
                ))
                .map(|witness_idx_offset| {
                    create_coin_message_input(message, num_witnesses + *witness_idx_offset as u16)
                })
        }
    }
}

fn resolve_predicate_resource(resource: CoinType, code: Vec<u8>, data: Vec<u8>) -> FuelInput {
    match resource {
        CoinType::Coin(coin) => create_coin_predicate(coin.asset_id, coin, code, data),
        CoinType::Message(message) => create_coin_message_predicate(message, code, data),
    }
}

pub fn create_coin_input(coin: Coin, witness_index: u16) -> FuelInput {
    FuelInput::coin_signed(
        coin.utxo_id,
        coin.owner.into(),
        coin.amount,
        coin.asset_id,
        TxPointer::default(),
        witness_index,
    )
}

pub fn create_coin_message_input(message: Message, witness_index: u16) -> FuelInput {
    if message.data.is_empty() {
        FuelInput::message_coin_signed(
            message.sender.into(),
            message.recipient.into(),
            message.amount,
            message.nonce,
            witness_index,
        )
    } else {
        FuelInput::message_data_signed(
            message.sender.into(),
            message.recipient.into(),
            message.amount,
            message.nonce,
            witness_index,
            message.data,
        )
    }
}

pub fn create_coin_predicate(
    asset_id: AssetId,
    coin: Coin,
    code: Vec<u8>,
    predicate_data: Vec<u8>,
) -> FuelInput {
    FuelInput::coin_predicate(
        coin.utxo_id,
        coin.owner.into(),
        coin.amount,
        asset_id,
        TxPointer::default(),
        0u64,
        code,
        predicate_data,
    )
}

pub fn create_coin_message_predicate(
    message: Message,
    code: Vec<u8>,
    predicate_data: Vec<u8>,
) -> FuelInput {
    if message.data.is_empty() {
        FuelInput::message_coin_predicate(
            message.sender.into(),
            message.recipient.into(),
            message.amount,
            message.nonce,
            0u64,
            code,
            predicate_data,
        )
    } else {
        FuelInput::message_data_predicate(
            message.sender.into(),
            message.recipient.into(),
            message.amount,
            message.nonce,
            0u64,
            message.data,
            code,
            predicate_data,
        )
    }
}

async fn generate_missing_witnesses(
    id: Bytes32,
    unresolved_signatures: &[Box<dyn Signer + Send + Sync>],
) -> Result<Vec<Witness>> {
    let mut witnesses = Vec::with_capacity(unresolved_signatures.len());
    for signer in unresolved_signatures {
        let message = CryptoMessage::from_bytes(*id);
        let signature = signer.sign(message).await?;

        witnesses.push(signature.as_ref().into());
    }

    Ok(witnesses)
}

#[cfg(test)]
mod tests {
    use std::iter::repeat_with;

    use fuel_crypto::Signature;
    use fuel_tx::{input::coin::CoinSigned, ConsensusParameters, UtxoId};

    use super::*;
    use crate::types::{bech32::Bech32Address, message::MessageStatus, DryRun};

    #[test]
    fn storage_slots_are_sorted_when_set() {
        let unsorted_storage_slots = [2, 1].map(given_a_storage_slot).to_vec();
        let sorted_storage_slots = [1, 2].map(given_a_storage_slot).to_vec();

        let builder =
            CreateTransactionBuilder::default().with_storage_slots(unsorted_storage_slots);

        assert_eq!(builder.storage_slots, sorted_storage_slots);
    }

    fn given_a_storage_slot(key: u8) -> StorageSlot {
        let mut bytes_32 = Bytes32::zeroed();
        bytes_32[0] = key;

        StorageSlot::new(bytes_32, Default::default())
    }

    #[test]
    fn create_message_coin_signed_if_data_is_empty() {
        assert!(matches!(
            create_coin_message_input(given_a_message(vec![]), 0),
            FuelInput::MessageCoinSigned(_)
        ));
    }

    #[test]
    fn create_message_data_signed_if_data_is_not_empty() {
        assert!(matches!(
            create_coin_message_input(given_a_message(vec![42]), 0),
            FuelInput::MessageDataSigned(_)
        ));
    }

    #[test]
    fn create_message_coin_predicate_if_data_is_empty() {
        assert!(matches!(
            create_coin_message_predicate(given_a_message(vec![]), vec![], vec![]),
            FuelInput::MessageCoinPredicate(_)
        ));
    }

    #[test]
    fn create_message_data_predicate_if_data_is_not_empty() {
        assert!(matches!(
            create_coin_message_predicate(given_a_message(vec![42]), vec![], vec![]),
            FuelInput::MessageDataPredicate(_)
        ));
    }

    fn given_a_message(data: Vec<u8>) -> Message {
        Message {
            sender: Bech32Address::default(),
            recipient: Bech32Address::default(),
            nonce: 0.into(),
            amount: 0,
            data,
            da_height: 0,
            status: MessageStatus::Unspent,
        }
    }

    fn given_inputs(num_inputs: u8) -> Vec<Input> {
        (0..num_inputs)
            .map(|i| {
                let bytes = [i; 32];
                let coin = CoinType::Coin(Coin {
                    utxo_id: UtxoId::new(bytes.into(), 0),
                    owner: Bech32Address::new("fuel", bytes),
                    ..Default::default()
                });
                Input::resource_signed(coin)
            })
            .collect()
    }

    fn given_witnesses(num_witnesses: usize) -> Vec<Witness> {
        repeat_with(Witness::default).take(num_witnesses).collect()
    }

    struct MockDryRunner {
        c_param: ConsensusParameters,
    }

    impl Default for MockDryRunner {
        fn default() -> Self {
            Self {
                c_param: ConsensusParameters::standard(),
            }
        }
    }

    #[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
    #[cfg_attr(not(target_arch = "wasm32"), async_trait)]
    impl DryRunner for MockDryRunner {
        async fn dry_run(&self, _: FuelTransaction) -> Result<DryRun> {
            Ok(DryRun {
                succeeded: true,
                script_gas: 0,
                variable_outputs: 0,
            })
        }

        fn consensus_parameters(&self) -> &ConsensusParameters {
            &self.c_param
        }

        async fn estimate_gas_price(&self, _block_horizon: u32) -> Result<u64> {
            Ok(0)
        }

        async fn maybe_estimate_predicates(
            &self,
            _tx: &FuelTransaction,
            _: Option<u32>,
        ) -> Result<Option<FuelTransaction>> {
            Ok(None)
        }
    }

    #[tokio::test]
    async fn create_tx_builder_witness_indexes_set_correctly() -> Result<()> {
        // given
        let num_witnesses = 2;
        let num_inputs = 3;

        let tb = CreateTransactionBuilder::default()
            .with_witnesses(given_witnesses(num_witnesses))
            .with_inputs(given_inputs(num_inputs));

        // when
        let tx = tb
            .with_build_strategy(Strategy::NoSignatures)
            .build(&MockDryRunner::default())
            .await?;

        // then
        let indexes: Vec<usize> = tx
            .inputs()
            .iter()
            .filter_map(|input| match input {
                FuelInput::CoinSigned(CoinSigned { witness_index, .. }) => {
                    Some(*witness_index as usize)
                }
                _ => None,
            })
            .collect();

        let expected_indexes: Vec<_> =
            (num_witnesses..(num_witnesses + num_inputs as usize)).collect();

        assert_eq!(indexes, expected_indexes);

        Ok(())
    }

    #[tokio::test]
    async fn script_tx_builder_witness_indexes_set_correctly() -> Result<()> {
        // given
        let num_witnesses = 6;
        let num_inputs = 4;

        let tb = ScriptTransactionBuilder::default()
            .with_witnesses(given_witnesses(num_witnesses))
            .with_inputs(given_inputs(num_inputs));

        // when
        let tx = tb
            .with_build_strategy(ScriptBuildStrategy::NoSignatures)
            .build(&MockDryRunner::default())
            .await?;

        // then
        let indexes: Vec<usize> = tx
            .inputs()
            .iter()
            .filter_map(|input| match input {
                FuelInput::CoinSigned(CoinSigned { witness_index, .. }) => {
                    Some(*witness_index as usize)
                }
                _ => None,
            })
            .collect();

        let expected_indexes: Vec<_> =
            (num_witnesses..(num_witnesses + num_inputs as usize)).collect();

        assert_eq!(indexes, expected_indexes);

        Ok(())
    }

    #[derive(Clone, Debug, Default)]
    struct MockSigner {
        address: Bech32Address,
    }

    #[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
    #[cfg_attr(not(target_arch = "wasm32"), async_trait)]
    impl Signer for MockSigner {
        async fn sign(&self, _message: CryptoMessage) -> Result<Signature> {
            Ok(Default::default())
        }
        fn address(&self) -> &Bech32Address {
            &self.address
        }
    }

    #[tokio::test]
    #[should_panic(expected = "already added `Signer` with address:")]
    async fn add_signer_called_multiple_times() {
        let mut tb = ScriptTransactionBuilder::default();
        let signer = MockSigner::default();

        tb.add_signer(signer.clone()).unwrap();
        tb.add_signer(signer.clone()).unwrap();
    }
}