stackrup 0.1.2

Stackrup into the world of micro-rollups using Stackr CLI
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
use clap::{App, Arg, SubCommand};
use ethers::prelude::*;
use ethers::signers::LocalWallet;
use parser::{append_js_functions_to_file, generate_import_statement, read_first_account};
use reqwest::Error as ReqwestError;
use serde::{Deserialize, Serialize};
use std::env;
use std::env::current_dir;
use std::error::Error;
use std::fs::{self, OpenOptions};
use std::io::{stderr, stdin, stdout, Read, Write};
use std::path::PathBuf;
use std::process::Command;
use std::{collections::HashMap, os::unix::io, sync::Arc};
use tokio::sync::Mutex;
use warp::filters::body::form;
use warp::Filter;

mod confighandler;
mod filehandler;
mod parser;

use crate::confighandler::{configgenerator, Config};
use crate::filehandler::{build_index_content, index_content};
use crate::filehandler::{filewriter, state_content, tsconfig_content, utils_content};
use crate::parser::configparser;
use crate::parser::create_js_function;
use crate::parser::importparser;
use crate::parser::parse_typescript_file;
use crate::parser::remove_unwanted_lines;

#[derive(Debug, Deserialize)]
struct TokenResponse {
    access_token: String,
    expires_in: u64,
    token_type: String,
    refresh_token: Option<String>,
}

#[derive(Serialize, Deserialize)]
struct SignedBinary {
    byteCode: Vec<u8>,
    signature: String,
    appID: i32,
}

#[derive(Serialize, Deserialize)]
struct Genesis {
    signedBinary: SignedBinary,
    genesisState: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let matches = App::new("My Rust CLI")
        .version("1.0")
        .author("Your Name")
        .about("A CLI with Google Auth")
        .subcommand(
            SubCommand::with_name("init")
                .about("Initialize the application")
                .arg(
                    Arg::with_name("project-name")
                        .long("project-name")
                        .help("Sets the project name")
                        .takes_value(true)
                        .required(true),
                )
                .arg(
                    Arg::with_name("private-key")
                        .long("private-key")
                        .help("Takes private key of the operator")
                        .takes_value(true)
                        .required(true),
                ),
        )
        .subcommand(SubCommand::with_name("compile"))
        .subcommand(SubCommand::with_name("deploy"))
        .subcommand(SubCommand::with_name("parse"))
        .get_matches();

