Skip to content

Commit

Permalink
spring cleaning (#666)
Browse files Browse the repository at this point in the history
* remove convertible trait

* clean 'static

* remove generic from conversion errror

* cleaning
  • Loading branch information
greged93 authored Dec 6, 2023
1 parent 2ce4842 commit 408bbd9
Show file tree
Hide file tree
Showing 21 changed files with 65 additions and 151 deletions.
10 changes: 5 additions & 5 deletions .trunk/trunk.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ cli:
plugins:
sources:
- id: trunk
ref: v1.2.6
ref: v1.3.0
uri: https://github.com/trunk-io/plugins
runtimes:
enabled:
Expand All @@ -16,21 +16,21 @@ runtimes:
lint:
enabled:
- [email protected]
- checkov@3.0.32
- checkov@3.1.9
- [email protected]
- git-diff-check
- [email protected]
- [email protected]
- [email protected]
- [email protected]
- prettier@3.0.3
- prettier@3.1.0
- [email protected]
- [email protected]
- [email protected]
- [email protected]
- [email protected].3
- [email protected].5
- [email protected]
- trufflehog@3.62.1
- trufflehog@3.63.2-rc0
- [email protected]
actions:
disabled:
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ serde_with = "2.3.1"
anyhow = "1.0.68"
async-trait = "0.1.58"
ctor = "0.2.4"
eyre = "0.6.8"
dotenv = "0.15.0"
eyre = "0.6.8"
git2 = "0.18.0"
lazy_static = "1.4.0"
pin-project = "1.1.2"
Expand Down
4 changes: 2 additions & 2 deletions crates/core/src/client/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,8 @@ pub enum EthApiError {
Other(#[from] anyhow::Error),
}

impl<T> From<ConversionError<T>> for EthApiError {
fn from(err: ConversionError<T>) -> Self {
impl From<ConversionError> for EthApiError {
fn from(err: ConversionError) -> Self {
Self::ConversionError(err.to_string())
}
}
Expand Down
4 changes: 2 additions & 2 deletions crates/core/src/client/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ struct InvalidFieldElementError;
impl std::error::Error for InvalidFieldElementError {}

impl std::fmt::Display for InvalidFieldElementError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "Invalid FieldElement")
}
}
Expand All @@ -47,7 +47,7 @@ pub fn decode_eth_call_return(call_result: &[FieldElement]) -> Result<Vec<FieldE
actual: 0,
})?;
let return_data_len: u64 =
return_data_len.try_into().map_err(|e: ValueOutOfRangeError| ConversionError::<()>::Other(e.to_string()))?;
return_data_len.try_into().map_err(|e: ValueOutOfRangeError| ConversionError::Other(e.to_string()))?;

