starknet_api 0.18.0-rc.1

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
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
#[cfg(test)]
#[path = "core_test.rs"]
mod core_test;

use std::fmt::Debug;
use std::str::FromStr;
use std::sync::LazyLock;

use apollo_sizeof::SizeOf;
use num_traits::ToPrimitive;
use primitive_types::H160;
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use starknet_types_core::felt::{Felt, NonZeroFelt};
use starknet_types_core::hash::{Pedersen, StarkHash as CoreStarkHash};

use crate::crypto::utils::PublicKey;
use crate::hash::{HashOutput, PoseidonHash, StarkHash};
use crate::serde_utils::{BytesAsHex, PrefixedBytesAsHex};
use crate::transaction::fields::{Calldata, ContractAddressSalt};
use crate::{impl_from_through_intermediate, StarknetApiError, StarknetApiResult};

/// Felt.
pub fn ascii_as_felt(ascii_str: &str) -> Result<Felt, StarknetApiError> {
    Felt::from_hex(hex::encode(ascii_str).as_str()).map_err(|_| StarknetApiError::OutOfRange {
        string: format!("The str {ascii_str}, does not fit into a single felt"),
    })
}

pub fn felt_to_u128(felt: &Felt) -> Result<u128, StarknetApiError> {
    felt.to_u128().ok_or(StarknetApiError::OutOfRange {
        string: format!("Felt {} is too big to convert to 'u128'", *felt,),
    })
}

/// A chain id.
#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub enum ChainId {
    Mainnet,
    Sepolia,
    IntegrationSepolia,
    Other(String),
}

impl Serialize for ChainId {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

impl<'de> Deserialize<'de> for ChainId {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Ok(ChainId::from(s))
    }
}
impl From<String> for ChainId {
    fn from(s: String) -> Self {
        match s.as_ref() {
            "SN_MAIN" => ChainId::Mainnet,
            "SN_SEPOLIA" => ChainId::Sepolia,
            "SN_INTEGRATION_SEPOLIA" => ChainId::IntegrationSepolia,
            other => ChainId::Other(other.to_owned()),
        }
    }
}
impl std::fmt::Display for ChainId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ChainId::Mainnet => write!(f, "SN_MAIN"),
            ChainId::Sepolia => write!(f, "SN_SEPOLIA"),
            ChainId::IntegrationSepolia => write!(f, "SN_INTEGRATION_SEPOLIA"),
            ChainId::Other(ref s) => write!(f, "{s}"),
        }
    }
}

impl TryFrom<&ChainId> for Felt {
    type Error = StarknetApiError;

    fn try_from(chain_id: &ChainId) -> Result<Self, Self::Error> {
        Self::from_hex(chain_id.as_hex().as_str()).map_err(|_| Self::Error::OutOfRange {
            string: format!("Failed to convert chain id {chain_id} to felt."),
        })
    }
}

impl ChainId {
    pub fn as_hex(&self) -> String {
        format!("0x{}", hex::encode(self.to_string()))
    }
}

/// Hex of 'StarknetOsConfig3'.
pub const STARKNET_OS_CONFIG_HASH_VERSION: Felt =
    Felt::from_hex_unchecked("0x537461726b6e65744f73436f6e66696733");

const DEFAULT_PUBLIC_KEYS_HASH: Felt = Felt::ZERO;

fn compute_public_keys_hash(public_keys: Option<&Vec<Felt>>) -> Felt {
    match public_keys {
        Some(public_keys) if !public_keys.is_empty() => Pedersen::hash_array(public_keys),
        _ => DEFAULT_PUBLIC_KEYS_HASH,
    }
}

/// Chain information for OS execution.
/// Contains minimal chain configuration needed for OS config hash computation.
// TODO(Meshi): Remove Once the blockifier ChainInfo do not support deprecated fee token.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OsChainInfo {
    #[serde(deserialize_with = "deserialize_chain_id_from_hex")]
    pub chain_id: ChainId,
    pub strk_fee_token_address: ContractAddress,
}

impl Default for OsChainInfo {
    fn default() -> Self {
        OsChainInfo {
            chain_id: ChainId::Other("0x0".to_string()),
            strk_fee_token_address: ContractAddress::default(),
        }
    }
}

