From 965b04aa5e1851c82a6cdc05b296a6d26a7967d5 Mon Sep 17 00:00:00 2001 From: Ammar Arif Date: Mon, 16 Sep 2024 11:43:14 -0400 Subject: [PATCH] rename all to felts --- bin/saya/src/args/mod.rs | 8 +- bin/saya/src/args/proof.rs | 6 +- bin/saya/src/args/starknet_account.rs | 6 +- bin/scheduler/src/main.rs | 4 +- crates/katana/controller/src/lib.rs | 17 +- crates/katana/core/src/backend/mod.rs | 4 +- crates/katana/core/src/backend/storage.rs | 6 +- .../core/src/service/messaging/ethereum.rs | 18 +- crates/katana/core/src/service/mod.rs | 6 +- crates/katana/executor/benches/utils.rs | 8 +- .../katana/executor/src/abstraction/error.rs | 6 +- .../executor/src/abstraction/executor.rs | 4 +- crates/katana/executor/src/abstraction/mod.rs | 6 +- .../src/implementation/blockifier/mod.rs | 4 +- .../src/implementation/blockifier/state.rs | 18 +- .../src/implementation/blockifier/utils.rs | 16 +- .../executor/src/implementation/noop.rs | 4 +- crates/katana/executor/tests/executor.rs | 12 +- crates/katana/executor/tests/fixtures/mod.rs | 8 +- .../executor/tests/fixtures/transaction.rs | 12 +- crates/katana/pool/src/pool.rs | 8 +- crates/katana/pool/src/validation/mod.rs | 4 +- crates/katana/pool/src/validation/stateful.rs | 4 +- crates/katana/primitives/src/block.rs | 20 +-- crates/katana/primitives/src/chain.rs | 36 ++-- crates/katana/primitives/src/class.rs | 6 +- crates/katana/primitives/src/contract.rs | 18 +- .../katana/primitives/src/conversion/rpc.rs | 6 +- crates/katana/primitives/src/event.rs | 6 +- .../primitives/src/genesis/allocation.rs | 42 ++--- .../katana/primitives/src/genesis/constant.rs | 4 +- crates/katana/primitives/src/genesis/json.rs | 31 ++-- crates/katana/primitives/src/genesis/mod.rs | 38 ++-- crates/katana/primitives/src/lib.rs | 6 +- crates/katana/primitives/src/message.rs | 6 +- crates/katana/primitives/src/receipt.rs | 10 +- crates/katana/primitives/src/trace.rs | 12 +- crates/katana/primitives/src/transaction.rs | 54 +++--- crates/katana/primitives/src/utils/mod.rs | 10 +- .../primitives/src/utils/transaction.rs | 170 +++++++++--------- crates/katana/rpc/rpc-api/src/dev.rs | 10 +- crates/katana/rpc/rpc-api/src/starknet.rs | 19 +- .../rpc/rpc-types-builder/src/state_update.rs | 4 +- crates/katana/rpc/rpc-types/src/account.rs | 6 +- crates/katana/rpc/rpc-types/src/lib.rs | 10 +- crates/katana/rpc/rpc-types/src/message.rs | 8 +- .../katana/rpc/rpc-types/src/transaction.rs | 10 +- crates/katana/rpc/rpc/src/dev.rs | 8 +- crates/katana/rpc/rpc/src/starknet/mod.rs | 4 +- crates/katana/rpc/rpc/src/starknet/read.rs | 18 +- crates/katana/rpc/rpc/src/utils/events.rs | 4 +- crates/katana/storage/codecs/src/lib.rs | 14 +- crates/katana/storage/db/src/codecs/mod.rs | 6 +- .../katana/storage/db/src/codecs/postcard.rs | 4 +- crates/katana/storage/db/src/mdbx/mod.rs | 26 ++- crates/katana/storage/provider/src/lib.rs | 4 +- .../storage/provider/src/providers/db/mod.rs | 4 +- .../provider/src/providers/fork/backend.rs | 8 +- .../provider/src/providers/fork/mod.rs | 2 +- .../provider/src/providers/in_memory/mod.rs | 2 +- .../storage/provider/src/traits/state.rs | 6 +- crates/katana/storage/provider/tests/block.rs | 4 +- crates/katana/storage/provider/tests/utils.rs | 8 +- crates/saya/core/src/lib.rs | 23 ++- crates/saya/core/src/prover/extract.rs | 14 +- crates/saya/core/src/prover/scheduler.rs | 10 +- 66 files changed, 439 insertions(+), 461 deletions(-) diff --git a/bin/saya/src/args/mod.rs b/bin/saya/src/args/mod.rs index 3c22e0e881..594004354b 100644 --- a/bin/saya/src/args/mod.rs +++ b/bin/saya/src/args/mod.rs @@ -182,7 +182,7 @@ impl TryFrom for SayaConfig { #[cfg(test)] mod tests { - use katana_primitives::felt::FieldElement; + use katana_primitives::Felt; use super::*; use crate::args::data_availability::CelestiaOptions; @@ -249,12 +249,12 @@ mod tests { let expected = StarknetAccountData { starknet_url: Url::parse("http://localhost:5030").unwrap(), - chain_id: FieldElement::from_hex("0x534e5f5345504f4c4941").unwrap(), - signer_address: FieldElement::from_hex( + chain_id: Felt::from_hex("0x534e5f5345504f4c4941").unwrap(), + signer_address: Felt::from_hex( "0x3aa0a12c62a46a200b1a1211e8cd09b520164104e76d79648ca459cf05db94", ) .unwrap(), - signer_key: FieldElement::from_hex( + signer_key: Felt::from_hex( "0x6b41bfa82e791a8b4e6b3ee058cb25b89714e4a23bd9a1ad6e6ba0bbc0b145b", ) .unwrap(), diff --git a/bin/saya/src/args/proof.rs b/bin/saya/src/args/proof.rs index 0549bda680..02362188a6 100644 --- a/bin/saya/src/args/proof.rs +++ b/bin/saya/src/args/proof.rs @@ -1,17 +1,17 @@ use clap::Args; use dojo_utils::env::DOJO_WORLD_ADDRESS_ENV_VAR; -use katana_primitives::felt::FieldElement; +use katana_primitives::Felt; use url::Url; #[derive(Debug, Args, Clone)] pub struct ProofOptions { #[arg(help = "The address of the World contract.")] #[arg(long = "world", env = DOJO_WORLD_ADDRESS_ENV_VAR)] - pub world_address: FieldElement, + pub world_address: Felt, #[arg(help = "The address of the Fact Registry contract.")] #[arg(long = "registry")] - pub fact_registry_address: FieldElement, + pub fact_registry_address: Felt, #[arg(long)] #[arg(value_name = "PROVER URL")] diff --git a/bin/saya/src/args/starknet_account.rs b/bin/saya/src/args/starknet_account.rs index cf8eb1b5aa..c764ef0430 100644 --- a/bin/saya/src/args/starknet_account.rs +++ b/bin/saya/src/args/starknet_account.rs @@ -5,7 +5,7 @@ use dojo_utils::env::{ DOJO_ACCOUNT_ADDRESS_ENV_VAR, DOJO_KEYSTORE_PASSWORD_ENV_VAR, DOJO_KEYSTORE_PATH_ENV_VAR, DOJO_PRIVATE_KEY_ENV_VAR, STARKNET_RPC_URL_ENV_VAR, }; -use katana_primitives::felt::FieldElement; +use katana_primitives::Felt; use url::Url; #[derive(Debug, Args, Clone)] @@ -21,11 +21,11 @@ pub struct StarknetAccountOptions { #[arg(long, env = DOJO_ACCOUNT_ADDRESS_ENV_VAR)] #[arg(help = "The address of the starknet account.")] - pub signer_address: FieldElement, + pub signer_address: Felt, #[arg(long, env = DOJO_PRIVATE_KEY_ENV_VAR)] #[arg(help = "The private key of the starknet account.")] - pub signer_key: Option, + pub signer_key: Option, #[arg(long = "keystore", env = DOJO_KEYSTORE_PATH_ENV_VAR)] #[arg(value_name = "PATH")] diff --git a/bin/scheduler/src/main.rs b/bin/scheduler/src/main.rs index b94ace2f71..0bfea5be0b 100644 --- a/bin/scheduler/src/main.rs +++ b/bin/scheduler/src/main.rs @@ -2,7 +2,7 @@ use std::fs; use std::sync::Arc; use clap::Parser; -use katana_primitives::felt::FieldElement; +use katana_primitives::Felt; use saya_core::prover::{HttpProverParams, ProgramInput, ProverIdentifier, Scheduler}; use saya_core::ProverAccessKey; use serde::{Deserialize, Serialize}; @@ -14,7 +14,7 @@ use tokio::io::AsyncWriteExt; #[clap(author, version, about, long_about = None)] pub struct CliInput { #[arg(short, long)] - pub world: FieldElement, + pub world: Felt, #[arg(short, long)] pub key: String, pub files: Vec, diff --git a/crates/katana/controller/src/lib.rs b/crates/katana/controller/src/lib.rs index 85722de8b7..9296e63cc6 100644 --- a/crates/katana/controller/src/lib.rs +++ b/crates/katana/controller/src/lib.rs @@ -8,7 +8,7 @@ use katana_primitives::contract::{ContractAddress, StorageKey, StorageValue}; use katana_primitives::genesis::allocation::{GenesisAllocation, GenesisContractAlloc}; use katana_primitives::genesis::constant::CONTROLLER_ACCOUNT_CONTRACT_CLASS_HASH; use katana_primitives::genesis::Genesis; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use slot::account_sdk::signers::webauthn::{CredentialID, WebauthnBackend, WebauthnSigner}; use slot::account_sdk::signers::{HashSigner, Signer, SignerTrait}; use slot::account_sdk::OriginProvider; @@ -47,9 +47,8 @@ fn add_controller_account_inner(genesis: &mut Genesis, user: slot::account::Acco storage: Some(get_contract_storage(credential_id, public_key)?), }; - let address = ContractAddress::from(FieldElement::from_bytes_be( - &user.contract_address.to_bytes_be(), - )); + let address = + ContractAddress::from(Felt::from_bytes_be(&user.contract_address.to_bytes_be())); (address, GenesisAllocation::Contract(account)) }; @@ -98,7 +97,7 @@ pub mod json { storage: Some(get_contract_storage(credential_id, public_key)?), }; - let address = ContractAddress::from(FieldElement::from_bytes_be( + let address = ContractAddress::from(Felt::from_bytes_be( &user.account.contract_address.to_bytes_be(), )); @@ -187,7 +186,7 @@ fn get_contract_storage( let storage = get_storage_var_address(MULTIPLE_OWNERS_COMPONENT_SUB_STORAGE, &[guid])?; // 1 for boolean True in Cairo. Refer to the provided link above. - let storage_mapping = HashMap::from([(storage, FieldElement::ONE)]); + let storage_mapping = HashMap::from([(storage, Felt::ONE)]); Ok(storage_mapping) } @@ -206,12 +205,12 @@ mod tests { // Controller address: 0x00397333e993ae162b476690e1401548ae97a8819955506b8bc918e067bdafc3 // - const CONTROLLER_ADDRESS: FieldElement = + const CONTROLLER_ADDRESS: Felt = felt!("0x00397333e993ae162b476690e1401548ae97a8819955506b8bc918e067bdafc3"); - const STORAGE_KEY: FieldElement = + const STORAGE_KEY: Felt = felt!("0x023d8ecd0d641047a8d21e3cd8016377ed5c9cd9009539cd92b73adb8c023f10"); - const STORAGE_VALUE: FieldElement = felt!("0x1"); + const STORAGE_VALUE: Felt = felt!("0x1"); const WEBAUTHN_CREDENTIAL_ID: &str = "ja0NkHny-dlfPnClYECdmce0xTCuGT0xFjeuStaVqCI"; const WEBAUTHN_PUBLIC_KEY: &str = "pQECAyYgASFYIBLHWNmpxCtO47cfOXw9nFCGftMq57xhvQC98aY_zQchIlggIgGHmWwQe1_FGi9GYqcYYpoPC9mkkf0f1rVD5UoGPEA"; diff --git a/crates/katana/core/src/backend/mod.rs b/crates/katana/core/src/backend/mod.rs index 477d504a2a..e8352d42b5 100644 --- a/crates/katana/core/src/backend/mod.rs +++ b/crates/katana/core/src/backend/mod.rs @@ -8,7 +8,7 @@ use katana_primitives::chain::ChainId; use katana_primitives::env::BlockEnv; use katana_primitives::transaction::TxHash; use katana_primitives::version::CURRENT_STARKNET_VERSION; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use katana_provider::providers::fork::ForkedProvider; use katana_provider::providers::in_memory::InMemoryProvider; use katana_provider::traits::block::{BlockHashProvider, BlockWriter}; @@ -157,7 +157,7 @@ impl Backend { }; let tx_hashes = txs.iter().map(|tx| tx.hash).collect::>(); - let header = Header::new(partial_header, FieldElement::ZERO); + let header = Header::new(partial_header, Felt::ZERO); let block = Block { header, body: txs }.seal(); let block = SealedBlockWithStatus { block, status: FinalityStatus::AcceptedOnL2 }; diff --git a/crates/katana/core/src/backend/storage.rs b/crates/katana/core/src/backend/storage.rs index 031e5c865f..9264cf4043 100644 --- a/crates/katana/core/src/backend/storage.rs +++ b/crates/katana/core/src/backend/storage.rs @@ -148,7 +148,7 @@ mod tests { use katana_primitives::state::StateUpdatesWithDeclaredClasses; use katana_primitives::trace::TxExecInfo; use katana_primitives::transaction::{InvokeTx, Tx, TxWithHash}; - use katana_primitives::FieldElement; + use katana_primitives::Felt; use katana_provider::providers::in_memory::InMemoryProvider; use katana_provider::traits::block::{ BlockHashProvider, BlockNumberProvider, BlockProvider, BlockStatusProvider, BlockWriter, @@ -185,7 +185,7 @@ mod tests { let genesis = Genesis { number: 23, - parent_hash: FieldElement::ZERO, + parent_hash: Felt::ZERO, state_root: felt!("1334"), timestamp: 6868, gas_prices: GasPrices { eth: 9090, strk: 8080 }, @@ -233,7 +233,7 @@ mod tests { status: FinalityStatus::AcceptedOnL1, block: Block { header: Header { - parent_hash: FieldElement::ZERO, + parent_hash: Felt::ZERO, number: 1, gas_prices: GasPrices::default(), timestamp: 123456, diff --git a/crates/katana/core/src/service/messaging/ethereum.rs b/crates/katana/core/src/service/messaging/ethereum.rs index 9ab91757e4..982f80f7aa 100644 --- a/crates/katana/core/src/service/messaging/ethereum.rs +++ b/crates/katana/core/src/service/messaging/ethereum.rs @@ -16,7 +16,7 @@ use katana_primitives::transaction::L1HandlerTx; use katana_primitives::utils::transaction::{ compute_l1_to_l2_message_hash, compute_l2_to_l1_message_hash, }; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use starknet::core::types::EthAddress; use tracing::{debug, trace, warn}; @@ -208,7 +208,7 @@ fn l1_handler_tx_from_log(log: Log, chain_id: ChainId) -> MessengerResult MessengerResult Vec { .collect() } -fn felt_from_u256(v: U256) -> FieldElement { - FieldElement::from_str(format!("{:#064x}", v).as_str()).unwrap() +fn felt_from_u256(v: U256) -> Felt { + Felt::from_str(format!("{:#064x}", v).as_str()).unwrap() } #[cfg(test)] @@ -257,7 +257,7 @@ mod tests { let from_address = felt!("0xbe3C44c09bc1a3566F3e1CA12e5AbA0fA4Ca72Be"); let to_address = felt!("0x39dc79e64f4bb3289240f88e0bae7d21735bef0d1a51b2bf3c4730cb16983e1"); let selector = felt!("0x2f15cff7b0eed8b9beb162696cf4e3e0e35fa7032af69cd1b7d2ac67a13f40f"); - let payload = vec![FieldElement::ONE, FieldElement::TWO]; + let payload = vec![Felt::ONE, Felt::TWO]; let nonce = 783082_u64; let fee = 30000_u128; @@ -303,8 +303,8 @@ mod tests { chain_id, message_hash, paid_fee_on_l1: fee, - version: FieldElement::ZERO, - nonce: FieldElement::from(nonce), + version: Felt::ZERO, + nonce: Felt::from(nonce), contract_address: to_address.into(), entry_point_selector: selector, }; @@ -319,7 +319,7 @@ mod tests { fn parse_msg_to_l1() { let from_address = selector!("from_address"); let to_address = selector!("to_address"); - let payload = vec![FieldElement::ONE, FieldElement::TWO]; + let payload = vec![Felt::ONE, Felt::TWO]; let messages = vec![MessageToL1 { from_address: from_address.into(), to_address, payload }]; diff --git a/crates/katana/core/src/service/mod.rs b/crates/katana/core/src/service/mod.rs index be12368f45..2ff904f733 100644 --- a/crates/katana/core/src/service/mod.rs +++ b/crates/katana/core/src/service/mod.rs @@ -11,7 +11,7 @@ use futures::stream::{Fuse, Stream, StreamExt}; use katana_executor::ExecutorFactory; use katana_pool::{TransactionPool, TxPool}; use katana_primitives::transaction::ExecutableTxWithHash; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use tracing::{error, info}; use self::block_producer::BlockProducer; @@ -97,11 +97,11 @@ pub struct TransactionMiner { /// stores whether there are pending transacions (if known) has_pending_txs: Option, /// Receives hashes of transactions that are ready from the pool - rx: Fuse>, + rx: Fuse>, } impl TransactionMiner { - pub fn new(rx: Receiver) -> Self { + pub fn new(rx: Receiver) -> Self { Self { rx: rx.fuse(), has_pending_txs: None } } diff --git a/crates/katana/executor/benches/utils.rs b/crates/katana/executor/benches/utils.rs index 6e9001e5f5..cc8d9ff9df 100644 --- a/crates/katana/executor/benches/utils.rs +++ b/crates/katana/executor/benches/utils.rs @@ -2,7 +2,7 @@ use katana_primitives::block::GasPrices; use katana_primitives::env::{BlockEnv, CfgEnv, FeeTokenAddressses}; use katana_primitives::genesis::constant::DEFAULT_FEE_TOKEN_ADDRESS; use katana_primitives::transaction::{ExecutableTxWithHash, InvokeTx, InvokeTxV1}; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use starknet::macros::{felt, selector}; pub fn tx() -> ExecutableTxWithHash { @@ -11,10 +11,10 @@ pub fn tx() -> ExecutableTxWithHash { calldata: vec![ DEFAULT_FEE_TOKEN_ADDRESS.into(), selector!("transfer"), - FieldElement::THREE, + Felt::THREE, felt!("0x100"), - FieldElement::ONE, - FieldElement::ZERO, + Felt::ONE, + Felt::ZERO, ], max_fee: 10_000, ..Default::default() diff --git a/crates/katana/executor/src/abstraction/error.rs b/crates/katana/executor/src/abstraction/error.rs index 9ad39c57c1..b4d02d2271 100644 --- a/crates/katana/executor/src/abstraction/error.rs +++ b/crates/katana/executor/src/abstraction/error.rs @@ -1,6 +1,6 @@ use katana_primitives::class::ClassHash; use katana_primitives::contract::{ContractAddress, Nonce}; -use katana_primitives::FieldElement; +use katana_primitives::Felt; /// Errors that can be returned by the executor. #[derive(Debug, thiserror::Error)] @@ -16,7 +16,7 @@ pub enum ExecutionError { ClassAlreadyDeclared(ClassHash), #[error("Entry point {0:#x} not found in contract")] - EntryPointNotFound(FieldElement), + EntryPointNotFound(Felt), #[error("Invalid input: {input_descriptor}; {info}")] InvalidInput { input_descriptor: String, info: String }, @@ -46,7 +46,7 @@ pub enum ExecutionError { "Insufficient balance: max fee {max_fee} exceeds account balance u256({balance_low}, \ {balance_high})" )] - InsufficientBalance { max_fee: u128, balance_low: FieldElement, balance_high: FieldElement }, + InsufficientBalance { max_fee: u128, balance_low: Felt, balance_high: Felt }, #[error("Actual fee ({actual_fee}) exceeded max fee ({max_fee})")] ActualFeeExceedsMaxFee { max_fee: u128, actual_fee: u128 }, diff --git a/crates/katana/executor/src/abstraction/executor.rs b/crates/katana/executor/src/abstraction/executor.rs index fee93b0ee5..c5f417bea0 100644 --- a/crates/katana/executor/src/abstraction/executor.rs +++ b/crates/katana/executor/src/abstraction/executor.rs @@ -2,7 +2,7 @@ use katana_primitives::block::ExecutableBlock; use katana_primitives::env::{BlockEnv, CfgEnv}; use katana_primitives::fee::TxFeeInfo; use katana_primitives::transaction::{ExecutableTxWithHash, TxWithHash}; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use katana_provider::traits::state::StateProvider; use crate::{ @@ -72,5 +72,5 @@ pub trait ExecutorExt { ) -> Vec>; /// Perform a contract entry point call and return the output. - fn call(&self, call: EntryPointCall) -> Result, ExecutionError>; + fn call(&self, call: EntryPointCall) -> Result, ExecutionError>; } diff --git a/crates/katana/executor/src/abstraction/mod.rs b/crates/katana/executor/src/abstraction/mod.rs index b98c5599bb..ff245e72d8 100644 --- a/crates/katana/executor/src/abstraction/mod.rs +++ b/crates/katana/executor/src/abstraction/mod.rs @@ -9,7 +9,7 @@ use katana_primitives::receipt::Receipt; use katana_primitives::state::{StateUpdates, StateUpdatesWithDeclaredClasses}; use katana_primitives::trace::TxExecInfo; use katana_primitives::transaction::TxWithHash; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use katana_provider::traits::contract::ContractClassProvider; use katana_provider::traits::state::StateProvider; use katana_provider::ProviderResult; @@ -96,9 +96,9 @@ pub struct EntryPointCall { /// The address of the contract whose function you're calling. pub contract_address: ContractAddress, /// The input to the function. - pub calldata: Vec, + pub calldata: Vec, /// The contract function name. - pub entry_point_selector: FieldElement, + pub entry_point_selector: Felt, } #[allow(clippy::large_enum_variant)] diff --git a/crates/katana/executor/src/implementation/blockifier/mod.rs b/crates/katana/executor/src/implementation/blockifier/mod.rs index eaeb94951b..0cb6cbeab9 100644 --- a/crates/katana/executor/src/implementation/blockifier/mod.rs +++ b/crates/katana/executor/src/implementation/blockifier/mod.rs @@ -16,7 +16,7 @@ use katana_primitives::block::{ExecutableBlock, GasPrices as KatanaGasPrices, Pa use katana_primitives::env::{BlockEnv, CfgEnv}; use katana_primitives::fee::TxFeeInfo; use katana_primitives::transaction::{ExecutableTx, ExecutableTxWithHash, TxWithHash}; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use katana_provider::traits::state::StateProvider; use tracing::info; @@ -278,7 +278,7 @@ impl ExecutorExt for StarknetVMProcessor<'_> { }) } - fn call(&self, call: EntryPointCall) -> Result, ExecutionError> { + fn call(&self, call: EntryPointCall) -> Result, ExecutionError> { let block_context = &self.block_context; let mut state = self.state.0.lock(); let state = MutRefState::new(&mut state.inner); diff --git a/crates/katana/executor/src/implementation/blockifier/state.rs b/crates/katana/executor/src/implementation/blockifier/state.rs index af801d1ebe..7a73524aed 100644 --- a/crates/katana/executor/src/implementation/blockifier/state.rs +++ b/crates/katana/executor/src/implementation/blockifier/state.rs @@ -7,7 +7,7 @@ use blockifier::state::state_api::{StateReader, StateResult}; use katana_cairo::starknet_api::core::{ClassHash, CompiledClassHash, Nonce}; use katana_cairo::starknet_api::state::StorageKey; use katana_primitives::class::{CompiledClass, FlattenedSierraClass}; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use katana_provider::error::ProviderError; use katana_provider::traits::contract::ContractClassProvider; use katana_provider::traits::state::StateProvider; @@ -129,7 +129,11 @@ impl ContractClassProvider for CachedState { return Ok(None); }; - if hash.0 == FieldElement::ZERO { Ok(None) } else { Ok(Some(hash.0)) } + if hash.0 == Felt::ZERO { + Ok(None) + } else { + Ok(Some(hash.0)) + } } fn sierra_class( &self, @@ -153,7 +157,11 @@ impl StateProvider for CachedState { return Ok(None); }; - if hash.0 == FieldElement::ZERO { Ok(None) } else { Ok(Some(hash.0)) } + if hash.0 == Felt::ZERO { + Ok(None) + } else { + Ok(Some(hash.0)) + } } fn nonce( @@ -238,7 +246,7 @@ mod tests { DEFAULT_OZ_ACCOUNT_CONTRACT_CASM, }; use katana_primitives::utils::class::{parse_compiled_class, parse_sierra_class}; - use katana_primitives::FieldElement; + use katana_primitives::Felt; use katana_provider::providers::in_memory::InMemoryProvider; use katana_provider::traits::contract::ContractClassWriter; use katana_provider::traits::state::{StateFactoryProvider, StateProvider, StateWriter}; @@ -524,7 +532,7 @@ mod tests { assert_eq!(actual_storage_value, None, "value of nonexistant contract should be None"); assert_eq!( actual_edge_storage_value, - Some(FieldElement::ZERO), + Some(Felt::ZERO), "edge case: value of nonexistant storage key but existant contract should return zero" ); assert_eq!(actual_compiled_hash, None); diff --git a/crates/katana/executor/src/implementation/blockifier/utils.rs b/crates/katana/executor/src/implementation/blockifier/utils.rs index 8dffe1a1f6..d4c2541b39 100644 --- a/crates/katana/executor/src/implementation/blockifier/utils.rs +++ b/crates/katana/executor/src/implementation/blockifier/utils.rs @@ -51,7 +51,7 @@ use katana_primitives::trace::{L1Gas, TxExecInfo, TxResources}; use katana_primitives::transaction::{ DeclareTx, DeployAccountTx, ExecutableTx, ExecutableTxWithHash, InvokeTx, }; -use katana_primitives::{class, event, message, trace, FieldElement}; +use katana_primitives::{class, event, message, trace, Felt}; use katana_provider::traits::contract::ContractClassProvider; use starknet::core::types::PriceUnit; use starknet::core::utils::parse_cairo_short_string; @@ -141,7 +141,7 @@ pub fn call( state: S, block_context: &BlockContext, initial_gas: u128, -) -> Result, ExecutionError> { +) -> Result, ExecutionError> { let mut state = cached_state::CachedState::new(state); let call = CallEntryPoint { @@ -550,13 +550,11 @@ pub fn to_class(class: class::CompiledClass) -> Result } /// TODO: remove this function once starknet api 0.8.0 is supported. -fn starknet_api_ethaddr_to_felt( - value: katana_cairo::starknet_api::core::EthAddress, -) -> FieldElement { +fn starknet_api_ethaddr_to_felt(value: katana_cairo::starknet_api::core::EthAddress) -> Felt { let mut bytes = [0u8; 32]; // Padding H160 with zeros to 32 bytes (big endian) bytes[12..32].copy_from_slice(value.0.as_bytes()); - FieldElement::from_bytes_be(&bytes) + Felt::from_bytes_be(&bytes) } pub fn to_exec_info(exec_info: TransactionExecutionInfo) -> TxExecInfo { @@ -660,7 +658,7 @@ mod tests { use katana_cairo::starknet_api::core::EntryPointSelector; use katana_cairo::starknet_api::felt; use katana_cairo::starknet_api::transaction::{EventContent, EventData, EventKey}; - use katana_primitives::felt::FieldElement; + use katana_primitives::Felt; use super::*; @@ -694,7 +692,7 @@ mod tests { // // This is how blockifier pass the chain id to the contract through a syscall. // https://github.com/dojoengine/blockifier/blob/f2246ce2862d043e4efe2ecf149a4cb7bee689cd/crates/blockifier/src/execution/syscalls/hint_processor.rs#L600-L602 - let actual_id = FieldElement::from_hex(blockifier_id.as_hex().as_str()).unwrap(); + let actual_id = Felt::from_hex(blockifier_id.as_hex().as_str()).unwrap(); assert_eq!(actual_id, id) } @@ -793,7 +791,7 @@ mod tests { }; let expected_storage_read_values = call.storage_read_values.clone(); - let expected_storage_keys: HashSet = + let expected_storage_keys: HashSet = call.accessed_storage_keys.iter().map(|v| *v.key()).collect(); let expected_inner_calls: Vec<_> = call.inner_calls.clone().into_iter().map(to_call_info).collect(); diff --git a/crates/katana/executor/src/implementation/noop.rs b/crates/katana/executor/src/implementation/noop.rs index e8551c4e48..5dd23631e8 100644 --- a/crates/katana/executor/src/implementation/noop.rs +++ b/crates/katana/executor/src/implementation/noop.rs @@ -4,7 +4,7 @@ use katana_primitives::contract::{ContractAddress, Nonce, StorageKey, StorageVal use katana_primitives::env::{BlockEnv, CfgEnv}; use katana_primitives::fee::TxFeeInfo; use katana_primitives::transaction::{ExecutableTxWithHash, TxWithHash}; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use katana_provider::traits::contract::ContractClassProvider; use katana_provider::traits::state::StateProvider; use katana_provider::ProviderResult; @@ -86,7 +86,7 @@ impl ExecutorExt for NoopExecutor { vec![] } - fn call(&self, call: EntryPointCall) -> Result, ExecutionError> { + fn call(&self, call: EntryPointCall) -> Result, ExecutionError> { let _ = call; Ok(vec![]) } diff --git a/crates/katana/executor/tests/executor.rs b/crates/katana/executor/tests/executor.rs index 4673cf2f11..3af54f6814 100644 --- a/crates/katana/executor/tests/executor.rs +++ b/crates/katana/executor/tests/executor.rs @@ -11,7 +11,7 @@ use katana_primitives::genesis::constant::{ DEFAULT_OZ_ACCOUNT_CONTRACT_CLASS_HASH, DEFAULT_PREFUNDED_ACCOUNT_BALANCE, DEFAULT_UDC_ADDRESS, }; use katana_primitives::transaction::TxWithHash; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use katana_provider::traits::state::StateProvider; use starknet::core::utils::{ get_storage_var_address, get_udc_deployed_address, UdcUniqueSettings, UdcUniqueness, @@ -55,7 +55,11 @@ fn test_executor_with_valid_blocks_impl( // ensure that all transactions succeeded, if not panic with the error message and tx index let has_failed = transactions.iter().enumerate().find_map(|(i, (_, res))| { - if let ExecutionResult::Failed { error } = res { Some((i, error)) } else { None } + if let ExecutionResult::Failed { error } = res { + Some((i, error)) + } else { + None + } }); if let Some((pos, error)) = has_failed { @@ -89,7 +93,7 @@ fn test_executor_with_valid_blocks_impl( .expect("storage should exist"); assert!( - updated_main_acc_balance < FieldElement::from(DEFAULT_PREFUNDED_ACCOUNT_BALANCE), + updated_main_acc_balance < Felt::from(DEFAULT_PREFUNDED_ACCOUNT_BALANCE), "sender balance should decrease" ); assert_eq!(actual_new_acc_balance, felt!("0x9999999999999999"), "account balance is updated"); @@ -223,7 +227,7 @@ fn test_executor_with_valid_blocks_impl( let actual_storage_value_4_1 = state_provider .storage( deployed_contract.into(), - get_storage_var_address("ERC20_total_supply", &[]).unwrap() + FieldElement::ONE, + get_storage_var_address("ERC20_total_supply", &[]).unwrap() + Felt::ONE, ) .unwrap(); let actual_storage_value_5 = state_provider diff --git a/crates/katana/executor/tests/fixtures/mod.rs b/crates/katana/executor/tests/fixtures/mod.rs index 62c524cba3..dbed9690a2 100644 --- a/crates/katana/executor/tests/fixtures/mod.rs +++ b/crates/katana/executor/tests/fixtures/mod.rs @@ -21,7 +21,7 @@ use katana_primitives::transaction::{ }; use katana_primitives::utils::class::{parse_compiled_class, parse_sierra_class}; use katana_primitives::version::Version; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use katana_provider::providers::in_memory::InMemoryProvider; use katana_provider::traits::block::BlockWriter; use katana_provider::traits::state::{StateFactoryProvider, StateProvider}; @@ -120,7 +120,7 @@ pub fn valid_blocks() -> [ExecutableBlock; 3] { ], max_fee: 4367000000000000, signature: vec![], - nonce: FieldElement::ZERO, + nonce: Felt::ZERO, }))), // declare contract ExecutableTxWithHash::new(ExecutableTx::Declare({ @@ -129,7 +129,7 @@ pub fn valid_blocks() -> [ExecutableBlock; 3] { compiled_class, sierra_class: Some(sierra), transaction: DeclareTx::V2(DeclareTxV2 { - nonce: FieldElement::ONE, + nonce: Felt::ONE, max_fee: 27092100000000000, chain_id, signature: vec![], @@ -208,7 +208,7 @@ pub fn valid_blocks() -> [ExecutableBlock; 3] { ], max_fee: 2700700000000000, signature: vec![], - nonce: FieldElement::TWO, + nonce: Felt::TWO, }))), ], }, diff --git a/crates/katana/executor/tests/fixtures/transaction.rs b/crates/katana/executor/tests/fixtures/transaction.rs index 92c15efc51..bad306fd1b 100644 --- a/crates/katana/executor/tests/fixtures/transaction.rs +++ b/crates/katana/executor/tests/fixtures/transaction.rs @@ -6,7 +6,7 @@ use katana_primitives::genesis::constant::DEFAULT_FEE_TOKEN_ADDRESS; use katana_primitives::genesis::Genesis; use katana_primitives::transaction::ExecutableTxWithHash; use katana_primitives::utils::transaction::compute_invoke_v1_tx_hash; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use num_traits::ToPrimitive; use starknet::accounts::{Account, ExecutionEncoder, ExecutionEncoding, SingleOwnerAccount}; use starknet::core::types::{ @@ -22,10 +22,10 @@ use super::{cfg, genesis}; #[allow(unused)] pub fn invoke_executable_tx( address: ContractAddress, - private_key: FieldElement, + private_key: Felt, chain_id: ChainId, nonce: Nonce, - max_fee: FieldElement, + max_fee: Felt, signed: bool, ) -> ExecutableTxWithHash { let url = "http://localhost:5050"; @@ -109,7 +109,7 @@ pub fn executable_tx(signed: bool, genesis: &Genesis, cfg: CfgEnv) -> Executable *addr, account.private_key().unwrap(), cfg.chain_id, - FieldElement::ZERO, + Felt::ZERO, // this is an arbitrary large fee so that it doesn't fail felt!("0x999999999999999"), signed, @@ -132,8 +132,8 @@ pub fn executable_tx_without_max_fee( *addr, account.private_key().unwrap(), cfg.chain_id, - FieldElement::ZERO, - FieldElement::ZERO, + Felt::ZERO, + Felt::ZERO, signed, ) } diff --git a/crates/katana/pool/src/pool.rs b/crates/katana/pool/src/pool.rs index 883fdf746d..47ec956073 100644 --- a/crates/katana/pool/src/pool.rs +++ b/crates/katana/pool/src/pool.rs @@ -211,7 +211,7 @@ where pub(crate) mod test_utils { use katana_primitives::contract::{ContractAddress, Nonce}; - use katana_primitives::FieldElement; + use katana_primitives::Felt; use rand::Rng; use super::*; @@ -241,7 +241,7 @@ pub(crate) mod test_utils { hash: TxHash::from_bytes_be(&random_bytes::<32>()), nonce: Nonce::from_bytes_be(&random_bytes::<32>()), sender: { - let felt = FieldElement::from_bytes_be(&random_bytes::<32>()); + let felt = Felt::from_bytes_be(&random_bytes::<32>()); ContractAddress::from(felt) }, } @@ -290,7 +290,7 @@ pub(crate) mod test_utils { mod tests { use katana_primitives::contract::{ContractAddress, Nonce}; - use katana_primitives::FieldElement; + use katana_primitives::Felt; use super::test_utils::*; use super::Pool; @@ -400,7 +400,7 @@ mod tests { // Create 100 transactions with the same sender but increasing nonce let total = 100u128; - let sender = ContractAddress::from(FieldElement::from_hex("0x1337").unwrap()); + let sender = ContractAddress::from(Felt::from_hex("0x1337").unwrap()); let txs: Vec = (0..total) .map(|i| PoolTx::new().with_sender(sender).with_nonce(Nonce::from(i))) .collect(); diff --git a/crates/katana/pool/src/validation/mod.rs b/crates/katana/pool/src/validation/mod.rs index 68943ecd73..fe885ea276 100644 --- a/crates/katana/pool/src/validation/mod.rs +++ b/crates/katana/pool/src/validation/mod.rs @@ -3,7 +3,7 @@ pub mod stateful; use katana_primitives::class::ClassHash; use katana_primitives::contract::{ContractAddress, Nonce}; use katana_primitives::transaction::TxHash; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use crate::tx::PoolTransaction; @@ -25,7 +25,7 @@ pub enum InvalidTransactionError { /// The specified transaction fee. max_fee: u128, /// The account's balance of the fee token. - balance: FieldElement, + balance: Felt, }, /// Error when the specified transaction fee is insufficient to cover the minimum fee required. diff --git a/crates/katana/pool/src/validation/stateful.rs b/crates/katana/pool/src/validation/stateful.rs index 798e0dccc9..88052435da 100644 --- a/crates/katana/pool/src/validation/stateful.rs +++ b/crates/katana/pool/src/validation/stateful.rs @@ -16,7 +16,7 @@ use katana_executor::{SimulationFlag, StateProviderDb}; use katana_primitives::contract::{ContractAddress, Nonce}; use katana_primitives::env::{BlockEnv, CfgEnv}; use katana_primitives::transaction::{ExecutableTx, ExecutableTxWithHash}; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use katana_provider::error::ProviderError; use katana_provider::traits::state::StateProvider; use parking_lot::Mutex; @@ -136,7 +136,7 @@ impl Validator for TxValidator { match result { res @ Ok(ValidationOutcome::Valid { .. }) => { // update the nonce of the account in the pool only for valid tx - let updated_nonce = current_nonce + FieldElement::ONE; + let updated_nonce = current_nonce + Felt::ONE; this.pool_nonces.insert(address, updated_nonce); res } diff --git a/crates/katana/primitives/src/block.rs b/crates/katana/primitives/src/block.rs index 671489c55d..7c410886a5 100644 --- a/crates/katana/primitives/src/block.rs +++ b/crates/katana/primitives/src/block.rs @@ -3,7 +3,7 @@ use starknet::core::crypto::compute_hash_on_elements; use crate::contract::ContractAddress; use crate::transaction::{ExecutableTxWithHash, TxHash, TxWithHash}; use crate::version::Version; -use crate::FieldElement; +use crate::Felt; pub type BlockIdOrTag = starknet::core::types::BlockId; pub type BlockTag = starknet::core::types::BlockTag; @@ -18,7 +18,7 @@ pub enum BlockHashOrNumber { /// Block number type. pub type BlockNumber = u64; /// Block hash type. -pub type BlockHash = FieldElement; +pub type BlockHash = Felt; /// Finality status of a canonical block. #[derive(Debug, Copy, Clone, PartialEq, Eq)] @@ -33,7 +33,7 @@ pub enum FinalityStatus { #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct PartialHeader { pub number: BlockNumber, - pub parent_hash: FieldElement, + pub parent_hash: Felt, pub gas_prices: GasPrices, pub timestamp: u64, pub sequencer_address: ContractAddress, @@ -66,13 +66,13 @@ pub struct Header { pub number: BlockNumber, pub gas_prices: GasPrices, pub timestamp: u64, - pub state_root: FieldElement, + pub state_root: Felt, pub sequencer_address: ContractAddress, pub version: Version, } impl Header { - pub fn new(partial_header: PartialHeader, state_root: FieldElement) -> Self { + pub fn new(partial_header: PartialHeader, state_root: Felt) -> Self { Self { state_root, number: partial_header.number, @@ -85,16 +85,16 @@ impl Header { } /// Computes the hash of the header. - pub fn compute_hash(&self) -> FieldElement { + pub fn compute_hash(&self) -> Felt { compute_hash_on_elements(&vec![ self.number.into(), // block number self.state_root, // state root self.sequencer_address.into(), // sequencer address self.timestamp.into(), // block timestamp - FieldElement::ZERO, // transaction commitment - FieldElement::ZERO, // event commitment - FieldElement::ZERO, // protocol version - FieldElement::ZERO, // extra data + Felt::ZERO, // transaction commitment + Felt::ZERO, // event commitment + Felt::ZERO, // protocol version + Felt::ZERO, // extra data self.parent_hash, // parent hash ]) } diff --git a/crates/katana/primitives/src/chain.rs b/crates/katana/primitives/src/chain.rs index ecce9bd794..d8c359892f 100644 --- a/crates/katana/primitives/src/chain.rs +++ b/crates/katana/primitives/src/chain.rs @@ -1,8 +1,7 @@ use starknet::core::utils::{cairo_short_string_to_felt, CairoShortStringToFeltError}; use starknet::macros::short_string; -use crate::felt::FromStrError; -use crate::FieldElement; +use crate::{Felt, FromStrError}; /// Known chain ids that has been assigned a name. #[derive(Debug, Clone, Copy, PartialEq, Eq, strum_macros::Display)] @@ -15,18 +14,18 @@ pub enum NamedChainId { impl NamedChainId { /// `SN_MAIN` in ASCII - pub const SN_MAIN: FieldElement = short_string!("SN_MAIN"); + pub const SN_MAIN: Felt = short_string!("SN_MAIN"); /// `SN_GOERLI` in ASCII - pub const SN_GOERLI: FieldElement = short_string!("SN_GOERLI"); + pub const SN_GOERLI: Felt = short_string!("SN_GOERLI"); /// `SN_SEPOLIA` in ASCII - pub const SN_SEPOLIA: FieldElement = short_string!("SN_SEPOLIA"); + pub const SN_SEPOLIA: Felt = short_string!("SN_SEPOLIA"); /// Returns the id of the chain. It is the ASCII representation of a predefined string /// constants. #[inline] - pub const fn id(&self) -> FieldElement { + pub const fn id(&self) -> Felt { match self { NamedChainId::Mainnet => Self::SN_MAIN, NamedChainId::Goerli => Self::SN_GOERLI, @@ -48,11 +47,11 @@ impl NamedChainId { /// This `struct` is created by the [`NamedChainId::try_from`] method. #[derive(Debug, thiserror::Error)] #[error("Unknown named chain id {0:#x}")] -pub struct NamedChainTryFromError(FieldElement); +pub struct NamedChainTryFromError(Felt); -impl TryFrom for NamedChainId { +impl TryFrom for NamedChainId { type Error = NamedChainTryFromError; - fn try_from(value: FieldElement) -> Result { + fn try_from(value: Felt) -> Result { if value == Self::SN_MAIN { Ok(Self::Mainnet) } else if value == Self::SN_GOERLI { @@ -71,7 +70,7 @@ impl TryFrom for NamedChainId { pub enum ChainId { /// A chain id with a known chain name. Named(NamedChainId), - Id(FieldElement), + Id(Felt), } #[derive(Debug, thiserror::Error)] @@ -95,16 +94,13 @@ impl ChainId { /// If the `str` starts with `0x` it is parsed as a hex string, otherwise it is parsed as a /// Cairo short string. pub fn parse(s: &str) -> Result { - let id = if s.starts_with("0x") { - FieldElement::from_hex(s)? - } else { - cairo_short_string_to_felt(s)? - }; + let id = + if s.starts_with("0x") { Felt::from_hex(s)? } else { cairo_short_string_to_felt(s)? }; Ok(ChainId::from(id)) } /// Returns the chain id value. - pub const fn id(&self) -> FieldElement { + pub const fn id(&self) -> Felt { match self { ChainId::Named(name) => name.id(), ChainId::Id(id) => *id, @@ -114,7 +110,7 @@ impl ChainId { impl Default for ChainId { fn default() -> Self { - ChainId::Id(FieldElement::ZERO) + ChainId::Id(Felt::ZERO) } } @@ -136,13 +132,13 @@ impl std::fmt::Display for ChainId { } } -impl From for ChainId { - fn from(value: FieldElement) -> Self { +impl From for ChainId { + fn from(value: Felt) -> Self { NamedChainId::try_from(value).map(ChainId::Named).unwrap_or(ChainId::Id(value)) } } -impl From for FieldElement { +impl From for Felt { fn from(value: ChainId) -> Self { value.id() } diff --git a/crates/katana/primitives/src/class.rs b/crates/katana/primitives/src/class.rs index e825e5c889..570266c45a 100644 --- a/crates/katana/primitives/src/class.rs +++ b/crates/katana/primitives/src/class.rs @@ -2,12 +2,12 @@ use katana_cairo::lang::sierra::program::Program; use katana_cairo::lang::starknet_classes::casm_contract_class::CasmContractClass; use katana_cairo::lang::starknet_classes::contract_class::ContractEntryPoints; -use crate::FieldElement; +use crate::Felt; /// The canonical hash of a contract class. This is the identifier of a class. -pub type ClassHash = FieldElement; +pub type ClassHash = Felt; /// The hash of a compiled contract class. -pub type CompiledClassHash = FieldElement; +pub type CompiledClassHash = Felt; pub type SierraClass = starknet::core::types::contract::SierraClass; pub type FlattenedSierraClass = starknet::core::types::FlattenedSierraClass; diff --git a/crates/katana/primitives/src/contract.rs b/crates/katana/primitives/src/contract.rs index 028bd8a95a..4473d4169b 100644 --- a/crates/katana/primitives/src/contract.rs +++ b/crates/katana/primitives/src/contract.rs @@ -4,23 +4,23 @@ use derive_more::Deref; use starknet::core::utils::normalize_address; use crate::class::ClassHash; -use crate::FieldElement; +use crate::Felt; /// Represents the type for a contract storage key. -pub type StorageKey = FieldElement; +pub type StorageKey = Felt; /// Represents the type for a contract storage value. -pub type StorageValue = FieldElement; +pub type StorageValue = Felt; /// Represents the type for a contract nonce. -pub type Nonce = FieldElement; +pub type Nonce = Felt; /// Represents a contract address. #[derive(Default, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Hash, Debug, Deref)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct ContractAddress(#[deref] pub FieldElement); +pub struct ContractAddress(#[deref] pub Felt); impl ContractAddress { - pub fn new(address: FieldElement) -> Self { + pub fn new(address: Felt) -> Self { ContractAddress(normalize_address(address)) } } @@ -31,13 +31,13 @@ impl fmt::Display for ContractAddress { } } -impl From for ContractAddress { - fn from(value: FieldElement) -> Self { +impl From for ContractAddress { + fn from(value: Felt) -> Self { ContractAddress::new(value) } } -impl From for FieldElement { +impl From for Felt { fn from(value: ContractAddress) -> Self { value.0 } diff --git a/crates/katana/primitives/src/conversion/rpc.rs b/crates/katana/primitives/src/conversion/rpc.rs index d0015e4adc..76db13145e 100644 --- a/crates/katana/primitives/src/conversion/rpc.rs +++ b/crates/katana/primitives/src/conversion/rpc.rs @@ -27,7 +27,7 @@ use crate::class::{ ClassHash, CompiledClassHash, DeprecatedCompiledClass, FlattenedSierraClass, SierraCompiledClass, SierraProgram, }; -use crate::FieldElement; +use crate::Felt; /// Converts the legacy inner compiled class type [DeprecatedCompiledClass] into its RPC equivalent /// [`ContractClass`]. @@ -158,7 +158,7 @@ pub fn flattened_sierra_to_compiled_class( /// Compute the compiled class hash from the given [`FlattenedSierraClass`]. pub fn compiled_class_hash_from_flattened_sierra_class( contract_class: &FlattenedSierraClass, -) -> Result { +) -> Result { let contract_class = rpc_to_cairo_contract_class(contract_class)?; let casm = CasmContractClass::from_contract_class(contract_class, true, usize::MAX)?; let compiled_class: CompiledClass = serde_json::from_str(&serde_json::to_string(&casm)?)?; @@ -243,7 +243,7 @@ fn decompress_legacy_program_data(data: &[u8]) -> Result, compiler_version: Option, #[serde_as(as = "Vec")] - data: Vec, + data: Vec, debug_info: Option, hints: BTreeMap>, identifiers: BTreeMap, diff --git a/crates/katana/primitives/src/event.rs b/crates/katana/primitives/src/event.rs index d0b7e4c0db..56224d9a1c 100644 --- a/crates/katana/primitives/src/event.rs +++ b/crates/katana/primitives/src/event.rs @@ -1,14 +1,14 @@ use core::fmt; use std::num::ParseIntError; -use crate::FieldElement; +use crate::Felt; #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct OrderedEvent { pub order: u64, - pub keys: Vec, - pub data: Vec, + pub keys: Vec, + pub data: Vec, } /// Represents a continuation token for implementing paging in event queries. diff --git a/crates/katana/primitives/src/genesis/allocation.rs b/crates/katana/primitives/src/genesis/allocation.rs index 32f69c1e57..3c6cef8f4d 100644 --- a/crates/katana/primitives/src/genesis/allocation.rs +++ b/crates/katana/primitives/src/genesis/allocation.rs @@ -13,7 +13,7 @@ use starknet::signers::SigningKey; use super::constant::DEFAULT_OZ_ACCOUNT_CONTRACT_CLASS_HASH; use crate::class::ClassHash; use crate::contract::{ContractAddress, StorageKey, StorageValue}; -use crate::FieldElement; +use crate::Felt; /// Represents a contract allocation in the genesis block. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] @@ -27,7 +27,7 @@ pub enum GenesisAllocation { impl GenesisAllocation { /// Get the public key of the account contract if it's an account contract, otherwise `None`. - pub fn public_key(&self) -> Option { + pub fn public_key(&self) -> Option { match self { Self::Contract(_) => None, Self::Account(account) => Some(account.public_key()), @@ -51,7 +51,7 @@ impl GenesisAllocation { } /// Get the nonce. - pub fn nonce(&self) -> Option { + pub fn nonce(&self) -> Option { match self { Self::Contract(contract) => contract.nonce, Self::Account(account) => account.nonce(), @@ -79,7 +79,7 @@ pub enum GenesisAccountAlloc { } impl GenesisAccountAlloc { - pub fn public_key(&self) -> FieldElement { + pub fn public_key(&self) -> Felt { match self { Self::Account(account) => account.public_key, Self::DevAccount(account) => account.public_key, @@ -100,7 +100,7 @@ impl GenesisAccountAlloc { } } - pub fn nonce(&self) -> Option { + pub fn nonce(&self) -> Option { match self { Self::Account(account) => account.nonce, Self::DevAccount(account) => account.nonce, @@ -114,7 +114,7 @@ impl GenesisAccountAlloc { } } - pub fn private_key(&self) -> Option { + pub fn private_key(&self) -> Option { match self { Self::Account(_) => None, Self::DevAccount(account) => Some(account.private_key), @@ -133,7 +133,7 @@ pub struct GenesisContractAlloc { pub balance: Option, /// The initial nonce of the contract. #[serde(skip_serializing_if = "Option::is_none")] - pub nonce: Option, + pub nonce: Option, /// The initial storage values of the contract. #[serde(skip_serializing_if = "Option::is_none")] pub storage: Option>, @@ -146,7 +146,7 @@ pub struct GenesisContractAlloc { pub struct DevGenesisAccount { /// The private key associated with the public key of the account. #[serde_as(as = "UfeHex")] - pub private_key: FieldElement, + pub private_key: Felt, #[deref] #[deref_mut] #[serde(flatten)] @@ -156,7 +156,7 @@ pub struct DevGenesisAccount { impl DevGenesisAccount { /// Creates a new dev account with the given `private_key` and `class_hash`. - pub fn new(private_key: FieldElement, class_hash: ClassHash) -> (ContractAddress, Self) { + pub fn new(private_key: Felt, class_hash: ClassHash) -> (ContractAddress, Self) { let public_key = public_key_from_private_key(private_key); let (addr, inner) = GenesisAccount::new(public_key, class_hash); (addr, Self { private_key, inner }) @@ -164,7 +164,7 @@ impl DevGenesisAccount { /// Creates a new dev account with the allocated `balance`. pub fn new_with_balance( - private_key: FieldElement, + private_key: Felt, class_hash: ClassHash, balance: U256, ) -> (ContractAddress, Self) { @@ -180,7 +180,7 @@ impl DevGenesisAccount { pub struct GenesisAccount { /// The public key associated with the account for validation. #[serde_as(as = "UfeHex")] - pub public_key: FieldElement, + pub public_key: Felt, /// The class hash of the account contract. #[serde_as(as = "UfeHex")] pub class_hash: ClassHash, @@ -188,26 +188,22 @@ pub struct GenesisAccount { pub balance: Option, /// The initial nonce of the account. #[serde(skip_serializing_if = "Option::is_none")] - pub nonce: Option, + pub nonce: Option, /// The initial storage values of the account. #[serde(skip_serializing_if = "Option::is_none")] pub storage: Option>, } impl GenesisAccount { - pub fn new(public_key: FieldElement, class_hash: ClassHash) -> (ContractAddress, Self) { - let address = get_contract_address( - FieldElement::from(666u32), - class_hash, - &[public_key], - FieldElement::ZERO, - ); + pub fn new(public_key: Felt, class_hash: ClassHash) -> (ContractAddress, Self) { + let address = + get_contract_address(Felt::from(666u32), class_hash, &[public_key], Felt::ZERO); (ContractAddress::from(address), Self { public_key, class_hash, ..Default::default() }) } pub fn new_with_balance( - public_key: FieldElement, + public_key: Felt, class_hash: ClassHash, balance: U256, ) -> (ContractAddress, Self) { @@ -229,7 +225,7 @@ pub struct DevAllocationsGenerator { total: u16, seed: [u8; 32], balance: U256, - class_hash: FieldElement, + class_hash: Felt, } impl DevAllocationsGenerator { @@ -270,7 +266,7 @@ impl DevAllocationsGenerator { private_key_bytes[0] %= 0x8; seed = private_key_bytes; - let private_key = FieldElement::from_bytes_be(&private_key_bytes); + let private_key = Felt::from_bytes_be(&private_key_bytes); DevGenesisAccount::new_with_balance(private_key, self.class_hash, self.balance) }) .collect() @@ -279,6 +275,6 @@ impl DevAllocationsGenerator { /// Helper function for generating the public key from the `private_key` using /// the Stark curve. -fn public_key_from_private_key(private_key: FieldElement) -> FieldElement { +fn public_key_from_private_key(private_key: Felt) -> Felt { SigningKey::from_secret_scalar(private_key).verifying_key().scalar() } diff --git a/crates/katana/primitives/src/genesis/constant.rs b/crates/katana/primitives/src/genesis/constant.rs index 5a48762a5d..87da9783d0 100644 --- a/crates/katana/primitives/src/genesis/constant.rs +++ b/crates/katana/primitives/src/genesis/constant.rs @@ -5,7 +5,7 @@ use starknet::macros::felt; use crate::class::{ClassHash, CompiledClass, CompiledClassHash, SierraClass}; use crate::contract::{ContractAddress, StorageKey}; use crate::utils::class::{parse_compiled_class, parse_sierra_class}; -use crate::FieldElement; +use crate::Felt; /// The default universal deployer contract address. /// Corresponds to 0x041a78e741e5af2fec34b695679bc6891742439f7afb8484ecd7766661ad02bf @@ -106,7 +106,7 @@ lazy_static! { /// /// This is to compute the base storage address of the balance because the fee token balance is /// stored as a U256 value and as such has to be split into two U128 values (low and high). -pub(super) fn get_fee_token_balance_base_storage_address(address: ContractAddress) -> FieldElement { +pub(super) fn get_fee_token_balance_base_storage_address(address: ContractAddress) -> Felt { get_storage_var_address("ERC20_balances", &[address.into()]).unwrap() } diff --git a/crates/katana/primitives/src/genesis/json.rs b/crates/katana/primitives/src/genesis/json.rs index 986080ba34..c927e354d9 100644 --- a/crates/katana/primitives/src/genesis/json.rs +++ b/crates/katana/primitives/src/genesis/json.rs @@ -43,7 +43,7 @@ use crate::class::{ClassHash, CompiledClass, SierraClass}; use crate::contract::{ContractAddress, StorageKey, StorageValue}; use crate::genesis::GenesisClass; use crate::utils::class::{parse_compiled_class_v1, parse_deprecated_compiled_class}; -use crate::FieldElement; +use crate::Felt; type Object = Map; @@ -181,7 +181,7 @@ pub struct UniversalDeployerConfigJson { pub struct GenesisContractJson { pub class: Option, pub balance: Option, - pub nonce: Option, + pub nonce: Option, pub storage: Option>, } @@ -189,13 +189,13 @@ pub struct GenesisContractJson { #[serde(rename_all = "camelCase")] pub struct GenesisAccountJson { /// The public key of the account. - pub public_key: FieldElement, + pub public_key: Felt, pub balance: Option, - pub nonce: Option, + pub nonce: Option, /// The class hash of the account contract. If not provided, the default account class is used. pub class: Option, pub storage: Option>, - pub private_key: Option, + pub private_key: Option, } #[derive(Debug, thiserror::Error)] @@ -257,7 +257,7 @@ pub enum GenesisJsonError { #[serde(rename_all = "camelCase")] pub struct GenesisJson { pub parent_hash: BlockHash, - pub state_root: FieldElement, + pub state_root: Felt, pub number: BlockNumber, pub timestamp: u64, pub sequencer_address: ContractAddress, @@ -318,7 +318,7 @@ impl TryFrom for Genesis { fn try_from(value: GenesisJson) -> Result { // a lookup table for classes that is assigned a name - let mut class_names: HashMap = HashMap::new(); + let mut class_names: HashMap = HashMap::new(); let mut classes: HashMap = HashMap::new(); #[cfg(feature = "slot")] @@ -1215,12 +1215,10 @@ mod tests { fn genesis_from_json_with_unresolved_paths() { let file = File::open("./src/genesis/test-genesis.json").unwrap(); let json: GenesisJson = serde_json::from_reader(file).unwrap(); - assert!( - Genesis::try_from(json) - .unwrap_err() - .to_string() - .contains("Unresolved class artifact path") - ); + assert!(Genesis::try_from(json) + .unwrap_err() + .to_string() + .contains("Unresolved class artifact path")); } #[test] @@ -1264,8 +1262,9 @@ mod tests { .expect("failed to load genesis file"); let res = Genesis::try_from(json); - assert!( - res.unwrap_err().to_string().contains(&format!("Class name '{name}' already exists")) - ) + assert!(res + .unwrap_err() + .to_string() + .contains(&format!("Class name '{name}' already exists"))) } } diff --git a/crates/katana/primitives/src/genesis/mod.rs b/crates/katana/primitives/src/genesis/mod.rs index d65ad481d7..a2548b67ca 100644 --- a/crates/katana/primitives/src/genesis/mod.rs +++ b/crates/katana/primitives/src/genesis/mod.rs @@ -34,7 +34,7 @@ use crate::contract::{ContractAddress, StorageKey, StorageValue}; use crate::state::StateUpdatesWithDeclaredClasses; use crate::utils::split_u256; use crate::version::CURRENT_STARKNET_VERSION; -use crate::FieldElement; +use crate::Felt; #[serde_with::serde_as] #[derive(Debug, Clone, Serialize, Deserialize)] @@ -88,7 +88,7 @@ pub struct Genesis { pub parent_hash: BlockHash, /// The genesis block state root. #[serde_as(as = "UfeHex")] - pub state_root: FieldElement, + pub state_root: Felt, /// The genesis block number. pub number: BlockNumber, /// The genesis block timestamp. @@ -204,7 +204,7 @@ impl Genesis { // the storage address of low u128 of the balance let low_bal_storage_var = bal_base_storage_var; // the storage address of high u128 of the balance - let high_bal_storage_var = bal_base_storage_var + FieldElement::ONE; + let high_bal_storage_var = bal_base_storage_var + Felt::ONE; fee_token_storage.insert(low_bal_storage_var, low); fee_token_storage.insert(high_bal_storage_var, high); @@ -213,17 +213,16 @@ impl Genesis { // TODO: put this in a separate function - let name: FieldElement = cairo_short_string_to_felt(&self.fee_token.name).unwrap(); - let symbol: FieldElement = cairo_short_string_to_felt(&self.fee_token.symbol).unwrap(); - let decimals: FieldElement = self.fee_token.decimals.into(); + let name: Felt = cairo_short_string_to_felt(&self.fee_token.name).unwrap(); + let symbol: Felt = cairo_short_string_to_felt(&self.fee_token.symbol).unwrap(); + let decimals: Felt = self.fee_token.decimals.into(); let (total_supply_low, total_supply_high) = split_u256(fee_token_total_supply); fee_token_storage.insert(ERC20_NAME_STORAGE_SLOT, name); fee_token_storage.insert(ERC20_SYMBOL_STORAGE_SLOT, symbol); fee_token_storage.insert(ERC20_DECIMAL_STORAGE_SLOT, decimals); fee_token_storage.insert(ERC20_TOTAL_SUPPLY_STORAGE_SLOT, total_supply_low); - fee_token_storage - .insert(ERC20_TOTAL_SUPPLY_STORAGE_SLOT + FieldElement::ONE, total_supply_high); + fee_token_storage.insert(ERC20_TOTAL_SUPPLY_STORAGE_SLOT + Felt::ONE, total_supply_high); states .state_updates @@ -300,12 +299,12 @@ impl Default for Genesis { ]); Self { - parent_hash: FieldElement::ZERO, + parent_hash: Felt::ZERO, number: 0, - state_root: FieldElement::ZERO, + state_root: Felt::ZERO, timestamp: 0, gas_prices: GasPrices::default(), - sequencer_address: FieldElement::ZERO.into(), + sequencer_address: Felt::ZERO.into(), classes, allocations: BTreeMap::new(), fee_token, @@ -436,9 +435,9 @@ mod tests { // setup expected storage values - let name: FieldElement = cairo_short_string_to_felt(&fee_token.name).unwrap(); - let symbol: FieldElement = cairo_short_string_to_felt(&fee_token.symbol).unwrap(); - let decimals: FieldElement = fee_token.decimals.into(); + let name: Felt = cairo_short_string_to_felt(&fee_token.name).unwrap(); + let symbol: Felt = cairo_short_string_to_felt(&fee_token.symbol).unwrap(); + let decimals: Felt = fee_token.decimals.into(); // there are only two allocations so the total token supply is // 0xD3C21BCECCEDA1000000 * 2 = 0x1a784379d99db42000000 @@ -450,8 +449,7 @@ mod tests { fee_token_storage.insert(ERC20_SYMBOL_STORAGE_SLOT, symbol); fee_token_storage.insert(ERC20_DECIMAL_STORAGE_SLOT, decimals); fee_token_storage.insert(ERC20_TOTAL_SUPPLY_STORAGE_SLOT, total_supply_low); - fee_token_storage - .insert(ERC20_TOTAL_SUPPLY_STORAGE_SLOT + FieldElement::ONE, total_supply_high); + fee_token_storage.insert(ERC20_TOTAL_SUPPLY_STORAGE_SLOT + Felt::ONE, total_supply_high); for (address, alloc) in &allocations { if let Some(balance) = alloc.balance() { @@ -463,7 +461,7 @@ mod tests { // the storage address of low u128 of the balance let low_bal_storage_var = bal_base_storage_var; // the storage address of high u128 of the balance - let high_bal_storage_var = bal_base_storage_var + FieldElement::ONE; + let high_bal_storage_var = bal_base_storage_var + Felt::ONE; fee_token_storage.insert(low_bal_storage_var, low); fee_token_storage.insert(high_bal_storage_var, high); @@ -700,7 +698,7 @@ mod tests { Some(&total_supply_low) ); assert_eq!( - fee_token_storage.get(&(ERC20_TOTAL_SUPPLY_STORAGE_SLOT + FieldElement::ONE)), + fee_token_storage.get(&(ERC20_TOTAL_SUPPLY_STORAGE_SLOT + Felt::ONE)), Some(&total_supply_high) ); @@ -722,7 +720,7 @@ mod tests { // the storage address of low u128 of the balance let low_bal_storage_var = bal_base_storage_var; // the storage address of high u128 of the balance - let high_bal_storage_var = bal_base_storage_var + FieldElement::ONE; + let high_bal_storage_var = bal_base_storage_var + Felt::ONE; assert_eq!(fee_token_storage.get(&low_bal_storage_var), Some(&low)); assert_eq!(fee_token_storage.get(&high_bal_storage_var), Some(&high)); @@ -742,7 +740,7 @@ mod tests { "total supply must be calculated from allocations balances correctly" ); assert_eq!( - fee_token_storage.get(&(ERC20_TOTAL_SUPPLY_STORAGE_SLOT + FieldElement::ONE)), + fee_token_storage.get(&(ERC20_TOTAL_SUPPLY_STORAGE_SLOT + Felt::ONE)), Some(&actual_total_supply_high), "total supply must be calculated from allocations balances correctly" ); diff --git a/crates/katana/primitives/src/lib.rs b/crates/katana/primitives/src/lib.rs index 636a3bd7d5..43261c0d38 100644 --- a/crates/katana/primitives/src/lib.rs +++ b/crates/katana/primitives/src/lib.rs @@ -19,8 +19,4 @@ pub mod conversion; pub mod state; pub mod utils; -pub use felt::FieldElement; - -pub mod felt { - pub use starknet::core::types::{Felt as FieldElement, FromStrError}; -} +pub use starknet::core::types::{Felt, FromStrError}; diff --git a/crates/katana/primitives/src/message.rs b/crates/katana/primitives/src/message.rs index 1558fb4640..20b66fab6d 100644 --- a/crates/katana/primitives/src/message.rs +++ b/crates/katana/primitives/src/message.rs @@ -1,11 +1,11 @@ use crate::contract::ContractAddress; -use crate::FieldElement; +use crate::Felt; #[derive(Debug, Clone, PartialEq, Eq, Default)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct OrderedL2ToL1Message { pub order: u64, pub from_address: ContractAddress, - pub to_address: FieldElement, - pub payload: Vec, + pub to_address: Felt, + pub payload: Vec, } diff --git a/crates/katana/primitives/src/receipt.rs b/crates/katana/primitives/src/receipt.rs index 1f508dc04e..76f5268350 100644 --- a/crates/katana/primitives/src/receipt.rs +++ b/crates/katana/primitives/src/receipt.rs @@ -3,7 +3,7 @@ use alloy_primitives::B256; use crate::contract::ContractAddress; use crate::fee::TxFeeInfo; use crate::trace::TxResources; -use crate::FieldElement; +use crate::Felt; #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] @@ -11,9 +11,9 @@ pub struct Event { /// The contract address that emitted the event. pub from_address: ContractAddress, /// The event keys. - pub keys: Vec, + pub keys: Vec, /// The event data. - pub data: Vec, + pub data: Vec, } /// Represents a message sent to L1. @@ -23,9 +23,9 @@ pub struct MessageToL1 { /// The L2 contract address that sent the message. pub from_address: ContractAddress, /// The L1 contract address that the message is sent to. - pub to_address: FieldElement, + pub to_address: Felt, /// The payload of the message. - pub payload: Vec, + pub payload: Vec, } /// Receipt for a `Invoke` transaction. diff --git a/crates/katana/primitives/src/trace.rs b/crates/katana/primitives/src/trace.rs index f72c92b3bf..3530f5e251 100644 --- a/crates/katana/primitives/src/trace.rs +++ b/crates/katana/primitives/src/trace.rs @@ -6,7 +6,7 @@ use crate::class::ClassHash; use crate::contract::ContractAddress; use crate::event::OrderedEvent; use crate::message::OrderedL2ToL1Message; -use crate::FieldElement; +use crate::Felt; pub type ExecutionResources = vm::runners::cairo_runner::ExecutionResources; @@ -83,13 +83,13 @@ pub struct CallInfo { /// The class hash, not given if it can be deduced from the storage address. pub class_hash: Option, /// The entry point selector. - pub entry_point_selector: FieldElement, + pub entry_point_selector: Felt, /// The entry point type. pub entry_point_type: EntryPointType, /// The data used as the input to the execute entry point. - pub calldata: Vec, + pub calldata: Vec, /// The data returned by the entry point execution. - pub retdata: Vec, + pub retdata: Vec, /// The resources used by the execution. pub execution_resources: ExecutionResources, /// The list of ordered events generated by the execution. @@ -97,9 +97,9 @@ pub struct CallInfo { /// The list of ordered l2 to l1 messages generated by the execution. pub l2_to_l1_messages: Vec, /// The list of storage addresses being read during the execution. - pub storage_read_values: Vec, + pub storage_read_values: Vec, /// The list of storage addresses being accessed during the execution. - pub accessed_storage_keys: HashSet, + pub accessed_storage_keys: HashSet, /// The list of inner calls triggered by the current call. pub inner_calls: Vec, /// The total gas consumed by the call. diff --git a/crates/katana/primitives/src/transaction.rs b/crates/katana/primitives/src/transaction.rs index fbbd754170..0fe976d77b 100644 --- a/crates/katana/primitives/src/transaction.rs +++ b/crates/katana/primitives/src/transaction.rs @@ -10,10 +10,10 @@ use crate::utils::transaction::{ compute_deploy_account_v1_tx_hash, compute_deploy_account_v3_tx_hash, compute_invoke_v1_tx_hash, compute_l1_handler_tx_hash, }; -use crate::{utils, FieldElement}; +use crate::{utils, Felt}; /// The hash of a transaction. -pub type TxHash = FieldElement; +pub type TxHash = Felt; /// The sequential number for all the transactions. pub type TxNumber = u64; @@ -139,9 +139,9 @@ pub struct InvokeTxV1 { /// sender. pub nonce: Nonce, /// The data used as the input to the execute entry point of sender account contract. - pub calldata: Vec, + pub calldata: Vec, /// The transaction signature associated with the sender address. - pub signature: Vec, + pub signature: Vec, /// The max fee that the sender is willing to pay for the transaction. pub max_fee: u128, } @@ -157,24 +157,24 @@ pub struct InvokeTxV3 { pub sender_address: ContractAddress, /// The nonce value of the account. Corresponds to the number of transactions initiated by /// sender. - pub nonce: FieldElement, + pub nonce: Felt, /// The data used as the input to the execute entry point of sender account contract. - pub calldata: Vec, + pub calldata: Vec, /// The transaction signature associated with the sender address. - pub signature: Vec, + pub signature: Vec, /// Resource bounds for the transaction execution. pub resource_bounds: ResourceBoundsMapping, /// The tip for the transaction. pub tip: u64, /// Data needed to allow the paymaster to pay for the transaction in native tokens. - pub paymaster_data: Vec, + pub paymaster_data: Vec, /// Data needed to deploy the account contract from which this tx will be initiated. This field /// is used when the transaction is initiated from a address that is not yet deployed. The /// account contract will be deployed first before the function invocation is executed. /// /// The list contains the class_hash, salt, and the calldata needed for the constructor for /// account deployment. - pub account_deployment_data: Vec, + pub account_deployment_data: Vec, /// The storage domain of the account's nonce (an account has a nonce per da mode) pub nonce_data_availability_mode: DataAvailabilityMode, /// The storage domain of the account's balance from which fee will be charged @@ -242,9 +242,9 @@ pub struct DeclareTxV1 { pub sender_address: ContractAddress, /// The nonce value of the account. Corresponds to the number of transactions initiated by /// sender. - pub nonce: FieldElement, + pub nonce: Felt, /// The transaction signature associated with the sender address. - pub signature: Vec, + pub signature: Vec, /// The class hash of the contract class to be declared. pub class_hash: ClassHash, /// The max fee that the sender is willing to pay for the transaction. @@ -263,9 +263,9 @@ pub struct DeclareTxV2 { pub sender_address: ContractAddress, /// The nonce value of the account. Corresponds to the number of transactions initiated by /// sender. - pub nonce: FieldElement, + pub nonce: Felt, /// The transaction signature associated with the sender address. - pub signature: Vec, + pub signature: Vec, /// The class hash of the contract class to be declared. pub class_hash: ClassHash, /// The compiled class hash of the contract class (only if it's a Sierra class). @@ -286,9 +286,9 @@ pub struct DeclareTxV3 { pub sender_address: ContractAddress, /// The nonce value of the account. Corresponds to the number of transactions initiated by /// sender. - pub nonce: FieldElement, + pub nonce: Felt, /// The transaction signature associated with the sender address. - pub signature: Vec, + pub signature: Vec, /// The class hash of the contract class to be declared. pub class_hash: ClassHash, /// The CASM class hash of the Sierra contract class. @@ -298,9 +298,9 @@ pub struct DeclareTxV3 { /// The tip for the transaction pub tip: u64, /// Data needed to allow the paymaster to pay for the transaction in native tokens - pub paymaster_data: Vec, + pub paymaster_data: Vec, /// Data needed to deploy the account contract from which this tx will be initiated - pub account_deployment_data: Vec, + pub account_deployment_data: Vec, /// The storage domain of the account's nonce (an account has a nonce per da mode) pub nonce_data_availability_mode: DataAvailabilityMode, /// The storage domain of the account's balance from which fee will be charged @@ -360,15 +360,15 @@ pub struct L1HandlerTx { /// Amount of fee paid on L1. pub paid_fee_on_l1: u128, /// Transaction version. - pub version: FieldElement, + pub version: Felt, /// L1 to L2 message hash. pub message_hash: B256, /// The input to the L1 handler function. - pub calldata: Vec, + pub calldata: Vec, /// Contract address of the L1 handler. pub contract_address: ContractAddress, /// The L1 handler function selector. - pub entry_point_selector: FieldElement, + pub entry_point_selector: Felt, } impl L1HandlerTx { @@ -412,15 +412,15 @@ pub struct DeployAccountTxV1 { /// sender. pub nonce: Nonce, /// The transaction signature associated with the sender address. - pub signature: Vec, + pub signature: Vec, /// The hash of the contract class from which the account contract will be deployed from. pub class_hash: ClassHash, /// The contract address of the account contract that will be deployed. pub contract_address: ContractAddress, /// The salt used to generate the contract address. - pub contract_address_salt: FieldElement, + pub contract_address_salt: Felt, /// The input data to the constructor function of the contract class. - pub constructor_calldata: Vec, + pub constructor_calldata: Vec, /// The max fee that the sender is willing to pay for the transaction. pub max_fee: u128, } @@ -436,21 +436,21 @@ pub struct DeployAccountTxV3 { /// sender. pub nonce: Nonce, /// The transaction signature associated with the sender address. - pub signature: Vec, + pub signature: Vec, /// The hash of the contract class from which the account contract will be deployed from. pub class_hash: ClassHash, /// The contract address of the account contract that will be deployed. pub contract_address: ContractAddress, /// The salt used to generate the contract address. - pub contract_address_salt: FieldElement, + pub contract_address_salt: Felt, /// The input data to the constructor function of the contract class. - pub constructor_calldata: Vec, + pub constructor_calldata: Vec, /// Resource bounds for the transaction execution pub resource_bounds: ResourceBoundsMapping, /// The tip for the transaction pub tip: u64, /// Data needed to allow the paymaster to pay for the transaction in native tokens - pub paymaster_data: Vec, + pub paymaster_data: Vec, /// The storage domain of the account's nonce (an account has a nonce per da mode) pub nonce_data_availability_mode: DataAvailabilityMode, /// The storage domain of the account's balance from which fee will be charged diff --git a/crates/katana/primitives/src/utils/mod.rs b/crates/katana/primitives/src/utils/mod.rs index 9c1591434b..16f132b780 100644 --- a/crates/katana/primitives/src/utils/mod.rs +++ b/crates/katana/primitives/src/utils/mod.rs @@ -1,6 +1,6 @@ use alloy_primitives::U256; -use crate::FieldElement; +use crate::Felt; pub mod class; pub mod transaction; @@ -8,10 +8,10 @@ pub mod transaction; /// Split a [U256] into its high and low 128-bit parts in represented as [FieldElement]s. /// The first element in the returned tuple is the low part, and the second element is the high /// part. -pub fn split_u256(value: U256) -> (FieldElement, FieldElement) { +pub fn split_u256(value: U256) -> (Felt, Felt) { let low_u128: u128 = (value & U256::from(u128::MAX)).to(); let high_u128: u128 = U256::from(value >> 128).to(); - (FieldElement::from(low_u128), FieldElement::from(high_u128)) + (Felt::from(low_u128), Felt::from(high_u128)) } #[cfg(test)] @@ -27,7 +27,7 @@ mod tests { let (low, high) = split_u256(value); // Then - assert_eq!(low, FieldElement::from(u128::MAX)); - assert_eq!(high, FieldElement::from(u128::MAX)); + assert_eq!(low, Felt::from(u128::MAX)); + assert_eq!(high, Felt::from(u128::MAX)); } } diff --git a/crates/katana/primitives/src/utils/transaction.rs b/crates/katana/primitives/src/utils/transaction.rs index 6abc658df8..c8af6848a5 100644 --- a/crates/katana/primitives/src/utils/transaction.rs +++ b/crates/katana/primitives/src/utils/transaction.rs @@ -3,14 +3,14 @@ use starknet::core::crypto::compute_hash_on_elements; use starknet::core::types::{DataAvailabilityMode, EthAddress, MsgToL1, MsgToL2, ResourceBounds}; use starknet_crypto::poseidon_hash_many; -use crate::FieldElement; +use crate::Felt; /// 2^ 128 -const QUERY_VERSION_OFFSET: FieldElement = - FieldElement::from_raw([576460752142434320, 18446744073709551584, 17407, 18446744073700081665]); +const QUERY_VERSION_OFFSET: Felt = + Felt::from_raw([576460752142434320, 18446744073709551584, 17407, 18446744073700081665]); /// Cairo string for "invoke" -const PREFIX_INVOKE: FieldElement = FieldElement::from_raw([ +const PREFIX_INVOKE: Felt = Felt::from_raw([ 513398556346534256, 18446744073709551615, 18446744073709551615, @@ -18,7 +18,7 @@ const PREFIX_INVOKE: FieldElement = FieldElement::from_raw([ ]); /// Cairo string for "declare" -const PREFIX_DECLARE: FieldElement = FieldElement::from_raw([ +const PREFIX_DECLARE: Felt = Felt::from_raw([ 191557713328401194, 18446744073709551615, 18446744073709551615, @@ -26,7 +26,7 @@ const PREFIX_DECLARE: FieldElement = FieldElement::from_raw([ ]); /// Cairo string for "deploy_account" -const PREFIX_DEPLOY_ACCOUNT: FieldElement = FieldElement::from_raw([ +const PREFIX_DEPLOY_ACCOUNT: Felt = Felt::from_raw([ 461298303000467581, 18446744073709551615, 18443211694809419988, @@ -34,7 +34,7 @@ const PREFIX_DEPLOY_ACCOUNT: FieldElement = FieldElement::from_raw([ ]); /// Cairo string for "l1_handler" -const PREFIX_L1_HANDLER: FieldElement = FieldElement::from_raw([ +const PREFIX_L1_HANDLER: Felt = Felt::from_raw([ 157895833347907735, 18446744073709551615, 18446744073708665300, @@ -44,22 +44,22 @@ const PREFIX_L1_HANDLER: FieldElement = FieldElement::from_raw([ /// Compute the hash of a V1 DeployAccount transaction. #[allow(clippy::too_many_arguments)] pub fn compute_deploy_account_v1_tx_hash( - sender_address: FieldElement, - constructor_calldata: &[FieldElement], - class_hash: FieldElement, - contract_address_salt: FieldElement, + sender_address: Felt, + constructor_calldata: &[Felt], + class_hash: Felt, + contract_address_salt: Felt, max_fee: u128, - chain_id: FieldElement, - nonce: FieldElement, + chain_id: Felt, + nonce: Felt, is_query: bool, -) -> FieldElement { +) -> Felt { let calldata_to_hash = [&[class_hash, contract_address_salt], constructor_calldata].concat(); compute_hash_on_elements(&[ PREFIX_DEPLOY_ACCOUNT, - if is_query { QUERY_VERSION_OFFSET + FieldElement::ONE } else { FieldElement::ONE }, /* version */ + if is_query { QUERY_VERSION_OFFSET + Felt::ONE } else { Felt::ONE }, /* version */ sender_address, - FieldElement::ZERO, // entry_point_selector + Felt::ZERO, // entry_point_selector compute_hash_on_elements(&calldata_to_hash), max_fee.into(), chain_id, @@ -70,23 +70,23 @@ pub fn compute_deploy_account_v1_tx_hash( /// Compute the hash of a V3 DeployAccount transaction. #[allow(clippy::too_many_arguments)] pub fn compute_deploy_account_v3_tx_hash( - contract_address: FieldElement, - constructor_calldata: &[FieldElement], - class_hash: FieldElement, - contract_address_salt: FieldElement, + contract_address: Felt, + constructor_calldata: &[Felt], + class_hash: Felt, + contract_address_salt: Felt, tip: u64, l1_gas_bounds: &ResourceBounds, l2_gas_bounds: &ResourceBounds, - paymaster_data: &[FieldElement], - chain_id: FieldElement, - nonce: FieldElement, + paymaster_data: &[Felt], + chain_id: Felt, + nonce: Felt, nonce_da_mode: &DataAvailabilityMode, fee_da_mode: &DataAvailabilityMode, is_query: bool, -) -> FieldElement { +) -> Felt { poseidon_hash_many(&[ PREFIX_DEPLOY_ACCOUNT, - if is_query { QUERY_VERSION_OFFSET + FieldElement::THREE } else { FieldElement::THREE }, /* version */ + if is_query { QUERY_VERSION_OFFSET + Felt::THREE } else { Felt::THREE }, /* version */ contract_address, hash_fee_fields(tip, l1_gas_bounds, l2_gas_bounds), poseidon_hash_many(paymaster_data), @@ -101,18 +101,18 @@ pub fn compute_deploy_account_v3_tx_hash( /// Compute the hash of a V1 Declare transaction. pub fn compute_declare_v1_tx_hash( - sender_address: FieldElement, - class_hash: FieldElement, + sender_address: Felt, + class_hash: Felt, max_fee: u128, - chain_id: FieldElement, - nonce: FieldElement, + chain_id: Felt, + nonce: Felt, is_query: bool, -) -> FieldElement { +) -> Felt { compute_hash_on_elements(&[ PREFIX_DECLARE, - if is_query { QUERY_VERSION_OFFSET + FieldElement::ONE } else { FieldElement::ONE }, /* version */ + if is_query { QUERY_VERSION_OFFSET + Felt::ONE } else { Felt::ONE }, /* version */ sender_address, - FieldElement::ZERO, // entry_point_selector + Felt::ZERO, // entry_point_selector compute_hash_on_elements(&[class_hash]), max_fee.into(), chain_id, @@ -122,19 +122,19 @@ pub fn compute_declare_v1_tx_hash( /// Compute the hash of a V2 Declare transaction. pub fn compute_declare_v2_tx_hash( - sender_address: FieldElement, - class_hash: FieldElement, + sender_address: Felt, + class_hash: Felt, max_fee: u128, - chain_id: FieldElement, - nonce: FieldElement, - compiled_class_hash: FieldElement, + chain_id: Felt, + nonce: Felt, + compiled_class_hash: Felt, is_query: bool, -) -> FieldElement { +) -> Felt { compute_hash_on_elements(&[ PREFIX_DECLARE, - if is_query { QUERY_VERSION_OFFSET + FieldElement::TWO } else { FieldElement::TWO }, /* version */ + if is_query { QUERY_VERSION_OFFSET + Felt::TWO } else { Felt::TWO }, /* version */ sender_address, - FieldElement::ZERO, // entry_point_selector + Felt::ZERO, // entry_point_selector compute_hash_on_elements(&[class_hash]), max_fee.into(), chain_id, @@ -146,23 +146,23 @@ pub fn compute_declare_v2_tx_hash( /// Compute the hash of a V3 Declare transaction. #[allow(clippy::too_many_arguments)] pub fn compute_declare_v3_tx_hash( - sender_address: FieldElement, - class_hash: FieldElement, - compiled_class_hash: FieldElement, + sender_address: Felt, + class_hash: Felt, + compiled_class_hash: Felt, tip: u64, l1_gas_bounds: &ResourceBounds, l2_gas_bounds: &ResourceBounds, - paymaster_data: &[FieldElement], - chain_id: FieldElement, - nonce: FieldElement, + paymaster_data: &[Felt], + chain_id: Felt, + nonce: Felt, nonce_da_mode: &DataAvailabilityMode, fee_da_mode: &DataAvailabilityMode, - account_deployment_data: &[FieldElement], + account_deployment_data: &[Felt], is_query: bool, -) -> FieldElement { +) -> Felt { poseidon_hash_many(&[ PREFIX_DECLARE, - if is_query { QUERY_VERSION_OFFSET + FieldElement::THREE } else { FieldElement::THREE }, /* version */ + if is_query { QUERY_VERSION_OFFSET + Felt::THREE } else { Felt::THREE }, /* version */ sender_address, hash_fee_fields(tip, l1_gas_bounds, l2_gas_bounds), poseidon_hash_many(paymaster_data), @@ -177,18 +177,18 @@ pub fn compute_declare_v3_tx_hash( /// Compute the hash of a V1 Invoke transaction. pub fn compute_invoke_v1_tx_hash( - sender_address: FieldElement, - calldata: &[FieldElement], + sender_address: Felt, + calldata: &[Felt], max_fee: u128, - chain_id: FieldElement, - nonce: FieldElement, + chain_id: Felt, + nonce: Felt, is_query: bool, -) -> FieldElement { +) -> Felt { compute_hash_on_elements(&[ PREFIX_INVOKE, - if is_query { QUERY_VERSION_OFFSET + FieldElement::ONE } else { FieldElement::ONE }, /* version */ + if is_query { QUERY_VERSION_OFFSET + Felt::ONE } else { Felt::ONE }, /* version */ sender_address, - FieldElement::ZERO, // entry_point_selector + Felt::ZERO, // entry_point_selector compute_hash_on_elements(calldata), max_fee.into(), chain_id, @@ -199,22 +199,22 @@ pub fn compute_invoke_v1_tx_hash( /// Compute the hash of a V3 Invoke transaction. #[allow(clippy::too_many_arguments)] pub fn compute_invoke_v3_tx_hash( - sender_address: FieldElement, - calldata: &[FieldElement], + sender_address: Felt, + calldata: &[Felt], tip: u64, l1_gas_bounds: &ResourceBounds, l2_gas_bounds: &ResourceBounds, - paymaster_data: &[FieldElement], - chain_id: FieldElement, - nonce: FieldElement, + paymaster_data: &[Felt], + chain_id: Felt, + nonce: Felt, nonce_da_mode: &DataAvailabilityMode, fee_da_mode: &DataAvailabilityMode, - account_deployment_data: &[FieldElement], + account_deployment_data: &[Felt], is_query: bool, -) -> FieldElement { +) -> Felt { poseidon_hash_many(&[ PREFIX_INVOKE, - if is_query { QUERY_VERSION_OFFSET + FieldElement::THREE } else { FieldElement::THREE }, /* version */ + if is_query { QUERY_VERSION_OFFSET + Felt::THREE } else { Felt::THREE }, /* version */ sender_address, hash_fee_fields(tip, l1_gas_bounds, l2_gas_bounds), poseidon_hash_many(paymaster_data), @@ -239,20 +239,20 @@ pub fn compute_invoke_v3_tx_hash( /// [Deoxys]: https://github.com/KasarLabs/deoxys/blob/82c49acdaa1167bc8dc67a3f6ad3d6856c6c7e89/crates/primitives/transactions/src/compute_hash.rs#L142-L151 /// [Starknet docs]: https://docs.starknet.io/architecture-and-concepts/network-architecture/messaging-mechanism/#hashing_l1-l2 pub fn compute_l1_handler_tx_hash( - version: FieldElement, - contract_address: FieldElement, - entry_point_selector: FieldElement, - calldata: &[FieldElement], - chain_id: FieldElement, - nonce: FieldElement, -) -> FieldElement { + version: Felt, + contract_address: Felt, + entry_point_selector: Felt, + calldata: &[Felt], + chain_id: Felt, + nonce: Felt, +) -> Felt { compute_hash_on_elements(&[ PREFIX_L1_HANDLER, version, contract_address, entry_point_selector, compute_hash_on_elements(calldata), - FieldElement::ZERO, // No fee on L2 for L1 handler tx + Felt::ZERO, // No fee on L2 for L1 handler tx chain_id, nonce, ]) @@ -262,9 +262,9 @@ pub fn compute_l1_handler_tx_hash( /// /// The hash that is used to consume the message in L1. pub fn compute_l2_to_l1_message_hash( - from_address: FieldElement, - to_address: FieldElement, - payload: &[FieldElement], + from_address: Felt, + to_address: Felt, + payload: &[Felt], ) -> B256 { let msg = MsgToL1 { from_address, to_address, payload: payload.to_vec() }; B256::from_slice(msg.hash().as_bytes()) @@ -275,16 +275,16 @@ pub fn compute_l2_to_l1_message_hash( /// Computes the hash of a L1 to L2 message. pub fn compute_l1_to_l2_message_hash( from_address: EthAddress, - to_address: FieldElement, - selector: FieldElement, - payload: &[FieldElement], + to_address: Felt, + selector: Felt, + payload: &[Felt], nonce: u64, ) -> B256 { let msg = MsgToL2 { from_address, to_address, selector, payload: payload.to_vec(), nonce }; B256::from_slice(msg.hash().as_bytes()) } -fn encode_gas_bound(name: &[u8], bound: &ResourceBounds) -> FieldElement { +fn encode_gas_bound(name: &[u8], bound: &ResourceBounds) -> Felt { let mut buffer = [0u8; 32]; let (remainder, max_price) = buffer.split_at_mut(128 / 8); let (gas_kind, max_amount) = remainder.split_at_mut(64 / 8); @@ -294,14 +294,14 @@ fn encode_gas_bound(name: &[u8], bound: &ResourceBounds) -> FieldElement { max_amount.copy_from_slice(&bound.max_amount.to_be_bytes()); max_price.copy_from_slice(&bound.max_price_per_unit.to_be_bytes()); - FieldElement::from_bytes_be(&buffer) + Felt::from_bytes_be(&buffer) } fn hash_fee_fields( tip: u64, l1_gas_bounds: &ResourceBounds, l2_gas_bounds: &ResourceBounds, -) -> FieldElement { +) -> Felt { poseidon_hash_many(&[ tip.into(), encode_gas_bound(b"L1_GAS", l1_gas_bounds), @@ -312,10 +312,10 @@ fn hash_fee_fields( fn encode_da_mode( nonce_da_mode: &DataAvailabilityMode, fee_da_mode: &DataAvailabilityMode, -) -> FieldElement { +) -> Felt { let nonce = (*nonce_da_mode as u64) << 32; let fee = *fee_da_mode as u64; - FieldElement::from(nonce + fee) + Felt::from(nonce + fee) } #[cfg(test)] @@ -329,7 +329,7 @@ mod tests { #[test] fn test_query_version_offset() { // 2^ 128 - assert_eq!(QUERY_VERSION_OFFSET, FieldElement::TWO.pow(128u8)); + assert_eq!(QUERY_VERSION_OFFSET, Felt::TWO.pow(128u8)); } #[test] @@ -359,7 +359,7 @@ mod tests { let salt = felt!("0x43a8fbe19d5ace41a2328bb870143241831180eb3c3c48096642d63709c3096"); let max_fee = felt!("0x38d7ea4c68000"); let chain_id = ChainId::MAINNET.id(); - let nonce = FieldElement::ZERO; + let nonce = Felt::ZERO; let actual_hash = compute_deploy_account_v1_tx_hash( contract_address, diff --git a/crates/katana/rpc/rpc-api/src/dev.rs b/crates/katana/rpc/rpc-api/src/dev.rs index 3de14ac807..7e7dc17073 100644 --- a/crates/katana/rpc/rpc-api/src/dev.rs +++ b/crates/katana/rpc/rpc-api/src/dev.rs @@ -1,6 +1,6 @@ use jsonrpsee::core::RpcResult; use jsonrpsee::proc_macros::rpc; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use katana_rpc_types::account::Account; #[cfg_attr(not(feature = "client"), rpc(server, namespace = "dev"))] @@ -19,12 +19,8 @@ pub trait DevApi { async fn increase_next_block_timestamp(&self, timestamp: u64) -> RpcResult<()>; #[method(name = "setStorageAt")] - async fn set_storage_at( - &self, - contract_address: FieldElement, - key: FieldElement, - value: FieldElement, - ) -> RpcResult<()>; + async fn set_storage_at(&self, contract_address: Felt, key: Felt, value: Felt) + -> RpcResult<()>; #[method(name = "predeployedAccounts")] async fn predeployed_accounts(&self) -> RpcResult>; diff --git a/crates/katana/rpc/rpc-api/src/starknet.rs b/crates/katana/rpc/rpc-api/src/starknet.rs index 9ca52b55db..378a48bcb9 100644 --- a/crates/katana/rpc/rpc-api/src/starknet.rs +++ b/crates/katana/rpc/rpc-api/src/starknet.rs @@ -4,7 +4,7 @@ use jsonrpsee::core::RpcResult; use jsonrpsee::proc_macros::rpc; use katana_primitives::block::{BlockIdOrTag, BlockNumber}; use katana_primitives::transaction::TxHash; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use katana_rpc_types::block::{ BlockHashAndNumber, BlockTxCount, MaybePendingBlockWithReceipts, MaybePendingBlockWithTxHashes, MaybePendingBlockWithTxs, @@ -67,8 +67,8 @@ pub trait StarknetApi { #[method(name = "getStorageAt")] async fn get_storage_at( &self, - contract_address: FieldElement, - key: FieldElement, + contract_address: Felt, + key: Felt, block_id: BlockIdOrTag, ) -> RpcResult; @@ -101,11 +101,8 @@ pub trait StarknetApi { /// Get the contract class definition in the given block associated with the given hash. #[method(name = "getClass")] - async fn get_class( - &self, - block_id: BlockIdOrTag, - class_hash: FieldElement, - ) -> RpcResult; + async fn get_class(&self, block_id: BlockIdOrTag, class_hash: Felt) + -> RpcResult; /// Get the contract class hash in the given block for the contract deployed at the given /// address. @@ -113,7 +110,7 @@ pub trait StarknetApi { async fn get_class_hash_at( &self, block_id: BlockIdOrTag, - contract_address: FieldElement, + contract_address: Felt, ) -> RpcResult; /// Get the contract class definition in the given block at the given address. @@ -121,7 +118,7 @@ pub trait StarknetApi { async fn get_class_at( &self, block_id: BlockIdOrTag, - contract_address: FieldElement, + contract_address: Felt, ) -> RpcResult; /// Get the number of transactions in a block given a block id. @@ -180,7 +177,7 @@ pub trait StarknetApi { async fn get_nonce( &self, block_id: BlockIdOrTag, - contract_address: FieldElement, + contract_address: Felt, ) -> RpcResult; } diff --git a/crates/katana/rpc/rpc-types-builder/src/state_update.rs b/crates/katana/rpc/rpc-types-builder/src/state_update.rs index 9f0fa78d0c..8d898485d0 100644 --- a/crates/katana/rpc/rpc-types-builder/src/state_update.rs +++ b/crates/katana/rpc/rpc-types-builder/src/state_update.rs @@ -1,5 +1,5 @@ use katana_primitives::block::BlockHashOrNumber; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use katana_provider::traits::block::{BlockHashProvider, BlockNumberProvider}; use katana_provider::traits::state::StateRootProvider; use katana_provider::traits::state_update::StateUpdateProvider; @@ -37,7 +37,7 @@ where .expect("should exist if block exists"); match block_num { - 0 => FieldElement::ZERO, + 0 => Felt::ZERO, _ => StateRootProvider::state_root(&self.provider, (block_num - 1).into())? .expect("should exist if not genesis"), } diff --git a/crates/katana/rpc/rpc-types/src/account.rs b/crates/katana/rpc/rpc-types/src/account.rs index 47fc8b225f..bc8e759765 100644 --- a/crates/katana/rpc/rpc-types/src/account.rs +++ b/crates/katana/rpc/rpc-types/src/account.rs @@ -2,7 +2,7 @@ use alloy_primitives::U256; use katana_primitives::class::ClassHash; use katana_primitives::contract::ContractAddress; use katana_primitives::genesis::allocation::GenesisAccountAlloc; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use serde::{Deserialize, Serialize}; use serde_with::serde_as; use starknet::core::serde::unsigned_field_element::{UfeHex, UfeHexOption}; @@ -13,10 +13,10 @@ use starknet::core::serde::unsigned_field_element::{UfeHex, UfeHexOption}; pub struct Account { pub address: ContractAddress, #[serde_as(as = "UfeHex")] - pub public_key: FieldElement, + pub public_key: Felt, #[serde_as(as = "UfeHexOption")] #[serde(skip_serializing_if = "Option::is_none")] - pub private_key: Option, + pub private_key: Option, #[serde_as(as = "UfeHex")] pub class_hash: ClassHash, pub balance: U256, diff --git a/crates/katana/rpc/rpc-types/src/lib.rs b/crates/katana/rpc/rpc-types/src/lib.rs index 61535c59de..708b905994 100644 --- a/crates/katana/rpc/rpc-types/src/lib.rs +++ b/crates/katana/rpc/rpc-types/src/lib.rs @@ -24,22 +24,22 @@ use starknet::core::serde::unsigned_field_element::UfeHex; /// default. #[serde_as] #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct FeltAsHex(#[serde_as(serialize_as = "UfeHex")] katana_primitives::FieldElement); +pub struct FeltAsHex(#[serde_as(serialize_as = "UfeHex")] katana_primitives::Felt); -impl From for FeltAsHex { - fn from(value: katana_primitives::FieldElement) -> Self { +impl From for FeltAsHex { + fn from(value: katana_primitives::Felt) -> Self { Self(value) } } -impl From for katana_primitives::FieldElement { +impl From for katana_primitives::Felt { fn from(value: FeltAsHex) -> Self { value.0 } } impl Deref for FeltAsHex { - type Target = katana_primitives::FieldElement; + type Target = katana_primitives::Felt; fn deref(&self) -> &Self::Target { &self.0 } diff --git a/crates/katana/rpc/rpc-types/src/message.rs b/crates/katana/rpc/rpc-types/src/message.rs index 5014796104..120ecf28ff 100644 --- a/crates/katana/rpc/rpc-types/src/message.rs +++ b/crates/katana/rpc/rpc-types/src/message.rs @@ -1,7 +1,7 @@ use katana_primitives::chain::ChainId; use katana_primitives::transaction::L1HandlerTx; use katana_primitives::utils::transaction::compute_l2_to_l1_message_hash; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Serialize, Deserialize)] @@ -11,12 +11,12 @@ impl MsgFromL1 { pub fn into_tx_with_chain_id(self, chain_id: ChainId) -> L1HandlerTx { // Set the L1 to L2 message nonce to 0, because this is just used // for the `estimateMessageFee` RPC. - let nonce = FieldElement::ZERO; + let nonce = Felt::ZERO; let message_hash = compute_l2_to_l1_message_hash( // This conversion will never fail bcs `from_address` is 20 bytes and the it will only // fail if the slice is > 32 bytes - FieldElement::from_bytes_be_slice(self.0.from_address.as_bytes()), + Felt::from_bytes_be_slice(self.0.from_address.as_bytes()), self.0.to_address, &self.0.payload, ); @@ -26,7 +26,7 @@ impl MsgFromL1 { chain_id, message_hash, calldata: self.0.payload, - version: FieldElement::ZERO, + version: Felt::ZERO, paid_fee_on_l1: Default::default(), contract_address: self.0.to_address.into(), entry_point_selector: self.0.entry_point_selector, diff --git a/crates/katana/rpc/rpc-types/src/transaction.rs b/crates/katana/rpc/rpc-types/src/transaction.rs index 83116798f7..231ce2d771 100644 --- a/crates/katana/rpc/rpc-types/src/transaction.rs +++ b/crates/katana/rpc/rpc-types/src/transaction.rs @@ -13,7 +13,7 @@ use katana_primitives::transaction::{ DeclareTx, DeclareTxV1, DeclareTxV2, DeclareTxV3, DeclareTxWithClass, DeployAccountTx, DeployAccountTxV1, DeployAccountTxV3, InvokeTx, InvokeTxV1, InvokeTxV3, TxHash, TxWithHash, }; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use num_traits::ToPrimitive; use serde::{Deserialize, Serialize}; use starknet::core::types::{ @@ -188,7 +188,7 @@ impl BroadcastedDeployAccountTx { tx.contract_address_salt, tx.class_hash, &tx.constructor_calldata, - FieldElement::ZERO, + Felt::ZERO, ); DeployAccountTx::V1(DeployAccountTxV1 { @@ -208,7 +208,7 @@ impl BroadcastedDeployAccountTx { tx.contract_address_salt, tx.class_hash, &tx.constructor_calldata, - FieldElement::ZERO, + Felt::ZERO, ); DeployAccountTx::V3(DeployAccountTxV3 { @@ -459,7 +459,7 @@ impl From for DeployAccountTx { tx.contract_address_salt, tx.class_hash, &tx.constructor_calldata, - FieldElement::ZERO, + Felt::ZERO, ); DeployAccountTx::V1(DeployAccountTxV1 { @@ -479,7 +479,7 @@ impl From for DeployAccountTx { tx.contract_address_salt, tx.class_hash, &tx.constructor_calldata, - FieldElement::ZERO, + Felt::ZERO, ); DeployAccountTx::V3(DeployAccountTxV3 { diff --git a/crates/katana/rpc/rpc/src/dev.rs b/crates/katana/rpc/rpc/src/dev.rs index afe4e80023..f2d039bcdf 100644 --- a/crates/katana/rpc/rpc/src/dev.rs +++ b/crates/katana/rpc/rpc/src/dev.rs @@ -4,7 +4,7 @@ use jsonrpsee::core::{async_trait, Error}; use katana_core::backend::Backend; use katana_core::service::block_producer::{BlockProducer, BlockProducerMode, PendingExecutor}; use katana_executor::ExecutorFactory; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use katana_rpc_api::dev::DevApiServer; use katana_rpc_types::account::Account; use katana_rpc_types::error::dev::DevApiError; @@ -81,9 +81,9 @@ impl DevApiServer for DevApi { async fn set_storage_at( &self, - _contract_address: FieldElement, - _key: FieldElement, - _value: FieldElement, + _contract_address: Felt, + _key: Felt, + _value: Felt, ) -> Result<(), Error> { // self.sequencer // .set_storage_at(contract_address.into(), key, value) diff --git a/crates/katana/rpc/rpc/src/starknet/mod.rs b/crates/katana/rpc/rpc/src/starknet/mod.rs index 00f68a4d6c..a5ec301e89 100644 --- a/crates/katana/rpc/rpc/src/starknet/mod.rs +++ b/crates/katana/rpc/rpc/src/starknet/mod.rs @@ -20,7 +20,7 @@ use katana_primitives::conversion::rpc::legacy_inner_to_rpc_class; use katana_primitives::env::BlockEnv; use katana_primitives::event::ContinuationToken; use katana_primitives::transaction::{ExecutableTxWithHash, TxHash, TxWithHash}; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use katana_provider::traits::block::{BlockHashProvider, BlockIdReader, BlockNumberProvider}; use katana_provider::traits::contract::ContractClassProvider; use katana_provider::traits::env::BlockEnvProvider; @@ -336,7 +336,7 @@ impl StarknetApi { from_block: BlockIdOrTag, to_block: BlockIdOrTag, address: Option, - keys: Option>>, + keys: Option>>, continuation_token: Option, chunk_size: u64, ) -> Result { diff --git a/crates/katana/rpc/rpc/src/starknet/read.rs b/crates/katana/rpc/rpc/src/starknet/read.rs index d1bd8d9e33..548d1aff82 100644 --- a/crates/katana/rpc/rpc/src/starknet/read.rs +++ b/crates/katana/rpc/rpc/src/starknet/read.rs @@ -3,7 +3,7 @@ use katana_executor::{EntryPointCall, ExecutionResult, ExecutorFactory}; use katana_primitives::block::{BlockHashOrNumber, BlockIdOrTag, FinalityStatus, PartialHeader}; use katana_primitives::transaction::{ExecutableTx, ExecutableTxWithHash, TxHash}; use katana_primitives::version::CURRENT_STARKNET_VERSION; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use katana_provider::traits::block::{BlockHashProvider, BlockIdReader, BlockNumberProvider}; use katana_provider::traits::transaction::TransactionProvider; use katana_rpc_api::starknet::StarknetApiServer; @@ -35,7 +35,7 @@ impl StarknetApiServer for StarknetApi { async fn get_nonce( &self, block_id: BlockIdOrTag, - contract_address: FieldElement, + contract_address: Felt, ) -> RpcResult { Ok(self.nonce_at(block_id, contract_address.into()).await?.into()) } @@ -44,7 +44,7 @@ impl StarknetApiServer for StarknetApi { Ok(self.latest_block_number().await?) } - async fn get_transaction_by_hash(&self, transaction_hash: FieldElement) -> RpcResult { + async fn get_transaction_by_hash(&self, transaction_hash: Felt) -> RpcResult { Ok(self.transaction(transaction_hash).await?.into()) } @@ -55,7 +55,7 @@ impl StarknetApiServer for StarknetApi { async fn get_class_at( &self, block_id: BlockIdOrTag, - contract_address: FieldElement, + contract_address: Felt, ) -> RpcResult { Ok(self.class_at_address(block_id, contract_address.into()).await?) } @@ -296,7 +296,7 @@ impl StarknetApiServer for StarknetApi { async fn get_transaction_receipt( &self, - transaction_hash: FieldElement, + transaction_hash: Felt, ) -> RpcResult { self.on_io_blocking_task(move |this| { let provider = this.inner.backend.blockchain.provider(); @@ -341,7 +341,7 @@ impl StarknetApiServer for StarknetApi { async fn get_class_hash_at( &self, block_id: BlockIdOrTag, - contract_address: FieldElement, + contract_address: Felt, ) -> RpcResult { Ok(self.class_hash_at_address(block_id, contract_address.into()).await?.into()) } @@ -349,7 +349,7 @@ impl StarknetApiServer for StarknetApi { async fn get_class( &self, block_id: BlockIdOrTag, - class_hash: FieldElement, + class_hash: Felt, ) -> RpcResult { Ok(self.class_at_hash(block_id, class_hash).await?) } @@ -413,8 +413,8 @@ impl StarknetApiServer for StarknetApi { async fn get_storage_at( &self, - contract_address: FieldElement, - key: FieldElement, + contract_address: Felt, + key: Felt, block_id: BlockIdOrTag, ) -> RpcResult { self.on_io_blocking_task(move |this| { diff --git a/crates/katana/rpc/rpc/src/utils/events.rs b/crates/katana/rpc/rpc/src/utils/events.rs index a92f3ec1bf..2df9ef2f03 100644 --- a/crates/katana/rpc/rpc/src/utils/events.rs +++ b/crates/katana/rpc/rpc/src/utils/events.rs @@ -8,7 +8,7 @@ use katana_primitives::contract::ContractAddress; use katana_primitives::event::ContinuationToken; use katana_primitives::receipt::Event; use katana_primitives::transaction::TxHash; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use katana_provider::error::ProviderError; use katana_provider::traits::block::BlockProvider; use katana_provider::traits::transaction::ReceiptProvider; @@ -42,7 +42,7 @@ pub struct Filter { /// contract are considered. pub address: Option, /// The keys to filter by. - pub keys: Option>>, + pub keys: Option>>, } /// Internal cursor diff --git a/crates/katana/storage/codecs/src/lib.rs b/crates/katana/storage/codecs/src/lib.rs index ff18972ec0..822ff01510 100644 --- a/crates/katana/storage/codecs/src/lib.rs +++ b/crates/katana/storage/codecs/src/lib.rs @@ -1,5 +1,5 @@ use katana_primitives::contract::ContractAddress; -use katana_primitives::FieldElement; +use katana_primitives::Felt; /// Trait for writing compact representation of the types that implement it. pub trait Compact: Sized { @@ -63,9 +63,9 @@ macro_rules! impl_compact_felt { if len > 0 { let mut arr = [0u8; 32]; arr[32 - len..].copy_from_slice(&buf[..len]); - (FieldElement::from_bytes_be(&arr).into(), &buf[len..]) + (Felt::from_bytes_be(&arr).into(), &buf[len..]) } else { - (FieldElement::ZERO.into(), buf) + (Felt::ZERO.into(), buf) } } } @@ -74,20 +74,20 @@ macro_rules! impl_compact_felt { } impl_compact_for_uints!(u64); -impl_compact_felt!(FieldElement, ContractAddress); +impl_compact_felt!(Felt, ContractAddress); #[cfg(test)] mod tests { - use katana_primitives::FieldElement; + use katana_primitives::Felt; use crate::Compact; #[test] fn felt_compact() { let mut compacted = vec![]; - let value = FieldElement::from(124123137u128); + let value = Felt::from(124123137u128); let compacted_size = value.to_compact(&mut compacted); - let (uncompacted, _) = FieldElement::from_compact(&compacted, compacted_size); + let (uncompacted, _) = Felt::from_compact(&compacted, compacted_size); assert_eq!(value, uncompacted); } diff --git a/crates/katana/storage/db/src/codecs/mod.rs b/crates/katana/storage/db/src/codecs/mod.rs index 9c57ec7034..049168919c 100644 --- a/crates/katana/storage/db/src/codecs/mod.rs +++ b/crates/katana/storage/db/src/codecs/mod.rs @@ -4,7 +4,7 @@ pub mod postcard; use katana_primitives::block::FinalityStatus; use katana_primitives::class::FlattenedSierraClass; use katana_primitives::contract::ContractAddress; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use crate::error::CodecError; @@ -62,7 +62,7 @@ macro_rules! impl_encode_and_decode_for_felts { impl Decode for $ty { fn decode>(bytes: B) -> Result { - Ok(FieldElement::from_bytes_be_slice(bytes.as_ref()).into()) + Ok(Felt::from_bytes_be_slice(bytes.as_ref()).into()) } } )* @@ -70,7 +70,7 @@ macro_rules! impl_encode_and_decode_for_felts { } impl_encode_and_decode_for_uints!(u64); -impl_encode_and_decode_for_felts!(FieldElement, ContractAddress); +impl_encode_and_decode_for_felts!(Felt, ContractAddress); impl Compress for FlattenedSierraClass { type Compressed = Vec; diff --git a/crates/katana/storage/db/src/codecs/postcard.rs b/crates/katana/storage/db/src/codecs/postcard.rs index 83f46f8d13..7acf83bead 100644 --- a/crates/katana/storage/db/src/codecs/postcard.rs +++ b/crates/katana/storage/db/src/codecs/postcard.rs @@ -3,7 +3,7 @@ use katana_primitives::contract::{ContractAddress, GenericContractInfo}; use katana_primitives::receipt::Receipt; use katana_primitives::trace::TxExecInfo; use katana_primitives::transaction::Tx; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use postcard; use super::{Compress, Decompress}; @@ -37,7 +37,7 @@ impl_compress_and_decompress_for_table_values!( TxExecInfo, Header, Receipt, - FieldElement, + Felt, ContractAddress, BlockList, GenericContractInfo, diff --git a/crates/katana/storage/db/src/mdbx/mod.rs b/crates/katana/storage/db/src/mdbx/mod.rs index 9948f506b3..aba55be121 100644 --- a/crates/katana/storage/db/src/mdbx/mod.rs +++ b/crates/katana/storage/db/src/mdbx/mod.rs @@ -208,7 +208,7 @@ mod tests { use katana_primitives::block::Header; use katana_primitives::contract::{ContractAddress, GenericContractInfo}; - use katana_primitives::FieldElement; + use katana_primitives::Felt; use starknet::macros::felt; use super::*; @@ -365,12 +365,12 @@ mod tests { let mut dup_cursor = tx.cursor::().unwrap(); let subkey = felt!("0x9"); - let value = FieldElement::from(1u8); + let value = Felt::from(1u8); let entry1 = StorageEntry { key: subkey, value }; dup_cursor.upsert(key, entry1).expect(ERROR_UPSERT); assert_eq!(dup_cursor.seek_by_key_subkey(key, subkey), Ok(Some(entry1))); - let value = FieldElement::from(2u8); + let value = Felt::from(2u8); let entry2 = StorageEntry { key: subkey, value }; dup_cursor.upsert(key, entry2).expect(ERROR_UPSERT); assert_eq!(dup_cursor.seek_by_key_subkey(key, subkey), Ok(Some(entry1))); @@ -408,16 +408,16 @@ mod tests { // PUT (0, 0), (1, 0), (2, 0) let tx = db.tx_mut().expect(ERROR_INIT_TX); - (0..3).try_for_each(|key| tx.put::(key, FieldElement::ZERO)).expect(ERROR_PUT); + (0..3).try_for_each(|key| tx.put::(key, Felt::ZERO)).expect(ERROR_PUT); tx.commit().expect(ERROR_COMMIT); let tx = db.tx().expect(ERROR_INIT_TX); let mut cursor = tx.cursor::().expect(ERROR_INIT_CURSOR); let mut walker = Walker::new(&mut cursor, None); - assert_eq!(walker.next(), Some(Ok((0, FieldElement::ZERO)))); - assert_eq!(walker.next(), Some(Ok((1, FieldElement::ZERO)))); - assert_eq!(walker.next(), Some(Ok((2, FieldElement::ZERO)))); + assert_eq!(walker.next(), Some(Ok((0, Felt::ZERO)))); + assert_eq!(walker.next(), Some(Ok((1, Felt::ZERO)))); + assert_eq!(walker.next(), Some(Ok((2, Felt::ZERO)))); assert_eq!(walker.next(), None); } @@ -427,9 +427,7 @@ mod tests { // PUT let tx = db.tx_mut().expect(ERROR_INIT_TX); - (0..=4) - .try_for_each(|key| tx.put::(key, FieldElement::ZERO)) - .expect(ERROR_PUT); + (0..=4).try_for_each(|key| tx.put::(key, Felt::ZERO)).expect(ERROR_PUT); tx.commit().expect(ERROR_COMMIT); let key_to_insert = 5; @@ -437,19 +435,19 @@ mod tests { let mut cursor = tx.cursor::().expect(ERROR_INIT_CURSOR); // INSERT - assert_eq!(cursor.insert(key_to_insert, FieldElement::ZERO), Ok(())); - assert_eq!(cursor.current(), Ok(Some((key_to_insert, FieldElement::ZERO)))); + assert_eq!(cursor.insert(key_to_insert, Felt::ZERO), Ok(())); + assert_eq!(cursor.current(), Ok(Some((key_to_insert, Felt::ZERO)))); // INSERT (failure) assert_eq!( - cursor.insert(key_to_insert, FieldElement::ZERO), + cursor.insert(key_to_insert, Felt::ZERO), Err(DatabaseError::Write { table: BlockHashes::NAME, error: libmdbx::Error::KeyExist, key: Box::from(key_to_insert.encode()) }) ); - assert_eq!(cursor.current(), Ok(Some((key_to_insert, FieldElement::ZERO)))); + assert_eq!(cursor.current(), Ok(Some((key_to_insert, Felt::ZERO)))); tx.commit().expect(ERROR_COMMIT); diff --git a/crates/katana/storage/provider/src/lib.rs b/crates/katana/storage/provider/src/lib.rs index 41750e2d90..b7c1f7b430 100644 --- a/crates/katana/storage/provider/src/lib.rs +++ b/crates/katana/storage/provider/src/lib.rs @@ -12,7 +12,7 @@ use katana_primitives::receipt::Receipt; use katana_primitives::state::{StateUpdates, StateUpdatesWithDeclaredClasses}; use katana_primitives::trace::TxExecInfo; use katana_primitives::transaction::{TxHash, TxNumber, TxWithHash}; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use traits::block::{BlockIdReader, BlockStatusProvider, BlockWriter}; use traits::contract::{ContractClassProvider, ContractClassWriter}; use traits::env::BlockEnvProvider; @@ -312,7 +312,7 @@ impl StateRootProvider for BlockchainProvider where Db: StateRootProvider, { - fn state_root(&self, block_id: BlockHashOrNumber) -> ProviderResult> { + fn state_root(&self, block_id: BlockHashOrNumber) -> ProviderResult> { self.provider.state_root(block_id) } } diff --git a/crates/katana/storage/provider/src/providers/db/mod.rs b/crates/katana/storage/provider/src/providers/db/mod.rs index 16acb00476..2954dce1c2 100644 --- a/crates/katana/storage/provider/src/providers/db/mod.rs +++ b/crates/katana/storage/provider/src/providers/db/mod.rs @@ -28,7 +28,7 @@ use katana_primitives::receipt::Receipt; use katana_primitives::state::{StateUpdates, StateUpdatesWithDeclaredClasses}; use katana_primitives::trace::TxExecInfo; use katana_primitives::transaction::{TxHash, TxNumber, TxWithHash}; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use crate::error::ProviderError; use crate::traits::block::{ @@ -245,7 +245,7 @@ impl BlockStatusProvider for DbProvider { } impl StateRootProvider for DbProvider { - fn state_root(&self, block_id: BlockHashOrNumber) -> ProviderResult> { + fn state_root(&self, block_id: BlockHashOrNumber) -> ProviderResult> { let db_tx = self.0.tx()?; let block_num = match block_id { diff --git a/crates/katana/storage/provider/src/providers/fork/backend.rs b/crates/katana/storage/provider/src/providers/fork/backend.rs index 72756fd803..8b41259fd1 100644 --- a/crates/katana/storage/provider/src/providers/fork/backend.rs +++ b/crates/katana/storage/provider/src/providers/fork/backend.rs @@ -18,7 +18,7 @@ use katana_primitives::conversion::rpc::{ compiled_class_hash_from_flattened_sierra_class, flattened_sierra_to_compiled_class, legacy_rpc_to_compiled_class, }; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use parking_lot::Mutex; use starknet::core::types::{BlockId, ContractClass as RpcContractClass, StarknetError}; use starknet::providers::{Provider, ProviderError as StarknetProviderError}; @@ -186,7 +186,7 @@ where BackendRequest::Nonce(Request { payload, sender }) => { let fut = Box::pin(async move { let res = provider - .get_nonce(block, FieldElement::from(payload)) + .get_nonce(block, Felt::from(payload)) .await .map_err(BackendError::StarknetProvider); @@ -199,7 +199,7 @@ where BackendRequest::Storage(Request { payload: (addr, key), sender }) => { let fut = Box::pin(async move { let res = provider - .get_storage_at(FieldElement::from(addr), key, block) + .get_storage_at(Felt::from(addr), key, block) .await .map_err(BackendError::StarknetProvider); @@ -212,7 +212,7 @@ where BackendRequest::ClassHash(Request { payload, sender }) => { let fut = Box::pin(async move { let res = provider - .get_class_hash_at(block, FieldElement::from(payload)) + .get_class_hash_at(block, Felt::from(payload)) .await .map_err(BackendError::StarknetProvider); diff --git a/crates/katana/storage/provider/src/providers/fork/mod.rs b/crates/katana/storage/provider/src/providers/fork/mod.rs index 114857d4c6..104b1a9328 100644 --- a/crates/katana/storage/provider/src/providers/fork/mod.rs +++ b/crates/katana/storage/provider/src/providers/fork/mod.rs @@ -410,7 +410,7 @@ impl StateRootProvider for ForkedProvider { fn state_root( &self, block_id: BlockHashOrNumber, - ) -> ProviderResult> { + ) -> ProviderResult> { let state_root = self.block_number_by_id(block_id)?.and_then(|num| { self.storage.read().block_headers.get(&num).map(|header| header.state_root) }); diff --git a/crates/katana/storage/provider/src/providers/in_memory/mod.rs b/crates/katana/storage/provider/src/providers/in_memory/mod.rs index 6a27bad218..2fc8b7aac4 100644 --- a/crates/katana/storage/provider/src/providers/in_memory/mod.rs +++ b/crates/katana/storage/provider/src/providers/in_memory/mod.rs @@ -445,7 +445,7 @@ impl StateRootProvider for InMemoryProvider { fn state_root( &self, block_id: BlockHashOrNumber, - ) -> ProviderResult> { + ) -> ProviderResult> { let state_root = self.block_number_by_id(block_id)?.and_then(|num| { self.storage.read().block_headers.get(&num).map(|header| header.state_root) }); diff --git a/crates/katana/storage/provider/src/traits/state.rs b/crates/katana/storage/provider/src/traits/state.rs index 3c80891aac..736534a861 100644 --- a/crates/katana/storage/provider/src/traits/state.rs +++ b/crates/katana/storage/provider/src/traits/state.rs @@ -1,7 +1,7 @@ use katana_primitives::block::BlockHashOrNumber; use katana_primitives::class::ClassHash; use katana_primitives::contract::{ContractAddress, Nonce, StorageKey, StorageValue}; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use super::contract::ContractClassProvider; use crate::ProviderResult; @@ -9,7 +9,7 @@ use crate::ProviderResult; #[auto_impl::auto_impl(&, Box, Arc)] pub trait StateRootProvider: Send + Sync { /// Retrieves the state root of a block. - fn state_root(&self, block_id: BlockHashOrNumber) -> ProviderResult>; + fn state_root(&self, block_id: BlockHashOrNumber) -> ProviderResult>; } #[auto_impl::auto_impl(&, Box, Arc)] @@ -26,7 +26,7 @@ pub trait StateProvider: ContractClassProvider + Send + Sync + std::fmt::Debug { /// Returns the class hash of a contract. fn class_hash_of_contract(&self, address: ContractAddress) - -> ProviderResult>; + -> ProviderResult>; } /// A type which can create [`StateProvider`] for states at a particular block. diff --git a/crates/katana/storage/provider/tests/block.rs b/crates/katana/storage/provider/tests/block.rs index a5ea696017..57cfca9ff9 100644 --- a/crates/katana/storage/provider/tests/block.rs +++ b/crates/katana/storage/provider/tests/block.rs @@ -27,7 +27,7 @@ use fixtures::{ db_provider, fork_provider, fork_provider_with_spawned_fork_network, in_memory_provider, mock_state_updates, provider_with_states, }; -use katana_primitives::FieldElement; +use katana_primitives::Felt; #[apply(insert_block_cases)] fn insert_block_with_in_memory_provider( @@ -255,7 +255,7 @@ where assert_eq!(actual_status, Some(FinalityStatus::AcceptedOnL2)); assert_eq!(actual_block_with_tx_hashes, Some(expected_block_with_tx_hashes)); - let tx_hash = FieldElement::ZERO; + let tx_hash = Felt::ZERO; let actual_receipt = provider.receipt_by_hash(tx_hash)?; let actual_execution = provider.transaction_execution(tx_hash)?; diff --git a/crates/katana/storage/provider/tests/utils.rs b/crates/katana/storage/provider/tests/utils.rs index 15cf62f7b5..122372f98a 100644 --- a/crates/katana/storage/provider/tests/utils.rs +++ b/crates/katana/storage/provider/tests/utils.rs @@ -3,7 +3,7 @@ use katana_primitives::fee::TxFeeInfo; use katana_primitives::receipt::{InvokeTxReceipt, Receipt}; use katana_primitives::trace::TxExecInfo; use katana_primitives::transaction::{InvokeTx, Tx, TxHash, TxWithHash}; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use starknet::core::types::PriceUnit; pub fn generate_dummy_txs_and_receipts( @@ -44,8 +44,7 @@ pub fn generate_dummy_blocks_and_receipts( let (body, receipts, executions) = generate_dummy_txs_and_receipts(tx_count); let header = Header { parent_hash, number: i, ..Default::default() }; - let block = - Block { header, body }.seal_with_hash(FieldElement::from(rand::random::())); + let block = Block { header, body }.seal_with_hash(Felt::from(rand::random::())); parent_hash = block.header.hash; @@ -67,8 +66,7 @@ pub fn generate_dummy_blocks_empty(count: u64) -> Vec { let header = Header { parent_hash, number: i, ..Default::default() }; let body = vec![]; - let block = - Block { header, body }.seal_with_hash(FieldElement::from(rand::random::())); + let block = Block { header, body }.seal_with_hash(Felt::from(rand::random::())); parent_hash = block.header.hash; diff --git a/crates/saya/core/src/lib.rs b/crates/saya/core/src/lib.rs index 1b25b579e3..3a71b5e213 100644 --- a/crates/saya/core/src/lib.rs +++ b/crates/saya/core/src/lib.rs @@ -13,7 +13,6 @@ use futures::future; use katana_primitives::block::{BlockNumber, FinalityStatus, SealedBlock, SealedBlockWithStatus}; use katana_primitives::state::StateUpdatesWithDeclaredClasses; use katana_primitives::transaction::Tx; -use katana_primitives::FieldElement; use katana_rpc_types::trace::TxExecutionInfo; use prover::{HttpProverParams, ProverIdentifier}; pub use prover_sdk::ProverAccessKey; @@ -55,8 +54,8 @@ pub struct SayaConfig { pub start_block: u64, pub batch_size: usize, pub data_availability: Option, - pub world_address: FieldElement, - pub fact_registry_address: FieldElement, + pub world_address: Felt, + pub fact_registry_address: Felt, pub skip_publishing_proof: bool, pub starknet_account: StarknetAccountData, } @@ -66,9 +65,9 @@ pub struct StarknetAccountData { #[serde(deserialize_with = "url_deserializer")] pub starknet_url: Url, #[serde(deserialize_with = "felt_string_deserializer")] - pub chain_id: FieldElement, - pub signer_address: FieldElement, - pub signer_key: FieldElement, + pub chain_id: Felt, + pub signer_address: Felt, + pub signer_key: Felt, } pub fn url_deserializer<'de, D>(deserializer: D) -> Result @@ -79,7 +78,7 @@ where Url::parse(&s).map_err(serde::de::Error::custom) } -pub fn felt_string_deserializer<'de, D>(deserializer: D) -> Result +pub fn felt_string_deserializer<'de, D>(deserializer: D) -> Result where D: serde::Deserializer<'de>, { @@ -103,7 +102,7 @@ pub struct Saya { struct FetchedBlockInfo { block_number: BlockNumber, block: SealedBlock, - prev_state_root: FieldElement, + prev_state_root: Felt, state_updates: StateUpdatesWithDeclaredClasses, exec_infos: Vec, } @@ -199,8 +198,8 @@ impl Saya { async fn prefetch_blocks( &mut self, block_numbers: RangeInclusive, - previous_block_state_root: FieldElement, - ) -> SayaResult<(FieldElement, Vec)> { + previous_block_state_root: Felt, + ) -> SayaResult<(Felt, Vec)> { // Fetch all blocks from the current block to the latest block let fetched_blocks = future::try_join_all( block_numbers.clone().map(|block_number| self.provider.fetch_block(block_number)), @@ -319,7 +318,7 @@ impl Saya { prev_state_root, block_number, block_hash: block.block.header.hash, - config_hash: FieldElement::from(0u64), + config_hash: Felt::from(0u64), message_to_starknet_segment, message_to_appchain_segment, state_updates: state_updates_to_prove, @@ -354,7 +353,7 @@ impl Saya { file.write_all(proof.as_bytes()).await.context("Failed to write proof.")?; } - let serialized_proof: Vec = parse(&proof)?.into(); + let serialized_proof: Vec = parse(&proof)?.into(); let world_da = state_diff.world_da.unwrap(); // Publish state difference if DA client is available diff --git a/crates/saya/core/src/prover/extract.rs b/crates/saya/core/src/prover/extract.rs index 7a760183f5..61783f3bae 100644 --- a/crates/saya/core/src/prover/extract.rs +++ b/crates/saya/core/src/prover/extract.rs @@ -2,15 +2,15 @@ use anyhow::anyhow; use bigdecimal::BigDecimal; use katana_primitives::contract::ContractAddress; use katana_primitives::state::StateUpdates; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use num_traits::ToPrimitive; use super::{MessageToAppchain, MessageToStarknet, ProgramInput}; pub fn program_input_from_program_output( - output: Vec, + output: Vec, state_updates: StateUpdates, - world: FieldElement, + world: Felt, ) -> anyhow::Result { let prev_state_root = output[0]; let block_number = serde_json::from_str(&output[2].to_string()).unwrap(); @@ -49,9 +49,7 @@ pub fn program_input_from_program_output( Ok(input) } -fn get_message_to_starknet_segment( - output: &[FieldElement], -) -> anyhow::Result> { +fn get_message_to_starknet_segment(output: &[Felt]) -> anyhow::Result> { let mut message_to_starknet_segment: Vec = vec![]; let mut index = 0; loop { @@ -69,9 +67,7 @@ fn get_message_to_starknet_segment( Ok(message_to_starknet_segment) } -fn get_message_to_appchain_segment( - output: &[FieldElement], -) -> anyhow::Result> { +fn get_message_to_appchain_segment(output: &[Felt]) -> anyhow::Result> { let mut message_to_appchain_segment: Vec = vec![]; let mut index = 0; loop { diff --git a/crates/saya/core/src/prover/scheduler.rs b/crates/saya/core/src/prover/scheduler.rs index 72fdadcd0c..e89896761d 100644 --- a/crates/saya/core/src/prover/scheduler.rs +++ b/crates/saya/core/src/prover/scheduler.rs @@ -3,7 +3,7 @@ use cairo_proof_parser::output::{extract_output, ExtractOutputResult}; use futures::future::BoxFuture; use futures::FutureExt; use katana_primitives::state::StateUpdates; -use katana_primitives::FieldElement; +use katana_primitives::Felt; use tokio::sync::{mpsc, oneshot}; use tracing::{info, trace}; @@ -32,7 +32,7 @@ pub struct Scheduler { } impl Scheduler { - pub fn new(capacity: usize, world: FieldElement, prover: ProverIdentifier) -> Self { + pub fn new(capacity: usize, world: Felt, prover: ProverIdentifier) -> Self { let (senders, receivers): (Vec<_>, Vec<_>) = (0..capacity).map(|_| oneshot::channel::()).unzip(); @@ -77,7 +77,7 @@ impl Scheduler { pub async fn merge( inputs: Vec, - world: FieldElement, + world: Felt, prover: ProverIdentifier, ) -> anyhow::Result<(Proof, ProgramInput)> { let mut scheduler = Scheduler::new(inputs.len(), world, prover); @@ -134,7 +134,7 @@ async fn combine_proofs( prover: ProverIdentifier, state_updates1: StateUpdates, state_updates2: StateUpdates, - world: FieldElement, + world: Felt, number_of_inputs: usize, ) -> anyhow::Result { let ExtractOutputResult { program_output: program_output1, program_output_hash: _ } = @@ -164,7 +164,7 @@ async fn combine_proofs( /// calls. fn prove_recursively( mut inputs: Vec>, - world: FieldElement, + world: Felt, prover: ProverIdentifier, update_channel: mpsc::Sender<(u64, ProvingState)>, ) -> BoxFuture<'static, anyhow::Result<(Proof, ProgramInput)>> {