fuels_rs/
script.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use crate::errors::Error;
use forc::test::{forc_build, BuildCommand};
use forc::util::constants;
use forc::util::helpers::read_manifest;
use fuel_gql_client::client::FuelClient;
use fuel_tx::{Receipt, Transaction};
use std::path::PathBuf;
use sway_utils::find_manifest_dir;

/// Script is a very thin layer on top of fuel-client with some
/// extra functionalities needed and provided by the SDK.
pub struct Script {
    pub tx: Transaction,
}

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

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

    pub async fn call(self, fuel_client: &FuelClient) -> Result<Vec<Receipt>, Error> {
        let tx_id = fuel_client.submit(&self.tx).await.unwrap();

        let receipts = fuel_client.receipts(&tx_id.0.to_string()).await.unwrap();

        Ok(receipts)
    }

    /// Compiles a Sway script
    pub fn compile_sway_script(project_path: &str) -> Result<CompiledScript, Error> {
        let build_command = BuildCommand {
            path: Some(project_path.into()),
            print_finalized_asm: false,
            print_intermediate_asm: false,
            binary_outfile: None,
            offline_mode: false,
            silent_mode: true,
            use_ir: false,
            print_ir: false,
        };

        let raw =
            forc_build::build(build_command).map_err(|message| Error::CompilationError(message))?;

        let manifest_dir = find_manifest_dir(&PathBuf::from(project_path)).unwrap();
        let manifest = read_manifest(&manifest_dir).map_err(|e| {
            Error::CompilationError(format!("Failed to find manifest for contract: {}", e))
        })?;

        let node_url = match &manifest.network {
            Some(network) => &network.url,
            _ => constants::DEFAULT_NODE_URL,
        };

        Ok(CompiledScript {
            raw,
            target_network_url: node_url.to_string(),
        })
    }
}