Skip to content

Commit 52749e4

Browse files
committed
static main functin
1 parent 31a1370 commit 52749e4

File tree

2 files changed

+191
-1
lines changed

2 files changed

+191
-1
lines changed

contract-runner/src/main.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use clap::{Parser, ValueHint};
1111
use contract_runner::error::Error;
1212
use contract_runner::{cairo_run_program, Cairo1RunConfig, FuncArg};
1313
use itertools::Itertools;
14+
use std::thread::sleep;
1415
use std::{
1516
io::{self, Write},
1617
path::PathBuf,
@@ -195,10 +196,32 @@ fn run(args: impl Iterator<Item = String>) -> Result<Option<String>, Error> {
195196

196197
contract_runner::parse::parse(&args.filename);
197198

199+
let checker = args
200+
.filename
201+
.clone()
202+
.parent()
203+
.unwrap()
204+
.join("checker.cairo");
205+
let contract = args
206+
.filename
207+
.clone()
208+
.parent()
209+
.unwrap()
210+
.join("contract.cairo");
211+
212+
std::fs::rename(&args.filename, &contract).unwrap();
213+
std::fs::copy(&checker, &args.filename).unwrap();
214+
215+
sleep(std::time::Duration::from_secs(1));
216+
217+
// Compile the project
198218
let main_crate_ids = setup_project(&mut db, &args.filename).unwrap();
199219
let sierra_program_with_dbg =
200220
compile_prepared_db(&db, main_crate_ids, compiler_config).unwrap();
201221

222+
// Restore original lib.cairo
223+
std::fs::rename(&contract, &args.filename).unwrap();
224+
202225
sierra_program_with_dbg.program
203226
}
204227
};

contract-runner/src/parse.rs

Lines changed: 168 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,170 @@
11
use std::path::PathBuf;
22

3-
pub fn parse(_filename: PathBuf) {}
3+
pub fn parse(filename: &PathBuf) {
4+
println!("Parsing file: {}", filename.display());
5+
let file_content = std::fs::read_to_string(filename).expect("Failed to read file");
6+
7+
use std::env;
8+
9+
let current_dir = env::current_dir().expect("Failed to get current directory");
10+
println!("Current directory: {}", current_dir.display());
11+
12+
use std::path::Path;
13+
use std::process::Command;
14+
15+
// Get the directory of the file
16+
let dir = filename.parent().expect("Failed to get parent directory");
17+
18+
// Change to the directory containing the file
19+
std::env::set_current_dir(dir).expect("Failed to change directory");
20+
21+
// Run 'scarb expand' command
22+
let output = Command::new("scarb")
23+
.arg("expand")
24+
.output()
25+
.expect("Failed to execute scarb expand command");
26+
27+
if !output.status.success() {
28+
eprintln!(
29+
"Error running scarb expand: {}",
30+
String::from_utf8_lossy(&output.stderr)
31+
);
32+
} else {
33+
// Read the expanded Cairo file
34+
let expanded_file_path = Path::new("../target/dev/cairo_ex.expanded.cairo");
35+
match std::fs::read_to_string(expanded_file_path) {
36+
Ok(expanded_content) => {
37+
println!("Expanded Cairo file content:");
38+
println!("{}", expanded_content);
39+
40+
let updated = prepare(expanded_content);
41+
// Save the updated content to checker.cairo
42+
let checker_file_path = Path::new("checker.cairo");
43+
44+
match std::fs::write(checker_file_path, &updated) {
45+
Ok(_) => println!("Updated content saved to checker.cairo"),
46+
Err(e) => eprintln!("Failed to save updated content: {}", e),
47+
}
48+
}
49+
Err(e) => {
50+
eprintln!("Failed to read expanded Cairo file: {}", e);
51+
}
52+
}
53+
}
54+
55+
// Change back to the original directory
56+
std::env::set_current_dir(current_dir).expect("Failed to change back to original directory");
57+
58+
println!("File content: {}", file_content);
59+
}
60+
61+
fn prepare(expanded_content: String) -> String {
62+
let lines = expanded_content.lines().collect::<Vec<&str>>();
63+
let mut updated_lines = Vec::new();
64+
65+
let mut skip_lines = 0;
66+
67+
for line in lines {
68+
if skip_lines > 0 {
69+
updated_lines.push("//".to_string() + line);
70+
skip_lines -= 1;
71+
continue;
72+
} else if line.contains("#[starknet::interface]")
73+
|| line.contains("#[abi(embed_v0)]")
74+
|| line.contains("#[event]")
75+
|| line.contains("starknet::Event")
76+
{
77+
updated_lines.push("//".to_string() + line);
78+
} else if line.contains("core::gas::withdraw_gas_all(core::gas::get_builtin_costs())") {
79+
updated_lines.pop();
80+
updated_lines.push("//".to_string() + line);
81+
skip_lines = 1;
82+
} else if line.contains("mod") || line.contains("fn __wrapper") {
83+
updated_lines.push("pub ".to_string() + line);
84+
} else if line.contains("System") || line.contains("core::gas") {
85+
updated_lines.push("//".to_string() + line);
86+
} else if line.contains("impl ContractStateEventEmitter") {
87+
updated_lines.push("//".to_string() + line);
88+
skip_lines = u64::MAX;
89+
} else {
90+
updated_lines.push(line.to_string());
91+
}
92+
}
93+
94+
if skip_lines > 0 {
95+
updated_lines.push("}}".to_string());
96+
}
97+
98+
let main = r#"
99+
#[derive(Serde, Drop)]
100+
struct Calls {
101+
selector: felt252,
102+
calldata: Span<felt252>,
103+
}
104+
105+
#[derive(Serde, Drop)]
106+
struct Args {
107+
calls: Array<Calls>,
108+
}
109+
110+
fn main(input: Array<felt252>) -> Array<felt252> {
111+
let mut input = input.span();
112+
let mut args = Serde::<Args>::deserialize(ref input).unwrap();
113+
114+
let mut r = array![];
115+
116+
loop {
117+
let call = match args.calls.pop_front() {
118+
Option::Some(call) => call,
119+
Option::None => { break; },
120+
};
121+
122+
let ret = if call.selector == 3 {
123+
cairo_ex::HelloStarknet::__wrapper__HelloStarknetImpl__get_balance(call.calldata)
124+
} else {
125+
panic(array!['Invalid selector']);
126+
array![].span()
127+
};
128+
129+
r.append_span(ret);
130+
};
131+
132+
r
133+
}
134+
"#;
135+
136+
updated_lines.push(main.to_string());
137+
138+
updated_lines.join("\n")
139+
}
140+
141+
#[cfg(test)]
142+
mod tests {
143+
use cairo_lang_compiler::{
144+
compile_prepared_db, db::RootDatabase, project::setup_project, CompilerConfig,
145+
};
146+
147+
use super::*;
148+
149+
#[test]
150+
fn test_parse() {
151+
let filename = PathBuf::from("../../contract-binary-interpreter/cairo/src/contract.cairo");
152+
153+
parse(&filename.parent().unwrap().join("lib.cairo"));
154+
155+
let compiler_config = CompilerConfig {
156+
replace_ids: true,
157+
..CompilerConfig::default()
158+
};
159+
160+
let mut db = RootDatabase::builder()
161+
.detect_corelib()
162+
.skip_auto_withdraw_gas()
163+
.build()
164+
.unwrap();
165+
166+
let main_crate_ids = setup_project(&mut db, &filename).unwrap();
167+
let _sierra_program_with_dbg =
168+
compile_prepared_db(&db, main_crate_ids, compiler_config).unwrap();
169+
}
170+
}

0 commit comments

Comments
 (0)