starknet_api 0.18.0-rc.0

Starknet Rust types related to computation and execution.
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
use std::collections::HashMap;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;

use apollo_infra_utils::path::current_dir;
use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass;
use cairo_lang_utils::bigint::BigUintAsHex;
use num_bigint::BigUint;
use serde::{Deserialize, Serialize};
use starknet_types_core::felt::Felt;
use starknet_types_core::hash::{Pedersen, StarkHash as StarkHashTrait};

use crate::block::{
    BlockHash,
    BlockInfo,
    BlockNumber,
    BlockTimestamp,
    GasPrice,
    GasPriceVector,
    GasPrices,
    NonzeroGasPrice,
    StarknetVersion,
};
use crate::contract_class::{ContractClass, SierraVersion};
use crate::core::{ChainId, ContractAddress, Nonce, STARKNET_OS_CONFIG_HASH_VERSION};
use crate::deprecated_contract_class::{ContractClass as DeprecatedContractClass, Program};
use crate::executable_transaction::AccountTransaction;
use crate::execution_resources::GasAmount;
use crate::rpc_transaction::{InternalRpcTransaction, RpcTransaction};
use crate::transaction::fields::{
    AllResourceBounds,
    Fee,
    Proof,
    ProofFacts,
    ResourceBounds,
    ValidResourceBounds,
    PROOF_VERSION,
    VIRTUAL_OS_OUTPUT_VERSION,
    VIRTUAL_SNOS,
};
use crate::transaction::{Transaction, TransactionHash};

/// OS config hash for testing.
/// This is the Pedersen hash of [STARKNET_OS_CONFIG_HASH_VERSION, chain_id, strk_fee_token_address]
pub static TEST_OS_CONFIG_HASH: LazyLock<Felt> = LazyLock::new(|| {
    let chain_id_felt: Felt = (&*CHAIN_ID_FOR_TESTS).try_into().unwrap();
    let strk_fee_token_address: Felt = contract_address!(TEST_ERC20_CONTRACT_ADDRESS2).into();
    Pedersen::hash_array(&[STARKNET_OS_CONFIG_HASH_VERSION, chain_id_felt, strk_fee_token_address])
});
use crate::{contract_address, felt};

pub mod declare;
pub mod deploy_account;
pub mod invoke;
pub mod l1_handler;

// TODO(Dori, 1/2/2024): Remove these constants once all tests use the `contracts` and
//   `initial_test_state` modules for testing.
// Addresses.
pub const TEST_SEQUENCER_ADDRESS: &str = "0x1000";
pub const TEST_ERC20_CONTRACT_ADDRESS: &str = "0x1001";
pub const TEST_ERC20_CONTRACT_ADDRESS2: &str = "0x1002";

// The block number of the BlockContext being used for testing.
pub const CURRENT_BLOCK_NUMBER: u64 = 2001;
pub const CURRENT_BLOCK_NUMBER_FOR_VALIDATE: u64 = 2000;

// Offset (in blocks) from the current block number that determines the oldest
// block number whose block hash will be populated in the block-hash contract.
pub const BLOCK_HASH_HISTORY_RANGE: u64 = 51;

// The block timestamp of the BlockContext being used for testing.
pub const CURRENT_BLOCK_TIMESTAMP: u64 = 1072023;
pub const CURRENT_BLOCK_TIMESTAMP_FOR_VALIDATE: u64 = 1069200;

pub static CHAIN_ID_FOR_TESTS: LazyLock<ChainId> =
    LazyLock::new(|| ChainId::Other("CHAIN_ID_SUBDIR".to_owned()));

/// Returns the path to a file in the resources directory. This assumes the current working
/// directory has a `resources` folder. The value for file_path should be the path to the required
/// file in the folder "resources".
pub fn path_in_resources<P: AsRef<Path>>(file_path: P) -> PathBuf {
    current_dir().unwrap().join("resources").join(file_path)
}

/// Reads from the directory containing the manifest at run time, same as current working directory.
pub fn read_json_file<P: AsRef<Path>, T>(path_in_resource_dir: P) -> T
where
    T: for<'a> serde::de::Deserialize<'a>,
{
    let path = path_in_resources(path_in_resource_dir);
    let file =
        File::open(&path).unwrap_or_else(|_| panic!("Failed to open file at path: {path:?}"));
    serde_json::from_reader(file)
        .unwrap_or_else(|_| panic!("Failed to parse JSON from file at path: {path:?}"))
}

#[derive(Deserialize, Serialize, Debug)]
/// A struct used for reading the transaction test data (e.g., for transaction hash tests).
pub struct TransactionTestData {
    /// The actual transaction.
    pub transaction: Transaction,
    /// The expected transaction hash.
    pub transaction_hash: TransactionHash,
    /// An optional transaction hash to query.
    pub only_query_transaction_hash: Option<TransactionHash>,
    pub chain_id: ChainId,
    pub block_number: BlockNumber,
}