impl OsChainInfo {
    /// Computes the OS config hash for the given chain info.
    pub fn compute_os_config_hash(
        &self,
        public_keys: Option<&Vec<Felt>>,
    ) -> Result<Felt, StarknetApiError> {
        let mut data = vec![
            STARKNET_OS_CONFIG_HASH_VERSION,
            (&self.chain_id).try_into().map_err(|_| StarknetApiError::OutOfRange {
                string: format!("Invalid chain ID (cannot convert to Felt): {:?}", self.chain_id),
            })?,
            self.strk_fee_token_address.into(),
        ];
        let public_keys_hash = compute_public_keys_hash(public_keys);
        if public_keys_hash != DEFAULT_PUBLIC_KEYS_HASH {
            data.push(public_keys_hash);
        }
        Ok(Pedersen::hash_array(&data))
    }

    /// Computes the virtual OS config hash (without public keys).
    pub fn compute_virtual_os_config_hash(&self) -> Result<Felt, StarknetApiError> {
        self.compute_os_config_hash(None)
    }
}

/// Parses a hex string (e.g., "0x534e5f4d41494e") into a ChainId.
pub fn chain_id_from_hex_str(hex_str: &str) -> StarknetApiResult<ChainId> {
    let chain_id_str =
        std::str::from_utf8(&hex::decode(hex_str.trim_start_matches("0x")).map_err(|e| {
            StarknetApiError::InvalidChainIdHex(format!(
                "Failed to decode the hex string {hex_str}. Error: {e:?}"
            ))
        })?)
        .map_err(|e| {
            StarknetApiError::InvalidChainIdHex(format!(
                "Failed to convert to UTF-8 string. Error: {e}"
            ))
        })?
        .to_string();
    Ok(ChainId::from(chain_id_str))
}

pub fn deserialize_chain_id_from_hex<'de, D>(deserializer: D) -> Result<ChainId, D::Error>
where
    D: Deserializer<'de>,
{
    let hex_str = String::deserialize(deserializer)?;
    chain_id_from_hex_str(&hex_str).map_err(D::Error::custom)
}

/// The address of a contract, used for example in [StateDiff](`crate::state::StateDiff`),
/// [DeclareTransaction](`crate::transaction::DeclareTransaction`), and
/// [BlockHeader](`crate::block::BlockHeader`).
// The block hash table is stored in address 0x1,
// this is a special address that is not used for contracts.
pub const BLOCK_HASH_TABLE_ADDRESS: ContractAddress = ContractAddress(PatriciaKey(StarkHash::ONE));

#[derive(
    Debug,
    Default,
    Copy,
    Clone,
    derive_more::Display,
    Eq,
    PartialEq,
    Hash,
    Deserialize,
    Serialize,
    PartialOrd,
    Ord,
    derive_more::Deref,
    SizeOf,
)]
pub struct ContractAddress(pub PatriciaKey);

impl ContractAddress {
    /// Validates the contract address is in the valid range for external access.
    /// The lower bound is above the special saved addresses and the upper bound is congruent with
    /// the storage var address upper bound.
    pub fn validate(&self) -> Result<(), StarknetApiError> {
        let value = self.0.0;
        let l2_address_upper_bound = Felt::from(*L2_ADDRESS_UPPER_BOUND);
        if (value > BLOCK_HASH_TABLE_ADDRESS.0.0) && (value < l2_address_upper_bound) {
            return Ok(());
        }

        Err(StarknetApiError::OutOfRange { string: format!("[0x2, {l2_address_upper_bound})") })
    }
}

impl From<ContractAddress> for Felt {
    fn from(contract_address: ContractAddress) -> Felt {
        **contract_address
    }
}

impl From<u128> for ContractAddress {
    fn from(val: u128) -> Self {
        ContractAddress(PatriciaKey::from(val))
    }
}

impl_from_through_intermediate!(u128, ContractAddress, u8, u16, u32, u64);

impl FromStr for ContractAddress {
    type Err = StarknetApiError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let felt = Felt::from_str(s)
            .map_err(|e| StarknetApiError::OutOfRange { string: format!("{e}") })?;
        Ok(ContractAddress(PatriciaKey::try_from(felt)?))
    }
}

