fuels-contract 0.30.0

Fuel Rust SDK contracts.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
use anyhow::Result;
use fuel_gql_client::fuel_tx::{
    field::Script as ScriptField, ConsensusParameters, Input, Output, Receipt, Transaction,
    TxPointer, UtxoId,
};
use fuel_gql_client::fuel_types::{
    bytes::padded_len_usize, AssetId, Bytes32, ContractId, Immediate18, Word,
};
use fuel_gql_client::fuel_vm::{consts::REG_ONE, prelude::Opcode};
use itertools::{chain, Itertools};

use fuel_gql_client::client::schema::coin::Coin;
use fuel_tx::{Checkable, ScriptExecutionResult, Witness};
use fuels_core::parameters::TxParameters;
use fuels_signers::provider::Provider;
use fuels_signers::{Signer, WalletUnlocked};
use fuels_types::bech32::Bech32Address;
use fuels_types::{constants::WORD_SIZE, errors::Error};
use futures::{stream, StreamExt};
use std::collections::HashSet;
use std::iter;

use crate::contract::ContractCall;

#[derive(Default)]
/// Specifies offsets of Opcode::CALL parameters stored in the script
/// data from which they can be loaded into registers
struct CallParamOffsets {
    pub asset_id_offset: usize,
    pub amount_offset: usize,
    pub gas_forwarded_offset: usize,
    pub call_data_offset: usize,
}

/// Script provides methods to create and a call/simulate a
/// script transaction that carries out contract method calls
pub struct Script {
    pub tx: fuels_core::tx::Script,
}

#[derive(Debug, Clone)]
pub struct CompiledScript {
    pub raw: Vec<u8>,
    pub target_network_url: String,
}

impl Script {
    pub fn new(tx: fuels_core::tx::Script) -> Self {
        Self { tx }
    }

    /// Creates a Script from a contract call. The internal Transaction is initialized
    /// with the actual script instructions, script data needed to perform the call
    /// and transaction inputs/outputs consisting of assets and contracts
    pub async fn from_contract_calls(
        calls: &[ContractCall],
        tx_parameters: &TxParameters,
        wallet: &WalletUnlocked,
    ) -> Result<Self, Error> {
        let data_offset = Self::get_data_offset(calls.len());

        let (script_data, call_param_offsets) =
            Self::get_script_data(calls, data_offset, tx_parameters.gas_limit);

        let script = Self::get_instructions(calls, call_param_offsets);

        let required_asset_amounts = Self::calculate_required_asset_amounts(calls);
        let spendable_coins = Self::get_spendable_coins(wallet, &required_asset_amounts).await?;

        let (inputs, outputs) =
            Self::get_transaction_inputs_outputs(calls, wallet.address(), spendable_coins);

        let mut tx = Transaction::script(
            tx_parameters.gas_price,
            tx_parameters.gas_limit,
            tx_parameters.maturity,
            script,
            script_data,
            inputs,
            outputs,
            vec![],
        );

        let base_asset_amount = required_asset_amounts
            .iter()
            .find(|(asset_id, _)| *asset_id == AssetId::default());
        match base_asset_amount {
            Some((_, base_amount)) => wallet.add_fee_coins(&mut tx, *base_amount, 0).await?,
            None => wallet.add_fee_coins(&mut tx, 0, 0).await?,
        }
        wallet.sign_transaction(&mut tx).await.unwrap();

        Ok(Script::new(tx))
    }

    /// Calculates how much of each asset id the given calls require and
    /// proceeds to request spendable coins from `wallet` to cover that cost.
    async fn get_spendable_coins(
        wallet: &WalletUnlocked,
        required_asset_amounts: &[(AssetId, u64)],
    ) -> Result<Vec<Coin>, Error> {
        stream::iter(required_asset_amounts)
            .map(|(asset_id, amount)| wallet.get_spendable_coins(*asset_id, *amount))
            .buffer_unordered(10)
            .collect::<Vec<_>>()
            .await
            .into_iter()
            .flatten_ok()
            .collect()
    }

