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

use std::str::FromStr;

use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass;
use serde::{Deserialize, Serialize};
use starknet_types_core::felt::Felt;
use strum::EnumIter;
use thiserror::Error;

use crate::contract_class::compiled_class_hash::{HashVersion, HashableCompiledClass};
use crate::contract_class::{ClassInfo, ContractClass};
use crate::core::{ChainId, ClassHash, CompiledClassHash, ContractAddress, Nonce};
use crate::data_availability::DataAvailabilityMode;
use crate::transaction::fields::{
    AccountDeploymentData,
    Calldata,
    ContractAddressSalt,
    Fee,
    PaymasterData,
    ProofFacts,
    Tip,
    TransactionSignature,
    ValidResourceBounds,
};
use crate::transaction::{
    CalculateContractAddress,
    TransactionHash,
    TransactionHasher,
    TransactionVersion,
};
use crate::{CasmHashMismatch, StarknetApiError};

macro_rules! implement_inner_tx_getter_calls {
    ($(($field:ident, $field_type:ty)),*) => {
        $(pub fn $field(&self) -> $field_type {
            self.tx.$field().clone()
        })*
    };
}

macro_rules! implement_getter_calls {
    ($(($field:ident, $field_type:ty)),*) => {
        $(pub fn $field(&self) -> $field_type {
            self.$field
        })*
};
}

macro_rules! implement_account_tx_inner_getters {
    ($(($field:ident, $field_type:ty)),*) => {
        $(pub fn $field(&self) -> $field_type {
            match self {
                AccountTransaction::Declare(tx) => tx.tx.$field().clone(),
                AccountTransaction::DeployAccount(tx) => tx.tx.$field().clone(),
                AccountTransaction::Invoke(tx) => tx.tx.$field().clone(),
            }
        })*
    };
}

#[derive(Clone, Copy, Debug, Deserialize, EnumIter, Eq, Hash, PartialEq, Serialize)]
pub enum TransactionType {
    Declare,
    DeployAccount,
    InvokeFunction,
    L1Handler,
}

impl FromStr for TransactionType {
    type Err = StarknetApiError;

    fn from_str(tx_type: &str) -> Result<Self, Self::Err> {
        match tx_type {
            "Declare" | "DECLARE" => Ok(Self::Declare),
            "DeployAccount" | "DEPLOY_ACCOUNT" => Ok(Self::DeployAccount),
            "InvokeFunction" | "INVOKE_FUNCTION" => Ok(Self::InvokeFunction),
            "L1Handler" | "L1_HANDLER" => Ok(Self::L1Handler),
            unknown_tx_type => Err(Self::Err::UnknownTransactionType(unknown_tx_type.to_string())),
        }
    }
}

impl std::fmt::Display for TransactionType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let type_str = match self {
            Self::Declare => "DECLARE",
            Self::DeployAccount => "DEPLOY_ACCOUNT",
            Self::InvokeFunction => "INVOKE_FUNCTION",
            Self::L1Handler => "L1_HANDLER",
        };
        write!(f, "{type_str}")
    }
}

impl TransactionType {
    pub fn tx_type_as_felt(&self) -> Felt {
        let tx_type_name = self.to_string();
        Felt::from_bytes_be_slice(tx_type_name.as_bytes())
    }
}

/// Represents a paid Starknet transaction.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[allow(clippy::large_enum_variant)]
pub enum AccountTransaction {
    Declare(DeclareTransaction),
    DeployAccount(DeployAccountTransaction),
    Invoke(InvokeTransaction),
}

impl AccountTransaction {
    implement_account_tx_inner_getters!(
        (resource_bounds, ValidResourceBounds),
        (tip, Tip),
        (signature, TransactionSignature),
        (nonce, Nonce),
        (nonce_data_availability_mode, DataAvailabilityMode),
        (fee_data_availability_mode, DataAvailabilityMode),
        (paymaster_data, PaymasterData),
        (version, TransactionVersion)
    );

    pub fn contract_address(&self) -> ContractAddress {
        match self {
            AccountTransaction::Declare(tx_data) => tx_data.tx.sender_address(),
            AccountTransaction::DeployAccount(tx_data) => tx_data.contract_address,
            AccountTransaction::Invoke(tx_data) => tx_data.tx.sender_address(),
        }
    }

    pub fn sender_address(&self) -> ContractAddress {
        self.contract_address()
    }

    pub fn tx_hash(&self) -> TransactionHash {
        match self {
            AccountTransaction::Declare(tx_data) => tx_data.tx_hash,
            AccountTransaction::DeployAccount(tx_data) => tx_data.tx_hash,
            AccountTransaction::Invoke(tx_data) => tx_data.tx_hash,
        }
    }

    pub fn tx_type(&self) -> TransactionType {
        match self {
            Self::Declare(_) => TransactionType::Declare,
            Self::DeployAccount(_) => TransactionType::DeployAccount,
            Self::Invoke(_) => TransactionType::InvokeFunction,
        }
    }
}

