multiversx_sc_meta_lib/contract/generate_snippets/
snippet_crate_gen.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
use colored::Colorize;
use std::{
    fs::{self, File, OpenOptions},
    io::Write,
    path::Path,
};

use crate::version_history;

static SNIPPETS_SOURCE_FILE_NAME: &str = "interactor_main.rs";
static LIB_SOURCE_FILE_NAME: &str = "interact.rs";
static SC_CONFIG_PATH: &str = "../sc-config.toml";
static CONFIG_TOML_PATH: &str = "config.toml";
static CONFIG_SOURCE_FILE_NAME: &str = "config.rs";
static FULL_PROXY_ENTRY: &str = r#"[[proxy]]
path = "interactor/src/proxy.rs"
 "#;
static PROXY_PATH: &str = "interactor/src/proxy.rs";
static INTERACTOR_CS_TEST_FILE_NAME: &str = "interact_cs_tests.rs";
static INTERACTOR_TEST_FILE_NAME: &str = "interact_tests.rs";

pub(crate) fn create_snippets_folder(snippets_folder_path: &str) {
    // returns error if folder already exists, so we ignore the result
    let _ = fs::create_dir(snippets_folder_path);
}

pub(crate) fn create_snippets_gitignore(snippets_folder_path: &str, overwrite: bool) {
    let gitignore_path = format!("{snippets_folder_path}/.gitignore");
    let mut file = if overwrite {
        File::create(&gitignore_path).unwrap()
    } else {
        match File::options()
            .create_new(true)
            .write(true)
            .open(&gitignore_path)
        {
            Ok(f) => f,
            Err(_) => return,
        }
    };

    writeln!(
        &mut file,
        "# Pem files are used for interactions, but shouldn't be committed
*.pem"
    )
    .unwrap();
}

pub(crate) fn create_snippets_cargo_toml(
    snippets_folder_path: &str,
    contract_crate_name: &str,
    overwrite: bool,
) {
    let cargo_toml_path = format!("{snippets_folder_path}/Cargo.toml");
    let mut file = if overwrite {
        File::create(&cargo_toml_path).unwrap()
    } else {
        match File::options()
            .create_new(true)
            .write(true)
            .open(&cargo_toml_path)
        {
            Ok(f) => f,
            Err(_) => return,
        }
    };

    let last_release_version = &version_history::LAST_VERSION;

    writeln!(
        &mut file,
        r#"[package]
name = "rust-interact"
version = "0.0.0"
authors = ["you"]
edition = "2021"
publish = false

[[bin]]
name = "rust-interact"
path = "src/{SNIPPETS_SOURCE_FILE_NAME}"

[lib]
path = "src/{LIB_SOURCE_FILE_NAME}"

[dependencies.{contract_crate_name}]
path = ".."

[dependencies.multiversx-sc-snippets]
version = "{last_release_version}"

[dependencies.multiversx-sc]
version = "{last_release_version}"

[dependencies]
clap = {{ version = "4.4.7", features = ["derive"] }}
serde = {{ version = "1.0", features = ["derive"] }}
toml = "0.8.6"

[features]
chain-simulator-tests = []
"#
    )
    .unwrap();
}

pub(crate) fn create_src_folder(snippets_folder_path: &str) {
    // returns error if folder already exists, so we ignore the result
    let src_folder_path = format!("{snippets_folder_path}/src");
    let _ = fs::create_dir(src_folder_path);
}

#[must_use]
pub(crate) fn create_and_get_lib_file(snippets_folder_path: &str, overwrite: bool) -> File {
    let lib_path = format!("{snippets_folder_path}/src/{LIB_SOURCE_FILE_NAME}");
    if overwrite {
        File::create(&lib_path).unwrap()
    } else {
        match File::options().create_new(true).write(true).open(&lib_path) {
            Ok(f) => f,
            Err(_) => {
                println!(
                    "{}",
                    format!("{lib_path} file already exists, --overwrite option was not provided",)
                        .yellow()
                );
                File::options().write(true).open(&lib_path).unwrap()
            },
        }
    }
}

pub(crate) fn create_main_file(snippets_folder_path: &str, contract_crate_name: &str) {
    let lib_path = format!("{snippets_folder_path}/src/{SNIPPETS_SOURCE_FILE_NAME}");

    let mut file = File::create(lib_path).unwrap();

    writeln!(
        &mut file,
        r#"
use multiversx_sc_snippets::imports::*;
use rust_interact::{contract_crate_name}_cli;

#[tokio::main]
async fn main() {{
    {contract_crate_name}_cli().await;
}}  
"#
    )
    .unwrap();
}

pub(crate) fn create_test_folder_and_get_files(snippets_folder_path: &str) -> (File, File) {
    let folder_path = format!("{snippets_folder_path}/tests");

    if !Path::new(&folder_path).exists() {
        fs::create_dir_all(&folder_path).expect("Failed to create tests directory");
    }

    let interactor_file_path = format!("{folder_path}/{INTERACTOR_TEST_FILE_NAME}");
    let interactor_cs_file_path = format!("{folder_path}/{INTERACTOR_CS_TEST_FILE_NAME}");

    let interactor_file =
        File::create(interactor_file_path).expect("Failed to create interact_tests.rs file");
    let interactor_cs_file =
        File::create(interactor_cs_file_path).expect("Failed to create interact_cs_tests.rs file");

    (interactor_file, interactor_cs_file)
}

pub(crate) fn create_sc_config_file(overwrite: bool) {
    // check if the file should be overwritten or if it already exists
    let mut file = if overwrite || !file_exists(SC_CONFIG_PATH) {
        File::create(SC_CONFIG_PATH).unwrap()
    } else {
        // file already exists
        let file = OpenOptions::new()
            .read(true)
            .append(true)
            .open(SC_CONFIG_PATH)
            .unwrap();

        if file_contains_proxy_path(SC_CONFIG_PATH).unwrap_or(false) {
            return;
        }

        file
    };

    // write full proxy toml entry to the file
    writeln!(&mut file, "\n{FULL_PROXY_ENTRY}").unwrap();
}

pub(crate) fn create_config_toml_file(snippets_folder_path: &str) {
    let config_path = format!("{snippets_folder_path}/{CONFIG_TOML_PATH}");
    let mut file = File::create(config_path).unwrap();

    writeln!(
        &mut file,
        r#"
# chain_type = 'simulator'
# gateway_uri = 'http://localhost:8085'

chain_type = 'real'
gateway_uri = 'https://devnet-gateway.multiversx.com'
"#
    )
    .unwrap();
}

pub(crate) fn create_config_rust_file(snippets_folder_path: &str) -> File {
    let lib_path = format!("{snippets_folder_path}/src/{CONFIG_SOURCE_FILE_NAME}");

    File::create(lib_path).unwrap()
}

fn file_exists(path: &str) -> bool {
    fs::metadata(path).is_ok()
}

fn file_contains_proxy_path(file_path: &str) -> std::io::Result<bool> {
    let file_content = fs::read_to_string(file_path)?;
    let proxy_entry = format!("path = \"{}\"", PROXY_PATH);

    Ok(file_content.contains(&proxy_entry))
}