fuels_programs/calls/
script_call.rs

1use std::{collections::HashSet, fmt::Debug};
2
3use fuel_tx::{ContractId, Output};
4use fuels_core::types::{
5    bech32::Bech32ContractId,
6    errors::{error, Result},
7    input::Input,
8};
9use itertools::chain;
10
11use crate::calls::utils::{generate_contract_inputs, generate_contract_outputs, sealed};
12
13#[derive(Debug, Clone)]
14/// Contains all data relevant to a single script call
15pub struct ScriptCall {
16    pub script_binary: Vec<u8>,
17    pub encoded_args: Result<Vec<u8>>,
18    pub inputs: Vec<Input>,
19    pub outputs: Vec<Output>,
20    pub external_contracts: Vec<Bech32ContractId>,
21}
22
23impl ScriptCall {
24    /// Add custom outputs to the `ScriptCall`.
25    pub fn with_outputs(mut self, outputs: Vec<Output>) -> Self {
26        self.outputs = outputs;
27        self
28    }
29
30    /// Add custom inputs to the `ScriptCall`.
31    pub fn with_inputs(mut self, inputs: Vec<Input>) -> Self {
32        self.inputs = inputs;
33        self
34    }
35
36    pub(crate) fn prepare_inputs_outputs(&self) -> Result<(Vec<Input>, Vec<Output>)> {
37        let contract_ids: HashSet<ContractId> = self
38            .external_contracts
39            .iter()
40            .map(|bech32| bech32.into())
41            .collect();
42        let num_of_contracts = contract_ids.len();
43
44        let inputs = chain!(
45            self.inputs.clone(),
46            generate_contract_inputs(contract_ids, self.outputs.len())
47        )
48        .collect();
49
50        // Note the contract_outputs are placed after the custom outputs and
51        // the contract_inputs are referencing them via `output_index`. The
52        // node will, upon receiving our request, use `output_index` to index
53        // the `inputs` array we've sent over.
54        let outputs = chain!(
55            self.outputs.clone(),
56            generate_contract_outputs(num_of_contracts, self.inputs.len()),
57        )
58        .collect();
59
60        Ok((inputs, outputs))
61    }
62
63    pub(crate) fn compute_script_data(&self) -> Result<Vec<u8>> {
64        self.encoded_args
65            .as_ref()
66            .map(|b| b.to_owned())
67            .map_err(|e| error!(Codec, "cannot encode script call arguments: {e}"))
68    }
69}
70
71impl sealed::Sealed for ScriptCall {}