// TODO(Mohammad): Add constructor for all the transaction's structs.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct DeclareTransaction {
    pub tx: crate::transaction::DeclareTransaction,
    pub tx_hash: TransactionHash,
    pub class_info: ClassInfo,
}

impl DeclareTransaction {
    implement_inner_tx_getter_calls!(
        (class_hash, ClassHash),
        (nonce, Nonce),
        (sender_address, ContractAddress),
        (signature, TransactionSignature),
        (version, TransactionVersion),
        // compiled_class_hash is only supported in V2 and V3, otherwise the getter panics.
        (compiled_class_hash, CompiledClassHash),
        // The following fields are only supported in V3, otherwise the getter panics.
        (tip, Tip),
        (nonce_data_availability_mode, DataAvailabilityMode),
        (fee_data_availability_mode, DataAvailabilityMode),
        (paymaster_data, PaymasterData),
        (account_deployment_data, AccountDeploymentData),
        (resource_bounds, ValidResourceBounds)
    );

    pub fn create(
        declare_tx: crate::transaction::DeclareTransaction,
        class_info: ClassInfo,
        chain_id: &ChainId,
    ) -> Result<Self, StarknetApiError> {
        validate_class_version_matches_tx_version(
            declare_tx.version(),
            &class_info.contract_class,
        )?;
        let tx_hash = declare_tx.calculate_transaction_hash(chain_id, &declare_tx.version())?;
        Ok(Self { tx: declare_tx, tx_hash, class_info })
    }

    pub fn contract_class(&self) -> ContractClass {
        self.class_info.contract_class.clone()
    }

    /// Casm contract class exists only for contract class V1, for version V0 the getter panics.
    pub fn casm_contract_class(&self) -> &CasmContractClass {
        let ContractClass::V1(versioned_casm) = &self.class_info.contract_class else {
            panic!("Contract class version must be V1.")
        };
        &versioned_casm.0
    }

    /// Verifies that the compiled class hash field in the declare tx,
    /// is compiled_class_hash_v2 of the compiled contract.
    pub fn check_compile_class_hash_v2_declaration(&self) -> Result<(), StarknetApiError> {
        let compiled_class = &self.class_info.contract_class;
        let compiled_class_hash_v2 = match &compiled_class {
            ContractClass::V0(_) => return Ok(()),
            ContractClass::V1((casm, _)) => casm.hash(&HashVersion::V2),
        };
        let compiled_class_hash = self.compiled_class_hash();
        if compiled_class_hash_v2 != compiled_class_hash {
            let err_var = CasmHashMismatch {
                hash: self.class_hash(),
                actual: compiled_class_hash,
                expected: compiled_class_hash_v2,
            };
            return Err(StarknetApiError::DeclareTransactionCasmHashMissMatch(Box::new(err_var)));
        }
        Ok(())
    }

    // Returns whether the declare transaction is for bootstrapping.
    // In this case, no account-related actions should be made besides the declaration.
    pub fn is_bootstrap_declare(&self, charge_fee: bool) -> bool {
        if let crate::transaction::DeclareTransaction::V3(tx) = &self.tx {
            return tx.sender_address == Self::bootstrap_address()
                && tx.nonce == Nonce(Felt::ZERO)
                && !charge_fee;
        }
        false
    }

    /// Returns the address of the bootstrap contract.
    /// Declare transactions can be sent from this contract with no validation, fee or nonce
    /// change. This is used for starting a new Starknet system.
    pub fn bootstrap_address() -> ContractAddress {
        // A felt representation of the string 'BOOTSTRAP'.
        ContractAddress::from(0x424f4f545354524150_u128)
    }
}

#[derive(Clone, Debug, Error, Eq, PartialEq)]
pub enum ValidateCompiledClassHashError {
    #[error(
        "Computed compiled class hash: {:#x} does not match the given value: {:#x}.",
        computed_class_hash.0, supplied_class_hash.0
    )]
    CompiledClassHashMismatch {
        computed_class_hash: CompiledClassHash,
        supplied_class_hash: CompiledClassHash,
    },
}

