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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
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::state::cached_state::CachedState;
use crate::{
    core::{
        contract_address::compute_deprecated_class_hash,
        transaction_hash::calculate_declare_transaction_hash,
    },
    definitions::{
        block_context::BlockContext, constants::VALIDATE_DECLARE_ENTRY_POINT_SELECTOR,
        transaction_type::TransactionType,
    },
    execution::{
        execution_entry_point::ExecutionEntryPoint, CallInfo, TransactionExecutionContext,
        TransactionExecutionInfo,
    },
    services::api::contract_classes::deprecated_contract_class::ContractClass,
    state::state_api::{State, StateReader},
    state::ExecutionResourcesManager,
    transaction::error::TransactionError,
    utils::{
        calculate_tx_resources, felt_to_hash, verify_no_calls_to_other_contracts, Address,
        ClassHash,
    },
};
use cairo_vm::felt::Felt252;
use num_traits::Zero;

use super::fee::charge_fee;
use super::{verify_version, Transaction};
use crate::services::api::contract_classes::compiled_class::CompiledClass;
use std::sync::Arc;

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///  Represents an internal transaction in the StarkNet network that is a declaration of a Cairo
///  contract class.
#[derive(Debug, Clone)]
pub struct Declare {
    pub class_hash: ClassHash,
    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 hash_value: Felt252,
    pub contract_class: ContractClass,
    pub skip_validate: bool,
    pub skip_execute: bool,
    pub skip_fee_transfer: bool,
}