#[derive(Debug, Default, Clone)]
pub struct NonceManager {
    next_nonce: HashMap<ContractAddress, Felt>,
}

impl NonceManager {
    pub fn get(&self, account_address: ContractAddress) -> Nonce {
        Nonce(*self.next_nonce.get(&account_address).unwrap_or(&Felt::default()))
    }

    pub fn next(&mut self, account_address: ContractAddress) -> Nonce {
        let next = self.next_nonce.remove(&account_address).unwrap_or_default();
        self.next_nonce.insert(account_address, next + 1);
        Nonce(next)
    }

    /// Decrements the nonce of the account, unless it is zero.
    pub fn rollback(&mut self, account_address: ContractAddress) {
        let current_nonce = *self.next_nonce.get(&account_address).unwrap_or(&Felt::default());
        if current_nonce != Felt::ZERO {
            self.next_nonce.insert(account_address, current_nonce - 1);
        }
    }
}

/// A utility macro to create a [`Nonce`] from a hex string / unsigned integer
/// representation.
#[macro_export]
macro_rules! nonce {
    ($s:expr) => {
        $crate::core::Nonce(starknet_types_core::felt::Felt::from($s))
    };
}

/// A utility macro to create a [`StorageKey`](crate::state::StorageKey) from a hex string /
/// unsigned integer representation.
#[macro_export]
macro_rules! storage_key {
    ($s:expr) => {
        $crate::state::StorageKey(starknet_api::patricia_key!($s))
    };
}

/// A utility macro to create a [`CompiledClassHash`](crate::core::CompiledClassHash) from a hex
/// string / unsigned integer representation.
#[macro_export]
macro_rules! compiled_class_hash {
    ($s:expr) => {
        $crate::core::CompiledClassHash(starknet_types_core::felt::Felt::from($s))
    };
}

/// A utility macro to create a [`ProofFacts`] from a list
/// of felt values.
#[macro_export]
macro_rules! proof_facts {
    ( $( $x:expr ),* ) => {
        $crate::transaction::fields::ProofFacts(vec![$($x),*].into())
    };
}

/// A utility macro to create a [`Proof`] from a list of u8
/// values.
#[macro_export]
macro_rules! proof {
    ( $( $x:expr ),* ) => {
        $crate::transaction::fields::Proof(vec![$($x),*].into())
    };
}

pub const VALID_L1_GAS_MAX_AMOUNT: u64 = 203484;
pub const VALID_L1_GAS_MAX_PRICE_PER_UNIT: u128 = 100000000000000;
// Enough to declare the test class, but under the OS's upper limit.
pub const VALID_L2_GAS_MAX_AMOUNT: u64 = 1_100_000_000;
pub const VALID_L2_GAS_MAX_PRICE_PER_UNIT: u128 = 100000000000000;
pub const VALID_L1_DATA_GAS_MAX_AMOUNT: u64 = 203484;
pub const VALID_L1_DATA_GAS_MAX_PRICE_PER_UNIT: u128 = 100000000000000;

#[allow(clippy::as_conversions)]
pub const VALID_ACCOUNT_BALANCE: Fee =
    Fee(VALID_L2_GAS_MAX_AMOUNT as u128 * VALID_L2_GAS_MAX_PRICE_PER_UNIT * 1000);

// V3 transactions:
pub const DEFAULT_L1_GAS_AMOUNT: GasAmount = GasAmount(u64::pow(10, 6));
pub const DEFAULT_L1_DATA_GAS_MAX_AMOUNT: GasAmount = GasAmount(u64::pow(10, 6));
pub const DEFAULT_L2_GAS_MAX_AMOUNT: GasAmount = GasAmount(u64::pow(10, 9));
pub const MAX_L1_GAS_PRICE: NonzeroGasPrice = DEFAULT_STRK_L1_GAS_PRICE;
pub const MAX_L2_GAS_PRICE: NonzeroGasPrice = DEFAULT_STRK_L2_GAS_PRICE;
pub const MAX_L1_DATA_GAS_PRICE: NonzeroGasPrice = DEFAULT_STRK_L1_DATA_GAS_PRICE;

pub const DEFAULT_ETH_L1_GAS_PRICE: NonzeroGasPrice =
    NonzeroGasPrice::new_unchecked(GasPrice(100 * u128::pow(10, 9))); // Given in units of Wei.
pub const DEFAULT_STRK_L1_GAS_PRICE: NonzeroGasPrice =
    NonzeroGasPrice::new_unchecked(GasPrice(100 * u128::pow(10, 9))); // Given in units of Fri.
pub const DEFAULT_ETH_L1_DATA_GAS_PRICE: NonzeroGasPrice =
    NonzeroGasPrice::new_unchecked(GasPrice(u128::pow(10, 6))); // Given in units of Wei.