/// Validates that the Declare transaction version is compatible with the Cairo contract version.
/// Versions 0 and 1 declare Cairo 0 contracts, while versions >=2 declare Cairo 1 contracts.
fn validate_class_version_matches_tx_version(
    declare_version: TransactionVersion,
    class: &ContractClass,
) -> Result<(), StarknetApiError> {
    let expected_cairo_version = if declare_version <= TransactionVersion::ONE { 0 } else { 1 };

    match class {
        ContractClass::V0(_) if expected_cairo_version == 0 => Ok(()),
        ContractClass::V1(_) if expected_cairo_version == 1 => Ok(()),
        _ => Err(StarknetApiError::ContractClassVersionMismatch {
            declare_version,
            cairo_version: expected_cairo_version,
        }),
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct DeployAccountTransaction {
    pub tx: crate::transaction::DeployAccountTransaction,
    pub tx_hash: TransactionHash,
    pub contract_address: ContractAddress,
}

impl DeployAccountTransaction {
    implement_inner_tx_getter_calls!(
        (class_hash, ClassHash),
        (constructor_calldata, Calldata),
        (contract_address_salt, ContractAddressSalt),
        (nonce, Nonce),
        (signature, TransactionSignature),
        (version, TransactionVersion),
        (resource_bounds, ValidResourceBounds),
        (tip, Tip),
        (nonce_data_availability_mode, DataAvailabilityMode),
        (fee_data_availability_mode, DataAvailabilityMode),
        (paymaster_data, PaymasterData)
    );
    implement_getter_calls!((tx_hash, TransactionHash), (contract_address, ContractAddress));

    pub fn tx(&self) -> &crate::transaction::DeployAccountTransaction {
        &self.tx
    }

    pub fn create(
        deploy_account_tx: crate::transaction::DeployAccountTransaction,
        chain_id: &ChainId,
    ) -> Result<Self, StarknetApiError> {
        let contract_address = deploy_account_tx.calculate_contract_address()?;
        let tx_hash =
            deploy_account_tx.calculate_transaction_hash(chain_id, &deploy_account_tx.version())?;
        Ok(Self { tx: deploy_account_tx, tx_hash, contract_address })
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct InvokeTransaction {
    pub tx: crate::transaction::InvokeTransaction,
    pub tx_hash: TransactionHash,
}

impl InvokeTransaction {
    implement_inner_tx_getter_calls!(
        (calldata, Calldata),
        (nonce, Nonce),
        (signature, TransactionSignature),
        (sender_address, ContractAddress),
        (version, TransactionVersion),
        (resource_bounds, ValidResourceBounds),
        (tip, Tip),
        (nonce_data_availability_mode, DataAvailabilityMode),
        (fee_data_availability_mode, DataAvailabilityMode),
        (paymaster_data, PaymasterData),
        (account_deployment_data, AccountDeploymentData),
        (proof_facts, ProofFacts)
    );
    implement_getter_calls!((tx_hash, TransactionHash));

    pub fn tx(&self) -> &crate::transaction::InvokeTransaction {
        &self.tx
    }

    pub fn create(
        invoke_tx: crate::transaction::InvokeTransaction,
        chain_id: &ChainId,
    ) -> Result<Self, StarknetApiError> {
        let tx_hash = invoke_tx.calculate_transaction_hash(chain_id, &invoke_tx.version())?;
        Ok(Self { tx: invoke_tx, tx_hash })
    }

    /// Returns the length of proof facts for client-side proving.
    pub fn proof_facts_length(&self) -> usize {
        match &self.tx {
            crate::transaction::InvokeTransaction::V3(tx) => tx.proof_facts.0.len(),
            // Client-side proving is only supported starting from V3.
            crate::transaction::InvokeTransaction::V0(_)
            | crate::transaction::InvokeTransaction::V1(_) => 0,
        }
    }
}

#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize, Hash)]
pub struct L1HandlerTransaction {
    pub tx: crate::transaction::L1HandlerTransaction,
    pub tx_hash: TransactionHash,
    pub paid_fee_on_l1: Fee,
}

impl L1HandlerTransaction {
    pub const L1_HANDLER_TYPE_NAME: &str = "L1_HANDLER";

    pub fn create(
        raw_tx: crate::transaction::L1HandlerTransaction,
        chain_id: &ChainId,
        paid_fee_on_l1: Fee,
    ) -> Result<L1HandlerTransaction, StarknetApiError> {
        let tx_hash = raw_tx.calculate_transaction_hash(chain_id, &raw_tx.version)?;
        Ok(Self { tx: raw_tx, tx_hash, paid_fee_on_l1 })
    }

    pub fn payload_size(&self) -> usize {
        // The calldata includes the "from" field, which is not a part of the payload.
        self.tx.calldata.0.len() - 1
    }
}

#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum Transaction {
    Account(AccountTransaction),
    L1Handler(L1HandlerTransaction),
}

impl Transaction {
    pub fn tx_hash(&self) -> TransactionHash {
        match self {
            Self::Account(tx) => tx.tx_hash(),
            Self::L1Handler(tx) => tx.tx_hash,
        }
    }

    pub fn tx_type(&self) -> TransactionType {
        match self {
            Self::Account(account_tx) => account_tx.tx_type(),
            Self::L1Handler(_) => TransactionType::L1Handler,
        }
    }

    pub fn version(&self) -> TransactionVersion {
        match self {
            Self::Account(account_tx) => account_tx.version(),
            Self::L1Handler(l1_handler_tx) => l1_handler_tx.tx.version,
        }
    }

    pub fn nonce(&self) -> Nonce {
        match self {
            Self::Account(account_tx) => account_tx.nonce(),
            Self::L1Handler(l1_handler_tx) => l1_handler_tx.tx.nonce,
        }
    }
}