// ------------------------------------------------------------
//                        Functions
// ------------------------------------------------------------
impl Declare {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        contract_class: ContractClass,
        chain_id: Felt252,
        sender_address: Address,
        max_fee: u128,
        version: Felt252,
        signature: Vec<Felt252>,
        nonce: Felt252,
    ) -> Result<Self, TransactionError> {
        let hash = compute_deprecated_class_hash(&contract_class)?;
        let class_hash = felt_to_hash(&hash);

        let hash_value = calculate_declare_transaction_hash(
            &contract_class,
            chain_id,
            &sender_address,
            max_fee,
            version.clone(),
            nonce.clone(),
        )?;

        let validate_entry_point_selector = VALIDATE_DECLARE_ENTRY_POINT_SELECTOR.clone();

        let internal_declare = Declare {
            class_hash,
            sender_address,
            validate_entry_point_selector,
            version,
            max_fee,
            signature,
            nonce,
            hash_value,
            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)
    }

    #[allow(clippy::too_many_arguments)]
    pub fn new_with_tx_hash(
        contract_class: ContractClass,
        sender_address: Address,
        max_fee: u128,
        version: Felt252,
        signature: Vec<Felt252>,
        nonce: Felt252,
        hash_value: Felt252,
    ) -> Result<Self, TransactionError> {
        let hash = compute_deprecated_class_hash(&contract_class)?;
        let class_hash = felt_to_hash(&hash);

        let validate_entry_point_selector = VALIDATE_DECLARE_ENTRY_POINT_SELECTOR.clone();

        let internal_declare = Declare {
            class_hash,
            sender_address,
            validate_entry_point_selector,
            version,
            max_fee,
            signature,
            nonce,
            hash_value,
            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)
    }

    pub fn get_calldata(&self) -> Vec<Felt252> {
        let bytes = Felt252::from_bytes_be(&self.class_hash);
        Vec::from([bytes])
    }

    /// Executes a call to the cairo-vm using the accounts_validation.cairo contract to validate
    /// the contract that is being declared. Then it returns the transaction execution info of the run.
    pub fn apply<S: StateReader>(
        &self,
        state: &mut CachedState<S>,
        block_context: &BlockContext,
    ) -> Result<TransactionExecutionInfo, TransactionError> {
        verify_version(&self.version, self.max_fee, &self.nonce, &self.signature)?;

        // validate transaction
        let mut resources_manager = ExecutionResourcesManager::default();
        let validate_info = if self.skip_validate {
            None
        } else {
            self.run_validate_entrypoint(state, &mut resources_manager, block_context)?
        };
        let 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,
            &vec![validate_info.clone()],
            TransactionType::Declare,
            changes,
            None,
            0,
        )
        .map_err(|_| TransactionError::ResourcesCalculation)?;

        Ok(TransactionExecutionInfo::new_without_fee_info(
            validate_info,
            None,
            None,
            actual_resources,
            Some(TransactionType::Declare),
        ))
    }

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // Internal Account Functions
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    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(),
        )
    }

    pub fn run_validate_entrypoint<S: StateReader>(
        &self,
        state: &mut CachedState<S>,
        resources_manager: &mut ExecutionResourcesManager,
        block_context: &BlockContext,
    ) -> Result<Option<CallInfo>, TransactionError> {
        if self.version.is_zero() || self.version == *QUERY_VERSION_BASE {
            return Ok(None);
        }

        let calldata = self.get_calldata();

        let entry_point = ExecutionEntryPoint::new(
            self.sender_address.clone(),
            calldata,
            self.validate_entry_point_selector.clone(),
            Address(Felt252::zero()),
            EntryPointType::External,
            None,
            None,
            0,
        );

        let ExecutionResult { call_info, .. } = entry_point.execute(
            state,
            block_context,
            resources_manager,
            &mut self.get_execution_context(block_context.invoke_tx_max_n_steps),
            false,
            block_context.validate_max_n_steps,
        )?;

        let call_info = call_info.ok_or(TransactionError::CallInfoIsNone)?;

        verify_no_calls_to_other_contracts(&call_info)
            .map_err(|_| TransactionError::UnauthorizedActionOnValidate)?;

        Ok(Some(call_info))
    }

    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(())
    }

    /// Calculates actual fee used by the transaction using the execution
    /// info returned by apply(), then updates the transaction execution info with the data of the fee.
    pub fn execute<S: StateReader>(
        &self,
        state: &mut CachedState<S>,
        block_context: &BlockContext,
    ) -> Result<TransactionExecutionInfo, TransactionError> {
        self.handle_nonce(state)?;
        let mut tx_exec_info = self.apply(state, block_context)?;

        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,
            &tx_exec_info.actual_resources,
            block_context,
            self.max_fee,
            &mut tx_execution_context,
            self.skip_fee_transfer,
        )?;

        state.set_contract_class(
            &self.class_hash,
            &CompiledClass::Deprecated(Arc::new(self.contract_class.clone())),
        )?;

        tx_exec_info.set_fee_info(actual_fee, fee_transfer_info);

        Ok(tx_exec_info)
    }

    pub(crate) fn create_for_simulation(
        &self,
        skip_validate: bool,
        skip_execute: bool,
        skip_fee_transfer: bool,
        ignore_max_fee: bool,
    ) -> Transaction {
        let tx = Declare {
            skip_validate,
            skip_execute,
            skip_fee_transfer,
            // Keep the max_fee value for V0 for validation
            max_fee: if ignore_max_fee && !self.version.is_zero() {
                u128::MAX
            } else {
                self.max_fee
            },
            ..self.clone()
        };

        Transaction::Declare(tx)
    }
}

// ---------------
//     Tests
// ---------------

#[cfg(test)]
mod tests {
    use super::*;
    use cairo_vm::{
        felt::{felt_str, Felt252},
        vm::runners::cairo_runner::ExecutionResources,
    };
    use num_traits::{One, Zero};
    use std::{collections::HashMap, path::PathBuf, sync::Arc};

    use crate::{
        definitions::{
            block_context::{BlockContext, StarknetChainId},
            constants::VALIDATE_DECLARE_ENTRY_POINT_SELECTOR,
            transaction_type::TransactionType,
        },
        execution::CallType,
        services::api::contract_classes::{
            compiled_class::CompiledClass, deprecated_contract_class::ContractClass,
        },
        state::cached_state::CachedState,
        state::in_memory_state_reader::InMemoryStateReader,
        utils::{felt_to_hash, Address},
    };

