Skip to content

Commit

Permalink
fix(blockifier): add caching for native contracts (#2080)
Browse files Browse the repository at this point in the history
Co-Authored-By: Bohdan Ohorodnii <[email protected]>
  • Loading branch information
rodrigo-pino and varex83 authored Nov 20, 2024
1 parent 2736adb commit 76821a3
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion crates/blockifier/src/test_utils/contracts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,8 @@ impl FeatureContract {
pub fn get_runnable_class(&self) -> RunnableContractClass {
#[cfg(feature = "cairo_native")]
if CairoVersion::Native == self.cairo_version() {
let native_contract_class = NativeContractClassV1::from_file(&self.get_compiled_path());
let native_contract_class =
NativeContractClassV1::compile_or_get_cached(&self.get_compiled_path()).into();
return RunnableContractClass::V1Native(native_contract_class);
}

Expand Down
22 changes: 22 additions & 0 deletions crates/blockifier/src/test_utils/struct_impls.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
#[cfg(feature = "cairo_native")]
use std::collections::HashMap;
use std::sync::Arc;
#[cfg(feature = "cairo_native")]
use std::sync::{LazyLock, RwLock};

use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass;
#[cfg(feature = "cairo_native")]
Expand Down Expand Up @@ -238,6 +242,10 @@ impl BouncerWeights {
}
}

#[cfg(feature = "cairo_native")]
static COMPILED_NATIVE_CONTRACT_CACHE: LazyLock<RwLock<HashMap<String, NativeContractClassV1>>> =
LazyLock::new(|| RwLock::new(HashMap::new()));

#[cfg(feature = "cairo_native")]
impl NativeContractClassV1 {
/// Convenience function to construct a NativeContractClassV1 from a raw contract class.
Expand Down Expand Up @@ -271,4 +279,18 @@ impl NativeContractClassV1 {
let raw_contract_class = get_raw_contract_class(contract_path);
Self::try_from_json_string(&raw_contract_class)
}

/// Compile a contract from a file or get it from the cache.
pub fn compile_or_get_cached(path: &str) -> Self {
let cache = COMPILED_NATIVE_CONTRACT_CACHE.read().unwrap();
if let Some(cached_class) = cache.get(path) {
return cached_class.clone();
}
std::mem::drop(cache);

let class = NativeContractClassV1::from_file(path);
let mut cache = COMPILED_NATIVE_CONTRACT_CACHE.write().unwrap();
cache.insert(path.to_string(), class.clone());
class
}
}

0 comments on commit 76821a3

Please sign in to comment.