    if let Some(init_matches) = matches.subcommand_matches("init") {
        let mut config = Config {
            project_name: String::new(),
            batch_size: 0,
            batch_time: 0,
            batcher_slot_time: 0,
            operator_accounts: Vec::new(),
            aggregator_rpcs: Vec::new(),
        };

        let client_id = "266578720767-7qf52i2g90hjjlv258b2bra1ktt4f9lv.apps.googleusercontent.com";
        let clientt_secret = "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";

        println!(
            r#"
        _             _                        _ _ 
    ___| |_ __ _  ___| | ___ __            ___| (_)
   / __| __/ _` |/ __| |/ / '__|  _____   / __| | |
   \__ \ || (_| | (__|   <| |    |_____| | (__| | |
   |___/\__\__,_|\___|_|\_\_|             \___|_|_|
                                                   
   "#
        );
        println!("Enter into the world of Micro Rollups");

        if let Some(project_name) = init_matches.value_of("project-name") {
            config.project_name = project_name.trim().to_string();
        }

        if let Some(private_key) = init_matches.value_of("private-key") {
            let mut operator_address = private_key.trim();

            operator_address = operator_address.trim_start_matches("0x");

            match operator_address.len() == 64 {
                true => println!(""),
                false => {
                    println!("Invalid private key length");
                    std::process::exit(1);
                }
            }

            config.operator_accounts.push(operator_address.to_string());
        }

        config.batch_time = 3000;

        config.batch_time = 10;

        config.batch_time = 1000;

        println!("Creating project ... {}", &config.project_name);
        let _ = fs::create_dir(&config.project_name);
        let path = format!("./{}/src", &config.project_name);
        let _ = fs::create_dir(&path);
        let _ = std::fs::write(format!("{}/state.ts", &path), state_content());
        let _ = std::fs::write(
            format!("./{}/stackr.config.ts", &config.project_name),
            "contents",
        );
        let _ = std::fs::write(
            format!("./{}/utils.ts", &config.project_name),
            utils_content(),
        );

        let _ = std::fs::write(
            format!("./{}/tsconfig.json", &config.project_name),
            tsconfig_content(),
        );

        let _ = filewriter(&config.project_name);

        let _ = configgenerator(&config, &config.project_name);

        let current_dir = env::current_dir()?;

        let project_dir = current_dir.join(format!("{}/", &config.project_name));

        let index_file_path = current_dir.join(format!("{}/src/index.ts", &config.project_name));

        let state_file_path = current_dir.join(format!("{}/src/state.ts", &config.project_name));

        let _ = importparser(&index_file_path);

        let _ = importparser(&state_file_path);

        println!("Running 'bun init -y'");
        let bun_init = Command::new("bun")
            .arg("init")
            .arg("-y")
            .current_dir(&project_dir)
            .output();

        match bun_init {
            Ok(output) => {
                eprintln!("{}", &project_dir.display());
                stdout().write_all(&output.stdout)?;
                stderr().write_all(&output.stderr)?;
                if !output.status.success() {
                    eprintln!("bun install failed with status: {}", output.status);
                    std::process::exit(1);
                }
            }
            Err(e) => {
                eprintln!("Failed to execute bun install: {}", e);
                eprintln!("{}", &project_dir.display());
                std::process::exit(1);
            }
        }

        println!("Running 'bun install ethers express body-parser'");
        let bun_install = Command::new("bun")
            .arg("install")
            .arg("ethers")
            .arg("express")
            .arg("body-parser")
            .arg("merkletreejs")
            .current_dir(&project_dir)
            .output();

        match bun_install {
            Ok(output) => {
                eprintln!("{}", &project_dir.display());
                stdout().write_all(&output.stdout)?;
                stderr().write_all(&output.stderr)?;
                if !output.status.success() {
                    eprintln!("bun install failed with status: {}", output.status);
                    std::process::exit(1);
                }
            }
            Err(e) => {
                eprintln!("Failed to execute bun install: {}", e);
                eprintln!("{}", &project_dir.display());
                std::process::exit(1);
            }
        }
    }

    if matches.subcommand_matches("compile").is_some() {
        println!("Compiling...");
        let _ = compilation();
    }

    if matches.subcommand_matches("deploy").is_some() {
        println!("Deploying...");
        deploy_command().await?;
    }

    Ok(())
}

fn compilation() -> Result<(), Box<dyn Error>> {
    let current_dir = env::current_dir()?;
    let build_dir = current_dir.join("build");
    if !build_dir.exists() {
        fs::create_dir(&build_dir)?;
        println!("Created build directory: {:?}", build_dir);
    }
    let state_file_dir = current_dir.join("src/state.ts");
    let _ = fs::copy(&state_file_dir, &current_dir.join("build/state.ts"));

    let import_statement = generate_import_statement(&state_file_dir)?;

    let run_function = create_js_function(&import_statement);

    let _ = fs::write(current_dir.join("build/stf.ts"), import_statement);

    let mut build_index = OpenOptions::new()
        .append(true)
        .open(current_dir.join("build/stf.ts"))?;
    let _ = build_index.write("\n".as_bytes());
    let _ = build_index
        .write(r#"import { StateMachine } from "@stackr/stackr-js/execution";"#.as_bytes());
    let _ = build_index.write("\n\n".as_bytes());
    let _ = build_index.write(run_function?.as_bytes());
    let _ = build_index.write("\n\n".as_bytes());
    let _ = build_index.write(build_index_content().as_bytes());

    let _ = importparser(&current_dir.join("build/state.ts"));
    let _ = remove_unwanted_lines(&current_dir.join("build/state.ts"));

    println!("Transpiling stf.ts from TS -> JS ... ");

    let js_transpile = Command::new("bun")
        .args(&[
            "build",
            "./build/stf.ts",
            "--outdir=build",
            "--target=bun",
            "--external=class-transformer",
            "--external=class-validator",
            "--external=@nestjs/microservices",
            "--external=@nestjs/websockets",
            "--external=@nestjs/platform-express",
        ])
        .current_dir(&current_dir)
        .output();

    match js_transpile {
        Ok(output) => {
            stdout().write_all(&output.stdout)?;
            stderr().write_all(&output.stderr)?;
            if !output.status.success() {
                eprintln!("js -> wasm failed: {}", output.status);
                std::process::exit(1);
            }
        }
        Err(e) => {
            eprintln!("Failed to transpile: {}", e);
            eprintln!("{}", &current_dir.display());
            std::process::exit(1);
        }
    }

    println!("Creating a WASM build ...");

    let javy_compile = Command::new("javy")
        .arg("compile")
        .arg("./build/stf.js")
        .arg("-o")
        .arg("./build/stf.wasm")
        .current_dir(&current_dir)
        .output();

    match javy_compile {
        Ok(output) => {
            stdout().write_all(&output.stdout)?;
            stderr().write_all(&output.stderr)?;
            if !output.status.success() {
                eprintln!("js -> wasm failed: {}", output.status);
                std::process::exit(1);
            }
        }
        Err(e) => {
            eprintln!("Failed to execute javy compile: {}", e);
            std::process::exit(1);
        }
    }

    let _ = configparser();

    println!("Compilation done !");
    Ok(())
}

async fn exchange_code_for_token(
    authorization_code: String,
    client_id: String,
    client_secret: String,
    redirect_uri: &str,
) -> Result<TokenResponse, ReqwestError> {
    let params = [
        ("code", authorization_code),
        ("client_id", client_id),
        ("client_secret", client_secret),
        ("redirect_uri", redirect_uri.to_string()),
        ("grant_type", "authorization_code".to_string()),
    ];

    let client = reqwest::Client::new();
    let res = client
        .post("https://oauth2.googleapis.com/token")
        .form(&params)
        .send()
        .await?;

    let token_response: TokenResponse = res.json().await?;
    Ok(token_response)
}

fn read_u32(prompt: &str, default: u32) -> u32 {
    loop {
        println!("{} (default {}):", prompt, default);
        let mut input = String::new();
        if stdin().read_line(&mut input).is_err() {
            println!("Error reading input. Using default value.");
            return default;
        }

        let input = input.trim();
        if input.is_empty() {
            return default;
        }

        match input.parse::<u32>() {
            Ok(num) => return num,
            Err(_) => println!("Invalid input. Please enter a valid number or just press enter to use the default."),
        }
    }
}

async fn deploy_command() -> Result<(), Box<dyn Error>> {
    let client = reqwest::Client::new();

    let current_dir = env::current_dir()?;

    let first_account_pvt_key = read_first_account(&current_dir.join("stackr.config.ts"))?;

    let binary_path = current_dir.join("build/stf.wasm");

    let byte_code = read_byte_code(&binary_path).await?;

    let byte_code_hash: [u8; 32] = ethers::utils::keccak256(&byte_code);

    let wallet = first_account_pvt_key.parse::<LocalWallet>()?;

    println!("Using the account : {}", wallet.address());

    let byte_code_signature =
        ethers::signers::Wallet::sign_hash(&wallet, (&byte_code_hash).into())?;

    let signed_binary = SignedBinary {
        byteCode: byte_code.clone(),
        signature: byte_code_signature.to_string(),
        appID: 0,
    };

    let genesis_state = "0".to_string();

    let payload = Genesis {
        signedBinary: signed_binary,
        genesisState: genesis_state,
    };

    let payload_json = serde_json::to_string(&payload)?;

    let res = client
        .post("http://localhost:3000/v0/genesis")
        .header("Content-Type", "application/json")
        .body(payload_json)
        .send()
        .await?;

    if res.status().is_success() {
        println!("Deployed successfully.");
    } else {
        eprintln!(
            "Failed to deploy: {:?} {:?}",
            res.status(),
            res.error_for_status()
        );
    }

    Ok(())
}

async fn read_byte_code(file_path: &PathBuf) -> Result<Vec<u8>, Box<dyn Error>> {
    // Asynchronously read the contents of the file.
    let mut file = fs::File::open(file_path)?;
    let mut buffer = Vec::new();
    file.read_to_end(&mut buffer)?;
    Ok(buffer)
}