/// The maximal size of storage var.
pub const MAX_STORAGE_ITEM_SIZE: u16 = 256;
/// The prefix used in the calculation of a contract address.
pub const CONTRACT_ADDRESS_PREFIX: &str = "STARKNET_CONTRACT_ADDRESS";
/// The size of the contract address domain.
pub const CONTRACT_ADDRESS_DOMAIN_SIZE: Felt = Felt::from_hex_unchecked(PATRICIA_KEY_UPPER_BOUND);
/// The address upper bound; it is defined to be congruent with the storage var address upper bound.
pub static L2_ADDRESS_UPPER_BOUND: LazyLock<NonZeroFelt> = LazyLock::new(|| {
    NonZeroFelt::try_from(CONTRACT_ADDRESS_DOMAIN_SIZE - Felt::from(MAX_STORAGE_ITEM_SIZE)).unwrap()
});

impl TryFrom<StarkHash> for ContractAddress {
    type Error = StarknetApiError;
    fn try_from(hash: StarkHash) -> Result<Self, Self::Error> {
        Ok(Self(PatriciaKey::try_from(hash)?))
    }
}

// TODO(Noa): Add a hash_function as a parameter
pub fn calculate_contract_address(
    salt: ContractAddressSalt,
    class_hash: ClassHash,
    constructor_calldata: &Calldata,
    deployer_address: ContractAddress,
) -> Result<ContractAddress, StarknetApiError> {
    let constructor_calldata_hash = Pedersen::hash_array(&constructor_calldata.0);
    let contract_address_prefix = format!("0x{}", hex::encode(CONTRACT_ADDRESS_PREFIX));
    let address = Pedersen::hash_array(&[
        Felt::from_hex(contract_address_prefix.as_str()).map_err(|_| {
            StarknetApiError::OutOfRange { string: contract_address_prefix.clone() }
        })?,
        *deployer_address.0.key(),
        salt.0,
        class_hash.0,
        constructor_calldata_hash,
    ]);
    let (_, address) = address.div_rem(&L2_ADDRESS_UPPER_BOUND);

    ContractAddress::try_from(address)
}

/// The hash of a ContractClass.
#[derive(
    Debug,
    Default,
    Copy,
    Clone,
    Eq,
    PartialEq,
    Hash,
    Deserialize,
    Serialize,
    PartialOrd,
    Ord,
    derive_more::Display,
    derive_more::Deref,
    SizeOf,
)]
pub struct ClassHash(pub StarkHash);

impl From<ClassHash> for Felt {
    fn from(class_hash: ClassHash) -> Felt {
        class_hash.0
    }
}

/// The hash of a compiled ContractClass.
#[derive(
    Debug,
    Default,
    Copy,
    Clone,
    Eq,
    PartialEq,
    Hash,
    Deserialize,
    Serialize,
    PartialOrd,
    Ord,
    derive_more::Display,
    SizeOf,
)]
pub struct CompiledClassHash(pub StarkHash);

impl From<CompiledClassHash> for Felt {
    fn from(compiled_class_hash: CompiledClassHash) -> Felt {
        compiled_class_hash.0
    }
}
/// A general type for nonces.
#[derive(
    Debug,
    Default,
    derive_more::Display,
    Copy,
    Clone,
    Eq,
    PartialEq,
    Hash,
    Deserialize,
    Serialize,
    PartialOrd,
    Ord,
    derive_more::Deref,
    SizeOf,
)]
pub struct Nonce(pub Felt);

impl Nonce {
    pub fn try_increment(&self) -> Result<Self, StarknetApiError> {
        // Check if an overflow occurred during increment.
        let incremented = self.0 + Felt::ONE;
        if incremented == Felt::ZERO {
            return Err(StarknetApiError::OutOfRange { string: format!("{self:?}") });
        }
        Ok(Self(incremented))
    }

    pub fn try_decrement(&self) -> Result<Self, StarknetApiError> {
        // Check if an underflow occurred during decrement.
        if self.0 == Felt::ZERO {
            return Err(StarknetApiError::OutOfRange { string: format!("{self:?}") });
        }
        Ok(Self(self.0 - Felt::ONE))
    }
}

