Skip to content

Commit

Permalink
feat: improve logging (#713)
Browse files Browse the repository at this point in the history
* wip tracing

* clean and add debug

* fix event filter conversion

* syntax cleaning
  • Loading branch information
greged93 authored Jan 15, 2024
1 parent 1553734 commit 125a1f2
Show file tree
Hide file tree
Showing 11 changed files with 123 additions and 100 deletions.
14 changes: 9 additions & 5 deletions .trunk/trunk.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
# To learn more about the format of this file, see https://docs.trunk.io/reference/trunk-yaml
version: 0.1
cli:
version: 1.17.2
version: 1.19.0
plugins:
sources:
- id: trunk
ref: v1.3.0
ref: v1.4.2
uri: https://github.com/trunk-io/plugins
runtimes:
enabled:
Expand All @@ -24,15 +24,19 @@ lint:
- markdownlint@0.38.0
- osv-scanner@1.5.0
- oxipng@9.0.0
- prettier@3.1.1
- prettier@3.2.2
- rustfmt@1.65.0
- shellcheck@0.9.0
- shfmt@3.6.0
- taplo@0.8.1
- terrascan@1.18.11
- trivy@0.48.2
- trufflehog@3.63.8
- trivy@0.48.3
- trufflehog@3.63.9
- yamllint@1.33.0
ignore:
- linters: [ALL]
paths:
- docker/**
actions:
disabled:
- trunk-announce
Expand Down
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions src/eth_rpc/servers/alchemy_rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ impl<P: Provider + Send + Sync + 'static> AlchemyRpc<P> {

#[async_trait]
impl<P: Provider + Send + Sync + 'static> AlchemyApiServer for AlchemyRpc<P> {
#[tracing::instrument(skip_all, ret, fields(address = %address, contract_addresses = ?contract_addresses))]
async fn token_balances(&self, address: Address, contract_addresses: Vec<Address>) -> Result<TokenBalances> {
let token_balances = self.kakarot_client.token_balances(address, contract_addresses).await?;
Ok(token_balances)
Expand Down
7 changes: 2 additions & 5 deletions src/models/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ use starknet::core::types::Event;
use starknet::providers::Provider;

use super::felt::Felt252Wrapper;
use crate::into_via_wrapper;
use crate::starknet_client::errors::EthApiError;
use crate::starknet_client::helpers::try_from_u8_iterator;
use crate::starknet_client::KakarotClient;
use crate::{into_via_wrapper, try_into_via_wrapper};

#[derive(Debug, Clone)]
pub struct StarknetEvent(Event);
Expand Down Expand Up @@ -43,10 +43,7 @@ impl StarknetEvent {
let (evm_contract_address, keys) =
self.0.keys.split_first().ok_or_else(|| EthApiError::KakarotDataFilteringError("Event".into()))?;

let address: Address = {
let felt_wrapper: Felt252Wrapper = (*evm_contract_address).into();
felt_wrapper.try_into()?
};
let address: Address = try_into_via_wrapper!(*evm_contract_address);

if keys.len() % 2 != 0 {
return Err(anyhow::anyhow!("Not a convertible event: Keys length is not even").into());
Expand Down
42 changes: 26 additions & 16 deletions src/models/event_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ use reth_rpc_types::{Filter, ValueOrArray};
use starknet::core::types::{BlockId, EventFilter};
use starknet::providers::Provider;
use starknet_crypto::FieldElement;
use tracing::debug;

use super::block::EthBlockNumberOrTag;
use super::felt::Felt252Wrapper;
use crate::starknet_client::errors::EthApiError;
use crate::starknet_client::helpers::split_u256;
use crate::starknet_client::KakarotClient;
use crate::{into_via_try_wrapper, into_via_wrapper};

pub struct EthEventFilter(Filter);

Expand All @@ -25,15 +27,18 @@ impl From<EthEventFilter> for Filter {
}

impl EthEventFilter {
#[tracing::instrument(skip_all, level = "debug")]
pub fn to_starknet_event_filter<P: Provider + Send + Sync>(
self,
client: &KakarotClient<P>,
) -> Result<EventFilter, EthApiError> {
let filter: Filter = self.into();
let block_hash = filter.get_block_hash();

debug!("ethereum event filter: {:?}", filter);

// Extract keys into topics
let mut keys: Vec<FieldElement> = filter
let keys: Vec<FieldElement> = filter
.topics
.into_iter()
.flat_map(|filter| match filter.to_value_or_array() {
Expand All @@ -54,27 +59,30 @@ impl EthEventFilter {
.collect();

// Get the filter address if any (added as first key)
if let Some(address) = filter.address.to_value_or_array() {
let address = match address {
ValueOrArray::Array(addresses) => addresses.first().copied(),
ValueOrArray::Value(address) => Some(address),
};
if let Some(address) = address {
let address: Felt252Wrapper = address.into();
keys = [vec![address.into()], keys].concat();
}
}
let address = filter.address.to_value_or_array().and_then(|a| match a {
ValueOrArray::Array(addresses) => addresses.first().copied(),
ValueOrArray::Value(address) => Some(address),
});

// Convert to expected format Vec<Vec<FieldElement>> or None if no keys and no address
let keys = if !keys.is_empty() | address.is_some() {
let keys = keys.into_iter().map(|key| vec![key]).collect();
// If address is present add it as first key, otherwise add an empty key
let keys = [address.map_or(vec![vec![]], |a| vec![vec![into_via_wrapper!(a)]]), keys].concat();
Some(keys)
} else {
None
};

// Convert to expected format Vec<Vec<FieldElement>> or None if no keys
let keys = if !keys.is_empty() { Some(keys.into_iter().map(|key| vec![key]).collect()) } else { None };
debug!("starknet event filter keys: {:?}", keys);

// Add filter block range
let starknet_filter = if let Some(block_hash) = block_hash {
let block_hash: Felt252Wrapper = block_hash.try_into()?;
let block_hash = into_via_try_wrapper!(block_hash);

EventFilter {
from_block: Some(BlockId::Hash(block_hash.clone().into())),
to_block: Some(BlockId::Hash(block_hash.into())),
from_block: Some(BlockId::Hash(block_hash)),
to_block: Some(BlockId::Hash(block_hash)),
address: Some(client.kakarot_address()),
keys,
}
Expand All @@ -89,6 +97,8 @@ impl EthEventFilter {
}
};

debug!("starknet event filter: {:?}", starknet_filter);

Ok(starknet_filter)
}
}
36 changes: 1 addition & 35 deletions src/models/felt.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,11 @@
use std::ops::Mul;

use reth_primitives::{Address, Bytes, H256, U256};
use reth_primitives::{Address, H256, U256};
use starknet::core::types::FieldElement;

use crate::models::errors::ConversionError;

#[derive(Clone, Debug)]
pub struct Felt252Wrapper(FieldElement);

impl Felt252Wrapper {
pub const ZERO: Self = Self(FieldElement::ZERO);
}

impl Mul for Felt252Wrapper {
type Output = Self;

fn mul(self, rhs: Self) -> Self::Output {
Self(self.0 * rhs.0)
}
}

impl From<FieldElement> for Felt252Wrapper {
fn from(felt: FieldElement) -> Self {
Self(felt)
Expand Down Expand Up @@ -111,13 +97,6 @@ impl From<Felt252Wrapper> for U256 {
}
}

impl From<Felt252Wrapper> for Bytes {
fn from(felt: Felt252Wrapper) -> Self {
let bytes = felt.0.to_bytes_be();
Self::from(bytes)
}
}

/// This macro provides a convenient way to convert a value from a source
/// type $val that implements Into<Felt252Wrapper> into a target type that
/// implements From<Felt252Wrapper>.
Expand Down Expand Up @@ -235,17 +214,4 @@ mod tests {
// When
Felt252Wrapper::try_from(hash).unwrap();
}

#[test]
fn test_bytes_from_felt() {
// Given
let felt = Felt252Wrapper::from(1);

// When
let bytes = Bytes::from(felt);

// Then
let expected = Bytes::from_str("0x0000000000000000000000000000000000000000000000000000000000000001").unwrap();
assert_eq!(expected, bytes);
}
}
33 changes: 13 additions & 20 deletions src/models/signature.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::into_via_wrapper;
use reth_primitives::U256;
use reth_rpc_types::{Parity, Signature as EthSignature};
use starknet::core::types::FieldElement;
Expand All @@ -23,28 +24,20 @@ impl TryFrom<StarknetSignature> for EthSignature {
type Error = StarknetSignatureError;

fn try_from(value: StarknetSignature) -> Result<Self, Self::Error> {
let r_low: U256 = Felt252Wrapper::from(
*value.0.get(0).ok_or_else(|| StarknetSignatureError::MissingSignatureParamsError("r".to_string()))?,
)
.into();
let r_high: U256 = Felt252Wrapper::from(
*value.0.get(1).ok_or_else(|| StarknetSignatureError::MissingSignatureParamsError("r".to_string()))?,
)
.into();
macro_rules! signature_param {
($index: expr, $param: expr) => {
into_via_wrapper!(*value.0.get($index).ok_or_else(|| {
StarknetSignatureError::MissingSignatureParamsError(format!("Starknet signature param {}", $param))
})?)
};
}
let r_low: U256 = signature_param!(0, "r");
let r_high: U256 = signature_param!(1, "r");
let r = r_low + (r_high << 128);
let s_low: U256 = Felt252Wrapper::from(
*value.0.get(2).ok_or_else(|| StarknetSignatureError::MissingSignatureParamsError("r".to_string()))?,
)
.into();
let s_high: U256 = Felt252Wrapper::from(
*value.0.get(3).ok_or_else(|| StarknetSignatureError::MissingSignatureParamsError("r".to_string()))?,
)
.into();
let s_low: U256 = signature_param!(2, "s");
let s_high: U256 = signature_param!(3, "s");
let s = s_low + (s_high << 128);
let v: U256 = Felt252Wrapper::from(
*value.0.get(4).ok_or_else(|| StarknetSignatureError::MissingSignatureParamsError("v".to_string()))?,
)
.into();
let v: U256 = signature_param!(4, "v");
let y_parity = if v == U256::from(0u8) {
Some(Parity(false))
} else if v == U256::from(1u8) {
Expand Down
7 changes: 7 additions & 0 deletions src/models/transaction/transaction_signed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use reth_rlp::Decodable as _;
use starknet::core::types::{BlockId as StarknetBlockId, BlockTag, BroadcastedInvokeTransaction};
use starknet::providers::Provider;
use starknet_crypto::FieldElement;
use tracing::debug;

use crate::starknet_client::constants::{CHAIN_ID, MAX_FEE};
use crate::starknet_client::errors::EthApiError;
Expand All @@ -20,6 +21,7 @@ impl From<Bytes> for StarknetTransactionSigned {
}

impl StarknetTransactionSigned {
#[tracing::instrument(skip_all, level = "debug")]
pub async fn to_broadcasted_invoke_transaction<P: Provider + Send + Sync>(
&self,
client: &KakarotClient<P>,
Expand Down Expand Up @@ -71,13 +73,18 @@ impl StarknetTransactionSigned {
// RLP encode the transaction without the signature
// Example: For Legacy Transactions: rlp([nonce, gas_price, gas_limit, to, value, data, chain_id, 0, 0])
let mut signed_data = Vec::new();

debug!("ethereum transaction: {:?}", transaction);

transaction.transaction.encode_without_signature(&mut signed_data);

let calldata = prepare_kakarot_eth_send_transaction(
client.kakarot_address(),
signed_data.into_iter().map(FieldElement::from).collect(),
);

debug!("starknet calldata: {:?}", calldata);

Ok(BroadcastedInvokeTransaction {
max_fee,
signature,
Expand Down
20 changes: 11 additions & 9 deletions src/models/transaction_receipt.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
use reth_primitives::bloom::logs_bloom;
use reth_primitives::contract::create_address;
use reth_primitives::{H256, U128, U256, U64, U8};
use reth_primitives::{U128, U256, U64, U8};
use reth_rpc_types::{Log, TransactionReceipt as EthTransactionReceipt};
use starknet::core::types::{
ExecutionResult, InvokeTransactionReceipt, MaybePendingTransactionReceipt, TransactionReceipt,
};
use starknet::providers::Provider;
use tracing::debug;

use super::event::StarknetEvent;
use super::felt::Felt252Wrapper;
use super::transaction::transaction::StarknetTransaction;
use crate::into_via_wrapper;
use crate::starknet_client::errors::EthApiError;
use crate::starknet_client::KakarotClient;

Expand All @@ -28,12 +30,15 @@ impl From<StarknetTransactionReceipt> for MaybePendingTransactionReceipt {
}

impl StarknetTransactionReceipt {
#[tracing::instrument(skip_all, level = "debug")]
pub async fn to_eth_transaction_receipt<P: Provider + Send + Sync>(
self,
client: &KakarotClient<P>,
) -> Result<Option<EthTransactionReceipt>, EthApiError> {
let starknet_tx_receipt: MaybePendingTransactionReceipt = self.into();

debug!("starknet transaction receipt: {:?}", starknet_tx_receipt);

let res_receipt = match starknet_tx_receipt {
MaybePendingTransactionReceipt::Receipt(receipt) => match receipt {
TransactionReceipt::Invoke(InvokeTransactionReceipt {
Expand All @@ -47,14 +52,9 @@ impl StarknetTransactionReceipt {
let starknet_tx: StarknetTransaction =
client.starknet_provider().get_transaction_by_hash(transaction_hash).await?.into();

let transaction_hash: Felt252Wrapper = transaction_hash.into();
let transaction_hash: Option<H256> = Some(transaction_hash.into());

let block_hash: Felt252Wrapper = block_hash.into();
let block_hash: Option<H256> = Some(block_hash.into());

let block_number: Felt252Wrapper = block_number.into();
let block_number: Option<U256> = Some(block_number.into());
let transaction_hash = Some(into_via_wrapper!(transaction_hash));
let block_hash = Some(into_via_wrapper!(block_hash));
let block_number = Some(into_via_wrapper!(block_number));

let eth_tx = starknet_tx.to_eth_transaction(client, block_hash, block_number, None).await?;
let from = eth_tx.from;
Expand Down Expand Up @@ -130,6 +130,8 @@ impl StarknetTransactionReceipt {
}
};

debug!("ethereum transaction receipt: {:?}", res_receipt);

Ok(Some(res_receipt))
}
}
Loading

0 comments on commit 125a1f2

Please sign in to comment.