let return_data = call_result.get(1..).ok_or_else(|| DataDecodingError::InvalidReturnArrayLength {
entrypoint: "eth_call or eth_send_transaction".into(),
Expand Down
30 changes: 11 additions & 19 deletions crates/core/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,6 @@ use crate::contracts::erc20::starknet_erc20::StarknetErc20;
use crate::contracts::kakarot_contract::KakarotContract;
use crate::models::balance::{FutureTokenBalance, TokenBalances};
use crate::models::block::{BlockWithTxHashes, BlockWithTxs, EthBlockId};
use crate::models::convertible::{
ConvertibleSignedTransaction, ConvertibleStarknetBlock, ConvertibleStarknetTransaction,
};
use crate::models::errors::ConversionError;
use crate::models::felt::Felt252Wrapper;
use crate::models::transaction::transaction::{StarknetTransaction, StarknetTransactions};
Expand All @@ -54,13 +51,13 @@ use crate::contracts::kakarot_contract::KakarotCoreReader;
abigen_legacy!(ContractAccount, "./artifacts/contract_account.json");
abigen_legacy!(Proxy, "./artifacts/proxy.json");

pub struct KakarotClient<P: Provider + Send + Sync + 'static> {
pub struct KakarotClient<P: Provider + Send + Sync> {
starknet_provider: Arc<P>,
kakarot_contract: KakarotContract<P>,
network: Network,
}

impl<P: Provider + Send + Sync + 'static> KakarotClient<P> {
impl<P: Provider + Send + Sync> KakarotClient<P> {
/// Create a new `KakarotClient`.
pub fn new(starknet_config: KakarotRpcConfig, starknet_provider: Arc<P>) -> Self {
let KakarotRpcConfig {
Expand All @@ -72,7 +69,7 @@ impl<P: Provider + Send + Sync + 'static> KakarotClient<P> {
} = starknet_config;

let provider = starknet_provider.clone();
let contract_reader = KakarotCoreReader::new(kakarot_address, provider.clone());
let contract_reader = KakarotCoreReader::new(kakarot_address, provider);

let kakarot_contract = KakarotContract::new(
proxy_account_class_hash,
Expand Down Expand Up @@ -198,12 +195,7 @@ impl<P: Provider + Send + Sync + 'static> KakarotClient<P> {

let proxy = ProxyReader::new(starknet_address, &self.starknet_provider);

let class_hash = match proxy.get_implementation().call().await {
Ok(class_hash) => class_hash,
// TODO: replace by proper error handling
// if the contract doesn't exist, we return 0
Err(_) => FieldElement::ZERO,
};
let class_hash = proxy.get_implementation().call().await.map_or(FieldElement::ZERO, |class_hash| class_hash);

if class_hash == self.kakarot_contract.contract_account_class_hash {
// Get the nonce of the contract account -> a storage variable
Expand Down Expand Up @@ -326,7 +318,7 @@ impl<P: Provider + Send + Sync + 'static> KakarotClient<P> {
_reward_percentiles: Option<Vec<f64>>,
) -> Result<FeeHistory, EthApiError> {
let block_count_usize =
usize::try_from(block_count).map_err(|e| ConversionError::<()>::ValueOutOfRange(e.to_string()))?;
usize::try_from(block_count).map_err(|e| ConversionError::ValueOutOfRange(e.to_string()))?;

let base_fee = self.base_fee_per_gas();

Expand Down Expand Up @@ -359,23 +351,23 @@ impl<P: Provider + Send + Sync + 'static> KakarotClient<P> {
let chain_id = request.chain_id.unwrap_or_else(|| CHAIN_ID.into());

let from = request.from.ok_or_else(|| EthApiError::MissingParameterError("from for estimate_gas".into()))?;
let nonce = self.nonce(from, block_id).await?.try_into().map_err(ConversionError::<u64>::from)?;
let nonce = self.nonce(from, block_id).await?.try_into().map_err(ConversionError::from)?;

let gas_limit = request.gas.unwrap_or(U256::ZERO).try_into().map_err(ConversionError::<u64>::from)?;
let gas_limit = request.gas.unwrap_or(U256::ZERO).try_into().map_err(ConversionError::from)?;
let max_fee_per_gas = request
.max_fee_per_gas
.unwrap_or_else(|| U256::from(BASE_FEE_PER_GAS))
.try_into()
.map_err(ConversionError::<u128>::from)?;
.map_err(ConversionError::from)?;
let max_priority_fee_per_gas = request
.max_priority_fee_per_gas
.unwrap_or_else(|| U256::from(self.max_priority_fee_per_gas()))
.try_into()
.map_err(ConversionError::<u128>::from)?;
.map_err(ConversionError::from)?;

let to = request.to.map_or(TransactionKind::Create, TransactionKind::Call);

let value = request.value.unwrap_or(U256::ZERO).try_into().map_err(ConversionError::<u128>::from)?;
let value = request.value.unwrap_or(U256::ZERO).try_into().map_err(ConversionError::from)?;

let data = request.input.data.unwrap_or_default();

Expand Down Expand Up @@ -569,7 +561,7 @@ impl<P: Provider + Send + Sync + 'static> KakarotClient<P> {
// if the url is invalid, return an empty simulation (allows to call simulate_transaction on Kakana,
// Madara, etc.)
if url.is_err() {
let gas_usage = (*ESTIMATE_GAS).try_into().map_err(ConversionError::UintConversionError)?;
let gas_usage = (*ESTIMATE_GAS).try_into().map_err(ConversionError::from)?;
let gas_price: Felt252Wrapper = (*MAX_FEE).into();
let overall_fee = Felt252Wrapper::from(gas_usage) * gas_price.clone();
return Ok(TransactionSimulationInfo {
Expand Down
2 changes: 1 addition & 1 deletion crates/core/src/contracts/erc20/ethereum_erc20.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ pub struct EthereumErc20<P> {
pub kakarot_address: FieldElement,
}

impl<P: Provider + Send + Sync + 'static> EthereumErc20<P> {
impl<P: Provider + Send + Sync> EthereumErc20<P> {
pub const fn new(address: FieldElement, provider: Arc<P>, kakarot_address: FieldElement) -> Self {
Self { address, provider, kakarot_address }
}
Expand Down
6 changes: 3 additions & 3 deletions crates/core/src/contracts/kakarot_contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ use starknet_crypto::FieldElement;

abigen_legacy!(KakarotCore, "./artifacts/kakarot.json");

pub struct KakarotContract<P: Provider + Send + Sync + 'static> {
pub struct KakarotContract<P: Provider + Send + Sync> {
pub proxy_account_class_hash: FieldElement,
pub externally_owned_account_class_hash: FieldElement,
pub contract_account_class_hash: FieldElement,
pub reader: KakarotCoreReader<Arc<P>>,
}

impl<P: Provider + Send + Sync + 'static> KakarotContract<P> {
pub fn new(
impl<P: Provider + Send + Sync> KakarotContract<P> {
pub const fn new(
proxy_account_class_hash: FieldElement,
externally_owned_account_class_hash: FieldElement,
contract_account_class_hash: FieldElement,
Expand Down
14 changes: 5 additions & 9 deletions crates/core/src/models/block.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use async_trait::async_trait;
use reth_primitives::{Address, BlockId as EthereumBlockId, BlockNumberOrTag, Bloom, Bytes, H256, H64, U256};
use reth_rpc_types::{Block, BlockTransactions, Header, RichBlock};
use starknet::core::types::{
Expand All @@ -7,7 +6,6 @@ use starknet::core::types::{
};
use starknet::providers::Provider;

use super::convertible::ConvertibleStarknetBlock;
use super::felt::Felt252Wrapper;
use crate::client::constants::{
DIFFICULTY, EARLIEST_BLOCK_NUMBER, GAS_LIMIT, GAS_USED, MIX_HASH, NONCE, SIZE, TOTAL_DIFFICULTY,
Expand All @@ -24,7 +22,7 @@ impl EthBlockId {
}

impl TryFrom<EthBlockId> for StarknetBlockId {
type Error = ConversionError<()>;
type Error = ConversionError;
fn try_from(eth_block_id: EthBlockId) -> Result<Self, Self::Error> {
match eth_block_id.0 {
EthereumBlockId::Hash(hash) => {
Expand Down Expand Up @@ -147,9 +145,8 @@ impl BlockWithTxs {
);
}

#[async_trait]
impl ConvertibleStarknetBlock for BlockWithTxHashes {
async fn to_eth_block<P: Provider + Send + Sync + 'static>(&self, client: &KakarotClient<P>) -> RichBlock {
impl BlockWithTxHashes {
pub async fn to_eth_block<P: Provider + Send + Sync>(&self, client: &KakarotClient<P>) -> RichBlock {
// TODO: Fetch real data
let gas_limit = *GAS_LIMIT;

Expand Down Expand Up @@ -226,9 +223,8 @@ impl ConvertibleStarknetBlock for BlockWithTxHashes {
}
}

#[async_trait]
impl ConvertibleStarknetBlock for BlockWithTxs {
async fn to_eth_block<P: Provider + Send + Sync + 'static>(&self, client: &KakarotClient<P>) -> RichBlock {
impl BlockWithTxs {
pub async fn to_eth_block<P: Provider + Send + Sync>(&self, client: &KakarotClient<P>) -> RichBlock {
// TODO: Fetch real data
let gas_limit = *GAS_LIMIT;

Expand Down
2 changes: 1 addition & 1 deletion crates/core/src/models/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ impl From<Vec<StarknetCall>> for Calls {

/// Converts a raw starknet transaction calldata to a vector of starknet calls.
impl TryFrom<Vec<FieldElement>> for Calls {
type Error = ConversionError<()>;
type Error = ConversionError;

fn try_from(value: Vec<FieldElement>) -> Result<Self, Self::Error> {
// in account calls, the calldata is first each call as {contract address, selector, data offset,
Expand Down
59 changes: 0 additions & 59 deletions crates/core/src/models/convertible.rs

This file was deleted.

12 changes: 9 additions & 3 deletions crates/core/src/models/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::client::helpers::DataDecodingError;

#[derive(Debug, Error)]
/// Conversion error
pub enum ConversionError<T> {
pub enum ConversionError {
/// Ethereum to Starknet transaction conversion error
#[error("transaction conversion error: {0}")]
TransactionConversionError(String),
Expand All @@ -26,9 +26,15 @@ pub enum ConversionError<T> {
#[error("value out of range: {0}")]
ValueOutOfRange(String),
/// Uint conversion error
#[error(transparent)]
UintConversionError(#[from] FromUintError<T>),
#[error("Uint conversion error: {0}")]
UintConversionError(String),
/// Other conversion error
#[error("failed to convert value: {0}")]
Other(String),
}

impl<T> From<FromUintError<T>> for ConversionError {
fn from(err: FromUintError<T>) -> Self {
Self::UintConversionError(err.to_string())
}
}
5 changes: 2 additions & 3 deletions crates/core/src/models/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ use starknet_crypto::FieldElement;
use super::felt::Felt252Wrapper;
use crate::client::errors::EthApiError;
use crate::client::KakarotClient;
use crate::models::convertible::ConvertibleStarknetEvent;

#[derive(Debug, Clone)]
pub struct StarknetEvent(Event);
Expand All @@ -27,8 +26,8 @@ impl From<Event> for StarknetEvent {
}
}

impl ConvertibleStarknetEvent for StarknetEvent {
fn to_eth_log<P: Provider + Send + Sync + 'static>(
impl StarknetEvent {
pub fn to_eth_log<P: Provider + Send + Sync>(
self,
client: &KakarotClient<P>,
block_hash: Option<H256>,
Expand Down
5 changes: 2 additions & 3 deletions crates/core/src/models/event_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use starknet::providers::Provider;
use starknet_crypto::FieldElement;

use super::block::EthBlockNumberOrTag;
use super::convertible::ConvertibleEthEventFilter;
use super::felt::Felt252Wrapper;
use crate::client::errors::EthApiError;
use crate::client::helpers::split_u256_into_field_elements;
Expand All @@ -25,8 +24,8 @@ impl From<EthEventFilter> for Filter {
}
}

impl ConvertibleEthEventFilter for EthEventFilter {
fn to_starknet_event_filter<P: Provider + Send + Sync + 'static>(
impl EthEventFilter {
pub fn to_starknet_event_filter<P: Provider + Send + Sync>(
self,
client: &KakarotClient<P>,
) -> Result<EventFilter, EthApiError> {
Expand Down
Loading

0 comments on commit 408bbd9

Please sign in to comment.