    use super::Declare;

    #[test]
    fn declare_fibonacci() {
        // accounts contract class must be stored before running declaration of fibonacci
        let contract_class =
            ContractClass::from_path("starknet_programs/account_without_validation.json").unwrap();

        // Instantiate CachedState
        let mut contract_class_cache = HashMap::new();

        //  ------------ contract data --------------------
        let hash = compute_deprecated_class_hash(&contract_class).unwrap();
        let class_hash = hash.to_be_bytes();

        contract_class_cache.insert(
            class_hash,
            CompiledClass::Deprecated(Arc::new(contract_class.clone())),
        );

        // store sender_address
        let sender_address = Address(1.into());
        // this is not conceptually correct as the sender address would be an
        // Account contract (not the contract that we are currently declaring)
        // but for testing reasons its ok

        let mut state_reader = InMemoryStateReader::default();
        state_reader
            .address_to_class_hash_mut()
            .insert(sender_address.clone(), class_hash);
        state_reader
            .address_to_nonce_mut()
            .insert(sender_address, Felt252::new(1));

        let mut state = CachedState::new(Arc::new(state_reader), contract_class_cache);

        //* ---------------------------------------
        //*    Test declare with previous data
        //* ---------------------------------------

        let fib_contract_class =
            ContractClass::from_path("starknet_programs/fibonacci.json").unwrap();

        let chain_id = StarknetChainId::TestNet.to_felt();

        // declare tx
        let internal_declare = Declare::new(
            fib_contract_class,
            chain_id,
            Address(Felt252::one()),
            0,
            1.into(),
            Vec::new(),
            Felt252::zero(),
        )
        .unwrap();

        //* ---------------------------------------
        //              Expected result
        //* ---------------------------------------

        // Value generated from selector _validate_declare_
        let entry_point_selector = Some(VALIDATE_DECLARE_ENTRY_POINT_SELECTOR.clone());

        let class_hash_felt = compute_deprecated_class_hash(&contract_class).unwrap();
        let expected_class_hash = felt_to_hash(&class_hash_felt);

        // Calldata is the class hash represented as a Felt252
        let calldata = [felt_str!(
            "151449101692423517761547521693863750221386499114738230243355039033913267347"
        )]
        .to_vec();

        let validate_info = Some(CallInfo {
            caller_address: Address(0.into()),
            call_type: Some(CallType::Call),
            contract_address: Address(Felt252::one()),
            entry_point_selector,
            entry_point_type: Some(EntryPointType::External),
            calldata,
            class_hash: Some(expected_class_hash),
            execution_resources: ExecutionResources {
                n_steps: 12,
                ..Default::default()
            },
            ..Default::default()
        });

        let actual_resources = HashMap::from([
            ("n_steps".to_string(), 2715),
            ("l1_gas_usage".to_string(), 1224),
            ("range_check_builtin".to_string(), 63),
            ("pedersen_builtin".to_string(), 15),
        ]);
        let transaction_exec_info = TransactionExecutionInfo {
            validate_info,
            call_info: None,
            revert_error: None,
            fee_transfer_info: None,
            actual_fee: 0,
            actual_resources,
            tx_type: Some(TransactionType::Declare),
        };

        // ---------------------
        //      Comparison
        // ---------------------
        assert_eq!(
            internal_declare
                .apply(&mut state, &BlockContext::default())
                .unwrap(),
            transaction_exec_info
        );
    }

