Skip to content

Commit

Permalink
restore native feature
Browse files Browse the repository at this point in the history
  • Loading branch information
enitrat committed Dec 4, 2024
1 parent 2c46a78 commit ff7b32b
Show file tree
Hide file tree
Showing 6 changed files with 64 additions and 59 deletions.
1 change: 0 additions & 1 deletion crates/ef-testing/src/evm_sequencer/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ where
}

pub fn get_raw_contract_class(contract_path: &str) -> String {
println!("path: {:?}", contract_path);
fs::read_to_string(contract_path).unwrap()
}

Expand Down
1 change: 0 additions & 1 deletion crates/ef-testing/src/evm_sequencer/evm_state/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,6 @@ impl Evm for KakarotSequencer {
// Set the base fee at index 'current_block'
let [low_fee, high_fee] = split_u256(base_fee);
let key = Felt::from_bytes_be_slice(b"current_block");
println!("key: {:?}", key);
let basefee_address = get_storage_var_address(KAKAROT_BASE_FEE, &[key]);
self.state_mut()
.set_storage_at(kakarot_address, basefee_address, low_fee.into())?;
Expand Down
3 changes: 0 additions & 3 deletions crates/ef-testing/src/evm_sequencer/sequencer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,9 +243,6 @@ lazy_static! {
let kakarot_json = CLASS_HASH_TO_JSON_CLASS.get(&KAKAROT_CLASS_HASH).unwrap();
let account_json = CLASS_HASH_TO_JSON_CLASS.get(&ACCOUNT_CONTRACT_CLASS_HASH).unwrap();
let uninitialized_json = CLASS_HASH_TO_JSON_CLASS.get(&UNINITIALIZED_ACCOUNT_CLASS_HASH).unwrap();
println!("Got uninitialized account's json of length {}", uninitialized_json.len());
println!("Got account's json of length {}", account_json.len());
println!("Got kakarot's json of length {}", kakarot_json.len());
let account_class = class_from_json_str(account_json, *ACCOUNT_CONTRACT_CLASS_HASH).unwrap_or_else(|err| panic!("{}", err));
let uninitialized_class = class_from_json_str(uninitialized_json, *UNINITIALIZED_ACCOUNT_CLASS_HASH).unwrap_or_else(|err| panic!("{}", err));
let kakarot_class = class_from_json_str(kakarot_json, *KAKAROT_CLASS_HASH).unwrap_or_else(|err| panic!("{}", err));
Expand Down
92 changes: 51 additions & 41 deletions crates/sequencer/src/native.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ use blockifier::execution::contract_class::{
CompiledClassV0, CompiledClassV1, RunnableCompiledClass,
};
use blockifier::execution::native::contract_class::NativeCompiledClassV1;
use cairo_lang_starknet_classes::contract_class::ContractClass;
use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass;
use cairo_lang_starknet_classes::contract_class::ContractClass as SierraContractClass;
use cairo_native::executor::AotContractExecutor;
use cairo_native::OptLevel;
use starknet_api::core::ClassHash;

use lazy_static::lazy_static;
Expand Down Expand Up @@ -36,69 +36,79 @@ fn setup_native_cache_dir() -> PathBuf {
/// Load a compiled native contract into memory
///
/// Tries to load the compiled contract class from library_output_path if it
/// exists, otherwise it will compile the raw_contract_class, load it into memory
/// exists, otherwise it will compile the raw_sierra_class, load it into memory
/// and save the compilation artifact to library_output_path.
fn native_try_from_json_string(
raw_contract_class: &str,
raw_sierra_class: &str,
library_output_path: &PathBuf,
) -> Result<NativeCompiledClassV1, Box<dyn std::error::Error>> {
let sierra_contract_class: ContractClass = serde_json::from_str(raw_contract_class)?;
let maybe_cached_executor = AotContractExecutor::load(library_output_path);

let compiled_class = serde_json::from_str(raw_contract_class)?;
// see blockifier/src/test_utils/struct_impls.rs
let sierra_contract_class: SierraContractClass =
serde_json::from_str(raw_sierra_class).unwrap();

let sierra_program = sierra_contract_class.extract_sierra_program()?;
let sierra_program = sierra_contract_class
.extract_sierra_program()
.expect("Cannot extract sierra program from sierra contract class");

// Compile the sierra contract class into casm
let casm_contract_class =
CasmContractClass::from_contract_class(sierra_contract_class.clone(), false, usize::MAX)
.expect("Cannot compile sierra contract class into casm contract class");
let casm = CompiledClassV1::try_from(casm_contract_class)
.expect("Cannot get CompiledClassV1 from CasmContractClass");

let maybe_cached_executor = AotContractExecutor::load(library_output_path);
if let Ok(executor) = maybe_cached_executor {
println!("Loaded cached executor");
let native_class = NativeCompiledClassV1::new(executor, compiled_class);
let native_class = NativeCompiledClassV1::new(executor, casm);
return Ok(native_class);
}

println!("Creating new executor");
let start_time = std::time::Instant::now();
let mut executor = AotContractExecutor::new(
&sierra_program,
&sierra_contract_class.entry_points_by_type,
OptLevel::Default,
)?;
cairo_native::OptLevel::Default,
)
.expect("Cannot compile sierra into native");
let duration = start_time.elapsed();
executor.save(library_output_path)?;
println!("Saved executor to {:?}", library_output_path);
println!("Created and saved AoTExecutor in {:.2?}", duration);

let native_class = NativeCompiledClassV1::new(executor, compiled_class);
let native_class = NativeCompiledClassV1::new(executor, casm);
Ok(native_class)
}

pub fn class_from_json_str(
raw_json: &str,
raw_sierra: &str,
class_hash: ClassHash,
) -> Result<RunnableCompiledClass, String> {
println!("raw json length {}", raw_json.len());
let class_def = raw_json.to_string();
println!("class def parsed");
let class: RunnableCompiledClass =
if let Ok(class) = CompiledClassV0::try_from_json_string(class_def.as_str()) {
class.into()
} else if let Ok(class) = CompiledClassV1::try_from_json_string(class_def.as_str()) {
println!("v1 contract");
class.into()
} else if let Ok(class) = {
println!("native contract");
let library_output_path = generate_library_path(class_hash);
let maybe_class = native_try_from_json_string(class_def.as_str(), &library_output_path);
if let Ok(class) = maybe_class {
Ok(class)
} else {
println!(
"Native contract failed with error {:?}",
maybe_class.err().unwrap()
);
Err(())
}
} {
class.into()
let class_def = raw_sierra.to_string();
let class: RunnableCompiledClass = if let Ok(class) =
CompiledClassV0::try_from_json_string(class_def.as_str())
{
class.into()
} else if let Ok(class) = CompiledClassV1::try_from_json_string(class_def.as_str()) {
class.into()
} else if let Ok(class) = {
let library_output_path = generate_library_path(class_hash);
let maybe_class =
native_try_from_json_string(class_def.as_str(), &library_output_path);
if let Ok(class) = maybe_class {
Ok(class)
} else {
return Err("not a valid contract class".to_string());
};
println!(
"Native contract failed with error {:?}",
maybe_class.err().unwrap()
);
Err(())
}
} {
class.into()
} else {
return Err("not a valid contract class".to_string());
};

Ok(class)
}
22 changes: 12 additions & 10 deletions crates/sequencer/src/sequencer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,23 +119,25 @@ mod tests {
use std::fmt::Display;
use std::fs::File;

use starknet_api::abi::abi_utils::get_storage_var_address;
use blockifier::bouncer::BouncerConfig;
use blockifier::context::ChainInfo;
use blockifier::context::{BlockContext, FeeTokenAddresses};
use blockifier::execution::contract_class::{RunnableCompiledClass, CompiledClassV0, CompiledClassV1};
use blockifier::execution::contract_class::{
CompiledClassV0, CompiledClassV1, RunnableCompiledClass,
};
use blockifier::state::state_api::State as BlockifierState;
use blockifier::versioned_constants::VersionedConstants;
use starknet::core::types::Felt;
use starknet::macros::selector;
use starknet_api::abi::abi_utils::get_storage_var_address;
use starknet_api::block::{BlockInfo, GasPriceVector, GasPrices};
use starknet_api::block::{BlockNumber, BlockTimestamp};
use starknet_api::core::{ChainId, ClassHash, ContractAddress, Nonce};
use starknet_api::executable_transaction::InvokeTransaction;
use starknet_api::transaction::{InvokeTransaction as InvokeTransactionTypes, InvokeTransactionV1};
use starknet_api::transaction::fields::{
Calldata, Fee, TransactionSignature,
use starknet_api::transaction::fields::{Calldata, Fee, TransactionSignature};
use starknet_api::transaction::{
InvokeTransaction as InvokeTransactionTypes, InvokeTransactionV1,
};
use starknet_api::block::{BlockInfo, GasPrices, GasPriceVector};

use crate::constants::test_constants::{
ETH_FEE_TOKEN_ADDRESS, SEQUENCER_ADDRESS, STRK_FEE_TOKEN_ADDRESS,
Expand Down Expand Up @@ -255,15 +257,15 @@ mod tests {
block_timestamp: BlockTimestamp(1),
sequencer_address: *SEQUENCER_ADDRESS,
gas_prices: GasPrices {
eth_gas_prices: GasPriceVector{
eth_gas_prices: GasPriceVector {
l1_gas_price: Default::default(),
l1_data_gas_price: Default::default(),
l2_gas_price: Default::default()
l2_gas_price: Default::default(),
},
strk_gas_prices: GasPriceVector{
strk_gas_prices: GasPriceVector {
l1_gas_price: Default::default(),
l1_data_gas_price: Default::default(),
l2_gas_price: Default::default()
l2_gas_price: Default::default(),
},
},
use_kzg_da: false,
Expand Down
4 changes: 1 addition & 3 deletions crates/sequencer/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,9 +260,7 @@ mod tests {

// Then
let expected = RunnableCompiledClass::V0(CompiledClassV0::default());
let actual = state
.get_compiled_class(ClassHash(Felt::ONE))
.unwrap();
let actual = state.get_compiled_class(ClassHash(Felt::ONE)).unwrap();
assert_eq!(expected, actual);
}

Expand Down

0 comments on commit ff7b32b

Please sign in to comment.