/// The selector of an [EntryPoint](`crate::state::EntryPoint`).
#[derive(
    Debug,
    Copy,
    Clone,
    Default,
    Eq,
    PartialEq,
    Hash,
    Deserialize,
    Serialize,
    PartialOrd,
    Ord,
    derive_more::Display,
)]
pub struct EntryPointSelector(pub StarkHash);

/// The root of the global state at a [Block](`crate::block::Block`)
/// and [StateUpdate](`crate::state::StateUpdate`).
#[derive(
    Debug,
    Copy,
    Clone,
    Default,
    Eq,
    PartialEq,
    Hash,
    Deserialize,
    Serialize,
    PartialOrd,
    Ord,
    derive_more::Display,
)]
pub struct GlobalRoot(pub StarkHash);

impl GlobalRoot {
    pub const ROOT_OF_EMPTY_STATE: GlobalRoot = GlobalRoot(HashOutput::ROOT_OF_EMPTY_TREE.0);
}

// Hex of 'STARKNET_STATE_V0'.
pub const GLOBAL_STATE_VERSION: Felt =
    Felt::from_hex_unchecked("0x535441524b4e45545f53544154455f5630");

/// The commitment on the transactions in a [Block](`crate::block::Block`).
#[derive(
    Debug,
    Copy,
    Clone,
    Default,
    Eq,
    PartialEq,
    Hash,
    Deserialize,
    Serialize,
    PartialOrd,
    Ord,
    derive_more::Display,
)]
pub struct TransactionCommitment(pub StarkHash);

/// The commitment on the events in a [Block](`crate::block::Block`).
#[derive(
    Debug,
    Copy,
    Clone,
    Default,
    Eq,
    PartialEq,
    Hash,
    Deserialize,
    Serialize,
    PartialOrd,
    Ord,
    derive_more::Display,
)]
pub struct EventCommitment(pub StarkHash);

/// The commitment on the receipts in a [Block](`crate::block::Block`).
#[derive(
    Debug,
    Copy,
    Clone,
    Default,
    Eq,
    PartialEq,
    Hash,
    Deserialize,
    Serialize,
    PartialOrd,
    Ord,
    derive_more::Display,
)]
pub struct ReceiptCommitment(pub StarkHash);

#[derive(
    Debug,
    Copy,
    Clone,
    Default,
    Eq,
    PartialEq,
    Hash,
    Deserialize,
    Serialize,
    PartialOrd,
    Ord,
    derive_more::Display,
)]
pub struct StateDiffCommitment(pub PoseidonHash);

/// A key for nodes of a Patricia tree.
// Invariant: key is in range.
#[derive(
    Copy,
    Clone,
    derive_more::Display,
    Eq,
    PartialEq,
    Default,
    Hash,
    Deserialize,
    Serialize,
    PartialOrd,
    Ord,
    derive_more:: Deref,
    SizeOf,
)]
#[display("{}", _0.to_fixed_hex_string())]
pub struct PatriciaKey(StarkHash);

// 2**251
pub const PATRICIA_KEY_UPPER_BOUND: &str =
    "0x800000000000000000000000000000000000000000000000000000000000000";

impl PatriciaKey {
    pub const ZERO: Self = Self(StarkHash::ZERO);
    pub const ONE: Self = Self(StarkHash::ONE);
    pub const TWO: Self = Self(StarkHash::TWO);

    pub fn key(&self) -> &StarkHash {
        &self.0
    }

    pub const fn from_hex_unchecked(val: &str) -> Self {
        Self(StarkHash::from_hex_unchecked(val))
    }
}

impl From<u128> for PatriciaKey {
    fn from(val: u128) -> Self {
        PatriciaKey::try_from(Felt::from(val)).expect("Failed to convert u128 to PatriciaKey.")
    }
}

impl_from_through_intermediate!(u128, PatriciaKey, u8, u16, u32, u64);

impl TryFrom<StarkHash> for PatriciaKey {
    type Error = StarknetApiError;

    fn try_from(value: StarkHash) -> Result<Self, Self::Error> {
        if value < CONTRACT_ADDRESS_DOMAIN_SIZE {
            return Ok(PatriciaKey(value));
        }
        Err(StarknetApiError::OutOfRange { string: format!("[0x0, {PATRICIA_KEY_UPPER_BOUND})") })
    }
}