    #[test]
    fn verify_version_zero_should_fail_max_fee() {
        // accounts contract class must be stored before running declaration of fibonacci
        let path = PathBuf::from("starknet_programs/account_without_validation.json");
        let contract_class = ContractClass::from_path(path).unwrap();

        // Instantiate CachedState
        let mut contract_class_cache = HashMap::new();

        //  ------------ contract data --------------------
        let hash = compute_deprecated_class_hash(&contract_class).unwrap();
        let class_hash = felt_to_hash(&hash);

        contract_class_cache.insert(class_hash, contract_class);

        //* ---------------------------------------
        //*    Test declare with previous data
        //* ---------------------------------------

        let fib_contract_class =
            ContractClass::from_path("starknet_programs/fibonacci.json").unwrap();

        let chain_id = StarknetChainId::TestNet.to_felt();
        let max_fee = 1000;
        let version = 0.into();

        // Declare tx should fail because max_fee > 0 and version == 0
        let internal_declare = Declare::new(
            fib_contract_class,
            chain_id,
            Address(Felt252::one()),
            max_fee,
            version,
            Vec::new(),
            Felt252::from(max_fee),
        );

        // ---------------------
        //      Comparison
        // ---------------------
        assert!(internal_declare.is_err());
        assert_matches!(
            internal_declare.unwrap_err(),
            TransactionError::InvalidMaxFee
        );
    }

    #[test]
    fn verify_version_zero_should_fail_nonce() {
        // accounts contract class must be stored before running declaration of fibonacci
        let path = PathBuf::from("starknet_programs/account_without_validation.json");
        let contract_class = ContractClass::from_path(path).unwrap();

        // Instantiate CachedState
        let mut contract_class_cache = HashMap::new();

        //  ------------ contract data --------------------
        let hash = compute_deprecated_class_hash(&contract_class).unwrap();
        let class_hash = felt_to_hash(&hash);

        contract_class_cache.insert(
            class_hash,
            CompiledClass::Deprecated(Arc::new(contract_class)),
        );

        // store sender_address
        let sender_address = Address(1.into());
        // this is not conceptually correct as the sender address would be an
        // Account contract (not the contract that we are currently declaring)
        // but for testing reasons its ok

        let mut state_reader = InMemoryStateReader::default();
        state_reader
            .address_to_class_hash_mut()
            .insert(sender_address.clone(), class_hash);
        state_reader
            .address_to_nonce_mut()
            .insert(sender_address, Felt252::new(1));

        let _state = CachedState::new(Arc::new(state_reader), contract_class_cache);

        //* ---------------------------------------
        //*    Test declare with previous data
        //* ---------------------------------------

        let fib_contract_class =
            ContractClass::from_path("starknet_programs/fibonacci.json").unwrap();

        let chain_id = StarknetChainId::TestNet.to_felt();
        let nonce = Felt252::from(148);
        let version = 0.into();

        // Declare tx should fail because nonce > 0 and version == 0
        let internal_declare = Declare::new(
            fib_contract_class,
            chain_id,
            Address(Felt252::one()),
            0,
            version,
            Vec::new(),
            nonce,
        );

        // ---------------------
        //      Comparison
        // ---------------------
        assert!(internal_declare.is_err());
        assert_matches!(
            internal_declare.unwrap_err(),
            TransactionError::InvalidNonce
        );
    }

    #[test]
    fn verify_signature_should_fail_not_empty_list() {
        // accounts contract class must be stored before running declaration of fibonacci
        let path = PathBuf::from("starknet_programs/account_without_validation.json");
        let contract_class = ContractClass::from_path(path).unwrap();

        // Instantiate CachedState
        let mut contract_class_cache = HashMap::new();

        //  ------------ contract data --------------------
        let hash = compute_deprecated_class_hash(&contract_class).unwrap();
        let class_hash = felt_to_hash(&hash);

        contract_class_cache.insert(
            class_hash,
            CompiledClass::Deprecated(Arc::new(contract_class)),
        );

        // store sender_address
        let sender_address = Address(1.into());
        // this is not conceptually correct as the sender address would be an
        // Account contract (not the contract that we are currently declaring)
        // but for testing reasons its ok

        let mut state_reader = InMemoryStateReader::default();
        state_reader
            .address_to_class_hash_mut()
            .insert(sender_address.clone(), class_hash);
        state_reader
            .address_to_nonce_mut()
            .insert(sender_address, Felt252::new(1));

        let _state = CachedState::new(Arc::new(state_reader), contract_class_cache);

        //* ---------------------------------------
        //*    Test declare with previous data
        //* ---------------------------------------

        let fib_contract_class =
            ContractClass::from_path("starknet_programs/fibonacci.json").unwrap();

        let chain_id = StarknetChainId::TestNet.to_felt();
        let signature = vec![1.into(), 2.into()];

        // Declare tx should fail because signature is not empty
        let internal_declare = Declare::new(
            fib_contract_class,
            chain_id,
            Address(Felt252::one()),
            0,
            0.into(),
            signature,
            Felt252::zero(),
        );

        // ---------------------
        //      Comparison
        // ---------------------
        assert!(internal_declare.is_err());
        assert_matches!(
            internal_declare.unwrap_err(),
            TransactionError::InvalidSignature
        );
    }