pub const DEFAULT_STRK_L1_DATA_GAS_PRICE: NonzeroGasPrice =
    NonzeroGasPrice::new_unchecked(GasPrice(u128::pow(10, 9))); // Given in units of Fri.
pub const DEFAULT_ETH_L2_GAS_PRICE: NonzeroGasPrice =
    NonzeroGasPrice::new_unchecked(GasPrice(u128::pow(10, 6)));
pub const DEFAULT_STRK_L2_GAS_PRICE: NonzeroGasPrice =
    NonzeroGasPrice::new_unchecked(GasPrice(u128::pow(10, 9)));

pub const DEFAULT_GAS_PRICES: GasPrices = GasPrices {
    eth_gas_prices: GasPriceVector {
        l1_gas_price: DEFAULT_ETH_L1_GAS_PRICE,
        l2_gas_price: DEFAULT_ETH_L2_GAS_PRICE,
        l1_data_gas_price: DEFAULT_ETH_L1_DATA_GAS_PRICE,
    },
    strk_gas_prices: GasPriceVector {
        l1_gas_price: DEFAULT_STRK_L1_GAS_PRICE,
        l2_gas_price: DEFAULT_STRK_L2_GAS_PRICE,
        l1_data_gas_price: DEFAULT_STRK_L1_DATA_GAS_PRICE,
    },
};

// Deprecated transactions:
pub const MAX_FEE: Fee = DEFAULT_L1_GAS_AMOUNT.nonzero_saturating_mul(DEFAULT_ETH_L1_GAS_PRICE);

// Dummy virtual OS program hash for testing.
pub const VIRTUAL_OS_PROGRAM_HASH: Felt = Felt::from_hex_unchecked("0x1");

/// Computes a deterministic block hash for testing purposes.
pub fn test_block_hash(block_number: u64) -> BlockHash {
    BlockHash(Felt::from(block_number * 100))
}

impl BlockInfo {
    pub fn create_for_testing() -> Self {
        Self {
            block_number: BlockNumber(CURRENT_BLOCK_NUMBER),
            block_timestamp: BlockTimestamp(CURRENT_BLOCK_TIMESTAMP),
            sequencer_address: contract_address!(TEST_SEQUENCER_ADDRESS),
            gas_prices: DEFAULT_GAS_PRICES,
            // TODO(Yoni): change to true.
            use_kzg_da: false,
            starknet_version: StarknetVersion::LATEST,
        }
    }

    pub fn create_for_testing_with_kzg(use_kzg_da: bool) -> Self {
        Self { use_kzg_da, ..Self::create_for_testing() }
    }
}

pub fn resource_bounds_for_testing() -> AllResourceBounds {
    AllResourceBounds {
        l1_gas: ResourceBounds {
            max_amount: GasAmount(VALID_L1_GAS_MAX_AMOUNT),
            max_price_per_unit: GasPrice(VALID_L1_GAS_MAX_PRICE_PER_UNIT),
        },
        l2_gas: ResourceBounds {
            max_amount: GasAmount(VALID_L2_GAS_MAX_AMOUNT),
            max_price_per_unit: GasPrice(VALID_L2_GAS_MAX_PRICE_PER_UNIT),
        },
        l1_data_gas: ResourceBounds {
            max_amount: GasAmount(VALID_L1_DATA_GAS_MAX_AMOUNT),
            max_price_per_unit: GasPrice(VALID_L1_DATA_GAS_MAX_PRICE_PER_UNIT),
        },
    }
}

pub fn valid_resource_bounds_for_testing() -> ValidResourceBounds {
    ValidResourceBounds::AllResources(resource_bounds_for_testing())
}

/// A trait for producing test transactions.
pub trait TestingTxArgs {
    fn get_rpc_tx(&self) -> RpcTransaction;
    fn get_internal_tx(&self) -> InternalRpcTransaction;
    /// Returns the executable transaction for the transaction.
    /// Note: In the declare transaction, `class_info` is constructed using a default compiled
    /// contract class, so if the test requires a specific contract class this function
    /// shouldn't be used.
    fn get_executable_tx(&self) -> AccountTransaction;
}

static TEST_CASM_CONTRACT_CLASS: LazyLock<ContractClass> = LazyLock::new(|| {
    let default_casm = CasmContractClass {
        prime: Default::default(),
        compiler_version: Default::default(),
        bytecode: vec![
            BigUintAsHex { value: BigUint::from(1_u8) },
            BigUintAsHex { value: BigUint::from(1_u8) },
            BigUintAsHex { value: BigUint::from(1_u8) },
        ],
        bytecode_segment_lengths: Default::default(),
        hints: Default::default(),
        pythonic_hints: Default::default(),
        entry_points_by_type: Default::default(),
    };
    ContractClass::V1((default_casm, SierraVersion::default()))
});