impl Debug for PatriciaKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("PatriciaKey").field(&self.0).finish()
    }
}

/// A utility macro to create a [`PatriciaKey`] from a hex string / unsigned integer representation.
#[cfg(any(feature = "testing", test))]
#[macro_export]
macro_rules! patricia_key {
    ($s:expr) => {
        $crate::core::PatriciaKey::try_from($crate::felt!($s)).unwrap()
    };
}

/// A utility macro to create a [`ClassHash`] from a hex string / unsigned integer representation.
#[cfg(any(feature = "testing", test))]
#[macro_export]
macro_rules! class_hash {
    ($s:expr) => {
        $crate::core::ClassHash($crate::felt!($s))
    };
}

/// A utility macro to create a [`ContractAddress`] from a hex string / unsigned integer
/// representation.
#[cfg(any(feature = "testing", test))]
#[macro_export]
macro_rules! contract_address {
    ($s:expr) => {
        $crate::core::ContractAddress($crate::patricia_key!($s))
    };
}

/// An Ethereum address.
#[derive(
    Debug, Copy, Clone, Default, Eq, PartialEq, Hash, Deserialize, Serialize, PartialOrd, Ord,
)]
#[serde(try_from = "PrefixedBytesAsHex<20_usize>", into = "PrefixedBytesAsHex<20_usize>")]
pub struct EthAddress(pub H160);

#[derive(
    Debug, Copy, Clone, Default, Eq, PartialEq, Hash, Deserialize, Serialize, PartialOrd, Ord,
)]
pub struct L1Address(pub Felt);

impl From<ContractAddress> for L1Address {
    fn from(address: ContractAddress) -> Self {
        L1Address(address.0.0)
    }
}

impl TryFrom<L1Address> for ContractAddress {
    type Error = StarknetApiError;

    fn try_from(address: L1Address) -> Result<Self, Self::Error> {
        Ok(ContractAddress(PatriciaKey::try_from(address.0)?))
    }
}

impl From<EthAddress> for L1Address {
    fn from(address: EthAddress) -> Self {
        L1Address(address.into())
    }
}

impl TryFrom<L1Address> for EthAddress {
    type Error = StarknetApiError;

    fn try_from(address: L1Address) -> Result<Self, Self::Error> {
        EthAddress::try_from(address.0)
    }
}

impl From<Felt> for L1Address {
    fn from(felt: Felt) -> Self {
        L1Address(felt)
    }
}

impl From<L1Address> for Felt {
    fn from(address: L1Address) -> Self {
        address.0
    }
}

impl TryFrom<Felt> for EthAddress {
    type Error = StarknetApiError;
    fn try_from(felt: Felt) -> Result<Self, Self::Error> {
        const COMPLIMENT_OF_H160: usize = std::mem::size_of::<Felt>() - H160::len_bytes();

        let bytes = felt.to_bytes_be();
        let (rest, h160_bytes) = bytes.split_at(COMPLIMENT_OF_H160);
        if rest != [0u8; COMPLIMENT_OF_H160] {
            return Err(StarknetApiError::OutOfRange { string: felt.to_string() });
        }

        Ok(EthAddress(H160::from_slice(h160_bytes)))
    }
}

impl From<EthAddress> for Felt {
    fn from(value: EthAddress) -> Self {
        Felt::from_bytes_be_slice(value.0.as_bytes())
    }
}

impl TryFrom<PrefixedBytesAsHex<20_usize>> for EthAddress {
    type Error = StarknetApiError;
    fn try_from(val: PrefixedBytesAsHex<20_usize>) -> Result<Self, Self::Error> {
        Ok(EthAddress(H160::from_slice(&val.0)))
    }
}

impl From<EthAddress> for PrefixedBytesAsHex<20_usize> {
    fn from(felt: EthAddress) -> Self {
        BytesAsHex(felt.0.to_fixed_bytes())
    }
}

/// A public key of a sequencer.
#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct SequencerPublicKey(pub PublicKey);

#[derive(
    Debug, Default, Clone, Copy, Eq, PartialEq, Hash, Deserialize, Serialize, PartialOrd, Ord,
)]
pub struct SequencerContractAddress(pub ContractAddress);