    fn calculate_required_asset_amounts(calls: &[ContractCall]) -> Vec<(AssetId, u64)> {
        let amounts_per_asset_id = Self::extract_required_amounts_per_asset_id(calls);
        Self::sum_up_amounts_for_each_asset_id(amounts_per_asset_id)
    }

    fn extract_required_amounts_per_asset_id(
        calls: &[ContractCall],
    ) -> impl Iterator<Item = (AssetId, u64)> + '_ {
        calls
            .iter()
            .map(|call| (call.call_parameters.asset_id, call.call_parameters.amount))
    }

    fn sum_up_amounts_for_each_asset_id(
        amounts_per_asset_id: impl Iterator<Item = (AssetId, u64)>,
    ) -> Vec<(AssetId, u64)> {
        amounts_per_asset_id
            .group_by(|(asset_id, _)| *asset_id)
            .into_iter()
            .map(|(asset_id, groups_w_same_asset_id)| {
                let total_amount_in_group = groups_w_same_asset_id.map(|(_, amount)| amount).sum();
                (asset_id, total_amount_in_group)
            })
            .collect()
    }

    /// Given a list of contract calls, create the actual opcodes used to call the contract
    fn get_instructions(calls: &[ContractCall], offsets: Vec<CallParamOffsets>) -> Vec<u8> {
        let num_calls = calls.len();

        let mut instructions = vec![];
        for (_, call_offsets) in (0..num_calls).zip(offsets.iter()) {
            instructions.extend(Self::get_single_call_instructions(call_offsets));
        }

        instructions.extend(Opcode::RET(REG_ONE).to_bytes());

        instructions
    }

    /// Returns script data, consisting of the following items in the given order:
    /// 1. Asset ID to be forwarded (AmountId::LEN)
    /// 2. Amount to be forwarded (1 * WORD_SIZE)
    /// 3. Gas to be forwarded (1 * WORD_SIZE)
    /// 4. Contract ID (ContractID::LEN);
    /// 5. Function selector (1 * WORD_SIZE);
    /// 6. Calldata offset (optional) (1 * WORD_SIZE)
    /// 7. Encoded arguments (optional) (variable length)
    fn get_script_data(
        calls: &[ContractCall],
        data_offset: usize,
        gas_limit: u64,
    ) -> (Vec<u8>, Vec<CallParamOffsets>) {
        let mut script_data = vec![];
        let mut param_offsets = vec![];

        // The data for each call is ordered into segments
        let mut segment_offset = data_offset;

        for call in calls {
            let call_param_offsets = CallParamOffsets {
                asset_id_offset: segment_offset,
                amount_offset: segment_offset + AssetId::LEN,
                gas_forwarded_offset: segment_offset + AssetId::LEN + WORD_SIZE,
                call_data_offset: segment_offset + AssetId::LEN + 2 * WORD_SIZE,
            };
            param_offsets.push(call_param_offsets);

            script_data.extend(call.call_parameters.asset_id.to_vec());

            script_data.extend(call.call_parameters.amount.to_be_bytes());

            // If gas_forwarded is not set, use the transaction gas limit
            let gas_forwarded = call.call_parameters.gas_forwarded.unwrap_or(gas_limit);
            script_data.extend(gas_forwarded.to_be_bytes());

            script_data.extend(call.contract_id.hash().as_ref());

            script_data.extend(call.encoded_selector);

            // If the method call takes custom inputs or has more than
            // one argument, we need to calculate the `call_data_offset`,
            // which points to where the data for the custom types start in the
            // transaction. If it doesn't take any custom inputs, this isn't necessary.
            let encoded_args_start_offset = if call.compute_custom_input_offset {
                // Custom inputs are stored after the previously added parameters,
                // including custom_input_offset
                let custom_input_offset =
                    segment_offset + AssetId::LEN + 2 * WORD_SIZE + ContractId::LEN + 2 * WORD_SIZE;
                script_data.extend(&(custom_input_offset as Word).to_be_bytes());
                custom_input_offset
            } else {
                segment_offset
            };

            let bytes = call.encoded_args.resolve(encoded_args_start_offset as u64);
            script_data.extend(bytes);

            // the data segment that holds the parameters for the next call
            // begins at the original offset + the data we added so far
            segment_offset = data_offset + script_data.len();
        }

        (script_data, param_offsets)
    }

    /// Returns the VM instructions for calling a contract method
    /// We use the Opcode to call a contract: `CALL` pointing at the
    /// following registers;
    ///
    /// 0x10 Script data offset
    /// 0x11 Gas forwarded
    /// 0x12 Coin amount
    /// 0x13 Asset ID
    ///
    /// Note that these are soft rules as we're picking this addresses simply because they
    /// non-reserved register.
    fn get_single_call_instructions(offsets: &CallParamOffsets) -> Vec<u8> {
        let instructions = vec![
            Opcode::MOVI(0x10, offsets.call_data_offset as Immediate18),
            Opcode::MOVI(0x11, offsets.gas_forwarded_offset as Immediate18),
            Opcode::LW(0x11, 0x11, 0),
            Opcode::MOVI(0x12, offsets.amount_offset as Immediate18),
            Opcode::LW(0x12, 0x12, 0),
            Opcode::MOVI(0x13, offsets.asset_id_offset as Immediate18),
            Opcode::CALL(0x10, 0x12, 0x13, 0x11),
        ];

        #[allow(clippy::iter_cloned_collect)]
        instructions.iter().copied().collect::<Vec<u8>>()
    }

    /// Returns the assets and contracts that will be consumed (inputs) and created (outputs)
    /// by the transaction
    fn get_transaction_inputs_outputs(
        calls: &[ContractCall],
        wallet_address: &Bech32Address,
        spendable_coins: Vec<Coin>,
    ) -> (Vec<Input>, Vec<Output>) {
        let asset_ids = Self::extract_unique_asset_ids(&spendable_coins);
        let contract_ids = Self::extract_unique_contract_ids(calls);
        let num_of_contracts = contract_ids.len();

        let inputs = chain!(
            Self::generate_contract_inputs(contract_ids),
            Self::convert_to_signed_coins(spendable_coins),
        )
        .collect();

        // Note the contract_outputs need to come first since the
        // contract_inputs are referencing them via `output_index`. The node
        // will, upon receiving our request, use `output_index` to index the
        // `inputs` array we've sent over.
        let outputs = chain!(
            Self::generate_contract_outputs(num_of_contracts),
            Self::generate_asset_change_outputs(wallet_address, asset_ids),
            Self::extract_variable_outputs(calls),
            Self::extract_message_outputs(calls)
        )
        .collect();
        (inputs, outputs)
    }

    fn extract_unique_asset_ids(spendable_coins: &[Coin]) -> HashSet<AssetId> {
        spendable_coins
            .iter()
            .map(|coin| coin.asset_id.clone().into())
            .collect()
    }

    fn extract_variable_outputs(calls: &[ContractCall]) -> Vec<Output> {
        calls
            .iter()
            .filter_map(|call| call.variable_outputs.clone())
            .flatten()
            .collect()
    }

    fn extract_message_outputs(calls: &[ContractCall]) -> Vec<Output> {
        calls
            .iter()
            .filter_map(|call| call.message_outputs.clone())
            .flatten()
            .collect()
    }

    fn generate_asset_change_outputs(
        wallet_address: &Bech32Address,
        asset_ids: HashSet<AssetId>,
    ) -> Vec<Output> {
        asset_ids
            .into_iter()
            .map(|asset_id| Output::change(wallet_address.into(), 0, asset_id))
            .collect()
    }

    fn generate_contract_outputs(num_of_contracts: usize) -> Vec<Output> {
        (0..num_of_contracts)
            .map(|idx| Output::contract(idx as u8, Bytes32::zeroed(), Bytes32::zeroed()))
            .collect()
    }

    fn convert_to_signed_coins(spendable_coins: Vec<Coin>) -> Vec<Input> {
        spendable_coins
            .into_iter()
            .map(|coin| {
                Input::coin_signed(
                    UtxoId::from(coin.utxo_id),
                    coin.owner.into(),
                    coin.amount.0,
                    coin.asset_id.into(),
                    TxPointer::default(),
                    0,
                    0,
                )
            })
            .collect()
    }

    fn generate_contract_inputs(contract_ids: HashSet<ContractId>) -> Vec<Input> {
        contract_ids
            .into_iter()
            .enumerate()
            .map(|(idx, contract_id)| {
                Input::contract(
                    UtxoId::new(Bytes32::zeroed(), idx as u8),
                    Bytes32::zeroed(),
                    Bytes32::zeroed(),
                    TxPointer::default(),
                    contract_id,
                )
            })
            .collect()
    }

    fn extract_unique_contract_ids(calls: &[ContractCall]) -> HashSet<ContractId> {
        calls
            .iter()
            .flat_map(|call| {
                call.external_contracts
                    .iter()
                    .map(|bech32| bech32.into())
                    .chain(iter::once((&call.contract_id).into()))
            })
            .collect()
    }

    /// Calculates the length of the script based on the number of contract calls it
    /// has to make and returns the offset at which the script data begins
    fn get_data_offset(num_calls: usize) -> usize {
        // use placeholder for call param offsets, we only care about the length
        let mut len_script =
            Script::get_single_call_instructions(&CallParamOffsets::default()).len() * num_calls;

        // to account for RET instruction which is added later
        len_script += Opcode::LEN;

        ConsensusParameters::DEFAULT.tx_offset()
            + fuel_tx::Script::script_offset_static()
            + padded_len_usize(len_script)
    }

    /// Execute the transaction in a state-modifying manner.
    pub async fn call(self, provider: &Provider) -> Result<Vec<Receipt>, Error> {
        let chain_info = provider.chain_info().await?;

        self.tx.check_without_signatures(
            chain_info.latest_block.header.height.0,
            &chain_info.consensus_parameters.into(),
        )?;

        provider.send_transaction(&self.tx).await
    }

    /// Execute the transaction in a simulated manner, not modifying blockchain state
    pub async fn simulate(self, provider: &Provider) -> Result<Vec<Receipt>, Error> {
        let chain_info = provider.chain_info().await?;

        self.tx.check_without_signatures(
            chain_info.latest_block.header.height.0,
            &chain_info.consensus_parameters.into(),
        )?;

        let receipts = provider.dry_run(&self.tx.clone().into()).await?;
        if receipts
            .iter()
            .any(|r|
                matches!(r, Receipt::ScriptResult { result, .. } if *result != ScriptExecutionResult::Success)
        ) {
            return Err(Error::RevertTransactionError(Default::default(), receipts));
        }

        Ok(receipts)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use fuel_gql_client::client::schema::coin::CoinStatus;
    use fuels_core::abi_encoder::ABIEncoder;
    use fuels_core::parameters::CallParameters;
    use fuels_core::Token;
    use fuels_types::bech32::Bech32ContractId;
    use fuels_types::param_types::ParamType;
    use rand::Rng;
    use std::slice;

    #[tokio::test]
    async fn test_script_data() {
        // Arrange
        const SELECTOR_LEN: usize = WORD_SIZE;
        const NUM_CALLS: usize = 3;

        let contract_ids = vec![
            Bech32ContractId::new("test", Bytes32::new([1u8; 32])),
            Bech32ContractId::new("test", Bytes32::new([1u8; 32])),
            Bech32ContractId::new("test", Bytes32::new([1u8; 32])),
        ];

        let asset_ids = vec![
            AssetId::from([4u8; 32]),
            AssetId::from([5u8; 32]),
            AssetId::from([6u8; 32]),
        ];

        let selectors = vec![[7u8; 8], [8u8; 8], [9u8; 8]];

        // Call 2 has multiple inputs, compute_custom_input_offset will be true

        let args = [Token::U8(1), Token::U16(2), Token::U8(3)]
            .map(|token| ABIEncoder::encode(&[token]).unwrap())
            .to_vec();

        let calls: Vec<ContractCall> = (0..NUM_CALLS)
            .map(|i| ContractCall {
                contract_id: contract_ids[i].clone(),
                encoded_selector: selectors[i],
                encoded_args: args[i].clone(),
                call_parameters: CallParameters::new(
                    Some(i as u64),
                    Some(asset_ids[i]),
                    Some(i as u64),
                ),
                compute_custom_input_offset: i == 1,
                variable_outputs: None,
                message_outputs: None,
                external_contracts: vec![],
                output_param: ParamType::Unit,
            })
            .collect();

        // Act
        let (script_data, param_offsets) = Script::get_script_data(&calls, 0, 0);

        // Assert
        assert_eq!(param_offsets.len(), NUM_CALLS);
        for (idx, offsets) in param_offsets.iter().enumerate() {
            let asset_id = script_data
                [offsets.asset_id_offset..offsets.asset_id_offset + AssetId::LEN]
                .to_vec();
            assert_eq!(asset_id, asset_ids[idx].to_vec());

            let amount =
                script_data[offsets.amount_offset..offsets.amount_offset + WORD_SIZE].to_vec();
            assert_eq!(amount, idx.to_be_bytes());

            let gas = script_data
                [offsets.gas_forwarded_offset..offsets.gas_forwarded_offset + WORD_SIZE]
                .to_vec();
            assert_eq!(gas, idx.to_be_bytes().to_vec());

            let contract_id =
                &script_data[offsets.call_data_offset..offsets.call_data_offset + ContractId::LEN];
            let expected_contract_id = contract_ids[idx].hash();
            assert_eq!(contract_id, expected_contract_id.as_slice());

            let selector_offset = offsets.call_data_offset + ContractId::LEN;
            let selector = script_data[selector_offset..selector_offset + SELECTOR_LEN].to_vec();
            assert_eq!(selector, selectors[idx].to_vec());
        }

        // Calls 1 and 3 have their input arguments after the selector
        let call_1_arg_offset = param_offsets[0].call_data_offset + ContractId::LEN + SELECTOR_LEN;
        let call_1_arg = script_data[call_1_arg_offset..call_1_arg_offset + WORD_SIZE].to_vec();
        assert_eq!(call_1_arg, args[0].resolve(0));

        let call_3_arg_offset = param_offsets[2].call_data_offset + ContractId::LEN + SELECTOR_LEN;
        let call_3_arg = script_data[call_3_arg_offset..call_3_arg_offset + WORD_SIZE].to_vec();
        assert_eq!(call_3_arg, args[2].resolve(0));

        // Call 2 has custom inputs and custom_input_offset
        let call_2_arg_offset = param_offsets[1].call_data_offset + ContractId::LEN + SELECTOR_LEN;
        let custom_input_offset =
            script_data[call_2_arg_offset..call_2_arg_offset + WORD_SIZE].to_vec();
        assert_eq!(
            custom_input_offset,
            (call_2_arg_offset + WORD_SIZE).to_be_bytes()
        );

        let custom_input_offset =
            param_offsets[1].call_data_offset + ContractId::LEN + SELECTOR_LEN + WORD_SIZE;
        let custom_input =
            script_data[custom_input_offset..custom_input_offset + WORD_SIZE].to_vec();
        assert_eq!(custom_input, args[1].resolve(0));
    }

    #[test]
    fn contract_input_present() {
        let call = ContractCall::new_with_random_id();

        let (inputs, _) = Script::get_transaction_inputs_outputs(
            slice::from_ref(&call),
            &random_bech32_addr(),
            Default::default(),
        );

        assert_eq!(
            inputs,
            vec![Input::contract(
                UtxoId::new(Bytes32::zeroed(), 0),
                Bytes32::zeroed(),
                Bytes32::zeroed(),
                TxPointer::default(),
                call.contract_id.into(),
            )]
        );
    }

    #[test]
    fn contract_input_is_not_duplicated() {
        let call = ContractCall::new_with_random_id();
        let call_w_same_contract =
            ContractCall::new_with_random_id().with_contract_id(call.contract_id.clone());

        let calls = [call, call_w_same_contract];

        let (inputs, _) = Script::get_transaction_inputs_outputs(
            &calls,
            &random_bech32_addr(),
            Default::default(),
        );

        assert_eq!(
            inputs,
            vec![Input::contract(
                UtxoId::new(Bytes32::zeroed(), 0),
                Bytes32::zeroed(),
                Bytes32::zeroed(),
                TxPointer::default(),
                calls[0].contract_id.clone().into(),
            )]
        );
    }

    #[test]
    fn contract_output_present() {
        let call = ContractCall::new_with_random_id();

        let (_, outputs) = Script::get_transaction_inputs_outputs(
            &[call],
            &random_bech32_addr(),
            Default::default(),
        );

        assert_eq!(
            outputs,
            vec![Output::contract(0, Bytes32::zeroed(), Bytes32::zeroed())]
        );
    }

    #[test]
    fn external_contract_input_present() {
        // given
        let external_contract_id = random_bech32_contract_id();
        let call = ContractCall::new_with_random_id()
            .with_external_contracts(vec![external_contract_id.clone()]);

        // when
        let (inputs, _) = Script::get_transaction_inputs_outputs(
            slice::from_ref(&call),
            &random_bech32_addr(),
            Default::default(),
        );

        // then
        let mut expected_contract_ids: HashSet<ContractId> =
            [call.contract_id.into(), external_contract_id.into()].into();

        for (index, input) in inputs.into_iter().enumerate() {
            match input {
                Input::Contract {
                    utxo_id,
                    balance_root,
                    state_root,
                    tx_pointer,
                    contract_id,
                } => {
                    assert_eq!(utxo_id, UtxoId::new(Bytes32::zeroed(), index as u8));
                    assert_eq!(balance_root, Bytes32::zeroed());
                    assert_eq!(state_root, Bytes32::zeroed());
                    assert_eq!(tx_pointer, TxPointer::default());
                    assert!(expected_contract_ids.contains(&contract_id));
                    expected_contract_ids.remove(&contract_id);
                }
                _ => {
                    panic!("Expected only inputs of type Input::Contract");
                }
            }
        }
    }

    #[test]
    fn external_contract_output_present() {
        // given
        let external_contract_id = random_bech32_contract_id();
        let call =
            ContractCall::new_with_random_id().with_external_contracts(vec![external_contract_id]);

        // when
        let (_, outputs) = Script::get_transaction_inputs_outputs(
            &[call],
            &random_bech32_addr(),
            Default::default(),
        );

        // then
        let expected_outputs = (0..=1)
            .map(|i| Output::contract(i, Bytes32::zeroed(), Bytes32::zeroed()))
            .collect::<Vec<_>>();

        assert_eq!(outputs, expected_outputs);
    }

    #[test]
    fn change_per_asset_id_added() {
        // given
        let wallet_addr = random_bech32_addr();
        let asset_ids = [AssetId::default(), AssetId::from([1; 32])];

        let coins = asset_ids
            .into_iter()
            .map(|asset_id| Coin {
                amount: 100u64.into(),
                block_created: 0u64.into(),
                asset_id: asset_id.into(),
                utxo_id: Default::default(),
                maturity: 0u64.into(),
                owner: Default::default(),
                status: CoinStatus::Unspent,
            })
            .collect();
        let call = ContractCall::new_with_random_id();

        // when
        let (_, outputs) = Script::get_transaction_inputs_outputs(&[call], &wallet_addr, coins);

        // then
        let change_outputs: HashSet<Output> = outputs[1..].iter().cloned().collect();

        let expected_change_outputs = asset_ids
            .into_iter()
            .map(|asset_id| Output::Change {
                to: wallet_addr.clone().into(),
                amount: 0,
                asset_id,
            })
            .collect();

        assert_eq!(change_outputs, expected_change_outputs);
    }

    #[test]
    fn spendable_coins_added_to_input() {
        // given
        let asset_ids = [AssetId::default(), AssetId::from([1; 32])];

        let generate_spendable_coins = || {
            asset_ids
                .into_iter()
                .enumerate()
                .map(|(index, asset_id)| Coin {
                    amount: (index * 10).into(),
                    block_created: 1u64.into(),
                    asset_id: asset_id.into(),
                    utxo_id: Default::default(),
                    maturity: 0u64.into(),
                    owner: Default::default(),
                    status: CoinStatus::Unspent,
                })
                .collect::<Vec<_>>()
        };

        let call = ContractCall::new_with_random_id();

        // when
        let (inputs, _) = Script::get_transaction_inputs_outputs(
            &[call],
            &random_bech32_addr(),
            generate_spendable_coins(),
        );

        // then
        let inputs_as_signed_coins: HashSet<Input> = inputs[1..].iter().cloned().collect();

        let expected_inputs = generate_spendable_coins()
            .into_iter()
            .map(|coin| {
                Input::coin_signed(
                    fuel_tx::UtxoId::from(coin.utxo_id),
                    coin.owner.into(),
                    coin.amount.0,
                    coin.asset_id.into(),
                    TxPointer::default(),
                    0,
                    0,
                )
            })
            .collect::<HashSet<_>>();

        assert_eq!(expected_inputs, inputs_as_signed_coins);
    }

    #[test]
    fn variable_outputs_appended_to_outputs() {
        // given
        let variable_outputs = [100, 200].map(|amount| {
            Output::variable(random_bech32_addr().into(), amount, Default::default())
        });

        let calls = variable_outputs
            .iter()
            .cloned()
            .map(|variable_output| {
                ContractCall::new_with_random_id().with_variable_outputs(vec![variable_output])
            })
            .collect::<Vec<_>>();

        // when
        let (_, outputs) = Script::get_transaction_inputs_outputs(
            &calls,
            &random_bech32_addr(),
            Default::default(),
        );

        // then
        let actual_variable_outputs: HashSet<Output> = outputs[2..].iter().cloned().collect();
        let expected_outputs: HashSet<Output> = variable_outputs.into();

        assert_eq!(expected_outputs, actual_variable_outputs);
    }

    #[test]
    fn message_outputs_appended_to_outputs() {
        // given
        let message_outputs =
            [100, 200].map(|amount| Output::message(random_bech32_addr().into(), amount));

        let calls = message_outputs
            .iter()
            .cloned()
            .map(|message_output| {
                ContractCall::new_with_random_id().with_message_outputs(vec![message_output])
            })
            .collect::<Vec<_>>();

        // when
        let (_, outputs) = Script::get_transaction_inputs_outputs(
            &calls,
            &random_bech32_addr(),
            Default::default(),
        );

        // then
        let actual_message_outputs: HashSet<Output> = outputs[2..].iter().cloned().collect();
        let expected_outputs: HashSet<Output> = message_outputs.into();

        assert_eq!(expected_outputs, actual_message_outputs);
    }

    #[test]
    fn will_collate_same_asset_ids() {
        let amounts = [100, 200];

        let asset_id = [1; 32].into();
        let calls = amounts.map(|amount| {
            ContractCall::new_with_random_id().with_call_parameters(CallParameters::new(
                Some(amount),
                Some(asset_id),
                None,
            ))
        });

        let asset_id_amounts = Script::calculate_required_asset_amounts(&calls);

        let expected_asset_id_amounts = [(asset_id, amounts.iter().sum())].into();

        assert_eq!(
            asset_id_amounts.into_iter().collect::<HashSet<_>>(),
            expected_asset_id_amounts
        )
    }

    impl ContractCall {
        pub fn new_with_random_id() -> Self {
            ContractCall {
                contract_id: random_bech32_contract_id(),
                encoded_args: Default::default(),
                encoded_selector: [0; 8],
                call_parameters: Default::default(),
                compute_custom_input_offset: false,
                variable_outputs: None,
                external_contracts: Default::default(),
                output_param: ParamType::Unit,
                message_outputs: None,
            }
        }
    }

    impl ContractCall {
        pub fn with_contract_id(self, contract_id: Bech32ContractId) -> Self {
            ContractCall {
                contract_id,
                ..self
            }
        }
        pub fn with_external_contracts(
            self,
            external_contracts: Vec<Bech32ContractId>,
        ) -> ContractCall {
            ContractCall {
                external_contracts,
                ..self
            }
        }

        pub fn with_variable_outputs(self, variable_outputs: Vec<Output>) -> ContractCall {
            ContractCall {
                variable_outputs: Some(variable_outputs),
                ..self
            }
        }

        pub fn with_message_outputs(self, message_outputs: Vec<Output>) -> ContractCall {
            ContractCall {
                message_outputs: Some(message_outputs),
                ..self
            }
        }

        pub fn with_call_parameters(self, call_parameters: CallParameters) -> ContractCall {
            ContractCall {
                call_parameters,
                ..self
            }
        }
    }

    fn random_bech32_addr() -> Bech32Address {
        Bech32Address::new("fuel", rand::thread_rng().gen::<[u8; 32]>())
    }

    fn random_bech32_contract_id() -> Bech32ContractId {
        Bech32ContractId::new("fuel", rand::thread_rng().gen::<[u8; 32]>())
    }
}