static TEST_DEPRECATED_CASM_CONTRACT_CLASS: LazyLock<ContractClass> = LazyLock::new(|| {
    let default_deprecated_casm = DeprecatedContractClass {
        abi: None,
        program: Program {
            attributes: serde_json::Value::Null,
            builtins: serde_json::Value::Array(vec![]),
            compiler_version: serde_json::Value::Null,
            data: serde_json::Value::Array(vec![]),
            debug_info: serde_json::Value::Null,
            hints: serde_json::Value::Object(serde_json::Map::new()),
            identifiers: serde_json::Value::Object(serde_json::Map::new()),
            main_scope: serde_json::Value::String("__main__".to_string()),
            prime: serde_json::Value::String(
                "0x800000000000011000000000000000000000000000000000000000000000001".to_string(),
            ),
            reference_manager: serde_json::Value::Object({
                let mut map = serde_json::Map::new();
                map.insert("references".to_string(), serde_json::Value::Array(vec![]));
                map
            }),
        },
        entry_points_by_type: Default::default(),
    };
    ContractClass::V0(default_deprecated_casm)
});

impl ContractClass {
    pub fn test_casm_contract_class() -> Self {
        TEST_CASM_CONTRACT_CLASS.clone()
    }

    pub fn test_deprecated_casm_contract_class() -> Self {
        TEST_DEPRECATED_CASM_CONTRACT_CLASS.clone()
    }
}

/// Formats a json object in the same way that python's json.dumps() formats.
pub(crate) struct PyJsonFormatter;

impl PyJsonFormatter {
    pub(crate) fn comma() -> &'static [u8; 2] {
        b", "
    }

    pub(crate) fn colon() -> &'static [u8; 2] {
        b": "
    }
}

impl serde_json::ser::Formatter for PyJsonFormatter {
    fn begin_array_value<W: ?Sized + std::io::Write>(
        &mut self,
        writer: &mut W,
        first: bool,
    ) -> std::io::Result<()> {
        if !first {
            writer.write_all(Self::comma())?;
        }
        Ok(())
    }

    fn begin_object_key<W: ?Sized + std::io::Write>(
        &mut self,
        writer: &mut W,
        first: bool,
    ) -> std::io::Result<()> {
        if !first {
            writer.write_all(Self::comma())?;
        }
        Ok(())
    }

    fn begin_object_value<W: ?Sized + std::io::Write>(
        &mut self,
        writer: &mut W,
    ) -> std::io::Result<()> {
        writer.write_all(Self::colon())
    }
}

pub(crate) fn py_json_dumps<T: ?Sized + Serialize>(value: &T) -> Result<String, serde_json::Error> {
    let mut string_buffer = vec![];
    let mut ser = serde_json::Serializer::with_formatter(&mut string_buffer, PyJsonFormatter);
    value.serialize(&mut ser)?;
    Ok(String::from_utf8(string_buffer).expect("serialized JSON should be valid UTF-8"))
}

impl ProofFacts {
    /// Returns a ProofFacts instance for testing with dummy program hash.
    /// For tests requiring validation, use a custom program hash.
    pub fn snos_proof_facts_for_testing() -> Self {
        Self::custom_proof_facts_for_testing(VIRTUAL_OS_PROGRAM_HASH, *TEST_OS_CONFIG_HASH)
    }

    /// Returns a ProofFacts instance for testing with custom fields.
    pub fn custom_proof_facts_for_testing(program_hash: Felt, config_hash: Felt) -> Self {
        let block_hash_history_start = CURRENT_BLOCK_NUMBER - BLOCK_HASH_HISTORY_RANGE;
        let block_number_u64 = block_hash_history_start + 2;
        let block_number = felt!(block_number_u64);
        let block_hash = test_block_hash(block_number_u64).0;
        assert!(
            block_number < felt!(CURRENT_BLOCK_NUMBER)
                && block_number >= felt!(block_hash_history_start),
            "To have a matching block hash stored in tests, the block number must be one whose \
             block hash is populated in the block-hash contract. block_number: {block_number}, \
             block_hash_history_start: {block_hash_history_start}"
        );
        // These fields are not verified by the OS (they are application-related).
        let l2_to_l1_messages_segment_size = Felt::ZERO;
        proof_facts![
            PROOF_VERSION,
            VIRTUAL_SNOS,
            program_hash,
            VIRTUAL_OS_OUTPUT_VERSION,
            block_number,
            block_hash,
            config_hash,
            l2_to_l1_messages_segment_size
        ]
    }
}

impl Proof {
    pub fn proof_for_testing() -> Self {
        // Arbitrary values for testing.
        proof!(1, 2, 3, 4, 5, 6)
    }
}