starknet_in_rust 0.4.0

A Rust implementation of Starknet execution logic
Documentation
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
use super::fee::charge_fee;
use super::{verify_version, Transaction};
use crate::core::contract_address::{compute_casm_class_hash, compute_sierra_class_hash};
use crate::definitions::constants::QUERY_VERSION_BASE;
use crate::execution::execution_entry_point::ExecutionResult;
use crate::services::api::contract_classes::deprecated_contract_class::EntryPointType;

use crate::services::api::contract_classes::compiled_class::CompiledClass;
use crate::state::cached_state::CachedState;
use crate::{
    core::transaction_hash::calculate_declare_v2_transaction_hash,
    definitions::{
        block_context::BlockContext,
        constants::{INITIAL_GAS_COST, VALIDATE_DECLARE_ENTRY_POINT_SELECTOR},
        transaction_type::TransactionType,
    },
    execution::{
        execution_entry_point::ExecutionEntryPoint, CallType, TransactionExecutionContext,
        TransactionExecutionInfo,
    },
    state::state_api::{State, StateReader},
    state::ExecutionResourcesManager,
    transaction::{error::TransactionError, invoke_function::verify_no_calls_to_other_contracts},
    utils::{calculate_tx_resources, Address},
};
use cairo_lang_starknet::casm_contract_class::CasmContractClass;
use cairo_lang_starknet::contract_class::ContractClass as SierraContractClass;
use cairo_vm::felt::Felt252;
use num_traits::Zero;
use std::sync::Arc;

/// Represents a declare transaction in the starknet network.
/// Declare creates a blueprint of a contract class that is used to deploy instances of the contract
/// DeclareV2 is meant to be used with the new cairo contract sintax, starting from Cairo1.
#[derive(Debug, Clone)]
pub struct DeclareV2 {
    pub sender_address: Address,
    pub validate_entry_point_selector: Felt252,
    pub version: Felt252,
    pub max_fee: u128,
    pub signature: Vec<Felt252>,
    pub nonce: Felt252,
    pub compiled_class_hash: Felt252,
    pub sierra_contract_class: SierraContractClass,
    pub sierra_class_hash: Felt252,
    pub hash_value: Felt252,
    pub casm_class: Option<CasmContractClass>,
    pub skip_validate: bool,
    pub skip_execute: bool,
    pub skip_fee_transfer: bool,
}

