cairo_lang_execute_utils/
lib.rs

1use std::collections::HashMap;
2use std::path::PathBuf;
3
4use anyhow::Context;
5use cairo_lang_casm::hints::Hint;
6use cairo_lang_executable::executable::{EntryPointKind, Executable, ExecutableEntryPoint};
7use cairo_lang_runner::{Arg, build_hints_dict};
8use cairo_lang_utils::bigint::BigUintAsHex;
9use cairo_vm::Felt252;
10use cairo_vm::types::program::Program;
11use cairo_vm::types::relocatable::MaybeRelocatable;
12use num_bigint::BigInt;
13
14// Returns a tuple containing:
15/// 1. The Program instance - set according to the type of the required entrypoint.
16/// 2. The hint by string mapping.
17///
18/// This is required for running an executable in the Cairo-VM.
19pub fn program_and_hints_from_executable(
20    executable: &Executable,
21    entrypoint: &ExecutableEntryPoint,
22) -> anyhow::Result<(Program, HashMap<String, Hint>)> {
23    let data: Vec<MaybeRelocatable> =
24        executable.program.bytecode.iter().map(Felt252::from).map(MaybeRelocatable::from).collect();
25    let (hints, string_to_hint) = build_hints_dict(&executable.program.hints);
26    let program = match entrypoint.kind {
27        EntryPointKind::Standalone => Program::new_for_proof(
28            entrypoint.builtins.clone(),
29            data,
30            entrypoint.offset,
31            entrypoint.offset + 4,
32            hints,
33            Default::default(),
34            Default::default(),
35            vec![],
36            None,
37        ),
38        EntryPointKind::Bootloader => Program::new(
39            entrypoint.builtins.clone(),
40            data,
41            Some(entrypoint.offset),
42            hints,
43            Default::default(),
44            Default::default(),
45            vec![],
46            None,
47        ),
48    }
49    .with_context(|| "Failed setting up program.")?;
50
51    Ok((program, string_to_hint))
52}
53
54/// Returns the user arguments for the program after parsing them from the provided file or list.
55/// `as_file` - The content of a flag with an optional path to a json containing the args as hex
56/// strings.
57/// `as_list` - The content of a flag with the direct numeric value of the list.
58/// Making sure not both are provided should be done by the cli.
59///
60/// This is required for running an executable in the Cairo-VM.
61pub fn user_args_from_flags(
62    as_file: Option<&PathBuf>,
63    as_list: &[BigInt],
64) -> anyhow::Result<Vec<Arg>> {
65    let user_args = if let Some(path) = as_file {
66        let as_vec: Vec<BigUintAsHex> = serde_json::from_reader(std::fs::File::open(path)?)
67            .with_context(|| "Failed reading args file.")?;
68        as_vec.into_iter().map(|v| Arg::Value(v.value.into())).collect()
69    } else {
70        as_list.iter().map(|v| Arg::Value(v.into())).collect()
71    };
72
73    Ok(user_args)
74}