    #[test]
    fn execute_class_already_declared_should_redeclare() {
        // accounts contract class must be stored before running declaration of fibonacci
        let path = PathBuf::from("starknet_programs/account_without_validation.json");
        let contract_class = ContractClass::from_path(path).unwrap();

        // Instantiate CachedState
        let mut contract_class_cache = HashMap::new();

        //  ------------ contract data --------------------
        let hash = compute_deprecated_class_hash(&contract_class).unwrap();
        let class_hash = felt_to_hash(&hash);

        contract_class_cache.insert(
            class_hash,
            CompiledClass::Deprecated(Arc::new(contract_class)),
        );

        // store sender_address
        let sender_address = Address(1.into());
        // this is not conceptually correct as the sender address would be an
        // Account contract (not the contract that we are currently declaring)
        // but for testing reasons its ok

        let mut state_reader = InMemoryStateReader::default();
        state_reader
            .address_to_class_hash_mut()
            .insert(sender_address.clone(), class_hash);
        state_reader
            .address_to_nonce_mut()
            .insert(sender_address, Felt252::zero());

        let mut state = CachedState::new(Arc::new(state_reader), contract_class_cache);

        //* ---------------------------------------
        //*    Test declare with previous data
        //* ---------------------------------------

        let fib_contract_class =
            ContractClass::from_path("starknet_programs/fibonacci.json").unwrap();

        let chain_id = StarknetChainId::TestNet.to_felt();

        // Declare same class twice
        let internal_declare = Declare::new(
            fib_contract_class.clone(),
            chain_id.clone(),
            Address(Felt252::one()),
            0,
            1.into(),
            Vec::new(),
            Felt252::zero(),
        )
        .unwrap();

        let second_internal_declare = Declare::new(
            fib_contract_class,
            chain_id,
            Address(Felt252::one()),
            0,
            1.into(),
            Vec::new(),
            Felt252::one(),
        )
        .unwrap();

        internal_declare
            .execute(&mut state, &BlockContext::default())
            .unwrap();

        assert!(state.get_contract_class(&class_hash).is_ok());

        second_internal_declare
            .execute(&mut state, &BlockContext::default())
            .unwrap();

        assert!(state.get_contract_class(&class_hash).is_ok());
    }