impl DeclareV2 {
    /// Creates a new instance of a [DeclareV2].
    /// It will calculate the sierra class hash and the transaction hash.
    /// ## Parameters:
    /// - sierra_contract_class: The sierra contract class of the contract to declare
    /// - casm_contract_class: The casm contract class of the contract to declare. This is optional.
    /// - compiled_class_hash: the class hash of the contract compiled with Cairo1 or newer.
    /// - chain_id: Id of the network where is going to be declare, those can be: Mainnet, Testnet.
    /// - sender_address: The address of the account declaring the contract.
    /// - max_fee: refers to max amount of fee that a declare takes.
    /// - version: The version of cairo contract being declare.
    /// - signature: Array of felts with the signatures of the contract.
    /// - nonce: The nonce of the contract.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        sierra_contract_class: &SierraContractClass,
        casm_contract_class: Option<CasmContractClass>,
        compiled_class_hash: Felt252,
        chain_id: Felt252,
        sender_address: Address,
        max_fee: u128,
        version: Felt252,
        signature: Vec<Felt252>,
        nonce: Felt252,
    ) -> Result<Self, TransactionError> {
        let sierra_class_hash = compute_sierra_class_hash(sierra_contract_class)?;

        let hash_value = calculate_declare_v2_transaction_hash(
            sierra_class_hash.clone(),
            compiled_class_hash.clone(),
            chain_id,
            &sender_address,
            max_fee,
            version.clone(),
            nonce.clone(),
        )?;

        Self::new_with_sierra_class_hash_and_tx_hash(
            sierra_contract_class,
            sierra_class_hash,
            casm_contract_class,
            compiled_class_hash,
            sender_address,
            max_fee,
            version,
            signature,
            nonce,
            hash_value,
        )
    }

    /// Creates a new instance of a declare with a precomputed sierra class hash and transaction hash.
    /// ## Parameters:
    /// - sierra_contract_class: The sierra contract class of the contract to declare
    /// - sierra_class_hash: The precomputed hash for the sierra contract
    /// - casm_contract_class: The casm contract class of the contract to declare. This is optional.
    /// - compiled_class_hash: the class hash of the contract compiled with Cairo1 or newer.
    /// - sender_address: The address of the account declaring the contract.
    /// - max_fee: refers to max amount of fee that a declare takes.
    /// - version: The version of cairo contract being declare.
    /// - signature: Array of felts with the signatures of the contract.
    /// - nonce: The nonce of the contract.
    /// - hash_value: The transaction hash_value.
    /// SAFETY: if `sierra_class_hash` doesn't correspond to the `sierra_contract_class` invariants
    /// may not hold.
    #[allow(clippy::too_many_arguments)]
    pub fn new_with_sierra_class_hash_and_tx_hash(
        sierra_contract_class: &SierraContractClass,
        sierra_class_hash: Felt252,
        casm_contract_class: Option<CasmContractClass>,
        compiled_class_hash: Felt252,
        sender_address: Address,
        max_fee: u128,
        version: Felt252,
        signature: Vec<Felt252>,
        nonce: Felt252,
        hash_value: Felt252,
    ) -> Result<Self, TransactionError> {
        let validate_entry_point_selector = VALIDATE_DECLARE_ENTRY_POINT_SELECTOR.clone();

        let internal_declare = DeclareV2 {
            sierra_contract_class: sierra_contract_class.to_owned(),
            sierra_class_hash,
            sender_address,
            validate_entry_point_selector,
            version,
            max_fee,
            signature,
            nonce,
            compiled_class_hash,
            hash_value,
            casm_class: casm_contract_class,
            skip_execute: false,
            skip_validate: false,
            skip_fee_transfer: false,
        };

        verify_version(
            &internal_declare.version,
            internal_declare.max_fee,
            &internal_declare.nonce,
            &internal_declare.signature,
        )?;

        Ok(internal_declare)
    }

    // creates a new instance of a declare but without the computation of the transaction hash.
    /// ## Parameters:
    /// - sierra_contract_class: The sierra contract class of the contract to declare.
    /// - casm_contract_class: The casm contract class of the contract to declare. This is optional.
    /// - compiled_class_hash: the class hash of the contract compiled with Cairo1 or newer.
    /// - sender_address: The address of the account declaring the contract.
    /// - max_fee: refers to max amount of fee that a declare takes.
    /// - version: The version of cairo contract being declare.
    /// - signature: Array of felts with the signatures of the contract.
    /// - nonce: The nonce of the contract.
    /// - hash_value: The transaction hash.
    #[allow(clippy::too_many_arguments)]
    pub fn new_with_tx_hash(
        sierra_contract_class: &SierraContractClass,
        casm_contract_class: Option<CasmContractClass>,
        compiled_class_hash: Felt252,
        sender_address: Address,
        max_fee: u128,
        version: Felt252,
        signature: Vec<Felt252>,
        nonce: Felt252,
        hash_value: Felt252,
    ) -> Result<Self, TransactionError> {
        let sierra_class_hash = compute_sierra_class_hash(sierra_contract_class)?;

        Self::new_with_sierra_class_hash_and_tx_hash(
            sierra_contract_class,
            sierra_class_hash,
            casm_contract_class,
            compiled_class_hash,
            sender_address,
            max_fee,
            version,
            signature,
            nonce,
            hash_value,
        )
    }

    /// Creates a new instance of a [DeclareV2] but without the computation of the sierra class hash.
    /// ## Parameters:
    /// - sierra_contract_class: The sierra contract class of the contract to declare
    /// - sierra_class_hash: The precomputed hash for the sierra contract
    /// - casm_contract_class: The casm contract class of the contract to declare. This is optional.
    /// - compiled_class_hash: the class hash of the contract compiled with Cairo1 or newer.
    /// - chain_id: Id of the network where is going to be declare, those can be: Mainnet, Testnet.
    /// - sender_address: The address of the account declaring the contract.
    /// - max_fee: refers to max amount of fee that a declare takes.
    /// - version: The version of cairo contract being declare.
    /// - signature: Array of felts with the signatures of the contract.
    /// - nonce: The nonce of the contract.
    #[allow(clippy::too_many_arguments)]
    pub fn new_with_sierra_class_hash(
        sierra_contract_class: &SierraContractClass,
        sierra_class_hash: Felt252,
        casm_contract_class: Option<CasmContractClass>,
        compiled_class_hash: Felt252,
        chain_id: Felt252,
        sender_address: Address,
        max_fee: u128,
        version: Felt252,
        signature: Vec<Felt252>,
        nonce: Felt252,
    ) -> Result<Self, TransactionError> {
        let hash_value = calculate_declare_v2_transaction_hash(
            sierra_class_hash.clone(),
            compiled_class_hash.clone(),
            chain_id,
            &sender_address,
            max_fee,
            version.clone(),
            nonce.clone(),
        )?;

        Self::new_with_sierra_class_hash_and_tx_hash(
            sierra_contract_class,
            sierra_class_hash,
            casm_contract_class,
            compiled_class_hash,
            sender_address,
            max_fee,
            version,
            signature,
            nonce,
            hash_value,
        )
    }

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //  Account Functions
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~

    /// creates the a new TransactionExecutionContexts which represent the state of the net after executing the contract.
    /// ## Parameter:
    /// n_steps: the number of steps that are required to execute the contract.
    pub fn get_execution_context(&self, n_steps: u64) -> TransactionExecutionContext {
        TransactionExecutionContext::new(
            self.sender_address.clone(),
            self.hash_value.clone(),
            self.signature.clone(),
            self.max_fee,
            self.nonce.clone(),
            n_steps,
            self.version.clone(),
        )
    }

    /// returns the calldata with which the contract is executed
    pub fn get_calldata(&self) -> Vec<Felt252> {
        let bytes = self.compiled_class_hash.clone();
        Vec::from([bytes])
    }

    // TODO: delete once used
    #[allow(dead_code)]
    fn handle_nonce<S: State + StateReader>(&self, state: &mut S) -> Result<(), TransactionError> {
        if self.version.is_zero() || self.version == *QUERY_VERSION_BASE {
            return Ok(());
        }

        let contract_address = &self.sender_address;
        let current_nonce = state.get_nonce_at(contract_address)?;
        if current_nonce != self.nonce {
            return Err(TransactionError::InvalidTransactionNonce(
                current_nonce.to_string(),
                self.nonce.to_string(),
            ));
        }

        state.increment_nonce(contract_address)?;

        Ok(())
    }

    /// Execute the validation of the contract in the cairo-vm. Returns a TransactionExecutionInfo if succesful.
    /// ## Parameter:
    /// - state: An state that implements the State and StateReader traits.
    /// - block_context: The block that contains the execution context
    pub fn execute<S: StateReader>(
        &self,
        state: &mut CachedState<S>,
        block_context: &BlockContext,
    ) -> Result<TransactionExecutionInfo, TransactionError> {
        verify_version(&self.version, self.max_fee, &self.nonce, &self.signature)?;

        let initial_gas = INITIAL_GAS_COST;

        let mut resources_manager = ExecutionResourcesManager::default();

        let (execution_result, _remaining_gas) = if self.skip_validate {
            (ExecutionResult::default(), 0)
        } else {
            let (info, gas) = self.run_validate_entrypoint(
                initial_gas,
                state,
                &mut resources_manager,
                block_context,
            )?;
            (info, gas)
        };

        let storage_changes = state.count_actual_storage_changes(Some((
            &block_context.starknet_os_config.fee_token_address,
            &self.sender_address,
        )))?;
        let actual_resources = calculate_tx_resources(
            resources_manager,
            &[execution_result.call_info.clone()],
            TransactionType::Declare,
            storage_changes,
            None,
            execution_result.n_reverted_steps,
        )?;

        let mut tx_execution_context =
            self.get_execution_context(block_context.invoke_tx_max_n_steps);
        let (fee_transfer_info, actual_fee) = charge_fee(
            state,
            &actual_resources,
            block_context,
            self.max_fee,
            &mut tx_execution_context,
            self.skip_fee_transfer,
        )?;
        self.compile_and_store_casm_class(state)?;

        let mut tx_exec_info = TransactionExecutionInfo::new_without_fee_info(
            execution_result.call_info,
            None,
            None,
            actual_resources,
            Some(TransactionType::Declare),
        );
        tx_exec_info.set_fee_info(actual_fee, fee_transfer_info);

        Ok(tx_exec_info)
    }

    pub(crate) fn compile_and_store_casm_class<S: State + StateReader>(
        &self,
        state: &mut S,
    ) -> Result<(), TransactionError> {
        let casm_class = match &self.casm_class {
            None => {
                CasmContractClass::from_contract_class(self.sierra_contract_class.clone(), true)
                    .map_err(|e| TransactionError::SierraCompileError(e.to_string()))?
            }
            Some(casm_contract_class) => casm_contract_class.clone(),
        };

        let casm_class_hash = compute_casm_class_hash(&casm_class)?;
        if casm_class_hash != self.compiled_class_hash {
            return Err(TransactionError::InvalidCompiledClassHash(
                casm_class_hash.to_string(),
                self.compiled_class_hash.to_string(),
            ));
        }
        state.set_compiled_class_hash(&self.sierra_class_hash, &self.compiled_class_hash)?;
        // theorically class_hash == compiled_class_hash in v2, so this is like setting class_hash -> compiled_class_hash
        // which is needed for get_compiled_class_hash later to work.
        state.set_compiled_class_hash(&self.compiled_class_hash, &self.compiled_class_hash)?;
        state.set_contract_class(
            &self.compiled_class_hash.to_be_bytes(),
            &CompiledClass::Casm(Arc::new(casm_class)),
        )?;

        Ok(())
    }

    fn run_validate_entrypoint<S: StateReader>(
        &self,
        mut remaining_gas: u128,
        state: &mut CachedState<S>,
        resources_manager: &mut ExecutionResourcesManager,
        block_context: &BlockContext,
    ) -> Result<(ExecutionResult, u128), TransactionError> {
        let calldata = [self.compiled_class_hash.clone()].to_vec();

        let entry_point = ExecutionEntryPoint {
            contract_address: self.sender_address.clone(),
            entry_point_selector: self.validate_entry_point_selector.clone(),
            initial_gas: remaining_gas,
            entry_point_type: EntryPointType::External,
            calldata,
            caller_address: Address(Felt252::zero()),
            code_address: None,
            class_hash: None,
            call_type: CallType::Call,
        };

        let mut tx_execution_context =
            self.get_execution_context(block_context.validate_max_n_steps);

        let execution_result = if self.skip_execute {
            ExecutionResult::default()
        } else {
            entry_point.execute(
                state,
                block_context,
                resources_manager,
                &mut tx_execution_context,
                true,
                block_context.validate_max_n_steps,
            )?
        };

        if execution_result.call_info.is_some() {
            verify_no_calls_to_other_contracts(&execution_result.call_info)?;
            remaining_gas -= execution_result.call_info.clone().unwrap().gas_consumed;
        }

        Ok((execution_result, remaining_gas))
    }

    // ---------------
    //   Simulation
    // ---------------
    pub(crate) fn create_for_simulation(
        &self,
        skip_validate: bool,
        skip_execute: bool,
        skip_fee_transfer: bool,
        ignore_max_fee: bool,
    ) -> Transaction {
        let tx = DeclareV2 {
            skip_validate,
            skip_execute,
            skip_fee_transfer,
            max_fee: if ignore_max_fee {
                u128::MAX
            } else {
                self.max_fee
            },
            ..self.clone()
        };

        Transaction::DeclareV2(Box::new(tx))
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;
    use std::{collections::HashMap, fs::File, io::BufReader, path::PathBuf};

    use super::DeclareV2;
    use crate::core::contract_address::{compute_casm_class_hash, compute_sierra_class_hash};
    use crate::definitions::constants::QUERY_VERSION_BASE;
    use crate::services::api::contract_classes::compiled_class::CompiledClass;
    use crate::state::state_api::StateReader;
    use crate::{
        state::cached_state::CachedState, state::in_memory_state_reader::InMemoryStateReader,
        utils::Address,
    };
    use cairo_lang_starknet::casm_contract_class::CasmContractClass;
    use cairo_vm::felt::Felt252;
    use num_traits::{One, Zero};

    #[test]
    fn create_declare_v2_without_casm_contract_class_test() {
        // read file to create sierra contract class
        let version;
        let path;
        #[cfg(not(feature = "cairo_1_tests"))]
        {
            version = Felt252::from(2);
            path = PathBuf::from("starknet_programs/cairo2/fibonacci.sierra");
        }

        #[cfg(feature = "cairo_1_tests")]
        {
            version = Felt252::from(1);
            path = PathBuf::from("starknet_programs/cairo1/fibonacci.sierra");
        }

        let file = File::open(path).unwrap();
        let reader = BufReader::new(file);
        let sierra_contract_class: cairo_lang_starknet::contract_class::ContractClass =
            serde_json::from_reader(reader).unwrap();
        let sender_address = Address(1.into());
        let casm_class =
            CasmContractClass::from_contract_class(sierra_contract_class.clone(), true).unwrap();
        let casm_class_hash = compute_casm_class_hash(&casm_class).unwrap();

        // create internal declare v2

        let internal_declare = DeclareV2::new_with_tx_hash(
            &sierra_contract_class,
            None,
            casm_class_hash,
            sender_address,
            0,
            version,
            [1.into()].to_vec(),
            Felt252::zero(),
            Felt252::one(),
        )
        .unwrap();

        // crate state to store casm contract class
        let casm_contract_class_cache = HashMap::new();
        let state_reader = Arc::new(InMemoryStateReader::default());
        let mut state = CachedState::new(state_reader, casm_contract_class_cache);

        // call compile and store
        assert!(internal_declare
            .compile_and_store_casm_class(&mut state)
            .is_ok());

        // test we  can retreive the data
        let expected_casm_class = CasmContractClass::from_contract_class(
            internal_declare.sierra_contract_class.clone(),
            true,
        )
        .unwrap();

        let casm_class = match state
            .get_contract_class(&internal_declare.compiled_class_hash.to_be_bytes())
            .unwrap()
        {
            CompiledClass::Casm(casm) => casm.as_ref().clone(),
            _ => unreachable!(),
        };

        assert_eq!(expected_casm_class, casm_class);
    }

    #[test]
    fn create_declare_v2_with_casm_contract_class_test() {
        // read file to create sierra contract class
        let version;
        let path;
        #[cfg(not(feature = "cairo_1_tests"))]
        {
            version = Felt252::from(2);
            path = PathBuf::from("starknet_programs/cairo2/fibonacci.sierra");
        }

        #[cfg(feature = "cairo_1_tests")]
        {
            version = Felt252::from(1);
            path = PathBuf::from("starknet_programs/cairo1/fibonacci.sierra");
        }

        let file = File::open(path).unwrap();
        let reader = BufReader::new(file);
        let sierra_contract_class: cairo_lang_starknet::contract_class::ContractClass =
            serde_json::from_reader(reader).unwrap();
        let sender_address = Address(1.into());
        let casm_class =
            CasmContractClass::from_contract_class(sierra_contract_class.clone(), true).unwrap();
        let casm_class_hash = compute_casm_class_hash(&casm_class).unwrap();

        // create internal declare v2

        let internal_declare = DeclareV2::new_with_tx_hash(
            &sierra_contract_class,
            Some(casm_class),
            casm_class_hash,
            sender_address,
            0,
            version,
            [1.into()].to_vec(),
            Felt252::zero(),
            Felt252::one(),
        )
        .unwrap();

        // crate state to store casm contract class
        let casm_contract_class_cache = HashMap::new();
        let state_reader = Arc::new(InMemoryStateReader::default());
        let mut state = CachedState::new(state_reader, casm_contract_class_cache);

        // call compile and store
        assert!(internal_declare
            .compile_and_store_casm_class(&mut state)
            .is_ok());

        // test we  can retreive the data
        let expected_casm_class = CasmContractClass::from_contract_class(
            internal_declare.sierra_contract_class.clone(),
            true,
        )
        .unwrap();

        let casm_class = match state
            .get_contract_class(&internal_declare.compiled_class_hash.to_be_bytes())
            .unwrap()
        {
            CompiledClass::Casm(casm) => casm.as_ref().clone(),
            _ => unreachable!(),
        };

        assert_eq!(expected_casm_class, casm_class);
    }

    #[test]
    fn create_declare_v2_test_with_version_query() {
        // read file to create sierra contract class
        let version;
        let path;
        #[cfg(not(feature = "cairo_1_tests"))]
        {
            version = &2.into() | &QUERY_VERSION_BASE.clone();
            path = PathBuf::from("starknet_programs/cairo2/fibonacci.sierra");
        }

        #[cfg(feature = "cairo_1_tests")]
        {
            version = &1.into() | &QUERY_VERSION_BASE.clone();
            path = PathBuf::from("starknet_programs/cairo1/fibonacci.sierra");
        }

        let file = File::open(path).unwrap();
        let reader = BufReader::new(file);
        let sierra_contract_class: cairo_lang_starknet::contract_class::ContractClass =
            serde_json::from_reader(reader).unwrap();
        let sierra_class_hash = compute_sierra_class_hash(&sierra_contract_class).unwrap();
        let sender_address = Address(1.into());
        let casm_class =
            CasmContractClass::from_contract_class(sierra_contract_class.clone(), true).unwrap();
        let casm_class_hash = compute_casm_class_hash(&casm_class).unwrap();

        // create internal declare v2

        let internal_declare = DeclareV2::new_with_sierra_class_hash_and_tx_hash(
            &sierra_contract_class,
            sierra_class_hash,
            Some(casm_class),
            casm_class_hash,
            sender_address,
            0,
            version,
            vec![],
            Felt252::zero(),
            Felt252::zero(),
        )
        .unwrap();

        // crate state to store casm contract class
        let casm_contract_class_cache = HashMap::new();
        let state_reader = Arc::new(InMemoryStateReader::default());
        let mut state = CachedState::new(state_reader, casm_contract_class_cache);

        // call compile and store
        assert!(internal_declare
            .compile_and_store_casm_class(&mut state)
            .is_ok());

        // test we  can retreive the data
        let expected_casm_class = CasmContractClass::from_contract_class(
            internal_declare.sierra_contract_class.clone(),
            true,
        )
        .unwrap();

        let casm_class = match state
            .get_contract_class(&internal_declare.compiled_class_hash.to_be_bytes())
            .unwrap()
        {
            CompiledClass::Casm(casm) => casm.as_ref().clone(),
            _ => unreachable!(),
        };

        assert_eq!(expected_casm_class, casm_class);
    }

    #[test]
    fn create_declare_v2_with_casm_contract_class_none_test() {
        // read file to create sierra contract class
        let version;
        let path;
        #[cfg(not(feature = "cairo_1_tests"))]
        {
            version = Felt252::from(2);
            path = PathBuf::from("starknet_programs/cairo2/fibonacci.sierra");
        }

        #[cfg(feature = "cairo_1_tests")]
        {
            version = Felt252::from(1);
            path = PathBuf::from("starknet_programs/cairo1/fibonacci.sierra");
        }

        let file = File::open(path).unwrap();
        let reader = BufReader::new(file);
        let sierra_contract_class: cairo_lang_starknet::contract_class::ContractClass =
            serde_json::from_reader(reader).unwrap();
        let sender_address = Address(1.into());
        let casm_class =
            CasmContractClass::from_contract_class(sierra_contract_class.clone(), true).unwrap();
        let casm_class_hash = compute_casm_class_hash(&casm_class).unwrap();

        // create internal declare v2

        let internal_declare = DeclareV2::new_with_tx_hash(
            &sierra_contract_class,
            None,
            casm_class_hash,
            sender_address,
            0,
            version,
            [1.into()].to_vec(),
            Felt252::zero(),
            Felt252::one(),
        )
        .unwrap();

        // crate state to store casm contract class
        let casm_contract_class_cache = HashMap::new();
        let state_reader = Arc::new(InMemoryStateReader::default());
        let mut state = CachedState::new(state_reader, casm_contract_class_cache);

        // call compile and store
        assert!(internal_declare
            .compile_and_store_casm_class(&mut state)
            .is_ok());

        // test we  can retreive the data
        let expected_casm_class = CasmContractClass::from_contract_class(
            internal_declare.sierra_contract_class.clone(),
            true,
        )
        .unwrap();

        let casm_class = match state
            .get_contract_class(&internal_declare.compiled_class_hash.to_be_bytes())
            .unwrap()
        {
            CompiledClass::Casm(casm) => casm.as_ref().clone(),
            _ => unreachable!(),
        };

        assert_eq!(expected_casm_class, casm_class);
    }

    #[test]
    fn create_declare_v2_wrong_casm_class_hash_test() {
        // read file to create sierra contract class
        let version;
        let path;
        #[cfg(not(feature = "cairo_1_tests"))]
        {
            version = Felt252::from(2);
            path = PathBuf::from("starknet_programs/cairo2/fibonacci.sierra");
        }

        #[cfg(feature = "cairo_1_tests")]
        {
            version = Felt252::from(1);
            path = PathBuf::from("starknet_programs/cairo1/fibonacci.sierra");
        }

        let file = File::open(path).unwrap();
        let reader = BufReader::new(file);
        let sierra_contract_class: cairo_lang_starknet::contract_class::ContractClass =
            serde_json::from_reader(reader).unwrap();
        let sender_address = Address(1.into());
        let casm_class =
            CasmContractClass::from_contract_class(sierra_contract_class.clone(), true).unwrap();
        let casm_class_hash = compute_casm_class_hash(&casm_class).unwrap();

        let sended_class_hash = Felt252::from(5);
        // create internal declare v2

        let internal_declare = DeclareV2::new_with_tx_hash(
            &sierra_contract_class,
            None,
            sended_class_hash.clone(),
            sender_address,
            0,
            version,
            [1.into()].to_vec(),
            Felt252::zero(),
            Felt252::one(),
        )
        .unwrap();

        // crate state to store casm contract class
        let casm_contract_class_cache = HashMap::new();
        let state_reader = Arc::new(InMemoryStateReader::default());
        let mut state = CachedState::new(state_reader, casm_contract_class_cache);

        let expected_err = format!(
            "Invalid compiled class, expected class hash: {}, but received: {}",
            casm_class_hash, sended_class_hash
        );
        assert_eq!(
            internal_declare
                .compile_and_store_casm_class(&mut state)
                .unwrap_err()
                .to_string(),
            expected_err
        );
    }
}