#[derive(Default)]
pub struct ScriptBuilder {
    gas_price: Word,
    gas_limit: Word,
    maturity: Word,
    script: Vec<u8>,
    script_data: Vec<u8>,
    inputs: Vec<Input>,
    outputs: Vec<Output>,
    witnesses: Vec<Witness>,
    asset_id: AssetId,
    amount: u64,
}

impl ScriptBuilder {
    pub fn new() -> ScriptBuilder {
        ScriptBuilder {
            gas_price: 0,
            gas_limit: 0,
            maturity: 0,
            script: vec![],
            script_data: vec![],
            inputs: vec![],
            outputs: vec![],
            witnesses: vec![],
            asset_id: AssetId::default(),
            amount: 0,
        }
    }

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

    pub fn set_script(mut self, script: Vec<Opcode>) -> ScriptBuilder {
        let script: Vec<u8> = script.into_iter().collect();
        self.script = script;
        self
    }

    pub fn set_inputs(mut self, inputs: Vec<Input>) -> ScriptBuilder {
        self.inputs = inputs;
        self
    }

    pub fn set_outputs(mut self, outputs: Vec<Output>) -> ScriptBuilder {
        self.outputs = outputs;
        self
    }

    pub fn set_gas_price(mut self, gas_price: Word) -> ScriptBuilder {
        self.gas_price = gas_price;
        self
    }

    pub fn set_gas_limit(mut self, gas_limit: Word) -> ScriptBuilder {
        self.gas_limit = gas_limit;
        self
    }

    pub fn set_maturity(mut self, maturity: Word) -> ScriptBuilder {
        self.maturity = maturity;
        self
    }

    pub fn set_asset_id(mut self, asset_id: AssetId) -> ScriptBuilder {
        self.asset_id = asset_id;
        self
    }

    pub fn set_amount(mut self, amount: u64) -> ScriptBuilder {
        self.amount = amount;
        self
    }

    pub async fn build(self, wallet: &WalletUnlocked) -> Result<Script, Error> {
        let mut tx = Transaction::script(
            self.gas_price,
            self.gas_limit,
            self.maturity,
            self.script,
            self.script_data,
            self.inputs.to_vec(),
            self.outputs.to_vec(),
            self.witnesses.to_vec(),
        );

        let base_amount = if self.asset_id == AssetId::default() {
            self.amount
        } else {
            0
        };

        wallet.add_fee_coins(&mut tx, base_amount, 0).await?;
        wallet.sign_transaction(&mut tx).await?;

        Ok(Script::new(tx))
    }
}