    #[test]
    fn execute_transaction_twice_should_fail() {
        // accounts contract class must be stored before running declaration of fibonacci
        let path = PathBuf::from("starknet_programs/account_without_validation.json");
        let contract_class = ContractClass::from_path(path).unwrap();

        // Instantiate CachedState
        let mut contract_class_cache = HashMap::new();

        //  ------------ contract data --------------------
        let hash = compute_deprecated_class_hash(&contract_class).unwrap();
        let class_hash = felt_to_hash(&hash);

        contract_class_cache.insert(
            class_hash,
            CompiledClass::Deprecated(Arc::new(contract_class)),
        );

        // store sender_address
        let sender_address = Address(1.into());
        // this is not conceptually correct as the sender address would be an
        // Account contract (not the contract that we are currently declaring)
        // but for testing reasons its ok

        let mut state_reader = InMemoryStateReader::default();
        state_reader
            .address_to_class_hash_mut()
            .insert(sender_address.clone(), class_hash);
        state_reader
            .address_to_nonce_mut()
            .insert(sender_address, Felt252::zero());

        let mut state = CachedState::new(Arc::new(state_reader), contract_class_cache);

        //* ---------------------------------------
        //*    Test declare with previous data
        //* ---------------------------------------

        let fib_contract_class =
            ContractClass::from_path("starknet_programs/fibonacci.json").unwrap();

        let chain_id = StarknetChainId::TestNet.to_felt();

        // Declare same class twice
        let internal_declare = Declare::new(
            fib_contract_class,
            chain_id,
            Address(Felt252::one()),
            0,
            1.into(),
            Vec::new(),
            Felt252::zero(),
        )
        .unwrap();

        internal_declare
            .execute(&mut state, &BlockContext::default())
            .unwrap();

        let expected_error = internal_declare.execute(&mut state, &BlockContext::default());

        // ---------------------
        //      Comparison
        // ---------------------

        assert!(expected_error.is_err());
        assert_matches!(
            expected_error.unwrap_err(),
            TransactionError::InvalidTransactionNonce(..)
        )
    }

    #[test]
    fn validate_transaction_should_fail() {
        // Instantiate CachedState
        let contract_class_cache = HashMap::new();

        let state_reader = Arc::new(InMemoryStateReader::default());

        let mut state = CachedState::new(state_reader, contract_class_cache);

        // There are no account contracts in the state, so the transaction should fail
        let fib_contract_class =
            ContractClass::from_path("starknet_programs/fibonacci.json").unwrap();

        let chain_id = StarknetChainId::TestNet.to_felt();

        let internal_declare = Declare::new(
            fib_contract_class,
            chain_id,
            Address(Felt252::one()),
            0,
            1.into(),
            Vec::new(),
            Felt252::zero(),
        )
        .unwrap();

        let internal_declare_error = internal_declare.execute(&mut state, &BlockContext::default());

        assert!(internal_declare_error.is_err());
        assert_matches!(
            internal_declare_error.unwrap_err(),
            TransactionError::NotDeployedContract(..)
        );
    }

    #[test]
    fn execute_transaction_charge_fee_should_fail() {
        // accounts contract class must be stored before running declaration of fibonacci
        let path = PathBuf::from("starknet_programs/account_without_validation.json");
        let contract_class = ContractClass::from_path(path).unwrap();

        // Instantiate CachedState
        let mut contract_class_cache = HashMap::new();

        //  ------------ contract data --------------------
        let hash = compute_deprecated_class_hash(&contract_class).unwrap();
        let class_hash = felt_to_hash(&hash);

        contract_class_cache.insert(
            class_hash,
            CompiledClass::Deprecated(Arc::new(contract_class)),
        );

        // store sender_address
        let sender_address = Address(1.into());
        // this is not conceptually correct as the sender address would be an
        // Account contract (not the contract that we are currently declaring)
        // but for testing reasons its ok

        let mut state_reader = InMemoryStateReader::default();
        state_reader
            .address_to_class_hash_mut()
            .insert(sender_address.clone(), class_hash);
        state_reader
            .address_to_nonce_mut()
            .insert(sender_address, Felt252::zero());

        let mut state = CachedState::new(Arc::new(state_reader), contract_class_cache);

        //* ---------------------------------------
        //*    Test declare with previous data
        //* ---------------------------------------

        let fib_contract_class =
            ContractClass::from_path("starknet_programs/fibonacci.json").unwrap();

        let chain_id = StarknetChainId::TestNet.to_felt();

        // Use non-zero value so that the actual fee calculation is done
        let internal_declare = Declare::new(
            fib_contract_class,
            chain_id,
            Address(Felt252::one()),
            10,
            1.into(),
            Vec::new(),
            Felt252::zero(),
        )
        .unwrap();

        // We expect a fee transfer failure because the fee token contract is not set up
        assert_matches!(
            internal_declare.execute(&mut state, &BlockContext::default()),
            Err(TransactionError::FeeTransferError(_))
        );
    }
}