repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/providers/eth_provider/database/types/transaction.rs
src/providers/eth_provider/database/types/transaction.rs
use alloy_primitives::B256; use alloy_rpc_types::Transaction; use alloy_serde::WithOtherFields; use serde::{Deserialize, Serialize}; use starknet::core::types::Felt; use std::ops::Deref; #[cfg(any(test, feature = "arbitrary", feature = "testing"))] use { alloy_consensus::Transaction as _, alloy_primitives::U256, arbitrary::Arbitrary, rand::Rng, reth_primitives::transaction::legacy_parity, reth_testing_utils::generators::{self}, }; /// Type alias for a transaction with additional fields. pub type ExtendedTransaction = WithOtherFields<Transaction>; /// A mapping between an Ethereum transaction hash and a Starknet transaction hash. #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] pub struct StoredEthStarknetTransactionHash { /// Contains both Ethereum and Starknet transaction hashes. #[serde(deserialize_with = "crate::providers::eth_provider::database::types::serde::deserialize_intermediate")] pub hashes: EthStarknetHashes, } impl From<EthStarknetHashes> for StoredEthStarknetTransactionHash { fn from(hashes: EthStarknetHashes) -> Self { Self { hashes } } } /// Inner struct that holds the Ethereum and Starknet transaction hashes. #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] pub struct EthStarknetHashes { /// The Ethereum transaction hash. pub eth_hash: B256, /// The Starknet transaction hash. pub starknet_hash: Felt, } /// A full transaction as stored in the database #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] pub struct StoredTransaction { #[serde(deserialize_with = "crate::providers::eth_provider::database::types::serde::deserialize_intermediate")] pub tx: WithOtherFields<Transaction>, } impl From<StoredTransaction> for WithOtherFields<Transaction> { fn from(tx: StoredTransaction) -> Self { tx.tx } } impl From<&StoredTransaction> for WithOtherFields<Transaction> { fn from(tx: &StoredTransaction) -> Self { tx.tx.clone() } } impl From<WithOtherFields<Transaction>> for StoredTransaction { fn from(tx: WithOtherFields<Transaction>) -> Self { Self { tx } } } impl Deref for StoredTransaction { type Target = WithOtherFields<Transaction>; fn deref(&self) -> &Self::Target { &self.tx } } #[cfg(any(test, feature = "arbitrary", feature = "testing"))] impl Arbitrary<'_> for StoredTransaction { fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> { // Initialize a random number generator. let mut rng = generators::rng(); // Generate a random integer between 0 and 2 to decide which transaction type to create. let random_choice = rng.gen_range(0..3); // Create a `primitive_tx` of a specific transaction type based on the random choice. let primitive_tx = match random_choice { 0 => reth_primitives::Transaction::Legacy(alloy_consensus::TxLegacy { chain_id: Some(u8::arbitrary(u)?.into()), ..Arbitrary::arbitrary(u)? }), 1 => reth_primitives::Transaction::Eip2930(alloy_consensus::TxEip2930::arbitrary(u)?), _ => reth_primitives::Transaction::Eip1559(alloy_consensus::TxEip1559::arbitrary(u)?), }; // Sign the generated transaction with a randomly generated key pair. let transaction_signed = generators::sign_tx_with_random_key_pair(&mut rng, primitive_tx); // Initialize a `Transaction` structure and populate it with the signed transaction's data. let mut tx = Transaction { hash: transaction_signed.hash, from: transaction_signed.recover_signer().unwrap(), block_hash: Some(B256::arbitrary(u)?), block_number: Some(u64::arbitrary(u)?), transaction_index: Some(u64::arbitrary(u)?), signature: Some(alloy_rpc_types::Signature { r: transaction_signed.signature.r(), s: transaction_signed.signature.s(), v: if transaction_signed.is_legacy() { U256::from(legacy_parity(&transaction_signed.signature, transaction_signed.chain_id()).to_u64()) } else { U256::from(transaction_signed.signature.v().to_u64()) }, y_parity: Some((transaction_signed.signature.v().y_parity()).into()), }), nonce: transaction_signed.nonce(), value: transaction_signed.value(), input: transaction_signed.input().clone(), chain_id: transaction_signed.chain_id(), transaction_type: Some(transaction_signed.tx_type().into()), to: transaction_signed.to(), gas: transaction_signed.gas_limit(), ..Default::default() }; // Populate the `tx` structure based on the specific type of transaction. match transaction_signed.transaction { reth_primitives::Transaction::Legacy(transaction) => { tx.gas_price = Some(transaction.gas_price); } reth_primitives::Transaction::Eip2930(transaction) => { tx.access_list = Some(transaction.access_list); tx.gas_price = Some(transaction.gas_price); } reth_primitives::Transaction::Eip1559(transaction) => { tx.max_fee_per_gas = Some(transaction.max_fee_per_gas); tx.max_priority_fee_per_gas = Some(transaction.max_priority_fee_per_gas); tx.access_list = Some(transaction.access_list); } reth_primitives::Transaction::Eip4844(_) | reth_primitives::Transaction::Eip7702(_) => { unreachable!("Non supported transaction type") } }; // Return the constructed `StoredTransaction` instance. Ok(Self { tx: WithOtherFields::new(tx) }) } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Hash { pub hash: B256, } #[cfg(test)] mod tests { use super::*; use arbitrary::Arbitrary; use rand::Rng; #[test] fn test_stored_transaction_arbitrary() { let mut bytes = [0u8; 1024]; rand::thread_rng().fill(bytes.as_mut_slice()); let _ = StoredTransaction::arbitrary(&mut arbitrary::Unstructured::new(&bytes)).unwrap(); } #[test] fn random_tx_signature() { for _ in 0..10 { let mut bytes = [0u8; 1024]; rand::thread_rng().fill(bytes.as_mut_slice()); // Generate a random transaction let transaction = StoredTransaction::arbitrary(&mut arbitrary::Unstructured::new(&bytes)).unwrap(); // Extract the signature from the generated transaction. let signature = transaction.signature.unwrap().try_into().unwrap(); // Convert the transaction to primitive type. let tx = transaction.clone().tx.try_into().unwrap(); // Reconstruct the signed transaction using the extracted `tx` and `signature`. let transaction_signed = reth_primitives::TransactionSigned::from_transaction_and_signature(tx, signature); // Verify that the `from` address in the original transaction matches the recovered signer address // from the reconstructed signed transaction. This confirms that the signature is valid. assert_eq!(transaction.from, transaction_signed.recover_signer().unwrap()); } } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/providers/eth_provider/database/types/serde/mod.rs
src/providers/eth_provider/database/types/serde/mod.rs
use serde::{de::value::MapDeserializer, Deserialize, Deserializer}; use serde_json::Value; use std::collections::HashMap; /// Used in order to perform a custom deserialization of the stored /// Ethereum data from the database. /// /// All the primitive types are stored as strings in the database. This caused problems when deserializing. /// /// # Example /// /// The database stores {"hash": "0x1234"}. This gets serialized to /// "{\"hash\":\"0x1234\"}". It's not possible to deserialize \"0x1234\" /// into a U64 or B256 type from `reth_primitives` (since \"0x1234\" is the /// serialized representation of the string "0x1234"). This function provides /// a custom deserialization that first deserializes the data into a /// `HashMap`<String, Value>, which can them be used to deserialize into the /// desired types. pub fn deserialize_intermediate<'de, D, T>(deserializer: D) -> Result<T, D::Error> where D: Deserializer<'de>, T: Deserialize<'de>, { let s: HashMap<String, Value> = HashMap::deserialize(deserializer)?; let deserializer = MapDeserializer::new(s.into_iter()); T::deserialize(deserializer).map_err(|err: serde_json::Error| serde::de::Error::custom(err.to_string())) }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/providers/sn_provider/mod.rs
src/providers/sn_provider/mod.rs
pub mod starknet_provider; pub use starknet_provider::StarknetProvider;
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/providers/sn_provider/starknet_provider.rs
src/providers/sn_provider/starknet_provider.rs
use crate::{ into_via_wrapper, providers::eth_provider::{ error::ExecutionError, starknet::{ERC20Reader, STARKNET_NATIVE_TOKEN}, utils::{class_hash_not_declared, contract_not_found}, }, }; use alloy_primitives::U256; use starknet::{ core::types::{BlockId, Felt}, providers::Provider, }; use std::ops::Deref; use tracing::Instrument; /// A provider wrapper around the Starknet provider to expose utility methods. #[derive(Debug, Clone)] pub struct StarknetProvider<SP: Provider + Send + Sync> { /// The underlying Starknet provider wrapped in an [`Arc`] for shared ownership across threads. provider: SP, } impl<SP: Provider + Send + Sync> Deref for StarknetProvider<SP> { type Target = SP; fn deref(&self) -> &Self::Target { &self.provider } } impl<SP> StarknetProvider<SP> where SP: Provider + Send + Sync, { /// Creates a new [`StarknetProvider`] instance from a Starknet provider. pub const fn new(provider: SP) -> Self { Self { provider } } /// Retrieves the balance of a Starknet address for a specified block. /// /// This method interacts with the Starknet native token contract to query the balance of the given /// address at a specific block. /// /// If the contract is not deployed or the class hash is not declared, a balance of 0 is returned /// instead of an error. pub async fn balance_at(&self, address: Felt, block_id: BlockId) -> Result<U256, ExecutionError> { // Create a new `ERC20Reader` instance for the Starknet native token let eth_contract = ERC20Reader::new(*STARKNET_NATIVE_TOKEN, &self.provider); // Call the `balanceOf` method on the contract for the given address and block ID, awaiting the result let span = tracing::span!(tracing::Level::INFO, "sn::balance"); let res = eth_contract.balanceOf(&address).block_id(block_id).call().instrument(span).await; // Check if the contract was not found or the class hash not declared, // returning a default balance of 0 if true. // The native token contract should be deployed on Kakarot, so this should not happen // We want to avoid errors in this case and return a default balance of 0 if contract_not_found(&res) || class_hash_not_declared(&res) { return Ok(Default::default()); } // Otherwise, extract the balance from the result, converting any errors to ExecutionError let balance = res.map_err(ExecutionError::from)?.balance; // Convert the low and high parts of the balance to U256 let low: U256 = into_via_wrapper!(balance.low); let high: U256 = into_via_wrapper!(balance.high); // Combine the low and high parts to form the final balance and return it Ok(low + (high << 128)) } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/config.rs
src/eth_rpc/config.rs
use eyre::{eyre, Result}; #[derive(Debug, Clone)] pub struct RPCConfig { pub socket_addr: String, } impl RPCConfig { pub const fn new(socket_addr: String) -> Self { Self { socket_addr } } pub fn from_env() -> Result<Self> { let socket_addr = std::env::var("KAKAROT_RPC_URL") .map_err(|_| eyre!("Missing mandatory environment variable: KAKAROT_RPC_URL"))?; Ok(Self::new(socket_addr)) } pub fn from_port(port: u16) -> Result<Self> { let mut config = Self::from_env()?; // Remove port from socket address and replace it with provided port let parts: Vec<&str> = config.socket_addr.split(':').collect(); if let Some(addr) = parts.first() { config.socket_addr = format!("{addr}:{port}"); } Ok(config) } } #[cfg(feature = "testing")] impl RPCConfig { pub fn new_test_config() -> Self { // Hardcode the socket address for testing environment Self::new("127.0.0.1:3030".to_string()) } pub fn new_test_config_from_port(port: u16) -> Self { let mut config = Self::new_test_config(); // Remove port from socket address and replace it with provided port let parts: Vec<&str> = config.socket_addr.split(':').collect(); if let Some(addr) = parts.first() { config.socket_addr = format!("{addr}:{port}"); } config } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/mod.rs
src/eth_rpc/mod.rs
// //! Kakarot RPC module for Ethereum. // //! It is an adapter layer to interact with Kakarot ZK-EVM. pub mod api; pub mod config; pub mod middleware; pub mod rpc; pub mod servers; use crate::{ eth_rpc::middleware::{metrics::RpcMetrics, MetricsLayer}, prometheus_handler::init_prometheus, }; use config::RPCConfig; use eyre::Result; use jsonrpsee::{ server::{ middleware::http::{InvalidPath, ProxyGetRequestLayer}, RpcServiceBuilder, ServerBuilder, ServerHandle, }, RpcModule, }; use prometheus::Registry; use std::net::{AddrParseError, Ipv4Addr, SocketAddr}; use thiserror::Error; use tower_http::cors::{Any, CorsLayer}; #[derive(Error, Debug)] pub enum RpcError { #[error(transparent)] IoError(#[from] std::io::Error), #[error(transparent)] ParseError(#[from] AddrParseError), #[error(transparent)] JsonRpcError(#[from] InvalidPath), #[error(transparent)] PrometheusHandlerError(#[from] crate::prometheus_handler::Error), #[error(transparent)] PrometheusError(#[from] prometheus::Error), } /// # Errors /// /// Will return `Err` if an error occurs when running the `ServerBuilder` start fails. pub async fn run_server( kakarot_rpc_module: RpcModule<()>, rpc_config: RPCConfig, ) -> Result<(SocketAddr, ServerHandle), RpcError> { let RPCConfig { socket_addr } = rpc_config; let cors = CorsLayer::new().allow_methods(Any).allow_origin(Any).allow_headers(Any); let http_middleware = tower::ServiceBuilder::new().layer(ProxyGetRequestLayer::new("/health", "net_health")?).layer(cors); // Creating the prometheus registry to register the metrics let registry = Registry::new(); // register the metrics let metrics = RpcMetrics::new(Some(&registry))?.map(|m| MetricsLayer::new(m, "http")); tokio::spawn(async move { // serve the prometheus metrics on the given port so that it can be read let _ = init_prometheus( SocketAddr::new( std::net::IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), get_env_or_default("PROMETHEUS_PORT", "9615").parse().unwrap(), ), registry, ) .await; }); // add the metrics as a middleware to the RPC so that every new RPC call fires prometheus metrics // upon start, finish etc. we don't need to manually handle each method, it should automatically // work for any new method. let rpc_middleware = RpcServiceBuilder::new().option_layer(metrics); let server = ServerBuilder::default() .max_connections(get_env_or_default("RPC_MAX_CONNECTIONS", "100").parse().unwrap()) .set_http_middleware(http_middleware) .set_rpc_middleware(rpc_middleware) .build(socket_addr.parse::<SocketAddr>()?) .await?; let addr = server.local_addr()?; let handle = server.start(kakarot_rpc_module); Ok((addr, handle)) } fn get_env_or_default(name: &str, default: &str) -> String { std::env::var(name).unwrap_or_else(|_| default.to_string()) }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/rpc.rs
src/eth_rpc/rpc.rs
use crate::{ client::EthClient, eth_rpc::{ api::{ alchemy_api::AlchemyApiServer, debug_api::DebugApiServer, eth_api::EthApiServer, kakarot_api::KakarotApiServer, net_api::NetApiServer, trace_api::TraceApiServer, txpool_api::TxPoolApiServer, web3_api::Web3ApiServer, }, servers::{ alchemy_rpc::AlchemyRpc, debug_rpc::DebugRpc, eth_rpc::EthRpc, kakarot_rpc::KakarotRpc, net_rpc::NetRpc, trace_rpc::TraceRpc, txpool_rpc::TxpoolRpc, web3_rpc::Web3Rpc, }, }, providers::{ alchemy_provider::AlchemyDataProvider, debug_provider::DebugDataProvider, pool_provider::PoolDataProvider, }, }; use jsonrpsee::{server::RegisterMethodError, Methods, RpcModule}; use starknet::providers::Provider; use std::{collections::HashMap, marker::PhantomData, sync::Arc}; /// Represents RPC modules that are supported by reth #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] pub enum KakarotRpcModule { Eth, Alchemy, Web3, Net, Debug, Trace, Txpool, KakarotRpc, } #[derive(Debug)] pub struct KakarotRpcModuleBuilder<SP> { modules: HashMap<KakarotRpcModule, Methods>, _phantom: PhantomData<SP>, } impl<SP> KakarotRpcModuleBuilder<SP> where SP: Provider + Clone + Send + Sync + 'static, { pub fn new(eth_client: Arc<EthClient<SP>>) -> Self { let eth_provider = eth_client.eth_provider().clone(); let alchemy_provider = Arc::new(AlchemyDataProvider::new(eth_provider.clone())); let pool_provider = Arc::new(PoolDataProvider::new(eth_client.clone())); let debug_provider = Arc::new(DebugDataProvider::new(eth_provider.clone())); let eth_rpc_module = EthRpc::new(eth_client).into_rpc(); let alchemy_rpc_module = AlchemyRpc::new(alchemy_provider).into_rpc(); let web3_rpc_module = Web3Rpc::default().into_rpc(); let net_rpc_module = NetRpc::new(eth_provider.clone()).into_rpc(); let debug_rpc_module = DebugRpc::new(debug_provider).into_rpc(); let trace_rpc_module = TraceRpc::new(eth_provider).into_rpc(); let kakarot_rpc_module = KakarotRpc.into_rpc(); let txpool_rpc_module = TxpoolRpc::new(pool_provider).into_rpc(); let mut modules = HashMap::new(); modules.insert(KakarotRpcModule::Eth, eth_rpc_module.into()); modules.insert(KakarotRpcModule::Alchemy, alchemy_rpc_module.into()); modules.insert(KakarotRpcModule::Web3, web3_rpc_module.into()); modules.insert(KakarotRpcModule::Net, net_rpc_module.into()); modules.insert(KakarotRpcModule::Debug, debug_rpc_module.into()); modules.insert(KakarotRpcModule::Trace, trace_rpc_module.into()); modules.insert(KakarotRpcModule::Txpool, txpool_rpc_module.into()); modules.insert(KakarotRpcModule::KakarotRpc, kakarot_rpc_module.into()); Self { modules, _phantom: PhantomData } } pub fn rpc_module(&self) -> Result<RpcModule<()>, RegisterMethodError> { let mut rpc_module = RpcModule::new(()); for methods in self.modules.values().cloned() { rpc_module.merge(methods)?; } Ok(rpc_module) } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/middleware/mod.rs
src/eth_rpc/middleware/mod.rs
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. //! JSON-RPC specific middleware. /// Grafana metrics middleware. pub mod metrics; /// Rate limit middleware. pub use metrics::*;
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/middleware/metrics.rs
src/eth_rpc/middleware/metrics.rs
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. //! RPC middleware to collect prometheus metrics on RPC calls. use crate::prometheus_handler::{ register, CounterVec, HistogramOpts, HistogramVec, Opts, PrometheusError, Registry, U64, }; use jsonrpsee::{server::middleware::rpc::RpcServiceT, types::Request, MethodResponse}; use pin_project_lite::pin_project; use std::{ future::Future, pin::Pin, task::{Context, Poll}, time::Instant, }; /// Histogram time buckets in microseconds. const HISTOGRAM_BUCKETS: [f64; 13] = [ 5.0, 25.0, 100.0, 500.0, 1_000.0, 2_500.0, 10_000.0, 25_000.0, 100_000.0, 1_000_000.0, 2_000_000.0, 5_000_000.0, 10_000_000.0, ]; /// Metrics for RPC middleware storing information about the number of requests started/completed, /// calls started/completed and their timings. #[derive(Debug, Clone)] pub struct RpcMetrics { /// Histogram over RPC execution times. calls_time: HistogramVec, /// Number of calls started. calls_started: CounterVec<U64>, /// Number of calls completed. calls_finished: CounterVec<U64>, } impl RpcMetrics { /// Create an instance of metrics pub fn new(metrics_registry: Option<&Registry>) -> Result<Option<Self>, PrometheusError> { if let Some(metrics_registry) = metrics_registry { Ok(Some(Self { calls_time: register( HistogramVec::new( HistogramOpts::new("eth_rpc_calls_time", "Total time [μs] of processed RPC calls") .buckets(HISTOGRAM_BUCKETS.to_vec()), &["protocol", "method"], )?, metrics_registry, )?, calls_started: register( CounterVec::new( Opts::new("eth_rpc_calls_started", "Number of received RPC calls (unique un-batched requests)"), &["protocol", "method"], )?, metrics_registry, )?, calls_finished: register( CounterVec::new( Opts::new( "eth_rpc_calls_finished", "Number of processed RPC calls (unique un-batched requests)", ), &["protocol", "method", "is_error"], )?, metrics_registry, )?, })) } else { Ok(None) } } } /// Metrics layer. #[derive(Clone, Debug)] pub struct MetricsLayer { inner: RpcMetrics, transport_label: &'static str, } impl MetricsLayer { /// Create a new [`MetricsLayer`]. pub const fn new(metrics: RpcMetrics, transport_label: &'static str) -> Self { Self { inner: metrics, transport_label } } } impl<S> tower::Layer<S> for MetricsLayer { type Service = Metrics<S>; fn layer(&self, inner: S) -> Self::Service { Metrics::new(inner, self.inner.clone(), self.transport_label) } } /// Metrics middleware. #[derive(Clone, Debug)] pub struct Metrics<S> { service: S, metrics: RpcMetrics, transport_label: &'static str, } impl<S> Metrics<S> { /// Create a new metrics middleware. pub const fn new(service: S, metrics: RpcMetrics, transport_label: &'static str) -> Self { Self { service, metrics, transport_label } } } impl<'a, S> RpcServiceT<'a> for Metrics<S> where S: Send + Sync + RpcServiceT<'a>, { type Future = ResponseFuture<'a, S::Future>; fn call(&self, req: Request<'a>) -> Self::Future { let now = Instant::now(); tracing::trace!( target: "rpc_metrics", "[{}] on_call name={} params={:?}", self.transport_label, req.method_name(), req.params(), ); self.metrics.calls_started.with_label_values(&[self.transport_label, req.method_name()]).inc(); ResponseFuture { fut: self.service.call(req.clone()), metrics: self.metrics.clone(), req, now, transport_label: self.transport_label, } } } pin_project! { /// Response future for metrics. pub struct ResponseFuture<'a, F> { #[pin] fut: F, metrics: RpcMetrics, req: Request<'a>, now: Instant, transport_label: &'static str, } } impl<'a, F> std::fmt::Debug for ResponseFuture<'a, F> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("ResponseFuture") } } impl<'a, F: Future<Output = MethodResponse>> Future for ResponseFuture<'a, F> { type Output = F::Output; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); let res = this.fut.poll(cx); if let Poll::Ready(rp) = &res { let method_name = this.req.method_name(); let transport_label = &this.transport_label; let now = this.now; let metrics = &this.metrics; tracing::trace!(target: "rpc_metrics", "[{transport_label}] on_response started_at={:?}", now); tracing::trace!(target: "rpc_metrics::extra", "[{transport_label}] result={:?}", rp); let micros = now.elapsed().as_micros(); tracing::debug!( target: "rpc_metrics", "[{transport_label}] {method_name} call took {} μs", micros, ); metrics.calls_time.with_label_values(&[transport_label, method_name]).observe(micros as _); metrics .calls_finished .with_label_values(&[ transport_label, method_name, // the label "is_error", so `success` should be regarded as false // and vice-versa to be registrered correctly. if rp.is_success() { "false" } else { "true" }, ]) .inc(); } res } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/api/debug_api.rs
src/eth_rpc/api/debug_api.rs
use alloy_primitives::{Bytes, B256}; use alloy_rpc_types::{BlockId, BlockNumberOrTag, TransactionRequest}; use alloy_rpc_types_trace::geth::{GethDebugTracingCallOptions, GethDebugTracingOptions, GethTrace, TraceResult}; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; /// Debug API /// Taken from Reth's DebugApi trait: /// <https://github.com/paradigmxyz/reth/blob/5d6ac4c815c562677d7ae6ad6b422b55ef4ed8e2/crates/rpc/rpc-api/src/debug.rs#L14> #[rpc(server, namespace = "debug")] #[async_trait] pub trait DebugApi { /// Returns an RLP-encoded header. #[method(name = "getRawHeader")] async fn raw_header(&self, block_id: BlockId) -> RpcResult<Bytes>; /// Returns an RLP-encoded block. #[method(name = "getRawBlock")] async fn raw_block(&self, block_id: BlockId) -> RpcResult<Bytes>; /// Returns a EIP-2718 binary-encoded transaction. /// /// If this is a pooled EIP-4844 transaction, the blob sidecar is included. #[method(name = "getRawTransaction")] async fn raw_transaction(&self, hash: B256) -> RpcResult<Option<Bytes>>; /// Returns an array of EIP-2718 binary-encoded transactions for the given [BlockId]. #[method(name = "getRawTransactions")] async fn raw_transactions(&self, block_id: BlockId) -> RpcResult<Vec<Bytes>>; /// Returns an array of EIP-2718 binary-encoded receipts. #[method(name = "getRawReceipts")] async fn raw_receipts(&self, block_id: BlockId) -> RpcResult<Vec<Bytes>>; /// Returns the Geth debug trace for the given block number. #[method(name = "traceBlockByNumber")] async fn trace_block_by_number( &self, block_number: BlockNumberOrTag, opts: Option<GethDebugTracingOptions>, ) -> RpcResult<Vec<TraceResult>>; /// Returns the Geth debug trace for the given block hash. #[method(name = "traceBlockByHash")] async fn trace_block_by_hash( &self, block_hash: B256, opts: Option<GethDebugTracingOptions>, ) -> RpcResult<Vec<TraceResult>>; /// Returns the Geth debug trace for the given transaction hash. #[method(name = "traceTransaction")] async fn trace_transaction( &self, transaction_hash: B256, opts: Option<GethDebugTracingOptions>, ) -> RpcResult<GethTrace>; /// Runs an `eth_call` within the context of a given block execution and returns the Geth debug trace. #[method(name = "traceCall")] async fn trace_call( &self, request: TransactionRequest, block_number: Option<BlockId>, opts: Option<GethDebugTracingCallOptions>, ) -> RpcResult<GethTrace>; }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/api/kakarot_api.rs
src/eth_rpc/api/kakarot_api.rs
use crate::providers::eth_provider::constant::Constant; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; #[rpc(server, namespace = "kakarot")] #[async_trait] pub trait KakarotApi { #[method(name = "getConfig")] async fn get_config(&self) -> RpcResult<Constant>; }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/api/alchemy_api.rs
src/eth_rpc/api/alchemy_api.rs
use crate::models::token::{TokenBalances, TokenMetadata}; use alloy_primitives::{Address, U256}; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; #[rpc(server, namespace = "alchemy")] #[async_trait] pub trait AlchemyApi { #[method(name = "getTokenBalances")] async fn token_balances(&self, address: Address, contract_addresses: Vec<Address>) -> RpcResult<TokenBalances>; #[method(name = "getTokenMetadata")] async fn token_metadata(&self, contract_address: Address) -> RpcResult<TokenMetadata>; #[method(name = "getTokenAllowance")] async fn token_allowance(&self, contract_address: Address, owner: Address, spender: Address) -> RpcResult<U256>; }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/api/net_api.rs
src/eth_rpc/api/net_api.rs
use alloy_primitives::U64; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; // TODO: Define and implement of methods of Net API #[rpc(server, namespace = "net")] #[async_trait] pub trait NetApi { /// Returns the protocol version encoded as a string. #[method(name = "version")] async fn version(&self) -> RpcResult<U64>; /// Returns number of peers connected to node. #[method(name = "peerCount")] fn peer_count(&self) -> RpcResult<U64>; /// Returns true if client is actively listening for network connections. /// Otherwise false. #[method(name = "listening")] fn listening(&self) -> RpcResult<bool>; /// Returns true if Kakarot RPC_URL is reachable. /// Otherwise throw an EthApiError. #[method(name = "health")] async fn health(&self) -> RpcResult<bool>; }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/api/txpool_api.rs
src/eth_rpc/api/txpool_api.rs
use crate::providers::eth_provider::database::types::transaction::ExtendedTransaction; use alloy_primitives::Address; use alloy_rpc_types_txpool::{TxpoolContent, TxpoolContentFrom, TxpoolInspect, TxpoolStatus}; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; /// Txpool API #[rpc(server, namespace = "txpool")] #[async_trait] pub trait TxPoolApi { /// Returns the number of transactions currently pending for inclusion in the next block(s), as /// well as the ones that are being scheduled for future execution only. /// /// See [here](https://geth.ethereum.org/docs/rpc/ns-txpool#txpool_status) for more details #[method(name = "status")] async fn txpool_status(&self) -> RpcResult<TxpoolStatus>; /// Returns a summary of all the transactions currently pending for inclusion in the next /// block(s), as well as the ones that are being scheduled for future execution only. /// /// See [here](https://geth.ethereum.org/docs/rpc/ns-txpool#txpool_inspect) for more details #[method(name = "inspect")] async fn txpool_inspect(&self) -> RpcResult<TxpoolInspect>; /// Retrieves the transactions contained within the txpool, returning pending /// transactions of this address, grouped by nonce. /// /// See [here](https://geth.ethereum.org/docs/rpc/ns-txpool#txpool_contentFrom) for more details #[method(name = "contentFrom")] async fn txpool_content_from(&self, from: Address) -> RpcResult<TxpoolContentFrom<ExtendedTransaction>>; /// Returns the details of all transactions currently pending for inclusion in the next /// block(s), grouped by nonce. /// /// See [here](https://geth.ethereum.org/docs/rpc/ns-txpool#txpool_content) for more details #[method(name = "content")] async fn txpool_content(&self) -> RpcResult<TxpoolContent<ExtendedTransaction>>; }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/api/mod.rs
src/eth_rpc/api/mod.rs
pub mod alchemy_api; pub mod debug_api; pub mod eth_api; pub mod kakarot_api; pub mod net_api; pub mod trace_api; pub mod txpool_api; pub mod web3_api;
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/api/trace_api.rs
src/eth_rpc/api/trace_api.rs
use alloy_rpc_types::BlockId; use alloy_rpc_types_trace::parity::LocalizedTransactionTrace; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; /// Trace API #[rpc(server, namespace = "trace")] #[async_trait] pub trait TraceApi { /// Returns the parity traces for the given block. #[method(name = "block")] async fn trace_block(&self, block_id: BlockId) -> RpcResult<Option<Vec<LocalizedTransactionTrace>>>; }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/api/web3_api.rs
src/eth_rpc/api/web3_api.rs
use alloy_primitives::{Bytes, B256}; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; #[rpc(server, namespace = "web3")] #[async_trait] pub trait Web3Api { /// Returns the client version of the running Kakarot RPC #[method(name = "clientVersion")] fn client_version(&self) -> RpcResult<String>; /// Returns Keccak256 of some input value #[method(name = "sha3")] fn sha3(&self, input: Bytes) -> RpcResult<B256>; }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/api/eth_api.rs
src/eth_rpc/api/eth_api.rs
use crate::providers::eth_provider::database::types::receipt::ExtendedTxReceipt; use alloy_eips::{BlockId, BlockNumberOrTag}; use alloy_primitives::{Address, Bytes, B256, B64, U256, U64}; use alloy_rpc_types::{ serde_helpers::JsonStorageKey, state::StateOverride, AccessListResult, Block, BlockOverrides, EIP1186AccountProofResponse, FeeHistory, Filter, FilterChanges, Index, SyncStatus, Transaction as EthTransaction, TransactionRequest, Work, }; use alloy_serde::WithOtherFields; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; /// Ethereum JSON-RPC API Trait /// Mostly based on <https://github.com/paradigmxyz/reth/blob/559124ac5a0b25030250203babcd8a94693df648/crates/rpc/rpc-api/src/eth.rs#L15> /// With some small modifications #[rpc(server, namespace = "eth")] #[async_trait] pub trait EthApi { #[method(name = "blockNumber")] async fn block_number(&self) -> RpcResult<U64>; /// Returns an object with data about the sync status or false. #[method(name = "syncing")] async fn syncing(&self) -> RpcResult<SyncStatus>; /// Returns the client coinbase address. #[method(name = "coinbase")] async fn coinbase(&self) -> RpcResult<Address>; /// Returns a list of addresses owned by client. #[method(name = "accounts")] async fn accounts(&self) -> RpcResult<Vec<Address>>; /// Returns the chain ID of the current network. #[method(name = "chainId")] async fn chain_id(&self) -> RpcResult<Option<U64>>; /// Returns information about a block by hash. #[method(name = "getBlockByHash")] async fn block_by_hash( &self, hash: B256, full: bool, ) -> RpcResult<Option<WithOtherFields<Block<WithOtherFields<EthTransaction>>>>>; /// Returns information about a block by number. #[method(name = "getBlockByNumber")] async fn block_by_number( &self, number: BlockNumberOrTag, full: bool, ) -> RpcResult<Option<WithOtherFields<Block<WithOtherFields<EthTransaction>>>>>; /// Returns the number of transactions in a block from a block matching the given block hash. #[method(name = "getBlockTransactionCountByHash")] async fn block_transaction_count_by_hash(&self, hash: B256) -> RpcResult<Option<U256>>; /// Returns the number of transactions in a block matching the given block number. #[method(name = "getBlockTransactionCountByNumber")] async fn block_transaction_count_by_number(&self, number: BlockNumberOrTag) -> RpcResult<Option<U256>>; /// Returns the number of uncles in a block from a block matching the given block hash. #[method(name = "getUncleCountByBlockHash")] async fn block_uncles_count_by_block_hash(&self, hash: B256) -> RpcResult<U256>; /// Returns the number of uncles in a block with given block number. #[method(name = "getUncleCountByBlockNumber")] async fn block_uncles_count_by_block_number(&self, number: BlockNumberOrTag) -> RpcResult<U256>; /// Returns an uncle block of the given block and index. #[method(name = "getUncleByBlockHashAndIndex")] async fn uncle_by_block_hash_and_index( &self, hash: B256, index: Index, ) -> RpcResult<Option<WithOtherFields<Block<WithOtherFields<EthTransaction>>>>>; /// Returns an uncle block of the given block and index. #[method(name = "getUncleByBlockNumberAndIndex")] async fn uncle_by_block_number_and_index( &self, number: BlockNumberOrTag, index: Index, ) -> RpcResult<Option<WithOtherFields<Block<WithOtherFields<EthTransaction>>>>>; /// Returns the information about a transaction requested by transaction hash. #[method(name = "getTransactionByHash")] async fn transaction_by_hash(&self, hash: B256) -> RpcResult<Option<WithOtherFields<EthTransaction>>>; /// Returns information about a transaction by block hash and transaction index position. #[method(name = "getTransactionByBlockHashAndIndex")] async fn transaction_by_block_hash_and_index( &self, hash: B256, index: Index, ) -> RpcResult<Option<WithOtherFields<EthTransaction>>>; /// Returns information about a transaction by block number and transaction index position. #[method(name = "getTransactionByBlockNumberAndIndex")] async fn transaction_by_block_number_and_index( &self, number: BlockNumberOrTag, index: Index, ) -> RpcResult<Option<WithOtherFields<EthTransaction>>>; /// Returns the receipt of a transaction by transaction hash. #[method(name = "getTransactionReceipt")] async fn transaction_receipt(&self, hash: B256) -> RpcResult<Option<ExtendedTxReceipt>>; /// Returns the balance of the account of given address. #[method(name = "getBalance")] async fn balance(&self, address: Address, block_number: Option<BlockId>) -> RpcResult<U256>; /// Returns the value from a storage position at a given address #[method(name = "getStorageAt")] async fn storage_at(&self, address: Address, index: JsonStorageKey, block_id: Option<BlockId>) -> RpcResult<B256>; /// Returns the number of transactions sent from an address at given block number. #[method(name = "getTransactionCount")] async fn transaction_count(&self, address: Address, block_id: Option<BlockId>) -> RpcResult<U256>; /// Returns code at a given address at given block number. #[method(name = "getCode")] async fn get_code(&self, address: Address, block_id: Option<BlockId>) -> RpcResult<Bytes>; /// Returns the logs corresponding to the given filter object. #[method(name = "getLogs")] async fn get_logs(&self, filter: Filter) -> RpcResult<FilterChanges>; /// Executes a new message call immediately without creating a transaction on the block chain. #[method(name = "call")] async fn call( &self, request: TransactionRequest, block_id: Option<BlockId>, state_overrides: Option<StateOverride>, block_overrides: Option<Box<BlockOverrides>>, ) -> RpcResult<Bytes>; /// Generates an access list for a transaction. /// /// This method creates an [EIP2930](https://eips.ethereum.org/EIPS/eip-2930) type accessList based on a given Transaction. /// /// An access list contains all storage slots and addresses touched by the transaction, except /// for the sender account and the chain's precompiles. /// /// It returns list of addresses and storage keys used by the transaction, plus the gas /// consumed when the access list is added. That is, it gives you the list of addresses and /// storage keys that will be used by that transaction, plus the gas consumed if the access /// list is included. Like estimateGas, this is an estimation; the list could change /// when the transaction is actually mined. Adding an accessList to your transaction does /// not necessary result in lower gas usage compared to a transaction without an access /// list. #[method(name = "createAccessList")] async fn create_access_list( &self, request: TransactionRequest, block_id: Option<BlockId>, ) -> RpcResult<AccessListResult>; /// Generates and returns an estimate of how much gas is necessary to allow the transaction to /// complete. #[method(name = "estimateGas")] async fn estimate_gas(&self, request: TransactionRequest, block_id: Option<BlockId>) -> RpcResult<U256>; /// Returns the current price per gas in wei. #[method(name = "gasPrice")] async fn gas_price(&self) -> RpcResult<U256>; /// Returns the Transaction fee history /// /// Introduced in EIP-1159 for getting information on the appropriate priority fee to use. /// /// Returns transaction base fee per gas and effective priority fee per gas for the /// requested/supported block range. The returned Fee history for the returned block range /// can be a subsection of the requested range if not all blocks are available. #[method(name = "feeHistory")] async fn fee_history( &self, block_count: U64, newest_block: BlockNumberOrTag, reward_percentiles: Option<Vec<f64>>, ) -> RpcResult<FeeHistory>; /// Returns the current maxPriorityFeePerGas per gas in wei. #[method(name = "maxPriorityFeePerGas")] async fn max_priority_fee_per_gas(&self) -> RpcResult<U256>; /// Introduced in EIP-4844, returns the current blob base fee in wei. #[method(name = "blobBaseFee")] async fn blob_base_fee(&self) -> RpcResult<U256>; /// Returns whether the client is actively mining new blocks. #[method(name = "mining")] async fn mining(&self) -> RpcResult<bool>; /// Returns the number of hashes per second that the node is mining with. #[method(name = "hashrate")] async fn hashrate(&self) -> RpcResult<U256>; /// Returns the hash of the current block, the seedHash, and the boundary condition to be met /// (“target”) #[method(name = "getWork")] async fn get_work(&self) -> RpcResult<Work>; /// Used for submitting mining hashrate. #[method(name = "submitHashrate")] async fn submit_hashrate(&self, hashrate: U256, id: B256) -> RpcResult<bool>; /// Used for submitting a proof-of-work solution. #[method(name = "submitWork")] async fn submit_work(&self, nonce: B64, pow_hash: B256, mix_digest: B256) -> RpcResult<bool>; /// Sends transaction; will block waiting for signer to return the /// transaction hash. #[method(name = "sendTransaction")] async fn send_transaction(&self, request: TransactionRequest) -> RpcResult<B256>; /// Sends signed transaction, returning its hash. #[method(name = "sendRawTransaction")] async fn send_raw_transaction(&self, bytes: Bytes) -> RpcResult<B256>; /// Returns an Ethereum specific signature with: sign(keccak256("\x19Ethereum Signed Message:\n" /// + len(message) + message))). #[method(name = "sign")] async fn sign(&self, address: Address, message: Bytes) -> RpcResult<Bytes>; /// Signs a transaction that can be submitted to the network at a later time using with /// `sendRawTransaction.` #[method(name = "signTransaction")] async fn sign_transaction(&self, transaction: TransactionRequest) -> RpcResult<Bytes>; /// Signs data via [EIP-712](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md). #[method(name = "signTypedData")] async fn sign_typed_data(&self, address: Address, data: serde_json::Value) -> RpcResult<Bytes>; /// Returns the account and storage values of the specified account including the Merkle-proof. /// This call can be used to verify that the data you are pulling from is not tampered with. #[method(name = "getProof")] async fn get_proof( &self, address: Address, keys: Vec<B256>, block_id: Option<BlockId>, ) -> RpcResult<EIP1186AccountProofResponse>; /// Creates a filter object, based on filter options, to notify when the state changes (logs). #[method(name = "newFilter")] async fn new_filter(&self, filter: Filter) -> RpcResult<U64>; /// Creates a filter in the node, to notify when a new block arrives. #[method(name = "newBlockFilter")] async fn new_block_filter(&self) -> RpcResult<U64>; /// Creates a filter in the node, to notify when new pending transactions arrive. #[method(name = "newPendingTransactionFilter")] async fn new_pending_transaction_filter(&self) -> RpcResult<U64>; /// Destroys a filter based on filter ID #[method(name = "uninstallFilter")] async fn uninstall_filter(&self, id: U64) -> RpcResult<bool>; /// Returns a list of all logs based on filter ID since the last log retrieval #[method(name = "getFilterChanges")] async fn get_filter_changes(&self, id: U64) -> RpcResult<FilterChanges>; /// Returns a list of all logs based on filter ID #[method(name = "getFilterLogs")] async fn get_filter_logs(&self, id: U64) -> RpcResult<FilterChanges>; /// Returns all transaction receipts for a given block. #[method(name = "getBlockReceipts")] async fn block_receipts(&self, block_id: Option<BlockId>) -> RpcResult<Option<Vec<ExtendedTxReceipt>>>; }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/servers/trace_rpc.rs
src/eth_rpc/servers/trace_rpc.rs
use crate::{ eth_rpc::api::trace_api::TraceApiServer, providers::eth_provider::provider::EthereumProvider, tracing::builder::TracerBuilder, }; use alloy_rpc_types::BlockId; use alloy_rpc_types_trace::parity::LocalizedTransactionTrace; use jsonrpsee::core::{async_trait, RpcResult}; use revm_inspectors::tracing::TracingInspectorConfig; use std::sync::Arc; /// The RPC module for implementing the Trace api #[derive(Debug)] pub struct TraceRpc<P: EthereumProvider> { eth_provider: P, } impl<P: EthereumProvider> TraceRpc<P> { pub const fn new(eth_provider: P) -> Self { Self { eth_provider } } } #[async_trait] impl<P: EthereumProvider + Send + Sync + 'static> TraceApiServer for TraceRpc<P> { /// Returns the parity traces for the given block. #[tracing::instrument(skip(self), err)] async fn trace_block(&self, block_id: BlockId) -> RpcResult<Option<Vec<LocalizedTransactionTrace>>> { tracing::info!("Serving debug_traceBlock"); let tracer = TracerBuilder::new(Arc::new(&self.eth_provider)) .await? .with_block_id(block_id) .await? .with_tracing_options(TracingInspectorConfig::default_parity().into()) .build()?; Ok(tracer.trace_block()?) } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/servers/debug_rpc.rs
src/eth_rpc/servers/debug_rpc.rs
use crate::{eth_rpc::api::debug_api::DebugApiServer, providers::debug_provider::DebugProvider}; use alloy_primitives::{Bytes, B256}; use alloy_rpc_types::{BlockId, BlockNumberOrTag, TransactionRequest}; use alloy_rpc_types_trace::geth::{GethDebugTracingCallOptions, GethDebugTracingOptions, GethTrace, TraceResult}; use jsonrpsee::core::{async_trait, RpcResult}; /// The RPC module for the implementing Net api #[derive(Debug)] pub struct DebugRpc<DP: DebugProvider> { debug_provider: DP, } impl<DP> DebugRpc<DP> where DP: DebugProvider, { pub const fn new(debug_provider: DP) -> Self { Self { debug_provider } } } #[async_trait] impl<DP> DebugApiServer for DebugRpc<DP> where DP: DebugProvider + Send + Sync + 'static, { /// Returns a RLP-encoded header. #[tracing::instrument(skip(self), err)] async fn raw_header(&self, block_id: BlockId) -> RpcResult<Bytes> { self.debug_provider.raw_header(block_id).await.map_err(Into::into) } /// Returns a RLP-encoded block. #[tracing::instrument(skip(self), err)] async fn raw_block(&self, block_id: BlockId) -> RpcResult<Bytes> { self.debug_provider.raw_block(block_id).await.map_err(Into::into) } /// Returns an EIP-2718 binary-encoded transaction. /// /// If this is a pooled EIP-4844 transaction, the blob sidecar is included. #[tracing::instrument(skip(self), err)] async fn raw_transaction(&self, hash: B256) -> RpcResult<Option<Bytes>> { self.debug_provider.raw_transaction(hash).await.map_err(Into::into) } /// Returns an array of EIP-2718 binary-encoded transactions for the given [BlockId]. #[tracing::instrument(skip(self), err)] async fn raw_transactions(&self, block_id: BlockId) -> RpcResult<Vec<Bytes>> { self.debug_provider.raw_transactions(block_id).await.map_err(Into::into) } /// Returns an array of EIP-2718 binary-encoded receipts. #[tracing::instrument(skip(self), err)] async fn raw_receipts(&self, block_id: BlockId) -> RpcResult<Vec<Bytes>> { self.debug_provider.raw_receipts(block_id).await.map_err(Into::into) } /// Returns the Geth debug trace for the given block number. #[tracing::instrument(skip(self, opts), err)] async fn trace_block_by_number( &self, block_number: BlockNumberOrTag, opts: Option<GethDebugTracingOptions>, ) -> RpcResult<Vec<TraceResult>> { self.debug_provider.trace_block_by_number(block_number, opts).await.map_err(Into::into) } /// Returns the Geth debug trace for the given block hash. #[tracing::instrument(skip(self, opts), err)] async fn trace_block_by_hash( &self, block_hash: B256, opts: Option<GethDebugTracingOptions>, ) -> RpcResult<Vec<TraceResult>> { self.debug_provider.trace_block_by_hash(block_hash, opts).await.map_err(Into::into) } /// Returns the Geth debug trace for the given transaction hash. #[tracing::instrument(skip(self, opts), err)] async fn trace_transaction( &self, transaction_hash: B256, opts: Option<GethDebugTracingOptions>, ) -> RpcResult<GethTrace> { self.debug_provider.trace_transaction(transaction_hash, opts).await.map_err(Into::into) } /// Runs an `eth_call` within the context of a given block execution and returns the Geth debug trace. #[tracing::instrument(skip(self, request, opts), err)] async fn trace_call( &self, request: TransactionRequest, block_number: Option<BlockId>, opts: Option<GethDebugTracingCallOptions>, ) -> RpcResult<GethTrace> { self.debug_provider.trace_call(request, block_number, opts).await.map_err(Into::into) } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/servers/txpool_rpc.rs
src/eth_rpc/servers/txpool_rpc.rs
use crate::{ eth_rpc::api::txpool_api::TxPoolApiServer, providers::{eth_provider::database::types::transaction::ExtendedTransaction, pool_provider::PoolProvider}, }; use alloy_primitives::Address; use alloy_rpc_types_txpool::{TxpoolContent, TxpoolContentFrom, TxpoolInspect, TxpoolStatus}; use jsonrpsee::core::{async_trait, RpcResult}; use tracing::instrument; /// The RPC module for implementing the Txpool api #[derive(Debug)] pub struct TxpoolRpc<PP: PoolProvider> { pool_provider: PP, } impl<PP> TxpoolRpc<PP> where PP: PoolProvider, { pub const fn new(pool_provider: PP) -> Self { Self { pool_provider } } } #[async_trait] impl<PP> TxPoolApiServer for TxpoolRpc<PP> where PP: PoolProvider + Send + Sync + 'static, { /// Returns the number of transactions currently pending for inclusion in the next block(s), as /// well as the ones that are being scheduled for future execution only. /// Ref: [Here](https://geth.ethereum.org/docs/rpc/ns-txpool#txpool_status) /// /// Handler for `txpool_status` #[instrument(skip(self))] async fn txpool_status(&self) -> RpcResult<TxpoolStatus> { self.pool_provider.txpool_status().await.map_err(Into::into) } /// Returns a summary of all the transactions currently pending for inclusion in the next /// block(s), as well as the ones that are being scheduled for future execution only. /// /// See [here](https://geth.ethereum.org/docs/rpc/ns-txpool#txpool_inspect) for more details /// /// Handler for `txpool_inspect` #[instrument(skip(self))] async fn txpool_inspect(&self) -> RpcResult<TxpoolInspect> { self.pool_provider.txpool_inspect().await.map_err(Into::into) } /// Retrieves the transactions contained within the txpool, returning pending /// transactions of this address, grouped by nonce. /// /// See [here](https://geth.ethereum.org/docs/rpc/ns-txpool#txpool_contentFrom) for more details /// Handler for `txpool_contentFrom` #[instrument(skip(self))] async fn txpool_content_from(&self, from: Address) -> RpcResult<TxpoolContentFrom<ExtendedTransaction>> { self.pool_provider.txpool_content_from(from).await.map_err(Into::into) } /// Returns the details of all transactions currently pending for inclusion in the next /// block(s), grouped by nonce. /// /// See [here](https://geth.ethereum.org/docs/rpc/ns-txpool#txpool_content) for more details /// Handler for `txpool_content` #[instrument(skip(self))] async fn txpool_content(&self) -> RpcResult<TxpoolContent<ExtendedTransaction>> { self.pool_provider.txpool_content().await.map_err(Into::into) } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/servers/eth_rpc.rs
src/eth_rpc/servers/eth_rpc.rs
use crate::{ client::{EthClient, TransactionHashProvider}, eth_rpc::api::eth_api::EthApiServer, providers::eth_provider::{ constant::MAX_PRIORITY_FEE_PER_GAS, database::types::{header::ExtendedBlock, receipt::ExtendedTxReceipt, transaction::ExtendedTransaction}, error::EthApiError, BlockProvider, ChainProvider, GasProvider, LogProvider, ReceiptProvider, StateProvider, TransactionProvider, }, }; use alloy_eips::{BlockId, BlockNumberOrTag}; use alloy_primitives::{Address, Bytes, B256, B64, U256, U64}; use alloy_rpc_types::{ serde_helpers::JsonStorageKey, state::StateOverride, AccessListResult, BlockOverrides, EIP1186AccountProofResponse, FeeHistory, Filter, FilterChanges, Index, SyncStatus, TransactionRequest, Work, }; use jsonrpsee::core::{async_trait, RpcResult}; use serde_json::Value; use starknet::providers::Provider; use std::sync::Arc; use tracing::Level; /// The RPC module for the Ethereum protocol required by Kakarot. #[derive(Debug)] pub struct EthRpc<SP> where SP: Provider + Send + Sync, { eth_client: Arc<EthClient<SP>>, } impl<SP> EthRpc<SP> where SP: Provider + Send + Sync, { pub const fn new(eth_client: Arc<EthClient<SP>>) -> Self { Self { eth_client } } } #[async_trait] impl<SP> EthApiServer for EthRpc<SP> where SP: Provider + Clone + Send + Sync + 'static, { #[tracing::instrument(skip_all, ret, err)] async fn block_number(&self) -> RpcResult<U64> { Ok(self.eth_client.eth_provider().block_number().await?) } #[tracing::instrument(skip_all, ret, err)] async fn syncing(&self) -> RpcResult<SyncStatus> { Ok(self.eth_client.eth_provider().syncing().await?) } async fn coinbase(&self) -> RpcResult<Address> { Err(EthApiError::Unsupported("eth_coinbase").into()) } #[tracing::instrument(skip_all, ret, err)] async fn accounts(&self) -> RpcResult<Vec<Address>> { Ok(Vec::new()) } #[tracing::instrument(skip_all, ret, err)] async fn chain_id(&self) -> RpcResult<Option<U64>> { Ok(self.eth_client.eth_provider().chain_id().await?) } #[tracing::instrument(skip(self), ret, err)] async fn block_by_hash(&self, hash: B256, full: bool) -> RpcResult<Option<ExtendedBlock>> { Ok(self.eth_client.eth_provider().block_by_hash(hash, full).await?) } #[tracing::instrument(skip(self), err)] async fn block_by_number(&self, number: BlockNumberOrTag, full: bool) -> RpcResult<Option<ExtendedBlock>> { Ok(self.eth_client.eth_provider().block_by_number(number, full).await?) } #[tracing::instrument(skip(self), ret, err)] async fn block_transaction_count_by_hash(&self, hash: B256) -> RpcResult<Option<U256>> { Ok(self.eth_client.eth_provider().block_transaction_count_by_hash(hash).await?) } #[tracing::instrument(skip(self), ret, err)] async fn block_transaction_count_by_number(&self, number: BlockNumberOrTag) -> RpcResult<Option<U256>> { Ok(self.eth_client.eth_provider().block_transaction_count_by_number(number).await?) } async fn block_uncles_count_by_block_hash(&self, _hash: B256) -> RpcResult<U256> { tracing::warn!("Kakarot chain does not produce uncles"); Ok(U256::ZERO) } async fn block_uncles_count_by_block_number(&self, _number: BlockNumberOrTag) -> RpcResult<U256> { tracing::warn!("Kakarot chain does not produce uncles"); Ok(U256::ZERO) } async fn uncle_by_block_hash_and_index(&self, _hash: B256, _index: Index) -> RpcResult<Option<ExtendedBlock>> { tracing::warn!("Kakarot chain does not produce uncles"); Ok(None) } async fn uncle_by_block_number_and_index( &self, _number: BlockNumberOrTag, _index: Index, ) -> RpcResult<Option<ExtendedBlock>> { tracing::warn!("Kakarot chain does not produce uncles"); Ok(None) } #[tracing::instrument(skip(self), ret, err)] async fn transaction_by_hash(&self, hash: B256) -> RpcResult<Option<ExtendedTransaction>> { Ok(self.eth_client.transaction_by_hash(hash).await?) } #[tracing::instrument(skip(self), ret, err)] async fn transaction_by_block_hash_and_index( &self, hash: B256, index: Index, ) -> RpcResult<Option<ExtendedTransaction>> { Ok(self.eth_client.eth_provider().transaction_by_block_hash_and_index(hash, index).await?) } #[tracing::instrument(skip(self), ret, err)] async fn transaction_by_block_number_and_index( &self, number: BlockNumberOrTag, index: Index, ) -> RpcResult<Option<ExtendedTransaction>> { Ok(self.eth_client.eth_provider().transaction_by_block_number_and_index(number, index).await?) } #[tracing::instrument(skip(self), ret, err)] async fn transaction_receipt(&self, hash: B256) -> RpcResult<Option<ExtendedTxReceipt>> { Ok(self.eth_client.eth_provider().transaction_receipt(hash).await?) } #[tracing::instrument(skip(self), ret, err)] async fn balance(&self, address: Address, block_id: Option<BlockId>) -> RpcResult<U256> { Ok(self.eth_client.eth_provider().balance(address, block_id).await?) } #[tracing::instrument(skip(self), ret, err)] async fn storage_at(&self, address: Address, index: JsonStorageKey, block_id: Option<BlockId>) -> RpcResult<B256> { Ok(self.eth_client.eth_provider().storage_at(address, index, block_id).await?) } #[tracing::instrument(skip(self), ret, err)] async fn transaction_count(&self, address: Address, block_id: Option<BlockId>) -> RpcResult<U256> { Ok(self.eth_client.eth_provider().transaction_count(address, block_id).await?) } #[tracing::instrument(skip(self), err)] async fn get_code(&self, address: Address, block_id: Option<BlockId>) -> RpcResult<Bytes> { Ok(self.eth_client.eth_provider().get_code(address, block_id).await?) } #[tracing::instrument(skip_all, err)] async fn get_logs(&self, filter: Filter) -> RpcResult<FilterChanges> { tracing::info!(?filter); Ok(self.eth_client.eth_provider().get_logs(filter).await?) } #[tracing::instrument(skip(self, request), err)] async fn call( &self, request: TransactionRequest, block_id: Option<BlockId>, state_overrides: Option<StateOverride>, block_overrides: Option<Box<BlockOverrides>>, ) -> RpcResult<Bytes> { Ok(self.eth_client.eth_provider().call(request, block_id, state_overrides, block_overrides).await?) } async fn create_access_list( &self, _request: TransactionRequest, _block_id: Option<BlockId>, ) -> RpcResult<AccessListResult> { Err(EthApiError::Unsupported("eth_createAccessList").into()) } #[tracing::instrument(skip(self, request), err)] async fn estimate_gas(&self, request: TransactionRequest, block_id: Option<BlockId>) -> RpcResult<U256> { Ok(U256::from(self.eth_client.eth_provider().estimate_gas(request, block_id).await?)) } #[tracing::instrument(skip_all, ret, err)] async fn gas_price(&self) -> RpcResult<U256> { Ok(self.eth_client.eth_provider().gas_price().await?) } #[tracing::instrument(skip(self), ret, err)] async fn fee_history( &self, block_count: U64, newest_block: BlockNumberOrTag, reward_percentiles: Option<Vec<f64>>, ) -> RpcResult<FeeHistory> { tracing::info!("Serving eth_feeHistory"); Ok(self.eth_client.eth_provider().fee_history(block_count, newest_block, reward_percentiles).await?) } #[tracing::instrument(skip_all, ret, err)] async fn max_priority_fee_per_gas(&self) -> RpcResult<U256> { Ok(U256::from(*MAX_PRIORITY_FEE_PER_GAS)) } async fn blob_base_fee(&self) -> RpcResult<U256> { Err(EthApiError::Unsupported("eth_blobBaseFee").into()) } async fn mining(&self) -> RpcResult<bool> { tracing::warn!("Kakarot chain does not use mining"); Ok(false) } async fn hashrate(&self) -> RpcResult<U256> { tracing::warn!("Kakarot chain does not produce hash rate"); Ok(U256::ZERO) } async fn get_work(&self) -> RpcResult<Work> { tracing::warn!("Kakarot chain does not produce work"); Ok(Work::default()) } async fn submit_hashrate(&self, _hashrate: U256, _id: B256) -> RpcResult<bool> { Err(EthApiError::Unsupported("eth_submitHashrate").into()) } async fn submit_work(&self, _nonce: B64, _pow_hash: B256, _mix_digest: B256) -> RpcResult<bool> { Err(EthApiError::Unsupported("eth_submitWork").into()) } async fn send_transaction(&self, _request: TransactionRequest) -> RpcResult<B256> { Err(EthApiError::Unsupported("eth_sendTransaction").into()) } #[tracing::instrument(skip_all, ret, err(level = Level::WARN))] async fn send_raw_transaction(&self, bytes: Bytes) -> RpcResult<B256> { tracing::info!("Serving eth_sendRawTransaction"); #[cfg(feature = "forwarding")] { use crate::providers::eth_provider::{constant::forwarding::MAIN_RPC_URL, error::TransactionError}; use alloy_provider::{Provider as _, ProviderBuilder}; use url::Url; let provider = ProviderBuilder::new().on_http(Url::parse(MAIN_RPC_URL.as_ref()).unwrap()); let tx_hash = provider .send_raw_transaction(&bytes) .await .map_err(|e| EthApiError::Transaction(TransactionError::Broadcast(e.into())))?; return Ok(*tx_hash.tx_hash()); } #[cfg(not(feature = "forwarding"))] { use crate::client::KakarotTransactions; Ok(self.eth_client.send_raw_transaction(bytes).await?) } } async fn sign(&self, _address: Address, _message: Bytes) -> RpcResult<Bytes> { Err(EthApiError::Unsupported("eth_sign").into()) } async fn sign_transaction(&self, _transaction: TransactionRequest) -> RpcResult<Bytes> { Err(EthApiError::Unsupported("eth_signTransaction").into()) } async fn sign_typed_data(&self, _address: Address, _data: Value) -> RpcResult<Bytes> { Err(EthApiError::Unsupported("eth_signTypedData").into()) } async fn get_proof( &self, _address: Address, _keys: Vec<B256>, _block_id: Option<BlockId>, ) -> RpcResult<EIP1186AccountProofResponse> { Err(EthApiError::Unsupported("eth_getProof").into()) } async fn new_filter(&self, _filter: Filter) -> RpcResult<U64> { Err(EthApiError::Unsupported("eth_newFilter").into()) } async fn new_block_filter(&self) -> RpcResult<U64> { Err(EthApiError::Unsupported("eth_newBlockFilter").into()) } async fn new_pending_transaction_filter(&self) -> RpcResult<U64> { Err(EthApiError::Unsupported("eth_newPendingTransactionFilter").into()) } async fn uninstall_filter(&self, _id: U64) -> RpcResult<bool> { Err(EthApiError::Unsupported("eth_uninstallFilter").into()) } async fn get_filter_changes(&self, _id: U64) -> RpcResult<FilterChanges> { Err(EthApiError::Unsupported("eth_getFilterChanges").into()) } async fn get_filter_logs(&self, _id: U64) -> RpcResult<FilterChanges> { Err(EthApiError::Unsupported("eth_getFilterLogs").into()) } async fn block_receipts(&self, block_id: Option<BlockId>) -> RpcResult<Option<Vec<ExtendedTxReceipt>>> { Ok(self.eth_client.eth_provider().block_receipts(block_id).await?) } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/servers/mod.rs
src/eth_rpc/servers/mod.rs
pub mod alchemy_rpc; pub mod debug_rpc; pub mod eth_rpc; pub mod kakarot_rpc; pub mod net_rpc; pub mod trace_rpc; pub mod txpool_rpc; pub mod web3_rpc;
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/servers/kakarot_rpc.rs
src/eth_rpc/servers/kakarot_rpc.rs
use crate::{ config::KakarotRpcConfig, eth_rpc::api::kakarot_api::KakarotApiServer, providers::eth_provider::{ constant::{Constant, MAX_LOGS}, starknet::kakarot_core::{get_white_listed_eip_155_transaction_hashes, MAX_FELTS_IN_CALLDATA}, }, }; use jsonrpsee::core::{async_trait, RpcResult}; #[derive(Debug)] pub struct KakarotRpc; #[async_trait] impl KakarotApiServer for KakarotRpc { async fn get_config(&self) -> RpcResult<Constant> { let starknet_config = KakarotRpcConfig::from_env().expect("Failed to load Kakarot RPC config"); Ok(Constant { max_logs: *MAX_LOGS, starknet_network: String::from(starknet_config.network_url), max_felts_in_calldata: *MAX_FELTS_IN_CALLDATA, white_listed_eip_155_transaction_hashes: get_white_listed_eip_155_transaction_hashes(), kakarot_address: starknet_config.kakarot_address, }) } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/servers/alchemy_rpc.rs
src/eth_rpc/servers/alchemy_rpc.rs
use crate::{ eth_rpc::api::alchemy_api::AlchemyApiServer, models::token::{TokenBalances, TokenMetadata}, providers::alchemy_provider::AlchemyProvider, }; use alloy_primitives::{Address, U256}; use async_trait::async_trait; use jsonrpsee::core::RpcResult; /// The RPC module for the Ethereum protocol required by Kakarot. #[derive(Debug)] pub struct AlchemyRpc<AP: AlchemyProvider> { alchemy_provider: AP, } impl<AP> AlchemyRpc<AP> where AP: AlchemyProvider, { pub const fn new(alchemy_provider: AP) -> Self { Self { alchemy_provider } } } #[async_trait] impl<AP> AlchemyApiServer for AlchemyRpc<AP> where AP: AlchemyProvider + Send + Sync + 'static, { #[tracing::instrument(skip(self, contract_addresses), ret, err)] async fn token_balances(&self, address: Address, contract_addresses: Vec<Address>) -> RpcResult<TokenBalances> { self.alchemy_provider.token_balances(address, contract_addresses).await.map_err(Into::into) } #[tracing::instrument(skip(self), ret, err)] async fn token_metadata(&self, contract_address: Address) -> RpcResult<TokenMetadata> { self.alchemy_provider.token_metadata(contract_address).await.map_err(Into::into) } #[tracing::instrument(skip(self), ret, err)] async fn token_allowance(&self, contract_address: Address, owner: Address, spender: Address) -> RpcResult<U256> { self.alchemy_provider.token_allowance(contract_address, owner, spender).await.map_err(Into::into) } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/servers/web3_rpc.rs
src/eth_rpc/servers/web3_rpc.rs
use crate::eth_rpc::api::web3_api::Web3ApiServer; use alloy_primitives::{keccak256, Bytes, B256}; use jsonrpsee::core::{async_trait, RpcResult}; /// The RPC module for the implementing Web3 Api { i.e rpc endpoints prefixed with web3_ } #[derive(Default, Debug)] pub struct Web3Rpc {} impl Web3Rpc { pub const fn new() -> Self { Self {} } } #[async_trait] impl Web3ApiServer for Web3Rpc { fn client_version(&self) -> RpcResult<String> { Ok(format!("kakarot_{}", env!("CARGO_PKG_VERSION"))) } fn sha3(&self, input: Bytes) -> RpcResult<B256> { Ok(keccak256(input)) } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/eth_rpc/servers/net_rpc.rs
src/eth_rpc/servers/net_rpc.rs
use crate::{eth_rpc::api::net_api::NetApiServer, providers::eth_provider::provider::EthereumProvider}; use alloy_primitives::U64; use jsonrpsee::core::{async_trait, RpcResult}; /// The RPC module for the implementing Net api #[derive(Debug)] pub struct NetRpc<P: EthereumProvider> { eth_provider: P, } impl<P: EthereumProvider> NetRpc<P> { pub const fn new(eth_provider: P) -> Self { Self { eth_provider } } } #[async_trait] impl<P: EthereumProvider + Send + Sync + 'static> NetApiServer for NetRpc<P> { async fn version(&self) -> RpcResult<U64> { Ok(self.eth_provider.chain_id().await?.unwrap_or_default()) } fn peer_count(&self) -> RpcResult<U64> { // Kakarot RPC currently does not have peers connected to node Ok(U64::ZERO) } fn listening(&self) -> RpcResult<bool> { // Kakarot RPC currently does not support peer-to-peer connections Ok(false) } async fn health(&self) -> RpcResult<bool> { // Calls starknet block_number method to check if it resolves let _ = self.eth_provider.block_number().await?; Ok(true) } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/client/mod.rs
src/client/mod.rs
use crate::{ constants::{ETH_CHAIN_ID, KKRT_BLOCK_GAS_LIMIT}, pool::{ mempool::{KakarotPool, TransactionOrdering}, validate::KakarotTransactionValidatorBuilder, }, providers::{ eth_provider::{ database::{ filter, filter::EthDatabaseFilterBuilder, types::transaction::{ExtendedTransaction, StoredEthStarknetTransactionHash}, Database, }, error::SignatureError, provider::{EthApiResult, EthDataProvider}, TransactionProvider, TxPoolProvider, }, sn_provider::StarknetProvider, }, }; use alloy_eips::eip2718::Encodable2718; use alloy_primitives::{Address, Bytes, B256}; use alloy_rlp::Decodable; use alloy_rpc_types_txpool::TxpoolContent; use alloy_serde::WithOtherFields; use async_trait::async_trait; use reth_chainspec::ChainSpec; use reth_primitives::{TransactionSigned, TransactionSignedEcRecovered}; use reth_rpc::eth::EthTxBuilder; use reth_rpc_eth_types::TransactionSource; use reth_transaction_pool::{ blobstore::NoopBlobStore, AllPoolTransactions, EthPooledTransaction, PoolConfig, PoolTransaction, TransactionOrigin, TransactionPool, }; use starknet::providers::Provider; use std::{collections::BTreeMap, sync::Arc}; #[async_trait] pub trait KakarotTransactions { /// Send a raw transaction to the network and returns the transactions hash. async fn send_raw_transaction(&self, transaction: Bytes) -> EthApiResult<B256>; } #[async_trait] pub trait TransactionHashProvider { /// Returns the transaction by hash. async fn transaction_by_hash(&self, hash: B256) -> EthApiResult<Option<ExtendedTransaction>>; } /// Provides a wrapper structure around the Ethereum Provider /// and the Mempool. #[derive(Debug, Clone)] pub struct EthClient<SP: Provider + Send + Sync> { eth_provider: EthDataProvider<SP>, pool: Arc<KakarotPool<EthDataProvider<SP>>>, } impl<SP> EthClient<SP> where SP: Provider + Clone + Sync + Send, { /// Get the Starknet provider from the Ethereum provider. pub const fn starknet_provider(&self) -> &StarknetProvider<SP> { self.eth_provider.starknet_provider() } /// Tries to start a [`EthClient`] by fetching the current chain id, initializing a [`EthDataProvider`] and a [`Pool`]. pub fn new(starknet_provider: SP, pool_config: PoolConfig, database: Database) -> Self { // Create a new EthDataProvider instance with the initialized database and Starknet provider. let eth_provider = EthDataProvider::new(database, StarknetProvider::new(starknet_provider)); let validator = KakarotTransactionValidatorBuilder::new(&Arc::new(ChainSpec { chain: (*ETH_CHAIN_ID).into(), max_gas_limit: KKRT_BLOCK_GAS_LIMIT, ..Default::default() })) .build::<_, EthPooledTransaction>(eth_provider.clone()); let pool = Arc::new(KakarotPool::new( validator, TransactionOrdering::default(), NoopBlobStore::default(), pool_config, )); Self { eth_provider, pool } } /// Returns a clone of the [`EthDataProvider`] pub const fn eth_provider(&self) -> &EthDataProvider<SP> { &self.eth_provider } /// Returns a clone of the `Pool` pub fn mempool(&self) -> Arc<KakarotPool<EthDataProvider<SP>>> { self.pool.clone() } } #[async_trait] impl<SP> KakarotTransactions for EthClient<SP> where SP: Provider + Clone + Sync + Send, { async fn send_raw_transaction(&self, transaction: Bytes) -> EthApiResult<B256> { // Decode the transaction data let transaction_signed = TransactionSigned::decode(&mut transaction.0.as_ref())?; // Recover the signer from the transaction let signer = transaction_signed.recover_signer().ok_or(SignatureError::Recovery)?; let hash = transaction_signed.hash(); let to = transaction_signed.to(); let transaction_signed_ec_recovered = TransactionSignedEcRecovered::from_signed_transaction(transaction_signed.clone(), signer); let encoded_length = transaction_signed_ec_recovered.clone().encode_2718_len(); let pool_transaction = EthPooledTransaction::new(transaction_signed_ec_recovered, encoded_length); // Deploy EVM transaction signer if Hive feature is enabled #[cfg(feature = "hive")] self.eth_provider.deploy_evm_transaction_signer(signer).await?; // Add the transaction to the pool and wait for it to be picked up by a relayer let hash = self .pool .add_transaction(TransactionOrigin::Local, pool_transaction) .await .inspect_err(|err| tracing::warn!(?err, ?hash, ?to, from = ?signer))?; Ok(hash) } } #[async_trait] impl<SP> TxPoolProvider for EthClient<SP> where SP: starknet::providers::Provider + Send + Sync, { fn content(&self) -> TxpoolContent<ExtendedTransaction> { #[inline] fn insert<T: PoolTransaction<Consensus = TransactionSignedEcRecovered>>( tx: &T, content: &mut BTreeMap<Address, BTreeMap<String, ExtendedTransaction>>, ) { content.entry(tx.sender()).or_default().insert( tx.nonce().to_string(), WithOtherFields::new( reth_rpc_types_compat::transaction::from_recovered::<reth_rpc::eth::EthTxBuilder>( tx.clone().into_consensus(), &EthTxBuilder {}, ), ), ); } let AllPoolTransactions { pending, queued } = self.pool.all_transactions(); let mut content = TxpoolContent::default(); for pending in pending { insert(&pending.transaction, &mut content.pending); } for queued in queued { insert(&queued.transaction, &mut content.queued); } content } async fn txpool_content(&self) -> EthApiResult<TxpoolContent<ExtendedTransaction>> { Ok(self.content()) } } #[async_trait] impl<SP> TransactionHashProvider for EthClient<SP> where SP: starknet::providers::Provider + Send + Sync, { async fn transaction_by_hash(&self, hash: B256) -> EthApiResult<Option<ExtendedTransaction>> { // Try to get the information from: // 1. The pool if the transaction is in the pool. // 2. The Ethereum provider if the transaction is not in the pool. let mut tx = self .pool .get(&hash) .map(|transaction| { WithOtherFields::new( TransactionSource::Pool(transaction.transaction.transaction().clone()) .into_transaction(&EthTxBuilder {}), ) }) .or(self.eth_provider.transaction_by_hash(hash).await?); if let Some(ref mut transaction) = tx { // Fetch the Starknet transaction hash if it exists. let filter = EthDatabaseFilterBuilder::<filter::EthStarknetTransactionHash>::default() .with_tx_hash(&transaction.hash) .build(); let hash_mapping: Option<StoredEthStarknetTransactionHash> = self.eth_provider.database().get_one(filter, None).await?; // Add the Starknet transaction hash to the transaction fields. if let Some(hash_mapping) = hash_mapping { transaction.other.insert( "starknet_transaction_hash".to_string(), serde_json::Value::String(hash_mapping.hashes.starknet_hash.to_fixed_hex_string()), ); } } Ok(tx) } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/prometheus_handler/mod.rs
src/prometheus_handler/mod.rs
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use bytes::Bytes; use http_body_util::Full; use hyper::{http::StatusCode, service::service_fn, Request, Response}; use hyper_util::{ rt::{TokioExecutor, TokioIo}, server, }; use prometheus::{core::Collector, Encoder, TextEncoder}; use std::net::SocketAddr; pub use prometheus::{ self, core::{ AtomicF64 as F64, AtomicI64 as I64, AtomicU64 as U64, GenericCounter as Counter, GenericCounterVec as CounterVec, GenericGauge as Gauge, GenericGaugeVec as GaugeVec, }, exponential_buckets, Error as PrometheusError, Histogram, HistogramOpts, HistogramVec, Opts, Registry, }; pub fn register<T: Clone + Collector + 'static>(metric: T, registry: &Registry) -> Result<T, PrometheusError> { registry.register(Box::new(metric.clone()))?; Ok(metric) } #[derive(Debug, thiserror::Error)] pub enum Error { /// Hyper internal error. #[error(transparent)] Hyper(#[from] hyper::Error), /// Http request error. #[error(transparent)] Http(#[from] Box<dyn std::error::Error + Send + Sync>), /// i/o error. #[error(transparent)] Io(#[from] std::io::Error), #[error("Prometheus port {0} already in use.")] PortInUse(SocketAddr), } #[allow(clippy::unused_async)] async fn request_metrics( req: Request<hyper::body::Incoming>, registry: Registry, ) -> Result<Response<Full<Bytes>>, hyper::http::Error> { if req.uri().path() == "/metrics" { let metric_families = registry.gather(); let mut buffer = vec![]; let encoder = TextEncoder::new(); encoder.encode(&metric_families, &mut buffer).unwrap(); Response::builder() .status(StatusCode::OK) .header("Content-Type", encoder.format_type()) .body(Full::new(Bytes::from(buffer))) } else { Response::builder().status(StatusCode::NOT_FOUND).body(Full::new(Bytes::from("Not found."))) } } /// Initializes the metrics context, and starts an HTTP server /// to serve metrics. pub async fn init_prometheus(prometheus_addr: SocketAddr, registry: Registry) -> Result<(), Error> { let listener = tokio::net::TcpListener::bind(&prometheus_addr).await.map_err(|_| Error::PortInUse(prometheus_addr))?; init_prometheus_with_listener(listener, registry).await } /// Init prometheus using the given listener. async fn init_prometheus_with_listener(listener: tokio::net::TcpListener, registry: Registry) -> Result<(), Error> { tracing::info!("〽️ Prometheus exporter started at {}", listener.local_addr().unwrap()); loop { // getting the tcp stream and ignoring the remote address let (tcp, _) = listener.accept().await?; // Use an adapter to access something implementing `tokio::io` traits as if they implement let io = TokioIo::new(tcp); // making a clone of registry, as it will be used in the service_fn closure let registry = registry.clone(); // Manufacturing a connection let conn = server::conn::auto::Builder::new(TokioExecutor::new()); // set up the connection to use the service implemented by request_metrics fn // await for the res // and send it off conn.serve_connection( io, service_fn(move |req: Request<hyper::body::Incoming>| request_metrics(req, registry.clone())), ) .await .map_err(Error::Http)?; } } #[cfg(test)] mod tests { use super::*; use http_body_util::BodyExt; use hyper::Uri; use hyper_util::{ client::legacy::{connect::HttpConnector, Client}, rt::TokioExecutor, }; #[tokio::test] async fn prometheus_works() { const METRIC_NAME: &str = "test_test_metric_name_test_test"; let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.expect("failed to create listener"); let local_addr = listener.local_addr().expect("failed to get local addr"); let registry = Registry::default(); register(prometheus::Counter::new(METRIC_NAME, "yeah").expect("Creates test counter"), &registry) .expect("Registers the test metric"); tokio::task::spawn(async { init_prometheus_with_listener(listener, registry).await.expect("failed to init prometheus"); }); let client: Client<HttpConnector, Full<Bytes>> = Client::builder(TokioExecutor::new()).build_http(); let res = client .get(Uri::try_from(&format!("http://{local_addr}/metrics")).expect("failed to parse URI")) .await .expect("failed to request metrics"); let buf = res.into_body().collect().await.unwrap().to_bytes(); let body = String::from_utf8(buf.to_vec()).expect("failed to convert body to String"); assert!(body.contains(&format!("{METRIC_NAME} 0"))); } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/test_utils/tx_waiter.rs
src/test_utils/tx_waiter.rs
use anyhow::Result; use starknet::{ core::types::{ExecutionResult, Felt, StarknetError}, providers::{Provider, ProviderError}, }; use std::time::Duration; use tracing::info; /// Code taken from /// <https://github.com/xJonathanLEI/starkli/blob/42c7cfc42102e399f76896ebbbc5291393f40d7e/src/utils.rs#L13> /// Credits to Jonathan Lei pub async fn watch_tx<P>(provider: P, transaction_hash: Felt, poll_interval: Duration, count: usize) -> Result<()> where P: Provider, { let mut i = 0usize; loop { if i >= count { return Err(anyhow::anyhow!("transaction not confirmed after {} tries", count)); } match provider.get_transaction_receipt(transaction_hash).await { Ok(receipt) => match receipt.receipt.execution_result() { ExecutionResult::Succeeded => { info!("Transaction confirmed successfully 🎉"); return Ok(()); } ExecutionResult::Reverted { reason } => { return Err(anyhow::anyhow!("transaction reverted: {}", reason)); } }, Err(ProviderError::StarknetError(StarknetError::TransactionHashNotFound)) => { info!("Transaction not confirmed yet..."); } // Some nodes are still serving error code `25` for tx hash not found. This is // technically a bug on the node's side, but we maximize compatibility here by also // accepting it. Err(err) => return Err(err.into()), } tokio::time::sleep(poll_interval).await; i += 1; } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/test_utils/evm_contract.rs
src/test_utils/evm_contract.rs
use super::eoa::{TX_GAS_LIMIT, TX_GAS_PRICE}; use crate::{models::felt::Felt252Wrapper, root_project_path}; use alloy_consensus::{TxEip1559, TxLegacy}; use alloy_dyn_abi::{DynSolValue, JsonAbiExt}; use alloy_json_abi::ContractObject; use alloy_primitives::{TxKind, U256}; use foundry_config::{find_project_root, load_config}; use reth_primitives::Transaction; use starknet::core::types::Felt; use std::{fs, path::Path}; #[derive(Clone, Debug)] pub enum TransactionInfo { FeeMarketInfo(TxFeeMarketInfo), LegacyInfo(TxLegacyInfo), } macro_rules! impl_common_info { ($field: ident, $type: ty) => { pub const fn $field(&self) -> $type { match self { TransactionInfo::FeeMarketInfo(info) => info.common.$field, TransactionInfo::LegacyInfo(info) => info.common.$field, } } }; } impl TransactionInfo { impl_common_info!(chain_id, Option<u64>); impl_common_info!(nonce, u64); impl_common_info!(value, u128); } #[derive(Clone, Debug, Default)] pub struct TxCommonInfo { pub chain_id: Option<u64>, pub nonce: u64, pub value: u128, } #[derive(Clone, Debug, Default)] pub struct TxFeeMarketInfo { pub common: TxCommonInfo, pub max_fee_per_gas: u128, pub max_priority_fee_per_gas: u128, } #[derive(Clone, Debug, Default)] pub struct TxLegacyInfo { pub common: TxCommonInfo, pub gas_price: u128, } pub trait EvmContract { fn load_contract_bytecode(contract_name: &str) -> Result<ContractObject, eyre::Error> { // Construct the path to the compiled JSON file using the root project path and configuration. let compiled_path = root_project_path!(Path::new(&load_config().out) .join(format!("{contract_name}.sol")) .join(format!("{contract_name}.json"))); // Read the contents of the JSON file into a string. let content = fs::read_to_string(compiled_path)?; // Deserialize the JSON content into a `ContractObject` and return it. Ok(serde_json::from_str(&content)?) } fn prepare_create_transaction( contract_bytecode: &ContractObject, constructor_args: &[DynSolValue], tx_info: &TxCommonInfo, ) -> Result<Transaction, eyre::Error> { // Get the ABI from the contract bytecode. // Return an error if the ABI is not found. let abi = contract_bytecode.abi.as_ref().ok_or_else(|| eyre::eyre!("No ABI found"))?; // Prepare the deployment data, which includes the bytecode and encoded constructor arguments (if any). let deploy_data = match abi.constructor() { Some(constructor) => contract_bytecode .bytecode .clone() .unwrap_or_default() .into_iter() .chain(constructor.abi_encode_input_raw(constructor_args)?) .collect(), None => contract_bytecode.bytecode.clone().unwrap_or_default().to_vec(), }; // Create and return an EIP-1559 transaction for contract creation. Ok(Transaction::Eip1559(TxEip1559 { chain_id: tx_info.chain_id.expect("chain id required"), nonce: tx_info.nonce, gas_limit: TX_GAS_LIMIT, max_fee_per_gas: TX_GAS_PRICE.into(), input: deploy_data.into(), ..Default::default() })) } #[allow(clippy::too_many_arguments)] fn prepare_call_transaction( &self, selector: &str, args: &[DynSolValue], tx_info: &TransactionInfo, ) -> Result<Transaction, eyre::Error>; } #[derive(Default, Debug)] pub struct KakarotEvmContract { pub bytecode: ContractObject, pub starknet_address: Felt, pub evm_address: Felt, } impl KakarotEvmContract { pub const fn new(bytecode: ContractObject, starknet_address: Felt, evm_address: Felt) -> Self { Self { bytecode, starknet_address, evm_address } } } impl EvmContract for KakarotEvmContract { fn prepare_call_transaction( &self, selector: &str, args: &[DynSolValue], tx_info: &TransactionInfo, ) -> Result<Transaction, eyre::Error> { // Get the ABI from the bytecode. // Return an error if the ABI is not found. let abi = self.bytecode.abi.as_ref().ok_or_else(|| eyre::eyre!("No ABI found"))?; // Get the function corresponding to the selector and encode the arguments let data = abi .function(selector) .ok_or_else(|| eyre::eyre!("No function found with selector: {}", selector)) .and_then(|function| { function .first() .ok_or_else(|| eyre::eyre!("No functions available"))? .abi_encode_input(args) .map_err(|_| eyre::eyre!("Failed to encode input")) })?; // Convert the EVM address to a `Felt252Wrapper`. let evm_address: Felt252Wrapper = self.evm_address.into(); // Create the transaction based on the transaction information type. let tx = match tx_info { TransactionInfo::FeeMarketInfo(fee_market) => Transaction::Eip1559(TxEip1559 { chain_id: tx_info.chain_id().expect("chain id required"), nonce: tx_info.nonce(), gas_limit: TX_GAS_LIMIT, to: TxKind::Call(evm_address.try_into()?), value: U256::from(tx_info.value()), input: data.into(), max_fee_per_gas: fee_market.max_fee_per_gas, max_priority_fee_per_gas: fee_market.max_priority_fee_per_gas, ..Default::default() }), TransactionInfo::LegacyInfo(legacy) => Transaction::Legacy(TxLegacy { chain_id: tx_info.chain_id(), nonce: tx_info.nonce(), gas_limit: TX_GAS_LIMIT, to: TxKind::Call(evm_address.try_into()?), value: U256::from(tx_info.value()), input: data.into(), gas_price: legacy.gas_price, }), }; Ok(tx) } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/test_utils/fixtures.rs
src/test_utils/fixtures.rs
use rstest::fixture; use tracing_subscriber::{filter, FmtSubscriber}; #[cfg(any(test, feature = "arbitrary", feature = "testing"))] use { super::katana::Katana, super::mongo::RANDOM_BYTES_SIZE, crate::test_utils::evm_contract::KakarotEvmContract, alloy_dyn_abi::DynSolValue, alloy_primitives::{Address, U256}, }; /// This fixture deploys a counter contract on Katana. #[cfg(any(test, feature = "arbitrary", feature = "testing"))] #[fixture] #[awt] pub async fn counter(#[future] katana_empty: Katana) -> (Katana, KakarotEvmContract) { let eoa = katana_empty.eoa(); let contract = eoa.deploy_evm_contract(Some("Counter"), &[]).await.expect("Failed to deploy Counter contract"); (katana_empty, contract) } /// This fixture deploys an empty contract on Katana. #[cfg(any(test, feature = "arbitrary", feature = "testing"))] #[fixture] #[awt] pub async fn contract_empty(#[future] katana_empty: Katana) -> (Katana, KakarotEvmContract) { let eoa = katana_empty.eoa(); let contract = eoa.deploy_evm_contract(None, &[]).await.expect("Failed to deploy empty contract"); (katana_empty, contract) } /// This fixture deploys an ERC20 contract on Katana. #[cfg(any(test, feature = "arbitrary", feature = "testing"))] #[fixture] #[awt] pub async fn erc20(#[future] katana_empty: Katana) -> (Katana, KakarotEvmContract) { let eoa = katana_empty.eoa(); let contract = eoa .deploy_evm_contract( Some("ERC20"), &[ DynSolValue::String("Test".into()), // name DynSolValue::String("TT".into()), // symbol DynSolValue::Uint(U256::from(18), 8), // decimals ], ) .await .expect("Failed to deploy ERC20 contract"); (katana_empty, contract) } /// This fixture deploys the plain opcodes contract on Katana. #[cfg(any(test, feature = "arbitrary", feature = "testing"))] #[fixture] #[awt] pub async fn plain_opcodes(#[future] counter: (Katana, KakarotEvmContract)) -> (Katana, KakarotEvmContract) { let katana = counter.0; let counter = counter.1; let eoa = katana.eoa(); let counter_address = Address::from_slice(&counter.evm_address.to_bytes_be()[12..]); let contract = eoa .deploy_evm_contract( Some("PlainOpcodes"), &[ DynSolValue::Address(counter_address), // counter address ], ) .await .expect("Failed to deploy PlainOpcodes contract"); (katana, contract) } /// This fixture creates a new test environment on Katana. #[cfg(any(test, feature = "arbitrary", feature = "testing"))] #[fixture] pub async fn katana() -> Katana { // Create a new test environment on Katana Katana::new(RANDOM_BYTES_SIZE).await } /// This fixture creates a new test environment on Katana. #[cfg(any(test, feature = "arbitrary", feature = "testing"))] #[fixture] pub async fn katana_empty() -> Katana { // Create a new test environment on Katana Katana::new_empty().await } /// This fixture configures the tests. The following setup /// is used: /// - The log level is set to `info` #[fixture] pub fn setup() { let filter = filter::EnvFilter::new("info"); let subscriber = FmtSubscriber::builder().with_env_filter(filter).finish(); let _ = tracing::subscriber::set_global_default(subscriber); }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/test_utils/macros.rs
src/test_utils/macros.rs
/// Macro to find the root path of the project. /// /// This macro utilizes the `find_project_root_path` function from the `utils` module. /// This function works by identifying the root directory of the current git repository. /// It starts at the current working directory and traverses up the directory tree until it finds a /// directory containing a `.git` folder. If no such directory is found, it uses the current /// directory as the root. /// /// After determining the project root, the macro creates a new path by joining the given relative /// path with the found project root path. /// /// The relative path must be specified as a string literal argument to the macro. /// /// # Examples /// /// ```ignore /// let full_path = root_project_path!("src/main.rs"); /// println!("Full path to main.rs: {:?}", full_path); /// ``` /// /// # Panics /// /// This macro will panic if it fails to find the root path of the project or if the root path /// cannot be represented as a UTF-8 string. #[macro_export] macro_rules! root_project_path { ($relative_path:expr) => {{ find_project_root(None).join(Path::new(&$relative_path)) }}; }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/test_utils/mod.rs
src/test_utils/mod.rs
pub mod constants; pub mod eoa; pub mod evm_contract; pub mod fixtures; pub mod hive; pub mod katana; pub mod macros; pub mod mock_provider; pub mod mongo; pub mod rpc; pub mod tx_waiter;
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/test_utils/eoa.rs
src/test_utils/eoa.rs
use crate::{ client::{EthClient, KakarotTransactions}, into_via_try_wrapper, providers::eth_provider::{ starknet::{kakarot_core::starknet_address, relayer::Relayer}, ChainProvider, TransactionProvider, }, test_utils::{ evm_contract::{EvmContract, KakarotEvmContract, TransactionInfo, TxCommonInfo, TxFeeMarketInfo}, tx_waiter::watch_tx, }, }; use alloy_consensus::TxEip1559; use alloy_dyn_abi::DynSolValue; use alloy_eips::eip2718::Encodable2718; use alloy_json_abi::ContractObject; use alloy_primitives::{Address, TxKind, B256, U256}; use alloy_signer_local::PrivateKeySigner; use async_trait::async_trait; use reth_primitives::{sign_message, Transaction, TransactionSigned}; use starknet::{ accounts::{Account, SingleOwnerAccount}, core::{ types::{BlockId, BlockTag, Felt, TransactionReceipt}, utils::get_selector_from_name, }, providers::{jsonrpc::HttpTransport, JsonRpcClient, Provider}, signers::LocalWallet, }; use std::sync::Arc; pub const TX_GAS_LIMIT: u64 = 5_000_000; pub const TX_GAS_PRICE: u64 = 10; /// EOA is an Ethereum-like Externally Owned Account (EOA) that can sign transactions and send them to the underlying Starknet provider. #[async_trait] pub trait Eoa<P: Provider + Send + Sync + Clone> { fn starknet_address(&self) -> Result<Felt, eyre::Error> { Ok(starknet_address(self.evm_address()?)) } fn evm_address(&self) -> Result<Address, eyre::Error> { let wallet = PrivateKeySigner::from_bytes(&self.private_key())?; Ok(wallet.address()) } fn private_key(&self) -> B256; fn eth_client(&self) -> &EthClient<P>; async fn nonce(&self) -> Result<U256, eyre::Error> { let eth_provider = self.eth_client().eth_provider(); let evm_address = self.evm_address()?; Ok(eth_provider.transaction_count(evm_address, None).await?) } fn sign_payload(&self, payload: B256) -> Result<alloy_primitives::Signature, eyre::Error> { let pk = self.private_key(); let signature = sign_message(pk, payload)?; Ok(signature) } fn sign_transaction(&self, tx: Transaction) -> Result<TransactionSigned, eyre::Error> { let signature = self.sign_payload(tx.signature_hash())?; Ok(TransactionSigned::from_transaction_and_signature(tx, signature)) } async fn send_transaction(&self, tx: TransactionSigned) -> Result<B256, eyre::Error> { let eth_client = self.eth_client(); let mut v = Vec::new(); tx.encode_2718(&mut v); Ok(eth_client.send_raw_transaction(v.into()).await?) } } #[derive(Debug)] pub struct KakarotEOA<P: Provider + Send + Sync + Clone + 'static> { pub private_key: B256, pub eth_client: Arc<EthClient<P>>, pub relayer: SingleOwnerAccount<JsonRpcClient<HttpTransport>, LocalWallet>, } impl<P: Provider + Send + Sync + Clone> KakarotEOA<P> { pub const fn new( private_key: B256, eth_client: Arc<EthClient<P>>, relayer: SingleOwnerAccount<JsonRpcClient<HttpTransport>, LocalWallet>, ) -> Self { Self { private_key, eth_client, relayer } } } #[async_trait] impl<P: Provider + Send + Sync + Clone> Eoa<P> for KakarotEOA<P> { fn private_key(&self) -> B256 { self.private_key } fn eth_client(&self) -> &EthClient<P> { &self.eth_client } } impl<P: Provider + Send + Sync + Clone> KakarotEOA<P> { fn starknet_provider(&self) -> &P { self.eth_client.starknet_provider() } /// Deploys an EVM contract given a contract name and constructor arguments /// Returns a `KakarotEvmContract` instance pub async fn deploy_evm_contract( &self, contract_name: Option<&str>, constructor_args: &[DynSolValue], ) -> Result<KakarotEvmContract, eyre::Error> { let nonce = self.nonce().await?; let nonce: u64 = nonce.try_into()?; let chain_id: u64 = self.eth_client.eth_provider().chain_id().await?.unwrap_or_default().try_into()?; // Empty bytecode if contract_name is None let bytecode = if let Some(name) = contract_name { <KakarotEvmContract as EvmContract>::load_contract_bytecode(name)? } else { ContractObject::default() }; let expected_address = { let expected_eth_address = self.evm_address().expect("Failed to get EVM address").create(nonce); Felt::from_bytes_be_slice(expected_eth_address.as_slice()) }; let tx = if contract_name.is_none() { Transaction::Eip1559(TxEip1559 { chain_id, nonce, gas_limit: TX_GAS_LIMIT, max_fee_per_gas: TX_GAS_PRICE.into(), ..Default::default() }) } else { <KakarotEvmContract as EvmContract>::prepare_create_transaction( &bytecode, constructor_args, &TxCommonInfo { nonce, chain_id: Some(chain_id), ..Default::default() }, )? }; let tx_signed = self.sign_transaction(tx)?; let _ = self.send_transaction(tx_signed.clone()).await?; // Prepare the relayer let relayer_balance = self .eth_client .starknet_provider() .balance_at(self.relayer.address(), BlockId::Tag(BlockTag::Latest)) .await?; let relayer_balance = into_via_try_wrapper!(relayer_balance)?; // Relay the transaction let starknet_transaction_hash = Relayer::new( self.relayer.address(), relayer_balance, self.starknet_provider(), Some(Arc::new(self.eth_client.eth_provider().database().clone())), ) .relay_transaction(&tx_signed) .await .expect("Failed to relay transaction"); watch_tx( self.eth_client.eth_provider().starknet_provider_inner(), starknet_transaction_hash, std::time::Duration::from_millis(300), 60, ) .await .expect("Tx polling failed"); let maybe_receipt = self .starknet_provider() .get_transaction_receipt(starknet_transaction_hash) .await .expect("Failed to get transaction receipt after retries"); let TransactionReceipt::Invoke(receipt) = maybe_receipt.receipt else { return Err(eyre::eyre!("Failed to deploy contract")); }; let selector = get_selector_from_name("evm_contract_deployed")?; let event = receipt .events .into_iter() .find(|event| event.keys.contains(&selector) && event.data.contains(&expected_address)) .ok_or_else(|| eyre::eyre!("Failed to find deployed contract address"))?; Ok(KakarotEvmContract::new(bytecode, event.data[1], event.data[0])) } /// Calls a `KakarotEvmContract` function and returns the Starknet transaction hash /// The transaction is signed and sent by the EOA /// The transaction is waited for until it is confirmed pub async fn call_evm_contract( &self, contract: &KakarotEvmContract, function: &str, args: &[DynSolValue], value: u128, ) -> Result<Transaction, eyre::Error> { let nonce = self.nonce().await?.try_into()?; let chain_id = self.eth_client.eth_provider().chain_id().await?.unwrap_or_default().to(); let tx = contract.prepare_call_transaction( function, args, &TransactionInfo::FeeMarketInfo(TxFeeMarketInfo { common: TxCommonInfo { chain_id: Some(chain_id), nonce, value }, max_fee_per_gas: 1000, max_priority_fee_per_gas: 1000, }), )?; let tx_signed = self.sign_transaction(tx.clone())?; let _ = self.send_transaction(tx_signed.clone()).await?; // Prepare the relayer let relayer_balance = self .eth_client .starknet_provider() .balance_at(self.relayer.address(), BlockId::Tag(BlockTag::Latest)) .await?; let relayer_balance = into_via_try_wrapper!(relayer_balance)?; // Relay the transaction let starknet_transaction_hash = Relayer::new( self.relayer.address(), relayer_balance, self.starknet_provider(), Some(Arc::new(self.eth_client.eth_provider().database().clone())), ) .relay_transaction(&tx_signed) .await .expect("Failed to relay transaction"); watch_tx( self.eth_client.eth_provider().starknet_provider_inner(), starknet_transaction_hash, std::time::Duration::from_millis(300), 60, ) .await .expect("Tx polling failed"); Ok(tx) } /// Transfers value to the given address /// The transaction is signed and sent by the EOA pub async fn transfer(&self, to: Address, value: u128) -> Result<Transaction, eyre::Error> { let tx = Transaction::Eip1559(TxEip1559 { chain_id: self.eth_client.eth_provider().chain_id().await?.unwrap_or_default().try_into()?, nonce: self.nonce().await?.try_into()?, gas_limit: TX_GAS_LIMIT, max_fee_per_gas: TX_GAS_PRICE.into(), to: TxKind::Call(to), value: U256::from(value), ..Default::default() }); let tx_signed = self.sign_transaction(tx.clone())?; let _ = self.send_transaction(tx_signed).await; Ok(tx) } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/test_utils/mock_provider.rs
src/test_utils/mock_provider.rs
use crate::providers::eth_provider::{ database::types::{header::ExtendedBlock, receipt::ExtendedTxReceipt, transaction::ExtendedTransaction}, provider::EthApiResult, BlockProvider, ChainProvider, GasProvider, LogProvider, ReceiptProvider, StateProvider, TransactionProvider, }; use alloy_eips::{BlockId, BlockNumberOrTag}; use alloy_primitives::{Address, Bytes, B256, U256, U64}; use alloy_rpc_types::{Filter, FilterChanges, Header, SyncStatus, TransactionRequest}; use async_trait::async_trait; use mockall::mock; mock! { #[derive(Clone, Debug)] pub EthereumProviderStruct {} #[async_trait] impl BlockProvider for EthereumProviderStruct { async fn header(&self, block_id: &BlockId) -> EthApiResult<Option<Header>>; async fn block_number(&self) -> EthApiResult<U64>; async fn block_by_hash( &self, hash: B256, full: bool, ) -> EthApiResult<Option<ExtendedBlock>>; async fn block_by_number( &self, number: BlockNumberOrTag, full: bool, ) -> EthApiResult<Option<ExtendedBlock>>; async fn block_transaction_count_by_hash(&self, hash: B256) -> EthApiResult<Option<U256>>; async fn block_transaction_count_by_number(&self, number_or_tag: BlockNumberOrTag) -> EthApiResult<Option<U256>>; async fn block_transactions(&self, block_id: Option<BlockId>) -> EthApiResult<Option<Vec<ExtendedTransaction>>>; } #[async_trait] impl ChainProvider for EthereumProviderStruct { async fn syncing(&self) -> EthApiResult<SyncStatus>; async fn chain_id(&self) -> EthApiResult<Option<U64>>; } #[async_trait] impl GasProvider for EthereumProviderStruct { async fn estimate_gas(&self, call: TransactionRequest, block_id: Option<BlockId>) -> EthApiResult<U256>; async fn fee_history(&self, block_count: U64, newest_block: BlockNumberOrTag, reward_percentiles: Option<Vec<f64>>) -> EthApiResult<alloy_rpc_types::FeeHistory>; async fn gas_price(&self) -> EthApiResult<U256>; } #[async_trait] impl LogProvider for EthereumProviderStruct { async fn get_logs(&self, filter: Filter) -> EthApiResult<FilterChanges>; } #[async_trait] impl ReceiptProvider for EthereumProviderStruct { async fn transaction_receipt(&self, hash: B256) -> EthApiResult<Option<ExtendedTxReceipt>>; async fn block_receipts(&self, block_id: Option<BlockId>) -> EthApiResult<Option<Vec<ExtendedTxReceipt>>>; } #[async_trait] impl StateProvider for EthereumProviderStruct { async fn balance(&self, address: Address, block_id: Option<BlockId>) -> EthApiResult<U256>; async fn storage_at(&self, address: Address, index: alloy_rpc_types::serde_helpers::JsonStorageKey, block_id: Option<BlockId>) -> EthApiResult<B256>; async fn get_code(&self, address: Address, block_id: Option<BlockId>) -> EthApiResult<Bytes>; async fn call(&self, request: TransactionRequest, block_id: Option<BlockId>, state_overrides: Option<alloy_rpc_types::state::StateOverride>, block_overrides: Option<Box<alloy_rpc_types::BlockOverrides>>) -> EthApiResult<Bytes>; } #[async_trait] impl TransactionProvider for EthereumProviderStruct { async fn transaction_by_hash(&self, hash: B256) -> EthApiResult<Option<ExtendedTransaction>>; async fn transaction_by_block_hash_and_index(&self, hash: B256, index: alloy_rpc_types::Index) -> EthApiResult<Option<ExtendedTransaction>>; async fn transaction_by_block_number_and_index(&self, number_or_tag: BlockNumberOrTag, index: alloy_rpc_types::Index) -> EthApiResult<Option<ExtendedTransaction>>; async fn transaction_count(&self, address: Address, block_id: Option<BlockId>) -> EthApiResult<U256>; } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/test_utils/constants.rs
src/test_utils/constants.rs
pub const ACCOUNT_EVM_ADDRESS: &str = "Account_evm_address"; pub const ACCOUNT_IMPLEMENTATION: &str = "Account_implementation"; pub const ACCOUNT_NONCE: &str = "Account_nonce"; pub const ACCOUNT_STORAGE: &str = "Account_storage"; pub const OWNABLE_OWNER: &str = "Ownable_owner"; pub const ACCOUNT_CAIRO1_HELPERS_CLASS_HASH: &str = "Account_cairo1_helpers_class_hash"; pub const ACCOUNT_AUTHORIZED_MESSAGE_HASHES: &str = "Account_authorized_message_hashes"; /// Pre EIP 155 authorized message hashes. Presently contains: /// - The Arachnid deployer message hash. pub const EIP_155_AUTHORIZED_MESSAGE_HASHES: [&str; 1] = ["0x3de642d76cf5cf9ffcf9b51e11b3b21e09f63278ed94a89281ca8054b2225434"]; pub const KAKAROT_EVM_TO_STARKNET_ADDRESS: &str = "Kakarot_evm_to_starknet_address"; pub const KAKAROT_NATIVE_TOKEN_ADDRESS: &str = "Kakarot_native_token_address"; pub const KAKAROT_ACCOUNT_CONTRACT_CLASS_HASH: &str = "Kakarot_account_contract_class_hash"; pub const KAKAROT_UNINITIALIZED_ACCOUNT_CLASS_HASH: &str = "Kakarot_uninitialized_account_class_hash"; pub const KAKAROT_CAIRO1_HELPERS_CLASS_HASH: &str = "Kakarot_cairo1_helpers_class_hash"; pub const KAKAROT_COINBASE: &str = "Kakarot_coinbase"; pub const KAKAROT_BASE_FEE: &str = "Kakarot_base_fee"; pub const KAKAROT_PREV_RANDAO: &str = "Kakarot_prev_randao"; pub const KAKAROT_BLOCK_GAS_LIMIT: &str = "Kakarot_block_gas_limit"; pub const KAKAROT_CHAIN_ID: &str = "Kakarot_chain_id";
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/test_utils/katana/genesis.rs
src/test_utils/katana/genesis.rs
use crate::{ providers::eth_provider::utils::split_u256, test_utils::constants::{ ACCOUNT_AUTHORIZED_MESSAGE_HASHES, ACCOUNT_CAIRO1_HELPERS_CLASS_HASH, ACCOUNT_EVM_ADDRESS, ACCOUNT_IMPLEMENTATION, EIP_155_AUTHORIZED_MESSAGE_HASHES, KAKAROT_ACCOUNT_CONTRACT_CLASS_HASH, KAKAROT_BASE_FEE, KAKAROT_BLOCK_GAS_LIMIT, KAKAROT_CAIRO1_HELPERS_CLASS_HASH, KAKAROT_CHAIN_ID, KAKAROT_COINBASE, KAKAROT_EVM_TO_STARKNET_ADDRESS, KAKAROT_NATIVE_TOKEN_ADDRESS, KAKAROT_PREV_RANDAO, KAKAROT_UNINITIALIZED_ACCOUNT_CLASS_HASH, OWNABLE_OWNER, }, }; use alloy_primitives::{B256, U256}; use alloy_signer_local::PrivateKeySigner; use eyre::{eyre, OptionExt, Result}; use katana_primitives::{ contract::{ContractAddress, StorageKey, StorageValue}, genesis::{ allocation::DevAllocationsGenerator, constant::{DEFAULT_FEE_TOKEN_ADDRESS, DEFAULT_PREFUNDED_ACCOUNT_BALANCE}, json::{ ClassNameOrHash, FeeTokenConfigJson, GenesisAccountJson, GenesisClassJson, GenesisContractJson, GenesisJson, PathOrFullArtifact, }, }, }; use rayon::prelude::*; use serde::Serialize; use serde_json::Value; use serde_with::serde_as; use starknet::core::{ serde::unsigned_field_element::UfeHex, types::{ contract::{legacy::LegacyContractClass, SierraClass}, Felt, }, utils::{get_contract_address, get_storage_var_address, get_udc_deployed_address, UdcUniqueness}, }; use std::{ collections::{BTreeMap, HashMap}, fs, marker::PhantomData, path::PathBuf, str::FromStr, sync::LazyLock, }; use walkdir::WalkDir; pub static SALT: LazyLock<Felt> = LazyLock::new(|| Felt::from_bytes_be(&[0u8; 32])); #[serde_as] #[derive(Serialize, Debug)] pub struct Hex(#[serde_as(as = "UfeHex")] pub Felt); #[derive(Serialize, Debug)] pub struct KatanaManifest { pub declarations: HashMap<String, Hex>, pub deployments: HashMap<String, Hex>, } #[derive(Debug, Clone, Default)] pub struct Uninitialized; #[derive(Debug, Clone)] pub struct Loaded; #[derive(Debug, Clone)] pub struct Initialized; #[derive(Debug, Clone, Default)] pub struct KatanaGenesisBuilder<T = Uninitialized> { coinbase: Felt, classes: Vec<GenesisClassJson>, class_hashes: HashMap<String, Felt>, contracts: BTreeMap<ContractAddress, GenesisContractJson>, accounts: BTreeMap<ContractAddress, GenesisAccountJson>, fee_token_storage: BTreeMap<StorageKey, StorageValue>, cache: HashMap<String, Felt>, status: PhantomData<T>, } // Copy pasted from Dojo repository as it is part of the Katana binary // https://github.com/dojoengine/dojo/blob/main/bin/katana/src/utils.rs#L6 fn parse_seed(seed: &str) -> [u8; 32] { let seed = seed.as_bytes(); if seed.len() >= 32 { unsafe { *seed[..32].as_ptr().cast::<[u8; 32]>() } } else { let mut actual_seed = [0u8; 32]; seed.iter().enumerate().for_each(|(i, b)| actual_seed[i] = *b); actual_seed } } impl<T> KatanaGenesisBuilder<T> { pub fn update_state<State>(self) -> KatanaGenesisBuilder<State> { KatanaGenesisBuilder { coinbase: self.coinbase, classes: self.classes, class_hashes: self.class_hashes, contracts: self.contracts, accounts: self.accounts, fee_token_storage: self.fee_token_storage, cache: self.cache, status: PhantomData::<State>, } } #[must_use] pub fn with_dev_allocation(mut self, amount: u16) -> Self { let dev_allocations = DevAllocationsGenerator::new(amount) .with_balance(U256::from(DEFAULT_PREFUNDED_ACCOUNT_BALANCE)) .with_seed(parse_seed("0")) .generate() .into_iter() .map(|(address, account)| { ( address, GenesisAccountJson { public_key: account.public_key, private_key: Some(account.private_key), balance: account.balance, nonce: account.nonce, class: None, storage: account.storage.clone(), }, ) }); self.accounts.extend(dev_allocations); self } fn kakarot_class_hash(&self) -> Result<Felt> { self.class_hashes.get("kakarot").copied().ok_or_eyre("Missing Kakarot class hash") } pub fn account_contract_class_hash(&self) -> Result<Felt> { self.class_hashes.get("account_contract").copied().ok_or_eyre("Missing account contract class hash") } pub fn uninitialized_account_class_hash(&self) -> Result<Felt> { self.class_hashes.get("uninitialized_account").copied().ok_or_eyre("Missing uninitialized account class hash") } pub fn cairo1_helpers_class_hash(&self) -> Result<Felt> { self.class_hashes.get("cairo1_helpers").copied().ok_or_eyre("Missing cairo1 helpers class hash") } } impl KatanaGenesisBuilder<Uninitialized> { /// Load the classes from the given path. Computes the class hashes and stores them in the builder. pub fn load_classes(mut self, path: PathBuf) -> KatanaGenesisBuilder<Loaded> { let entries = WalkDir::new(path).into_iter().filter(|e| e.is_ok() && e.as_ref().unwrap().file_type().is_file()); let classes = entries .par_bridge() .filter_map(|entry| { let path = entry.unwrap().path().to_path_buf(); // Skip class_hashes.json file if path.file_name().map_or(false, |name| name == "class_hashes.json") { return None; } let artifact = fs::read_to_string(&path).expect("Failed to read artifact"); let artifact = serde_json::from_str(&artifact).expect("Failed to parse artifact"); let class_hash = compute_class_hash(&artifact) .inspect_err(|e| eprintln!("Failed to compute class hash: {e:?} for {path:?}")) .ok()?; Some(( path, GenesisClassJson { class: PathOrFullArtifact::Artifact(artifact), class_hash: Some(class_hash), name: None, }, )) }) .collect::<Vec<_>>(); self.class_hashes = classes .iter() .map(|(path, class)| { ( path.file_stem().unwrap().to_str().unwrap().to_string(), class.class_hash.expect("all class hashes should be computed"), ) }) .collect(); self.classes = classes.into_iter().map(|(_, class)| class).collect(); self.update_state() } } impl KatanaGenesisBuilder<Loaded> { /// Add the Kakarot contract to the genesis. Updates the state to [Initialized]. /// Once in the [Initialized] status, the builder can be built. pub fn with_kakarot(mut self, coinbase_address: Felt, chain_id: Felt) -> Result<KatanaGenesisBuilder<Initialized>> { let kakarot_class_hash = self.kakarot_class_hash()?; let account_contract_class_hash = self.account_contract_class_hash()?; let uninitialized_account_class_hash = self.uninitialized_account_class_hash()?; let cairo1_helpers_class_hash = self.cairo1_helpers_class_hash()?; let block_gas_limit = 20_000_000u64.into(); // Construct the kakarot contract address. Based on the constructor args from // https://github.com/kkrt-labs/kakarot/blob/main/src/kakarot/kakarot.cairo#L23 let kakarot_address = ContractAddress::new(get_udc_deployed_address( *SALT, kakarot_class_hash, &UdcUniqueness::NotUnique, &[ Felt::ZERO, DEFAULT_FEE_TOKEN_ADDRESS.0, account_contract_class_hash, uninitialized_account_class_hash, cairo1_helpers_class_hash, block_gas_limit, chain_id, ], )); // Cache the address for later use. self.cache.insert("kakarot_address".to_string(), kakarot_address.0); self.cache.insert("cairo1_helpers".to_string(), cairo1_helpers_class_hash); // Construct the kakarot contract storage. let kakarot_storage = [ (storage_addr(KAKAROT_NATIVE_TOKEN_ADDRESS)?, *DEFAULT_FEE_TOKEN_ADDRESS), (storage_addr(KAKAROT_ACCOUNT_CONTRACT_CLASS_HASH)?, account_contract_class_hash), (storage_addr(KAKAROT_UNINITIALIZED_ACCOUNT_CLASS_HASH)?, uninitialized_account_class_hash), (storage_addr(KAKAROT_CAIRO1_HELPERS_CLASS_HASH)?, cairo1_helpers_class_hash), (storage_addr(KAKAROT_COINBASE)?, coinbase_address), (storage_addr(KAKAROT_BASE_FEE)?, Felt::ZERO), (storage_addr(KAKAROT_PREV_RANDAO)?, Felt::ZERO), (storage_addr(KAKAROT_BLOCK_GAS_LIMIT)?, block_gas_limit), (storage_addr(KAKAROT_CHAIN_ID)?, chain_id), ] .into_iter() .collect(); let kakarot = GenesisContractJson { class: Some(ClassNameOrHash::Hash(kakarot_class_hash)), balance: None, nonce: None, storage: Some(kakarot_storage), }; self.contracts.insert(kakarot_address, kakarot); self.coinbase = coinbase_address; Ok(self.update_state()) } } impl KatanaGenesisBuilder<Initialized> { /// Add an EOA to the genesis. The EOA is deployed to the address derived from the given private key. pub fn with_eoa(mut self, private_key: B256) -> Result<Self> { let evm_address = Self::evm_address(private_key)?; let kakarot_address = self.cache_load("kakarot_address")?; let account_contract_class_hash = self.account_contract_class_hash()?; let cairo1_helpers_class_hash = self.cairo1_helpers_class_hash()?; // Set the eoa storage let mut eoa_storage: BTreeMap<StorageKey, Felt> = [ (storage_addr(ACCOUNT_EVM_ADDRESS)?, evm_address), (storage_addr(OWNABLE_OWNER)?, kakarot_address), (storage_addr(ACCOUNT_IMPLEMENTATION)?, account_contract_class_hash), (storage_addr(ACCOUNT_CAIRO1_HELPERS_CLASS_HASH)?, cairo1_helpers_class_hash), ] .into_iter() .collect(); for hash in EIP_155_AUTHORIZED_MESSAGE_HASHES { let h = U256::from_str(hash).expect("Failed to parse EIP 155 authorized message hash"); let [low, high] = split_u256::<Felt>(h); eoa_storage.insert(get_storage_var_address(ACCOUNT_AUTHORIZED_MESSAGE_HASHES, &[low, high])?, Felt::ONE); } let eoa = GenesisContractJson { class: Some(ClassNameOrHash::Hash(account_contract_class_hash)), balance: None, nonce: None, storage: Some(eoa_storage), }; let starknet_address = self.compute_starknet_address(evm_address)?; self.contracts.insert(starknet_address, eoa); // Set the allowance for the EOA to the Kakarot contract. let key = get_storage_var_address("ERC20_allowances", &[*starknet_address, kakarot_address])?; let storage = [(key, u128::MAX.into()), (key + Felt::ONE, u128::MAX.into())].into_iter(); self.fee_token_storage.extend(storage); // Write the address to the Kakarot evm to starknet mapping let kakarot_address = ContractAddress::new(kakarot_address); let kakarot_contract = self.contracts.get_mut(&kakarot_address).ok_or_eyre("Kakarot contract missing")?; kakarot_contract .storage .get_or_insert_with(BTreeMap::new) .extend([(get_storage_var_address(KAKAROT_EVM_TO_STARKNET_ADDRESS, &[evm_address])?, starknet_address.0)]); Ok(self) } /// Fund the starknet address deployed for the evm address of the passed private key /// with the given amount of tokens. pub fn fund(mut self, pk: B256, amount: U256) -> Result<Self> { let evm_address = Self::evm_address(pk)?; let starknet_address = self.compute_starknet_address(evm_address)?; let eoa = self.contracts.get_mut(&starknet_address).ok_or_eyre("Missing EOA contract")?; let key = get_storage_var_address("ERC20_balances", &[*starknet_address])?; let amount_split = split_u256::<u128>(amount); let storage = [(key, amount_split[0].into()), (key + Felt::ONE, amount_split[1].into())].into_iter(); self.fee_token_storage.extend(storage); eoa.balance = Some(amount); Ok(self) } /// Consume the [`KatanaGenesisBuilder`] and returns the corresponding [`GenesisJson`]. pub fn build(self) -> Result<GenesisJson> { Ok(GenesisJson { sequencer_address: self.compute_starknet_address(self.coinbase)?, classes: self.classes, fee_token: FeeTokenConfigJson { name: "Ether".to_string(), symbol: "ETH".to_string(), decimals: 18, storage: Some(self.fee_token_storage), ..Default::default() }, accounts: self.accounts, contracts: self.contracts, ..Default::default() }) } /// Returns the manifest of the genesis. pub fn manifest(&self) -> KatanaManifest { KatanaManifest { declarations: self.class_hashes().clone().into_iter().map(|(k, v)| (k, Hex(v))).collect(), deployments: self.cache().clone().into_iter().map(|(k, v)| (k, Hex(v))).collect(), } } /// Compute the Starknet address for the given Ethereum address. pub fn compute_starknet_address(&self, evm_address: Felt) -> Result<ContractAddress> { let kakarot_address = self.cache_load("kakarot_address")?; let uninitialized_account_class_hash = self.uninitialized_account_class_hash()?; Ok(ContractAddress::new(get_contract_address( evm_address, uninitialized_account_class_hash, &[Felt::ONE, evm_address], kakarot_address, ))) } fn evm_address(pk: B256) -> Result<Felt> { Ok(Felt::from_bytes_be_slice(&PrivateKeySigner::from_bytes(&pk)?.address().into_array())) } pub fn cache_load(&self, key: &str) -> Result<Felt> { self.cache.get(key).copied().ok_or_else(|| eyre!("Cache miss for {key} address")) } pub const fn cache(&self) -> &HashMap<String, Felt> { &self.cache } pub const fn class_hashes(&self) -> &HashMap<String, Felt> { &self.class_hashes } } fn compute_class_hash(class: &Value) -> Result<Felt> { if let Ok(sierra) = serde_json::from_value::<SierraClass>(class.clone()) { Ok(sierra.class_hash()?) } else { let casm: LegacyContractClass = serde_json::from_value(class.clone())?; Ok(casm.class_hash()?) } } fn storage_addr(var_name: &str) -> Result<Felt> { Ok(get_storage_var_address(var_name, &[])?) }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/test_utils/katana/mod.rs
src/test_utils/katana/mod.rs
pub mod genesis; use super::mongo::MongoImage; use crate::{ client::EthClient, constants::KKRT_BLOCK_GAS_LIMIT, providers::eth_provider::{ constant::U64_HEX_STRING_LEN, database::{ ethereum::EthereumTransactionStore, filter::{self, format_hex, EthDatabaseFilterBuilder}, types::{ header::StoredHeader, log::StoredLog, receipt::{ExtendedTxReceipt, StoredTransactionReceipt}, transaction::{ExtendedTransaction, StoredTransaction}, }, CollectionName, }, provider::EthDataProvider, }, test_utils::eoa::KakarotEOA, }; use alloy_primitives::{Address, Bytes, U256}; use alloy_rpc_types::Log; use dojo_test_utils::sequencer::{Environment, StarknetConfig, TestSequencer}; use katana_primitives::{ chain::ChainId, genesis::{json::GenesisJson, Genesis}, }; use mongodb::{ bson, bson::{doc, Document}, options::{UpdateModifications, UpdateOptions}, }; use reth_transaction_pool::PoolConfig; use starknet::providers::{jsonrpc::HttpTransport, JsonRpcClient}; use std::{path::Path, sync::Arc}; use testcontainers::ContainerAsync; #[cfg(any(test, feature = "arbitrary", feature = "testing"))] use { super::mongo::MongoFuzzer, alloy_primitives::B256, alloy_rpc_types::Header, alloy_serde::WithOtherFields, katana_node::config::{ rpc::{ApiKind, RpcConfig}, Config, SequencingConfig, }, katana_primitives::chain_spec::ChainSpec, std::collections::HashSet, std::str::FromStr as _, }; fn load_genesis() -> Genesis { Genesis::try_from( GenesisJson::load(Path::new(env!("CARGO_MANIFEST_DIR")).join(".katana/genesis.json")) .expect("Failed to load genesis.json, run `make katana-genesis`"), ) .expect("Failed to convert GenesisJson to Genesis") } /// Returns a `TestSequencer` configured for Kakarot. #[cfg(any(test, feature = "arbitrary", feature = "testing"))] pub async fn katana_sequencer() -> TestSequencer { TestSequencer::start(Config { chain: ChainSpec { id: ChainId::parse("kaka_test").unwrap(), genesis: load_genesis() }, starknet: StarknetConfig { env: Environment { invoke_max_steps: u32::MAX, validate_max_steps: u32::MAX }, ..Default::default() }, sequencing: SequencingConfig { block_time: None, no_mining: false }, rpc: RpcConfig { addr: "127.0.0.1".parse().expect("Failed to parse IP address"), port: 0, max_connections: 100, allowed_origins: None, apis: HashSet::from([ApiKind::Starknet, ApiKind::Dev, ApiKind::Saya, ApiKind::Torii]), }, ..Default::default() }) .await } /// Represents the Katana test environment. #[allow(missing_debug_implementations)] pub struct Katana { /// The test sequencer instance for managing test execution. pub sequencer: TestSequencer, /// The Kakarot EOA (Externally Owned Account) instance. pub eoa: KakarotEOA<Arc<JsonRpcClient<HttpTransport>>>, /// The Ethereum client which contains the mempool and the eth provider pub eth_client: EthClient<Arc<JsonRpcClient<HttpTransport>>>, /// Stored headers to insert into the headers collection. pub headers: Vec<StoredHeader>, /// Stored transactions to insert into the transactions collection. pub transactions: Vec<StoredTransaction>, /// Stored transaction receipts to insert into the receipts collection. pub receipts: Vec<StoredTransactionReceipt>, /// Stored logs to insert into the logs collection. pub logs: Vec<StoredLog>, // /// The port number used for communication. // pub port: u16, /// Option to store the Docker container instance. /// It holds `Some` when the container is running, and `None` otherwise. pub container: Option<ContainerAsync<MongoImage>>, } impl<'a> Katana { #[cfg(any(test, feature = "arbitrary", feature = "testing"))] pub async fn new(rnd_bytes_size: usize) -> Self { let sequencer = katana_sequencer().await; let starknet_provider = Arc::new(JsonRpcClient::new(HttpTransport::new(sequencer.url()))); Self::initialize(sequencer, starknet_provider, rnd_bytes_size).await } #[cfg(any(test, feature = "arbitrary", feature = "testing"))] pub async fn new_empty() -> Self { use alloy_consensus::constants::EMPTY_ROOT_HASH; use alloy_primitives::{B256, B64}; let sequencer = katana_sequencer().await; let starknet_provider = Arc::new(JsonRpcClient::new(HttpTransport::new(sequencer.url()))); // Load the private key from the environment variables. dotenvy::dotenv().expect("Failed to load .env file"); let pk = std::env::var("EVM_PRIVATE_KEY").expect("Failed to get EVM private key"); let pk = B256::from_str(&pk).expect("Failed to parse EVM private key"); // Set the relayer private key in the environment variables. std::env::set_var("RELAYER_PRIVATE_KEY", format!("0x{:x}", sequencer.raw_account().private_key)); // Set the starknet network in the environment variables. std::env::set_var("STARKNET_NETWORK", format!("{}", sequencer.url())); // Initialize a MongoFuzzer instance with the specified random bytes size. let mut mongo_fuzzer = MongoFuzzer::new(0).await; mongo_fuzzer.headers.push(StoredHeader { header: Header { hash: B256::random(), total_difficulty: Some(U256::default()), mix_hash: Some(B256::default()), nonce: Some(B64::default()), withdrawals_root: Some(EMPTY_ROOT_HASH), base_fee_per_gas: Some(0), blob_gas_used: Some(0), excess_blob_gas: Some(0), number: 0, ..Default::default() }, }); // Finalize the empty MongoDB database initialization and get the database instance. let database = mongo_fuzzer.finalize().await; // Initialize the EthClient let eth_client = EthClient::new( starknet_provider, PoolConfig { gas_limit: KKRT_BLOCK_GAS_LIMIT, ..Default::default() }, database, ); // Create a new Kakarot EOA instance with the private key and EthDataProvider instance. let eoa = KakarotEOA::new(pk, Arc::new(eth_client.clone()), sequencer.account()); // Return a new instance of Katana with initialized fields. Self { sequencer, eoa, eth_client, container: Some(mongo_fuzzer.container), transactions: mongo_fuzzer.transactions, receipts: mongo_fuzzer.receipts, logs: mongo_fuzzer.logs, headers: mongo_fuzzer.headers, } } /// Initializes the Katana test environment. #[cfg(any(test, feature = "arbitrary", feature = "testing"))] async fn initialize( sequencer: TestSequencer, starknet_provider: Arc<JsonRpcClient<HttpTransport>>, rnd_bytes_size: usize, ) -> Self { // Load the private key from the environment variables. dotenvy::dotenv().expect("Failed to load .env file"); let pk = std::env::var("EVM_PRIVATE_KEY").expect("Failed to get EVM private key"); let pk = B256::from_str(&pk).expect("Failed to parse EVM private key"); // Set the relayer private key in the environment variables. std::env::set_var("RELAYER_PRIVATE_KEY", format!("0x{:x}", sequencer.raw_account().private_key)); // Set the starknet network in the environment variables. std::env::set_var("STARKNET_NETWORK", format!("{}", sequencer.url())); // Initialize a MongoFuzzer instance with the specified random bytes size. let mut mongo_fuzzer = MongoFuzzer::new(rnd_bytes_size).await; // Add random transactions to the MongoDB database. mongo_fuzzer.add_random_transactions(10).expect("Failed to add documents in the database"); // Add a hardcoded logs to the MongoDB database. mongo_fuzzer.add_random_logs(2).expect("Failed to logs in the database"); // Finalize the MongoDB database initialization and get the database instance. let database = mongo_fuzzer.finalize().await; // Initialize the EthClient let eth_client = EthClient::new( starknet_provider, PoolConfig { gas_limit: KKRT_BLOCK_GAS_LIMIT, ..Default::default() }, database, ); // Create a new Kakarot EOA instance with the private key and EthDataProvider instance. let eoa = KakarotEOA::new(pk, Arc::new(eth_client.clone()), sequencer.account()); // Return a new instance of Katana with initialized fields. Self { sequencer, eoa, eth_client, container: Some(mongo_fuzzer.container), transactions: mongo_fuzzer.transactions, receipts: mongo_fuzzer.receipts, logs: mongo_fuzzer.logs, headers: mongo_fuzzer.headers, } } pub fn eth_client(&self) -> EthClient<Arc<JsonRpcClient<HttpTransport>>> { self.eth_client.clone() } pub fn eth_provider(&self) -> Arc<EthDataProvider<Arc<JsonRpcClient<HttpTransport>>>> { Arc::new(self.eoa.eth_client.eth_provider().clone()) } pub fn starknet_provider(&self) -> Arc<JsonRpcClient<HttpTransport>> { self.eoa.eth_client.eth_provider().starknet_provider_inner().clone() } pub const fn eoa(&self) -> &KakarotEOA<Arc<JsonRpcClient<HttpTransport>>> { &self.eoa } pub const fn sequencer(&self) -> &TestSequencer { &self.sequencer } /// Adds mock logs to the database. pub async fn add_mock_logs(&self, n_logs: usize) { // Get the Ethereum provider instance. let provider = self.eth_provider(); // Get the database instance from the provider. let database = provider.database(); // Create a mock log object with predefined values. let log = Log { inner: alloy_primitives::Log { address: Address::with_last_byte(0x69), data: alloy_primitives::LogData::new_unchecked( vec![B256::with_last_byte(0x69)], Bytes::from_static(&[0x69]), ), }, block_hash: Some(B256::with_last_byte(0x69)), block_number: Some(0x69), block_timestamp: None, transaction_hash: Some(B256::with_last_byte(0x69)), transaction_index: Some(0x69), log_index: Some(0x69), removed: false, }; // Create a vector to hold all the BSON documents to be inserted let log_docs: Vec<Document> = std::iter::repeat(log.clone()) .take(n_logs) .map(|log| { let stored_log = StoredLog { log }; bson::to_document(&stored_log).expect("Failed to serialize StoredLog to BSON") }) .collect(); // Insert all the BSON documents into the MongoDB collection at once. database .inner() .collection(StoredLog::collection_name()) .insert_many(log_docs) .await .expect("Failed to insert logs into the database"); } /// Adds transactions to the database along with a corresponding header. pub async fn add_transactions_with_header_to_database(&self, txs: Vec<ExtendedTransaction>, header: Header) { let provider = self.eth_provider(); let database = provider.database(); let Header { number, .. } = header; let block_number = number; // Add the transactions to the database. let tx_collection = database.collection::<StoredTransaction>(); for tx in txs { database.upsert_transaction(tx).await.expect("Failed to update transaction in database"); } // We use the unpadded block number to filter the transactions in the database and // the padded block number to update the block number in the database. let unpadded_block_number = format_hex(block_number, 0); let padded_block_number = format_hex(block_number, U64_HEX_STRING_LEN); // The transactions get added in the database with the unpadded block number (due to U256 serialization using `human_readable`). // We need to update the block number to the padded version. tx_collection .update_many( doc! {"tx.blockNumber": &unpadded_block_number}, UpdateModifications::Document(doc! {"$set": {"tx.blockNumber": &padded_block_number}}), ) .with_options(UpdateOptions::builder().upsert(true).build()) .await .expect("Failed to update block number"); // Same issue as the transactions, we need to update the block number to the padded version once added // to the database. let header_collection = database.collection::<StoredHeader>(); let filter = EthDatabaseFilterBuilder::<filter::Header>::default().with_block_number(block_number).build(); database.update_one(StoredHeader { header }, filter, true).await.expect("Failed to update header in database"); header_collection .update_one( doc! {"header.number": unpadded_block_number}, UpdateModifications::Document(doc! {"$set": {"header.number": padded_block_number}}), ) .with_options(UpdateOptions::builder().upsert(true).build()) .await .expect("Failed to update block number"); } /// Retrieves the first stored transaction pub fn first_transaction(&self) -> Option<ExtendedTransaction> { self.transactions.first().map(Into::into) } /// Retrieves the current block number pub fn block_number(&self) -> u64 { self.headers.iter().map(|header| header.number).max().unwrap_or_default() } /// Retrieves the most recent stored transaction based on block number pub fn most_recent_transaction(&self) -> Option<ExtendedTransaction> { self.transactions .iter() .max_by_key(|stored_transaction| stored_transaction.block_number.unwrap_or_default()) .map(Into::into) } pub fn most_recent_reverted_receipt(&self) -> Option<ExtendedTxReceipt> { self.receipts .iter() .filter_map(|stored_receipt| { let receipt = WithOtherFields::from(stored_receipt.clone()); if receipt.other.contains_key("reverted") { Some(receipt) } else { None } }) .max_by_key(|receipt| receipt.block_number.unwrap_or_default()) } /// Retrieves the stored header by hash pub fn header_by_hash(&self, hash: B256) -> Option<Header> { self.headers.iter().find_map( |stored_header| { if stored_header.hash == hash { Some(stored_header.header.clone()) } else { None } }, ) } pub fn logs_with_min_topics(&self, min_topics: usize) -> Vec<Log> { self.logs.iter().filter(|stored_log| stored_log.topics().len() >= min_topics).map(Into::into).collect() } pub fn logs_by_address(&self, addresses: &[Address]) -> Vec<Log> { self.logs .iter() .filter(|stored_log| addresses.iter().any(|addr| *addr == stored_log.address())) .map(Into::into) .collect() } pub fn logs_by_block_number(&self, block_number: u64) -> Vec<Log> { self.logs .iter() .filter(|stored_log| stored_log.block_number.unwrap_or_default() == block_number) .map(Into::into) .collect() } pub fn logs_by_block_range(&self, block_range: std::ops::Range<u64>) -> Vec<Log> { self.logs .iter() .filter(|stored_log| { let block_number = stored_log.block_number.unwrap_or_default(); block_range.contains(&block_number) }) .map(Into::into) .collect() } pub fn logs_by_block_hash(&self, block_hash: B256) -> Vec<Log> { self.logs .iter() .filter(|stored_log| stored_log.block_hash.unwrap_or_default() == block_hash) .map(Into::into) .collect() } pub fn all_logs(&self) -> Vec<Log> { self.logs.iter().map(Into::into).collect() } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/test_utils/rpc/mod.rs
src/test_utils/rpc/mod.rs
use super::katana::Katana; use crate::eth_rpc::{config::RPCConfig, rpc::KakarotRpcModuleBuilder, run_server}; use jsonrpsee::server::ServerHandle; use serde::{Deserialize, Serialize}; use serde_json::Value; use std::net::SocketAddr; /// Sets up the environment for Kakarot RPC integration tests by deploying the Kakarot contracts /// and starting the Kakarot RPC server. /// /// This function: /// 1. Takes an `Arc<TestSequencer>` as input, which is used to deploy the Kakarot contracts and to /// set up the Kakarot RPC server. /// 2. Deploys the Kakarot contracts. /// 3. Creates Starknet and Kakarot clients. /// 4. Sets up and runs the Kakarot RPC module. /// /// # Arguments /// /// * `starknet_test_sequencer` - An Arc-wrapped `TestSequencer`. This is used to deploy the Kakarot /// contracts and to set up the Kakarot RPC server. /// /// # Returns /// /// This function returns a Result containing a tuple with the server's address and a handle to /// stop the server upon successful execution. /// /// The function may return an Err variant of `eyre::Report` if there are issues with deploying the /// Kakarot contracts, creating the clients, or running the RPC server. /// /// # Example /// ```ignore /// use kakarot_rpc::test_utils::start_kakarot_rpc_server; /// use kakarot_rpc_core::test_utils::fixtures::kakarot_test_env_ctx; /// use kakarot_rpc_core::test_utils::deploy_helpers::KakarotTestEnvironmentContext; /// use dojo_test_utils::sequencer::TestSequencer; /// use std::sync::Arc; /// use tokio::runtime::Runtime; /// use rstest::*; /// /// #[rstest] /// #[tokio::test] /// async fn test_case(kakarot_test_env_ctx: KakarotTestEnvironmentContext) { /// // Set up the Kakarot RPC integration environment. /// let (server_addr, server_handle) = start_kakarot_rpc_server(&kakarot_test_env_ctx).await.unwrap(); /// /// // Query whatever eth_rpc endpoints /// /// // Dont forget to close server at the end. /// server_handle.stop().expect("Failed to stop the server"); /// /// } /// ``` /// /// `allow(dead_code)` is used because this function is used in tests, /// and each test is compiled separately, so the compiler thinks this function is unused pub async fn start_kakarot_rpc_server(katana: &Katana) -> Result<(SocketAddr, ServerHandle), eyre::Report> { let eth_client = katana.eth_client(); Ok(run_server( KakarotRpcModuleBuilder::new(eth_client.into()).rpc_module()?, #[cfg(feature = "testing")] RPCConfig::new_test_config_from_port(rand::random()), #[cfg(not(feature = "testing"))] RPCConfig::from_port(3030), ) .await?) } /// Represents a builder for creating JSON-RPC requests. /// Taken from <https://github.com/paradigmxyz/reth/blob/main/crates/rpc/rpc-builder/tests/it/http.rs> #[derive(Clone, Serialize, Deserialize, Debug)] pub struct RawRpcParamsBuilder { method: String, params: Vec<Value>, id: i32, } impl RawRpcParamsBuilder { /// Sets the method name for the JSON-RPC request. pub fn new(method: impl Into<String>) -> Self { Self { method: method.into(), params: Vec::new(), id: 1 } } /// Adds a parameter to the JSON-RPC request. #[must_use] pub fn add_param<S: Serialize>(mut self, param: S) -> Self { self.params.push(serde_json::to_value(param).expect("Failed to serialize parameter")); self } /// Sets the ID for the JSON-RPC request. #[must_use] pub const fn set_id(mut self, id: i32) -> Self { self.id = id; self } /// Constructs the JSON-RPC request string based on the provided configurations. pub fn build(self) -> String { let Self { method, params, id } = self; format!( r#"{{"jsonrpc":"2.0","id":{},"method":"{}","params":[{}]}}"#, id, method, params.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(",") ) } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/test_utils/hive/mod.rs
src/test_utils/hive/mod.rs
use super::{ constants::{ ACCOUNT_CAIRO1_HELPERS_CLASS_HASH, ACCOUNT_IMPLEMENTATION, KAKAROT_EVM_TO_STARKNET_ADDRESS, OWNABLE_OWNER, }, katana::genesis::{KatanaGenesisBuilder, Loaded}, }; use account::{Account, KakarotAccount}; use alloy_primitives::{Address, Bytes, B256, U256, U64}; use katana_primitives::{ contract::ContractAddress, genesis::json::{ClassNameOrHash, GenesisContractJson, GenesisJson}, }; use serde::{Deserialize, Serialize}; use starknet::core::{types::Felt, utils::get_storage_var_address}; use std::collections::{BTreeMap, HashMap}; mod account; /// Types from <https://github.com/ethereum/go-ethereum/blob/master/core/genesis.go#L49C1-L58> #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct HiveGenesisConfig { pub config: Config, pub coinbase: Address, pub difficulty: U64, pub extra_data: Bytes, pub gas_limit: U64, pub nonce: U64, pub timestamp: U64, pub alloc: HashMap<Address, AccountInfo>, } #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct Config { pub chain_id: i128, pub homestead_block: i128, pub eip150_block: i128, pub eip150_hash: Option<B256>, pub eip155_block: i128, pub eip158_block: i128, } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct AccountInfo { pub balance: U256, pub code: Option<Bytes>, pub storage: Option<HashMap<U256, U256>>, } impl HiveGenesisConfig { /// Convert the [`HiveGenesisConfig`] into a [`GenesisJson`] using an [`KatanaGenesisBuilder`]<[Loaded]>. The [Loaded] /// marker type indicates that the Kakarot contract classes need to have been loaded into the builder. pub fn try_into_genesis_json(self, builder: KatanaGenesisBuilder<Loaded>) -> Result<GenesisJson, eyre::Error> { let coinbase_address = Felt::from_bytes_be_slice(self.coinbase.as_slice()); let builder = builder.with_kakarot(coinbase_address, self.config.chain_id.into())?; // Get the current state of the builder. let kakarot_address = builder.cache_load("kakarot_address")?; let account_contract_class_hash = builder.account_contract_class_hash()?; // Fetch the contracts from the alloc field. let mut additional_kakarot_storage = HashMap::with_capacity(self.alloc.len()); // 1 mapping per contract let mut fee_token_storage = HashMap::with_capacity(2 * self.alloc.len()); // 2 allowances per contract let contracts = self .alloc .into_iter() .map(|(address, info)| { let evm_address = Felt::from_bytes_be_slice(address.as_slice()); let starknet_address = builder.compute_starknet_address(evm_address)?.0; // Store the mapping from EVM to Starknet address. additional_kakarot_storage.insert( get_storage_var_address(KAKAROT_EVM_TO_STARKNET_ADDRESS, &[evm_address])?, starknet_address, ); // Get the Kakarot account in order to have the account type and storage. let code = info.code.unwrap_or_default(); let storage = info.storage.unwrap_or_default(); let storage: Vec<(U256, U256)> = storage.into_iter().collect(); let nonce = if code.is_empty() && storage.is_empty() { U256::ZERO } else { U256::from(1u8) }; let kakarot_account = KakarotAccount::new(&address, Account { code, nonce, storage, ..Default::default() })?; let mut kakarot_account_storage: Vec<(Felt, Felt)> = kakarot_account.storage().iter().map(|(k, v)| (*k, *v)).collect(); // Add the implementation to the storage. let implementation_key = get_storage_var_address(ACCOUNT_IMPLEMENTATION, &[])?; kakarot_account_storage.append(&mut vec![ (implementation_key, account_contract_class_hash), (get_storage_var_address(OWNABLE_OWNER, &[])?, kakarot_address), ( get_storage_var_address(ACCOUNT_CAIRO1_HELPERS_CLASS_HASH, &[])?, builder.cache_load("cairo1_helpers")?, ), ]); let key = get_storage_var_address("ERC20_allowances", &[starknet_address, kakarot_address])?; fee_token_storage.insert(key, u128::MAX.into()); fee_token_storage.insert(key + Felt::ONE, u128::MAX.into()); Ok(( ContractAddress::new(starknet_address), GenesisContractJson { class: Some(ClassNameOrHash::Hash(account_contract_class_hash)), balance: Some(info.balance), nonce: None, storage: Some(kakarot_account_storage.into_iter().collect()), }, )) }) .collect::<Result<HashMap<_, _>, eyre::Error>>()?; // Build the builder let kakarot_address = ContractAddress::new(kakarot_address); let mut genesis = builder.build()?; let kakarot_contract = genesis.contracts.entry(kakarot_address); kakarot_contract.and_modify(|contract| { contract.storage.get_or_insert_with(BTreeMap::new).extend(additional_kakarot_storage); }); genesis.fee_token.storage.get_or_insert_with(BTreeMap::new).extend(fee_token_storage); // Add the contracts to the genesis. genesis.contracts.extend(contracts); Ok(genesis) } } #[cfg(test)] mod tests { use super::*; use crate::{ providers::eth_provider::utils::split_u256, test_utils::{constants::ACCOUNT_STORAGE, katana::genesis::Initialized}, }; use std::{ path::{Path, PathBuf}, sync::LazyLock, }; static ROOT: LazyLock<PathBuf> = LazyLock::new(|| Path::new(env!("CARGO_MANIFEST_DIR")).to_path_buf()); static HIVE_GENESIS: LazyLock<HiveGenesisConfig> = LazyLock::new(|| { let hive_content = std::fs::read_to_string(ROOT.join("src/test_utils/hive/test_data/genesis.json")).unwrap(); serde_json::from_str(&hive_content).unwrap() }); static GENESIS_BUILDER_LOADED: LazyLock<KatanaGenesisBuilder<Loaded>> = LazyLock::new(|| KatanaGenesisBuilder::default().load_classes(ROOT.join("lib/kakarot/build"))); static GENESIS_BUILDER: LazyLock<KatanaGenesisBuilder<Initialized>> = LazyLock::new(|| { // The chain ID is hardcoded in the hive genesis file src/test_utils/hive/test_data/genesis.json GENESIS_BUILDER_LOADED.clone().with_kakarot(Felt::ZERO, Felt::from_hex_unchecked("7")).unwrap() }); static GENESIS: LazyLock<GenesisJson> = LazyLock::new(|| HIVE_GENESIS.clone().try_into_genesis_json(GENESIS_BUILDER_LOADED.clone()).unwrap()); #[test] fn test_correct_genesis_len() { assert_eq!(GENESIS.contracts.len(), 8); } #[test] fn test_genesis_accounts() { for (address, account) in HIVE_GENESIS.alloc.clone() { let starknet_address = GENESIS_BUILDER.compute_starknet_address(Felt::from_bytes_be_slice(address.as_slice())).unwrap().0; let contract = GENESIS.contracts.get(&ContractAddress::new(starknet_address)).unwrap(); // Check the balance assert_eq!(contract.balance, Some(account.balance)); // Check the storage for (key, value) in account.storage.unwrap_or_default() { let key = get_storage_var_address(ACCOUNT_STORAGE, &split_u256::<Felt>(key)).unwrap(); let low = U256::from_be_slice(contract.storage.as_ref().unwrap().get(&key).unwrap().to_bytes_be().as_slice()); let high = U256::from_be_slice( contract.storage.as_ref().unwrap().get(&(key + Felt::ONE)).unwrap().to_bytes_be().as_slice(), ); let actual_value = low + (high << 128); assert_eq!(actual_value, value); } } } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/test_utils/hive/account.rs
src/test_utils/hive/account.rs
#![allow(unreachable_pub)] use crate::providers::eth_provider::utils::split_u256; use alloy_consensus::constants::KECCAK_EMPTY; use alloy_primitives::{keccak256, Address, Bytes, U256}; use revm_interpreter::analysis::to_analysed; use revm_primitives::Bytecode; use starknet::core::utils::get_storage_var_address; use starknet_api::{core::Nonce, StarknetApiError}; use starknet_crypto::Felt; pub const ACCOUNT_BYTECODE_LEN: &str = "Account_bytecode_len"; pub const ACCOUNT_CODE_HASH: &str = "Account_code_hash"; pub const ACCOUNT_EVM_ADDRESS: &str = "Account_evm_address"; pub const ACCOUNT_IS_INITIALIZED: &str = "Account_is_initialized"; pub const ACCOUNT_NONCE: &str = "Account_nonce"; pub const ACCOUNT_STORAGE: &str = "Account_storage"; pub const ACCOUNT_VALID_JUMPDESTS: &str = "Account_valid_jumpdests"; /// An account. #[derive(Debug, PartialEq, Eq, Clone, Default)] pub struct Account { /// Balance. pub balance: U256, /// Code. pub code: Bytes, /// Nonce. pub nonce: U256, /// Storage. pub storage: Vec<(U256, U256)>, } #[macro_export] macro_rules! starknet_storage { ($storage_var: expr, $felt: expr) => { ( get_storage_var_address($storage_var, &[]).expect("Failed to get storage var address"), Felt::from($felt), ) }; ($storage_var: expr, [$($key: expr),*], $felt: expr) => { { let args = vec![$($key),*]; ( get_storage_var_address($storage_var, &args).expect("Failed to get storage var address"), Felt::from($felt), ) } }; } /// Structure representing a Kakarot account. /// Contains a nonce, Starknet storage, account /// type, evm address and starknet address. #[allow(dead_code)] #[derive(Debug, Clone, Default)] pub struct KakarotAccount { pub evm_address: Felt, pub nonce: Nonce, pub storage: Vec<(Felt, Felt)>, } impl KakarotAccount { pub fn storage(&self) -> &[(Felt, Felt)] { self.storage.as_slice() } } impl KakarotAccount { pub fn new(evm_address: &Address, account: Account) -> Result<Self, StarknetApiError> { let nonce = Felt::from( TryInto::<u128>::try_into(account.nonce) .map_err(|err| StarknetApiError::OutOfRange { string: err.to_string() })?, ); let evm_address = Felt::from_bytes_be_slice(&evm_address.0[..]); let mut storage = vec![ starknet_storage!(ACCOUNT_EVM_ADDRESS, evm_address), starknet_storage!(ACCOUNT_IS_INITIALIZED, 1u8), starknet_storage!(ACCOUNT_BYTECODE_LEN, account.code.len() as u32), starknet_storage!(ACCOUNT_NONCE, nonce), ]; // Initialize the bytecode storage var. let mut bytecode_storage: Vec<(Felt, Felt)> = pack_byte_array_to_starkfelt_array(&account.code) .enumerate() .map(|(i, bytes)| (Felt::from(i as u32), bytes)) .collect(); storage.append(&mut bytecode_storage); // Initialize the code hash var let account_is_empty = account.code.is_empty() && nonce == Felt::ZERO && account.balance == U256::ZERO; let code_hash = if account_is_empty { U256::ZERO } else if account.code.is_empty() { U256::from_be_slice(KECCAK_EMPTY.as_slice()) } else { U256::from_be_slice(keccak256(account.code.clone()).as_slice()) }; let code_hash_values: [u128; 2] = split_u256(code_hash); let code_hash_low_key = get_storage_var_address(ACCOUNT_CODE_HASH, &[]).expect("Failed to get storage var address"); let code_hash_high_key = next_storage_key(&code_hash_low_key); storage.extend([ (code_hash_low_key, Felt::from(code_hash_values[0])), (code_hash_high_key, Felt::from(code_hash_values[1])), ]); // Initialize the bytecode jumpdests. let bytecode = to_analysed(Bytecode::new_raw(account.code)); let valid_jumpdests: Vec<usize> = match bytecode { Bytecode::LegacyAnalyzed(legacy_analyzed_bytecode) => legacy_analyzed_bytecode .jump_table() .0 .iter() .enumerate() .filter_map(|(index, bit)| bit.as_ref().then(|| index)) .collect(), _ => unreachable!("Bytecode should be analysed"), }; let jumdpests_storage_address = get_storage_var_address(ACCOUNT_VALID_JUMPDESTS, &[]).expect("Failed to get storage var address"); for index in valid_jumpdests { storage.push((jumdpests_storage_address + Felt::from(index), Felt::ONE)); } // Initialize the storage vars. let mut evm_storage_storage: Vec<(Felt, Felt)> = account .storage .iter() .flat_map(|(k, v)| { let keys: [u128; 2] = split_u256(*k); let keys = keys.map(Into::into); let values: [u128; 2] = split_u256(*v); let values = values.map(Into::<Felt>::into); let low_key = get_storage_var_address(ACCOUNT_STORAGE, &keys).expect("Failed to get storage var address"); let high_key = next_storage_key(&low_key); vec![(low_key, values[0]), (high_key, values[1])] }) .collect(); storage.append(&mut evm_storage_storage); Ok(Self { storage, evm_address, nonce: Nonce(nonce) }) } } fn next_storage_key(key: &Felt) -> Felt { key + Felt::ONE } /// Splits a byte array into 31-byte chunks and converts each chunk to a Felt. fn pack_byte_array_to_starkfelt_array(bytes: &[u8]) -> impl Iterator<Item = Felt> + '_ { bytes.chunks(31).map(Felt::from_bytes_be_slice) } #[cfg(test)] mod tests { use super::*; use alloy_primitives::Bytes; #[test] fn test_pack_byte_array_to_starkfelt_array() { // Given let bytes = Bytes::from([0x01, 0x02, 0x03, 0x04, 0x05]); // When let result: Vec<_> = pack_byte_array_to_starkfelt_array(&bytes).collect(); // Then assert_eq!(result, vec![Felt::from(0x0001_0203_0405_u64)]); } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/src/test_utils/mongo/mod.rs
src/test_utils/mongo/mod.rs
use crate::providers::eth_provider::{ constant::U64_HEX_STRING_LEN, database::{ types::{ header::StoredHeader, log::StoredLog, receipt::{ExtendedTxReceipt, StoredTransactionReceipt}, transaction::StoredTransaction, }, CollectionName, Database, }, }; use alloy_primitives::{B256, U256}; use alloy_rpc_types::Transaction; use arbitrary::Arbitrary; use mongodb::{ bson::{self, doc, Document}, options::{DatabaseOptions, ReadConcern, UpdateModifications, UpdateOptions, WriteConcern}, Client, }; use reth_primitives::TxType; use serde::Serialize; use std::sync::LazyLock; use strum::{EnumIter, IntoEnumIterator}; use testcontainers::{ core::{IntoContainerPort, WaitFor}, runners::AsyncRunner, ContainerAsync, Image, }; /// Hardcoded chain ID for testing purposes. pub static CHAIN_ID: LazyLock<U256> = LazyLock::new(|| U256::from(1)); /// The size of the random bytes used for the arbitrary randomized implementation. pub const RANDOM_BYTES_SIZE: usize = 100_024; #[derive(Default, Debug)] pub struct MongoImage; impl Image for MongoImage { fn name(&self) -> &str { "mongo" } fn tag(&self) -> &str { "6.0.13" } fn ready_conditions(&self) -> Vec<WaitFor> { vec![WaitFor::Nothing] } } /// Enumeration of collections in the database. #[derive(Eq, Hash, PartialEq, Clone, Debug, EnumIter)] pub enum CollectionDB { /// Collection of block headers. Headers, /// Collection of transactions. Transactions, /// Collection of transaction receipts. Receipts, /// Collection of logs. Logs, } /// Struct representing a data generator for `MongoDB`. #[cfg(any(test, feature = "arbitrary", feature = "testing"))] #[derive(Debug)] pub struct MongoFuzzer { /// Stored headers to insert into the headers collection. pub headers: Vec<StoredHeader>, /// Stored transactions to insert into the transactions collection. pub transactions: Vec<StoredTransaction>, /// Stored transaction receipts to insert into the receipts collection. pub receipts: Vec<StoredTransactionReceipt>, /// Stored logs to insert into the logs collection. pub logs: Vec<StoredLog>, /// Connection to the [`MongoDB`] database. mongodb: Database, /// Random bytes size. rnd_bytes_size: usize, /// Container pub container: ContainerAsync<MongoImage>, } #[cfg(any(test, feature = "arbitrary", feature = "testing"))] impl MongoFuzzer { /// Asynchronously creates a new instance of `MongoFuzzer`. pub async fn new(rnd_bytes_size: usize) -> Self { let container = MongoImage.start().await.expect("Failed to start MongoDB container"); let host_ip = container.get_host().await.expect("Failed to get host IP"); let port = container.get_host_port_ipv4(27017.tcp()).await.expect("Failed to get host port"); let url = format!("mongodb://{host_ip}:{port}/"); // Initialize a MongoDB client with the generated port number. let mongo_client = Client::with_uri_str(url).await.expect("Failed to init mongo Client"); // Create a MongoDB database named "kakarot" with specified options. let mongodb = mongo_client .database_with_options( "kakarot", DatabaseOptions::builder() .read_concern(ReadConcern::majority()) .write_concern(WriteConcern::majority()) .build(), ) .into(); Self { headers: vec![], transactions: vec![], receipts: vec![], logs: vec![], mongodb, rnd_bytes_size, container, } } /// Finalizes the data generation and returns the `MongoDB` database. pub async fn finalize(&self) -> Database { futures::future::join_all(CollectionDB::iter().map(|collection| self.update_collection(collection))).await; self.mongodb.clone() } /// Mocks a database with the given number of transactions. pub async fn mock_database(&mut self, n_transactions: usize) -> Database { self.add_random_transactions(n_transactions).expect("Failed to add documents"); self.finalize().await } /// Adds random logs to the collection of logs. pub fn add_random_logs(&mut self, n_logs: usize) -> Result<(), Box<dyn std::error::Error>> { for _ in 0..n_logs { let bytes: Vec<u8> = (0..self.rnd_bytes_size).map(|_| rand::random()).collect(); let mut unstructured = arbitrary::Unstructured::new(&bytes); let mut log = StoredLog::arbitrary(&mut unstructured)?.log; let topics = log.inner.data.topics_mut_unchecked(); topics.clear(); topics.extend([ B256::arbitrary(&mut unstructured)?, B256::arbitrary(&mut unstructured)?, B256::arbitrary(&mut unstructured)?, B256::arbitrary(&mut unstructured)?, ]); // Ensure the block number in log <= max block number in the transactions collection. log.block_number = Some(log.block_number.unwrap_or_default().min(self.max_block_number())); self.logs.push(StoredLog { log }); } Ok(()) } /// Gets the highest block number in the transactions collection. pub fn max_block_number(&self) -> u64 { self.headers.iter().map(|header| header.number).max().unwrap_or_default() } /// Adds random transactions to the collection of transactions. pub fn add_random_transactions(&mut self, n_transactions: usize) -> Result<(), Box<dyn std::error::Error>> { for i in 0..n_transactions { // Build a transaction using the random byte size. let mut transaction = StoredTransaction::arbitrary(&mut arbitrary::Unstructured::new( &(0..self.rnd_bytes_size).map(|_| rand::random::<u8>()).collect::<Vec<_>>(), ))?; // For the first transaction, set the block number to 0 to mimic a genesis block. // // We need to have a block number of 0 for our tests (when testing the `EARLIEST` block number). if i == 0 { transaction.tx.block_number = Some(0); } // Generate a receipt for the transaction. let receipt = self.generate_transaction_receipt(&transaction.tx); // Convert the receipt into a vector of logs and append them to the existing logs collection. self.logs.append(&mut Vec::from(receipt.clone())); // Generate a header for the transaction and add it to the headers collection. self.headers.push(self.generate_transaction_header(&transaction.tx)); // Add the transaction to the transactions collection. self.transactions.push(transaction); // Add the receipt to the receipts collection. self.receipts.push(receipt); } self.add_random_transaction_with_other_field()?; // At the end of our transaction list, for our tests, we need to add a block header with a base fee. let mut header_with_base_fee = StoredHeader::arbitrary(&mut arbitrary::Unstructured::new( &(0..self.rnd_bytes_size).map(|_| rand::random::<u8>()).collect::<Vec<_>>(), )) .unwrap(); header_with_base_fee.header.number = self.max_block_number() + 1; header_with_base_fee.header.base_fee_per_gas = Some(0); self.headers.push(header_with_base_fee); Ok(()) } pub fn add_random_transaction_with_other_field(&mut self) -> Result<(), Box<dyn std::error::Error>> { // Build a transaction using the random byte size. let transaction = StoredTransaction::arbitrary(&mut arbitrary::Unstructured::new( &(0..self.rnd_bytes_size).map(|_| rand::random::<u8>()).collect::<Vec<_>>(), ))?; // Generate a receipt for the transaction. let receipt = self.generate_transaction_receipt(&transaction.tx); // add an reverted field to the receipt let mut receipt_with_other_fields: ExtendedTxReceipt = receipt.into(); receipt_with_other_fields .other .insert("reverted".to_string(), serde_json::Value::String("A custom revert reason".to_string())); let stored_receipt = StoredTransactionReceipt { receipt: receipt_with_other_fields }; // Convert the receipt into a vector of logs and append them to the existing logs collection. self.logs.append(&mut Vec::from(stored_receipt.clone())); // Generate a header for the transaction and add it to the headers collection. self.headers.push(self.generate_transaction_header(&transaction.tx)); // Add the transaction to the transactions collection. self.transactions.push(transaction); // Add the receipt to the receipts collection. self.receipts.push(stored_receipt); Ok(()) } /// Generates a transaction receipt based on the given transaction. fn generate_transaction_receipt(&self, transaction: &Transaction) -> StoredTransactionReceipt { let bytes: Vec<u8> = (0..self.rnd_bytes_size).map(|_| rand::random()).collect(); let mut unstructured = arbitrary::Unstructured::new(&bytes); let mut receipt = StoredTransactionReceipt::arbitrary(&mut unstructured).unwrap(); // Ensure the block number in receipt is equal to the block number in transaction. let mut modified_logs = (*receipt.receipt.inner.inner.as_receipt_with_bloom().unwrap()).clone(); for log in &mut modified_logs.receipt.logs { log.block_number = Some(transaction.block_number.unwrap_or_default()); log.block_hash = transaction.block_hash; } receipt.receipt.transaction_hash = transaction.hash; receipt.receipt.transaction_index = Some(transaction.transaction_index.unwrap_or_default()); receipt.receipt.from = transaction.from; receipt.receipt.to = transaction.to; receipt.receipt.block_number = transaction.block_number; receipt.receipt.block_hash = transaction.block_hash; receipt.receipt.inner.inner = match transaction.transaction_type.unwrap_or_default().try_into() { Ok(TxType::Legacy) => alloy_rpc_types::ReceiptEnvelope::Legacy(modified_logs), Ok(TxType::Eip2930) => alloy_rpc_types::ReceiptEnvelope::Eip2930(modified_logs), Ok(TxType::Eip1559) => alloy_rpc_types::ReceiptEnvelope::Eip1559(modified_logs), Ok(TxType::Eip4844) => alloy_rpc_types::ReceiptEnvelope::Eip4844(modified_logs), Ok(TxType::Eip7702) => alloy_rpc_types::ReceiptEnvelope::Eip7702(modified_logs), Err(_) => unreachable!(), }; receipt } /// Generates a block header based on the given transaction. fn generate_transaction_header(&self, transaction: &Transaction) -> StoredHeader { let bytes: Vec<u8> = (0..self.rnd_bytes_size).map(|_| rand::random()).collect(); let mut unstructured = arbitrary::Unstructured::new(&bytes); let mut header = StoredHeader::arbitrary(&mut unstructured).unwrap(); header.header.hash = transaction.block_hash.unwrap(); header.header.number = transaction.block_number.unwrap(); header } /// Updates the collection with the given collection type. async fn update_collection(&self, collection: CollectionDB) { match collection { CollectionDB::Headers => { self.update_documents::<StoredHeader>( StoredHeader::collection_name(), &self.headers, "header", "number", "number", ) .await; } CollectionDB::Transactions => { self.update_documents::<StoredTransaction>( StoredTransaction::collection_name(), &self.transactions, "tx", "hash", "blockNumber", ) .await; } CollectionDB::Receipts => { self.update_documents::<StoredTransactionReceipt>( StoredTransactionReceipt::collection_name(), &self.receipts, "receipt", "transactionHash", "blockNumber", ) .await; } CollectionDB::Logs => { self.update_documents::<StoredLog>( StoredLog::collection_name(), &self.logs, "log", "transactionHash", "blockNumber", ) .await; } } } /// Updates the documents in the collection with the given documents. async fn update_documents<T: Serialize>( &self, collection_name: &str, documents: &[T], doc: &str, value: &str, block_number: &str, ) { let collection = self.mongodb.inner().collection::<Document>(collection_name); let key = [doc, value].join("."); let block_key = [doc, block_number].join("."); for document in documents { // Serialize the StoredData into BSON let serialized_data = bson::to_document(document).expect("Failed to serialize StoredData"); // Insert the document in the collection collection .update_one( doc! {&key: serialized_data.get_document(doc).unwrap().get_str(value).unwrap()}, UpdateModifications::Document(doc! {"$set": serialized_data.clone()}), ) .with_options(UpdateOptions::builder().upsert(true).build()) .await .expect("Failed to insert documents"); let number = serialized_data.get_document(doc).unwrap().get_str(block_number).unwrap(); let padded_number = format!("0x{:0>width$}", &number[2..], width = U64_HEX_STRING_LEN); // Update the document by padding the block number to U64_HEX_STRING_LEN value. collection .update_one( doc! {&block_key: &number}, UpdateModifications::Document(doc! {"$set": {&block_key: padded_number}}), ) .with_options(UpdateOptions::builder().upsert(true).build()) .await .expect("Failed to insert documents"); } } } #[cfg(test)] mod tests { use super::*; use crate::providers::eth_provider::database::types::{ header::StoredHeader, receipt::StoredTransactionReceipt, transaction::StoredTransaction, }; #[tokio::test] async fn test_mongo_fuzzer() { // Generate a MongoDB fuzzer let mut mongo_fuzzer = MongoFuzzer::new(RANDOM_BYTES_SIZE).await; // Mocks a database with 100 transactions, receipts and headers. let database = mongo_fuzzer.mock_database(100).await; // Retrieves stored headers from the database. let _ = database.get_all::<StoredHeader>().await.unwrap(); // Retrieves stored transactions from the database. let transactions = database.get_all::<StoredTransaction>().await.unwrap(); // Retrieves stored receipts from the database. let receipts = database.get_all::<StoredTransactionReceipt>().await.unwrap(); // Transactions should not be empty. assert!(!receipts.is_empty()); // Transactions should not be empty. assert!(!transactions.is_empty()); // Iterates through transactions and receipts in parallel. for (transaction, receipt) in transactions.iter().zip(receipts.iter()) { // Asserts equality between transaction block hash and receipt block hash. assert_eq!(transaction.block_hash, receipt.receipt.block_hash); // Asserts equality between transaction block number and receipt block number. assert_eq!(transaction.block_number, receipt.receipt.block_number); // Asserts equality between transaction hash and receipt transaction hash. assert_eq!(transaction.hash, receipt.receipt.transaction_hash); // Asserts equality between transaction index and receipt transaction index. assert_eq!(transaction.transaction_index, receipt.receipt.transaction_index); // Asserts equality between transaction sender and receipt sender. assert_eq!(transaction.from, receipt.receipt.from); // Asserts equality between transaction recipient and receipt recipient. assert_eq!(transaction.to, receipt.receipt.to); // Asserts equality between transaction type and receipt type. assert_eq!(transaction.transaction_type.unwrap(), Into::<u8>::into(receipt.receipt.transaction_type())); } // Drop the inner MongoDB database. database.inner().drop().await.unwrap(); } }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/tests/entry.rs
tests/entry.rs
//! In order to avoid generating multiple separate test crates, //! we use a single entry point for all tests. Provides better //! performance in testing. pub mod tests;
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/tests/tests/debug_api.rs
tests/tests/debug_api.rs
#![allow(clippy::used_underscore_binding)] #![cfg(feature = "testing")] use alloy_eips::eip2718::{Decodable2718, Encodable2718}; use alloy_primitives::Bytes; use alloy_rlp::Encodable; use alloy_rpc_types::TransactionInfo; use alloy_serde::WithOtherFields; use kakarot_rpc::{ client::TransactionHashProvider, providers::eth_provider::{database::types::transaction::ExtendedTransaction, BlockProvider, ReceiptProvider}, test_utils::{ fixtures::{katana, setup}, katana::Katana, rpc::{start_kakarot_rpc_server, RawRpcParamsBuilder}, }, }; use reth_primitives::{Block, Log, Receipt, ReceiptWithBloom, TransactionSigned, TransactionSignedEcRecovered}; use reth_rpc_types_compat::transaction::from_recovered_with_block_context; use rstest::*; use serde_json::Value; #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_raw_transaction(#[future] katana: Katana, _setup: ()) { let (server_addr, server_handle) = start_kakarot_rpc_server(&katana).await.expect("Error setting up Kakarot RPC server"); // First transaction of the database let tx = katana.first_transaction().unwrap(); // Associated block header let header = katana.header_by_hash(tx.block_hash.unwrap()).unwrap(); // EIP1559 let reqwest_client = reqwest::Client::new(); let res = reqwest_client .post(format!("http://localhost:{}", server_addr.port())) .header("Content-Type", "application/json") .body(RawRpcParamsBuilder::new("debug_getRawTransaction").add_param(format!("0x{:064x}", tx.hash)).build()) .send() .await .expect("Failed to call Debug RPC"); let response = res.text().await.expect("Failed to get response body"); let raw: Value = serde_json::from_str(&response).expect("Failed to deserialize response body"); let rlp_bytes: Option<Bytes> = serde_json::from_value(raw["result"].clone()).expect("Failed to deserialize result"); assert!(rlp_bytes.is_some()); // We can decode the RLP bytes to get the transaction and compare it with the original transaction let transaction = TransactionSigned::decode_2718(&mut rlp_bytes.unwrap().as_ref()).unwrap(); let signer = transaction.recover_signer().unwrap(); let mut transaction = from_recovered_with_block_context( TransactionSignedEcRecovered::from_signed_transaction(transaction, signer), TransactionInfo { hash: Some(tx.hash), block_hash: tx.block_hash, block_number: tx.block_number, base_fee: header.base_fee_per_gas.map(Into::into), index: tx.transaction_index, }, &reth_rpc::eth::EthTxBuilder {}, ); let res = reqwest_client .post(format!("http://localhost:{}", server_addr.port())) .header("Content-Type", "application/json") .body(RawRpcParamsBuilder::new("eth_getTransactionByHash").add_param(format!("0x{:064x}", tx.hash)).build()) .send() .await .expect("Failed to call Debug RPC"); let response = res.text().await.expect("Failed to get response body"); let response: Value = serde_json::from_str(&response).expect("Failed to deserialize response body"); let rpc_transaction: alloy_rpc_types::Transaction = serde_json::from_value(response["result"].clone()).expect("Failed to deserialize result"); // As per https://github.com/paradigmxyz/reth/blob/603e39ab74509e0863fc023461a4c760fb2126d1/crates/rpc/rpc-types-compat/src/transaction/signature.rs#L17 if rpc_transaction.transaction_type.unwrap() == 0 { transaction.signature = Some(alloy_rpc_types::Signature { y_parity: rpc_transaction.signature.unwrap().y_parity, ..transaction.signature.unwrap() }); } // For EIP1559, `gas_price` is recomputed as per https://github.com/paradigmxyz/reth/blob/603e39ab74509e0863fc023461a4c760fb2126d1/crates/rpc/rpc-types-compat/src/transaction/mod.rs#L54 if rpc_transaction.transaction_type.unwrap() == 2 { transaction.gas_price = rpc_transaction.gas_price; } assert_eq!(transaction, rpc_transaction); drop(server_handle); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] /// Test for fetching raw transactions by block hash and block number. async fn test_raw_transactions(#[future] katana: Katana, _setup: ()) { // Start the Kakarot RPC server. let (server_addr, server_handle) = start_kakarot_rpc_server(&katana).await.expect("Error setting up Kakarot RPC server"); // Get the first transaction from the mock data. let tx = &katana.first_transaction().unwrap(); // Get the block hash from the transaction. let block_hash = tx.block_hash.unwrap(); // Get the block number from the transaction and convert it to a u64. let block_number = tx.block_number.unwrap(); // Fetch raw transactions by block hash. let reqwest_client = reqwest::Client::new(); let res_by_block_hash = reqwest_client .post(format!("http://localhost:{}", server_addr.port())) .header("Content-Type", "application/json") .body(RawRpcParamsBuilder::new("debug_getRawTransactions").add_param(format!("0x{block_hash:064x}")).build()) .send() .await .expect("Failed to call Debug RPC"); // Get the response body text from the block hash request. let response_by_block_hash = res_by_block_hash.text().await.expect("Failed to get response body"); // Deserialize the response body into a JSON value. let raw_by_block_hash: Value = serde_json::from_str(&response_by_block_hash).expect("Failed to deserialize response body"); // Deserialize the "result" field of the JSON value into a vector of bytes. let rlp_bytes_by_block_hash: Vec<Bytes> = serde_json::from_value(raw_by_block_hash["result"].clone()).expect("Failed to deserialize result"); // Fetch raw transactions by block number. let res_by_block_number = reqwest_client .post(format!("http://localhost:{}", server_addr.port())) .header("Content-Type", "application/json") .body(RawRpcParamsBuilder::new("debug_getRawTransactions").add_param(format!("0x{block_number:016x}")).build()) .send() .await .expect("Failed to call Debug RPC"); // Get the response body text from the block number request. let response_by_block_number = res_by_block_number.text().await.expect("Failed to get response body"); // Deserialize the response body into a JSON value. let raw_by_block_number: Value = serde_json::from_str(&response_by_block_number).expect("Failed to deserialize response body"); // Deserialize the "result" field of the JSON value into a vector of bytes. let rlp_bytes_by_block_number: Vec<Bytes> = serde_json::from_value(raw_by_block_number["result"].clone()).expect("Failed to deserialize result"); // Assert equality of transactions fetched by block hash and block number. assert_eq!(rlp_bytes_by_block_number, rlp_bytes_by_block_hash); // Get the Ethereum provider from the Katana instance. let eth_provider = katana.eth_provider(); for (i, actual_tx) in eth_provider.block_transactions(Some(block_number.into())).await.unwrap().unwrap().iter().enumerate() { // Fetch the transaction for the current transaction hash. let tx = katana.eth_client.transaction_by_hash(actual_tx.hash).await.unwrap().unwrap(); let signature = tx.signature.unwrap(); // Convert the transaction to a primitives transactions and encode it. let rlp_bytes = TransactionSigned::from_transaction_and_signature( tx.try_into().unwrap(), alloy_primitives::Signature::from_rs_and_parity( signature.r, signature.s, signature.y_parity.map_or(false, |v| v.0), ) .expect("Invalid signature"), ) .encoded_2718(); // Assert the equality of the constructed receipt with the corresponding receipt from both block hash and block number. assert_eq!(rlp_bytes_by_block_number[i], rlp_bytes); assert_eq!(rlp_bytes_by_block_hash[i], rlp_bytes); } // Stop the Kakarot RPC server. drop(server_handle); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] /// Test for fetching raw receipts by block hash and block number. async fn test_raw_receipts(#[future] katana: Katana, _setup: ()) { // Start the Kakarot RPC server. let (server_addr, server_handle) = start_kakarot_rpc_server(&katana).await.expect("Error setting up Kakarot RPC server"); // Get the first transaction from the mock data. let tx = &katana.first_transaction().unwrap(); // Get the block hash from the transaction. let block_hash = tx.block_hash.unwrap(); // Get the block number from the transaction and convert it to a u64. let block_number = tx.block_number.unwrap(); // Fetch raw receipts by block hash. let reqwest_client = reqwest::Client::new(); let res_by_block_hash = reqwest_client .post(format!("http://localhost:{}", server_addr.port())) .header("Content-Type", "application/json") .body(RawRpcParamsBuilder::new("debug_getRawReceipts").add_param(format!("0x{block_hash:064x}")).build()) .send() .await .expect("Failed to call Debug RPC"); // Get the response body text from the block hash request. let response_by_block_hash = res_by_block_hash.text().await.expect("Failed to get response body"); // Deserialize the response body into a JSON value. let raw_by_block_hash: Value = serde_json::from_str(&response_by_block_hash).expect("Failed to deserialize response body"); // Deserialize the "result" field of the JSON value into a vector of bytes. let rlp_bytes_by_block_hash: Vec<Bytes> = serde_json::from_value(raw_by_block_hash["result"].clone()).expect("Failed to deserialize result"); // Fetch raw receipts by block number. let res_by_block_number = reqwest_client .post(format!("http://localhost:{}", server_addr.port())) .header("Content-Type", "application/json") .body(RawRpcParamsBuilder::new("debug_getRawReceipts").add_param(format!("0x{block_number:016x}")).build()) .send() .await .expect("Failed to call Debug RPC"); // Get the response body text from the block number request. let response_by_block_number = res_by_block_number.text().await.expect("Failed to get response body"); // Deserialize the response body into a JSON value. let raw_by_block_number: Value = serde_json::from_str(&response_by_block_number).expect("Failed to deserialize response body"); // Deserialize the "result" field of the JSON value into a vector of bytes. let rlp_bytes_by_block_number: Vec<Bytes> = serde_json::from_value(raw_by_block_number["result"].clone()).expect("Failed to deserialize result"); // Assert equality of receipts fetched by block hash and block number. assert_eq!(rlp_bytes_by_block_number, rlp_bytes_by_block_hash); // Get eth provider let eth_provider = katana.eth_provider(); for (i, receipt) in eth_provider.block_receipts(Some(block_number.into())).await.unwrap().unwrap().iter().enumerate() { // Fetch the transaction receipt for the current receipt hash. let tx_receipt = eth_provider.transaction_receipt(receipt.transaction_hash).await.unwrap().unwrap(); // Construct a Receipt instance from the transaction receipt data. let r: Bytes = ReceiptWithBloom { receipt: Receipt { tx_type: Into::<u8>::into(tx_receipt.transaction_type()).try_into().unwrap(), success: tx_receipt.inner.status(), cumulative_gas_used: TryInto::<u64>::try_into(tx_receipt.inner.inner.cumulative_gas_used()).unwrap(), logs: tx_receipt .inner .inner .logs() .iter() .filter_map(|log| Log::new(log.address(), log.topics().to_vec(), log.data().data.clone())) .collect(), }, bloom: *receipt.inner.inner.logs_bloom(), } .encoded_2718() .into(); // Assert the equality of the constructed receipt with the corresponding receipt from both block hash and block number. assert_eq!(rlp_bytes_by_block_number[i], r); assert_eq!(rlp_bytes_by_block_hash[i], r); } // Stop the Kakarot RPC server. drop(server_handle); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_raw_block(#[future] katana: Katana, _setup: ()) { let (server_addr, server_handle) = start_kakarot_rpc_server(&katana).await.expect("Error setting up Kakarot RPC server"); // Get the first transaction from the mock data. let tx = &katana.first_transaction().unwrap(); // Get the block number from the transaction and convert it to a u64. let block_number = tx.block_number.unwrap(); let reqwest_client = reqwest::Client::new(); let res = reqwest_client .post(format!("http://localhost:{}", server_addr.port())) .header("Content-Type", "application/json") .body(RawRpcParamsBuilder::new("debug_getRawBlock").add_param(format!("0x{block_number:016x}")).build()) .send() .await .expect("Failed to call Debug RPC"); let response = res.text().await.expect("Failed to get response body"); let raw: Value = serde_json::from_str(&response).expect("Failed to deserialize response body"); let rlp_bytes: Option<Bytes> = serde_json::from_value(raw["result"].clone()).expect("Failed to deserialize result"); assert!(rlp_bytes.is_some()); // Query the block with eth_getBlockByNumber let res = reqwest_client .post(format!("http://localhost:{}", server_addr.port())) .header("Content-Type", "application/json") .body( RawRpcParamsBuilder::new("eth_getBlockByNumber") .add_param(format!("0x{block_number:x}")) .add_param(true) .build(), ) .send() .await .expect("Failed to call Debug RPC"); let response = res.text().await.expect("Failed to get response body"); let response: Value = serde_json::from_str(&response).expect("Failed to deserialize response body"); let rpc_block: WithOtherFields<alloy_rpc_types::Block<ExtendedTransaction>> = serde_json::from_value(response["result"].clone()).expect("Failed to deserialize result"); let primitive_block = Block::try_from(rpc_block.inner).unwrap(); // Encode primitive block and compare with the result of debug_getRawBlock let mut buf = Vec::new(); primitive_block.encode(&mut buf); assert_eq!(rlp_bytes.clone().unwrap(), Bytes::from(buf)); // Stop the Kakarot RPC server. drop(server_handle); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_raw_header(#[future] katana: Katana, _setup: ()) { // Start Kakarot RPC server and get its address and handle. let (server_addr, server_handle) = start_kakarot_rpc_server(&katana).await.expect("Error setting up Kakarot RPC server"); // Get the first transaction from the mock data. let tx = &katana.first_transaction().unwrap(); // Get the block hash from the transaction. let block_hash = tx.block_hash.unwrap(); // Get the block number from the transaction and convert it to a u64. let block_number = tx.block_number.unwrap(); // Create a reqwest client. let reqwest_client = reqwest::Client::new(); // Fetch raw header by block hash. let res_by_block_hash = reqwest_client .post(format!("http://localhost:{}", server_addr.port())) .header("Content-Type", "application/json") .body(RawRpcParamsBuilder::new("debug_getRawHeader").add_param(format!("0x{block_hash:064x}")).build()) .send() .await .expect("Failed to call Debug RPC"); let response_by_block_hash = res_by_block_hash.text().await.expect("Failed to get response body"); // Deserialize response body and extract RLP bytes. let raw_by_block_hash: Value = serde_json::from_str(&response_by_block_hash).expect("Failed to deserialize response body"); let rlp_bytes_by_block_hash: Bytes = serde_json::from_value(raw_by_block_hash["result"].clone()).expect("Failed to deserialize result"); // Fetch raw header by block number. let res_by_block_number = reqwest_client .post(format!("http://localhost:{}", server_addr.port())) .header("Content-Type", "application/json") .body(RawRpcParamsBuilder::new("debug_getRawHeader").add_param(format!("0x{block_number:016x}")).build()) .send() .await .expect("Failed to call Debug RPC"); let response_by_block_number = res_by_block_number.text().await.expect("Failed to get response body"); let raw_by_block_number: Value = serde_json::from_str(&response_by_block_number).expect("Failed to deserialize response body"); let rlp_bytes_by_block_number: Bytes = serde_json::from_value(raw_by_block_number["result"].clone()).expect("Failed to deserialize result"); // Assert equality of header fetched by block hash and block number. assert_eq!(rlp_bytes_by_block_number, rlp_bytes_by_block_hash); // Get eth provider. let eth_provider = katana.eth_provider(); // Fetch the transaction receipt for the current receipt hash. let block = eth_provider.block_by_number(block_number.into(), true).await.unwrap().unwrap(); // Encode header into RLP bytes and assert equality with RLP bytes fetched by block number. let mut data = vec![]; Block::try_from(block.inner).unwrap().header.encode(&mut data); assert_eq!(rlp_bytes_by_block_number, data); // Stop the Kakarot RPC server. drop(server_handle); }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/tests/tests/kakarot_api.rs
tests/tests/kakarot_api.rs
#![allow(clippy::used_underscore_binding)] #![cfg(feature = "testing")] use alloy_primitives::B256; use kakarot_rpc::{ providers::eth_provider::constant::Constant, test_utils::{ fixtures::{katana, setup}, katana::Katana, rpc::{start_kakarot_rpc_server, RawRpcParamsBuilder}, }, }; use rstest::*; use serde_json::Value; use starknet::core::types::Felt; use std::str::FromStr; #[cfg(feature = "forwarding")] #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_send_raw_transaction_forwarding(#[future] katana: Katana, _setup: ()) { use alloy_primitives::Bytes; use alloy_provider::{Provider as _, ProviderBuilder}; use mockito::Server; use std::env; use url::Url; let mut server = Server::new_async().await; let mock_server = server .mock("POST", "/") .with_status(200) .with_header("content-type", "application/json") .with_body( r#"{"jsonrpc":"2.0","id":1,"result":"0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"}"#, ) .create(); // Set the MAIN_RPC_URL environment variable env::set_var("MAIN_RPC_URL", server.url()); // Start the Kakarot RPC let (address, handle) = start_kakarot_rpc_server(&katana).await.expect("Error setting up Kakarot RPC server"); // Get an Ethereum provider let provider = ProviderBuilder::new().on_http(Url::parse(&format!("http://localhost:{}", address.port())).unwrap()); // Create a sample raw transaction let raw_tx = Bytes::from(vec![1, 2, 3, 4]); let pending_transaction = provider.send_raw_transaction(&raw_tx).await.unwrap(); let tx_hash = pending_transaction.tx_hash(); assert_eq!(*tx_hash, B256::from_str("1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef").unwrap()); // Verify that the mock was called mock_server.assert(); // Drop the handles at the end of the test drop(handle); drop(server); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_kakarot_get_config(#[future] katana: Katana, _setup: ()) { // Define variables let starknet_network = "http://0.0.0.0:1010/"; let white_listed_eip_155_transaction_hashes = "0xe65425dacfc1423823cb4766aa0192ffde61eaa9bf81af9fe15149a89ef36c28"; let max_logs = 10000; let max_felts_in_calldata = 22500; // Set environment variables for the test std::env::set_var("STARKNET_NETWORK", starknet_network); std::env::set_var("WHITE_LISTED_EIP_155_TRANSACTION_HASHES", white_listed_eip_155_transaction_hashes); std::env::set_var("MAX_LOGS", max_logs.to_string()); std::env::set_var("MAX_FELTS_IN_CALLDATA", max_felts_in_calldata.to_string()); std::env::set_var("KAKAROT_ADDRESS", "0x03d937c035c878245caf64531a5756109c53068da139362728feb561405371cb"); // Hardcoded expected values let expected_constant = Constant { max_logs: Some(max_logs), starknet_network: (starknet_network).to_string(), max_felts_in_calldata, white_listed_eip_155_transaction_hashes: vec![B256::from_str(white_listed_eip_155_transaction_hashes).unwrap()], kakarot_address: Felt::from_hex("0x03d937c035c878245caf64531a5756109c53068da139362728feb561405371cb").unwrap(), }; // Start the Kakarot RPC server let (server_addr, server_handle) = start_kakarot_rpc_server(&katana).await.expect("Error setting up Kakarot RPC server"); // Send the RPC request to get the configuration let reqwest_client = reqwest::Client::new(); let res = reqwest_client .post(format!("http://localhost:{}", server_addr.port())) .header("Content-Type", "application/json") .body(RawRpcParamsBuilder::new("kakarot_getConfig").build()) .send() .await .expect("kakarot_getConfig error"); // Deserialize the response let result_constant: Constant = serde_json::from_str(&res.text().await.expect("Failed to get response body")) .and_then(|raw: Value| serde_json::from_value(raw["result"].clone())) .expect("Failed to deserialize response body or convert result to Constant"); // Assert that the returned configuration matches the expected value assert_eq!(result_constant, expected_constant); drop(server_handle); }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/tests/tests/alchemy_api.rs
tests/tests/alchemy_api.rs
#![allow(clippy::used_underscore_binding)] #![cfg(feature = "testing")] use alloy_dyn_abi::DynSolValue; use alloy_primitives::{address, Address, U256}; use kakarot_rpc::{ models::{ felt::Felt252Wrapper, token::{TokenBalances, TokenMetadata}, }, test_utils::{ eoa::Eoa as _, evm_contract::KakarotEvmContract, fixtures::{erc20, setup}, katana::Katana, rpc::{start_kakarot_rpc_server, RawRpcParamsBuilder}, }, }; use rstest::*; use serde_json::Value; #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_token_balances(#[future] erc20: (Katana, KakarotEvmContract), _setup: ()) { // Given let katana = erc20.0; let erc20 = erc20.1; let eoa = katana.eoa(); let eoa_address = eoa.evm_address().expect("Failed to get Eoa EVM address"); let erc20_address: Address = Felt252Wrapper::from(erc20.evm_address).try_into().expect("Failed to convert EVM address"); let (server_addr, server_handle) = start_kakarot_rpc_server(&katana).await.expect("Error setting up Kakarot RPC server"); // When // Get the recipient address for minting tokens let to = Address::from_slice(eoa.evm_address().unwrap().as_slice()); // Set the amount of tokens to mint let amount = U256::from(10_000); // Call the mint function of the ERC20 contract eoa.call_evm_contract(&erc20, "mint", &[DynSolValue::Address(to), DynSolValue::Uint(amount, 256)], 0) .await .expect("Failed to mint ERC20 tokens"); // Then let reqwest_client = reqwest::Client::new(); let res = reqwest_client .post(format!("http://localhost:{}", server_addr.port())) .header("Content-Type", "application/json") .body( RawRpcParamsBuilder::new("alchemy_getTokenBalances") .add_param(eoa_address) .add_param([erc20_address]) .build(), ) .send() .await .expect("Failed to call Alchemy RPC"); // Get the response body let response = res.text().await.expect("Failed to get response body"); // Deserialize the response body let raw: Value = serde_json::from_str(&response).expect("Failed to deserialize response body"); // Deserialize the token balances from the response let balances: TokenBalances = serde_json::from_value(raw.get("result").cloned().unwrap()).expect("Failed to deserialize response body"); // Get the ERC20 balance from the token balances let erc20_balance = balances.token_balances[0].token_balance; // Assert that the ERC20 balance matches the minted amount assert_eq!(amount, erc20_balance); // Clean up by dropping the Kakarot RPC server handle drop(server_handle); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_token_metadata(#[future] erc20: (Katana, KakarotEvmContract), _setup: ()) { // Obtain the Katana instance let katana = erc20.0; // Obtain the ERC20 contract instance let erc20 = erc20.1; // Convert the ERC20 EVM address let erc20_address: Address = Felt252Wrapper::from(erc20.evm_address).try_into().expect("Failed to convert EVM address"); // Start the Kakarot RPC server let (server_addr, server_handle) = start_kakarot_rpc_server(&katana).await.expect("Error setting up Kakarot RPC server"); // When // Construct and send RPC request for token metadata let reqwest_client = reqwest::Client::new(); let res = reqwest_client .post(format!("http://localhost:{}", server_addr.port())) .header("Content-Type", "application/json") .body(RawRpcParamsBuilder::new("alchemy_getTokenMetadata").add_param(erc20_address).build()) .send() .await .expect("Failed to call Alchemy RPC"); // Then // Verify the response let response = res.text().await.expect("Failed to get response body"); // Deserialize the response body let raw: Value = serde_json::from_str(&response).expect("Failed to deserialize response body"); // Deserialize the token metadata from the response let metadata: TokenMetadata = serde_json::from_value(raw.get("result").cloned().unwrap()).expect("Failed to deserialize response body"); // Assert that the token metadata fields match the expected values assert_eq!(metadata.decimals, U256::from(18)); assert_eq!(metadata.name, "Test"); assert_eq!(metadata.symbol, "TT"); // Clean up by dropping the Kakarot RPC server handle drop(server_handle); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_token_allowance(#[future] erc20: (Katana, KakarotEvmContract), _setup: ()) { // Obtain the Katana instance let katana = erc20.0; // Obtain the ERC20 contract instance let erc20 = erc20.1; // Get the EOA (Externally Owned Account) let eoa = katana.eoa(); // Get the EVM address of the EOA let eoa_address = eoa.evm_address().expect("Failed to get Eoa EVM address"); // Convert the ERC20 EVM address let erc20_address: Address = Felt252Wrapper::from(erc20.evm_address).try_into().expect("Failed to convert EVM address"); // Set the spender address for testing allowance let spender_address = address!("1234567890123456789012345678901234567890"); // Start the Kakarot RPC server let (server_addr, server_handle) = start_kakarot_rpc_server(&katana).await.expect("Error setting up Kakarot RPC server"); // When // Set the allowance amount let allowance_amount = U256::from(5000); // Call the approve function of the ERC20 contract eoa.call_evm_contract( &erc20, "approve", &[DynSolValue::Address(spender_address), DynSolValue::Uint(allowance_amount, 256)], 0, ) .await .expect("Failed to approve allowance for ERC20 tokens"); // Then let reqwest_client = reqwest::Client::new(); // Send a POST request to the Kakarot RPC server let res = reqwest_client .post(format!("http://localhost:{}", server_addr.port())) .header("Content-Type", "application/json") .body( RawRpcParamsBuilder::new("alchemy_getTokenAllowance") .add_param(erc20_address) .add_param(eoa_address) .add_param(spender_address) .build(), ) .send() .await .expect("Failed to call Alchemy RPC"); // Get the response body let response = res.text().await.expect("Failed to get response body"); // Deserialize the response body let raw: Value = serde_json::from_str(&response).expect("Failed to deserialize response body"); // Deserialize the allowance amount from the response let allowance: U256 = serde_json::from_value(raw.get("result").cloned().unwrap()).expect("Failed to deserialize response body"); // Assert that the allowance amount matches the expected amount assert_eq!(allowance, allowance_amount); // Clean up by dropping the Kakarot RPC server handle drop(server_handle); }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/tests/tests/tracer.rs
tests/tests/tracer.rs
#![allow(clippy::used_underscore_binding)] #![cfg(feature = "testing")] use alloy_consensus::Transaction; use alloy_dyn_abi::DynSolValue; use alloy_primitives::{Address, Bytes, B256, B64, U256}; use alloy_rpc_types_trace::{ geth::{GethDebugTracingOptions, GethTrace, TraceResult}, parity::{Action, CallAction, CallOutput, CallType, TraceOutput, TransactionTrace}, }; use alloy_serde::{OtherFields, WithOtherFields}; use kakarot_rpc::{ providers::eth_provider::{BlockProvider, ChainProvider}, test_utils::{ eoa::Eoa, evm_contract::{EvmContract, KakarotEvmContract, TransactionInfo, TxCommonInfo, TxFeeMarketInfo}, fixtures::{plain_opcodes, setup}, katana::Katana, }, tracing::builder::TracerBuilder, }; use revm_inspectors::tracing::TracingInspectorConfig; use rstest::*; use serde_json::json; use starknet::{core::types::MaybePendingBlockWithTxHashes, providers::Provider}; use std::sync::Arc; /// The block number on which tracing will be performed. const TRACING_BLOCK_NUMBER: u64 = 0x3; /// The amount of transactions to be traced. const TRACING_TRANSACTIONS_COUNT: usize = 5; /// Helper to create a header. fn header(block_number: u64, hash: B256, parent_hash: B256, base_fee: u64) -> alloy_rpc_types::Header { alloy_rpc_types::Header { number: block_number, hash, parent_hash, gas_limit: u64::MAX, base_fee_per_gas: Some(base_fee), mix_hash: Some(B256::ZERO), nonce: Some(B64::ZERO), ..Default::default() } } /// Helper to set up the debug/tracing environment on Katana. pub async fn tracing( katana: &Katana, contract: &KakarotEvmContract, entry_point: &str, get_args: Box<dyn Fn(u64) -> Vec<DynSolValue>>, ) { let eoa = katana.eoa(); let eoa_address = eoa.evm_address().expect("Failed to get eoa address"); let nonce: u64 = eoa.nonce().await.expect("Failed to get nonce").to(); let chain_id = eoa.eth_client().eth_provider().chain_id().await.expect("Failed to get chain id").unwrap_or_default().to(); // Push 10 RPC transactions into the database. let mut txs = Vec::with_capacity(TRACING_TRANSACTIONS_COUNT); let max_fee_per_gas = 10; let max_priority_fee_per_gas = 1; for i in 0..TRACING_TRANSACTIONS_COUNT { let tx = contract .prepare_call_transaction( entry_point, &get_args(nonce + i as u64), &TransactionInfo::FeeMarketInfo(TxFeeMarketInfo { common: TxCommonInfo { nonce: nonce + i as u64, value: 0, chain_id: Some(chain_id) }, max_fee_per_gas, max_priority_fee_per_gas, }), ) .expect("Failed to prepare call transaction"); // Sign the transaction and convert it to a RPC transaction. let tx_signed = eoa.sign_transaction(tx.clone()).expect("Failed to sign transaction"); let tx = alloy_rpc_types::Transaction { transaction_type: Some(2), nonce: tx.nonce(), hash: tx_signed.hash(), to: tx.to(), from: eoa_address, block_number: Some(TRACING_BLOCK_NUMBER), chain_id: tx.chain_id(), gas: tx.gas_limit(), input: tx.input().clone(), signature: Some(alloy_rpc_types::Signature { r: tx_signed.signature().r(), s: tx_signed.signature().s(), v: U256::from(tx_signed.signature().v().to_u64()), y_parity: Some(alloy_rpc_types::Parity(tx_signed.signature().v().y_parity())), }), max_fee_per_gas: Some(max_fee_per_gas), gas_price: Some(max_fee_per_gas), max_priority_fee_per_gas: Some(max_priority_fee_per_gas), value: tx.value(), access_list: Some(Default::default()), ..Default::default() }; let mut tx = WithOtherFields::new(tx); // Add an out of resources field to the last transaction. if i == TRACING_TRANSACTIONS_COUNT - 1 { let mut out_of_resources = std::collections::BTreeMap::new(); out_of_resources .insert(String::from("reverted"), serde_json::Value::String("A custom revert reason".to_string())); tx.other = OtherFields::new(out_of_resources); } txs.push(tx); } // Add a block header pointing to a parent hash header in the database for these transactions. // This is required since tracing will start on the previous block. let maybe_parent_block = katana .eth_provider() .starknet_provider() .get_block_with_tx_hashes(starknet::core::types::BlockId::Number(TRACING_BLOCK_NUMBER - 1)) .await .expect("Failed to get block"); let parent_block_hash = match maybe_parent_block { MaybePendingBlockWithTxHashes::PendingBlock(_) => panic!("Pending block found"), MaybePendingBlockWithTxHashes::Block(block) => block.block_hash, }; let parent_block_hash = B256::from_slice(&parent_block_hash.to_bytes_be()[..]); let parent_header = header(TRACING_BLOCK_NUMBER - 1, parent_block_hash, B256::random(), max_fee_per_gas as u64); let header = header(TRACING_BLOCK_NUMBER, B256::random(), parent_block_hash, max_fee_per_gas as u64); katana.add_transactions_with_header_to_database(vec![], parent_header).await; katana.add_transactions_with_header_to_database(txs, header).await; } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_trace_block(#[future] plain_opcodes: (Katana, KakarotEvmContract), _setup: ()) { let katana = plain_opcodes.0; let plain_opcodes = plain_opcodes.1; tracing(&katana, &plain_opcodes, "createCounterAndInvoke", Box::new(|_| vec![])).await; // Get the Ethereum provider from the Katana instance. let eth_provider = katana.eth_provider(); // Create a new TracerBuilder instance. let tracer_builder_block = TracerBuilder::new(Arc::new(&eth_provider)).await.expect("Failed to create tracer_builder_block"); let tracer = tracer_builder_block .with_block_id(TRACING_BLOCK_NUMBER.into()) .await .expect("Failed to set block number") .with_tracing_options(TracingInspectorConfig::default_parity().into()) .build() .expect("Failed to build block_trace"); // Trace the block and get the block traces. let block_traces = tracer.trace_block().expect("Failed to trace block"); // Assert that traces is not None, meaning the response contains some traces. assert!(block_traces.is_some()); let trace_vec = block_traces.unwrap_or_default(); // We expect 3 traces per transaction: CALL, CREATE, and CALL. // Except for the last one which is out of resources. assert!(trace_vec.len() == 3 * (TRACING_TRANSACTIONS_COUNT - 1) + 1); // Get the last trace from the trace vector, which is expected to be out of resources. let out_of_resources_trace = trace_vec.last().unwrap(); // Assert that the block number of the out-of-resources trace is equal to the expected TRACING_BLOCK_NUMBER. assert_eq!(out_of_resources_trace.clone().block_number, Some(TRACING_BLOCK_NUMBER)); // Assert that the trace matches the expected default TransactionTrace. assert_eq!( out_of_resources_trace.trace, TransactionTrace { action: Action::Call(CallAction { from: Address::ZERO, call_type: CallType::Call, gas: Default::default(), input: Bytes::default(), to: Address::ZERO, value: U256::ZERO }), error: None, result: Some(TraceOutput::Call(CallOutput { gas_used: Default::default(), output: Bytes::default() })), subtraces: 0, trace_address: vec![], } ); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_debug_trace_block_by_number(#[future] plain_opcodes: (Katana, KakarotEvmContract), _setup: ()) { let katana = plain_opcodes.0; let plain_opcodes = plain_opcodes.1; tracing(&katana, &plain_opcodes, "createCounterAndInvoke", Box::new(|_| vec![])).await; // Define tracing options for the geth debug tracer. let opts: GethDebugTracingOptions = serde_json::from_value(json!({ "tracer": "callTracer", "tracerConfig": { "onlyTopCall": false }, "timeout": "300s" })) .expect("Failed to deserialize tracing options"); // Get the Ethereum provider from the Katana instance. let eth_provider = katana.eth_provider(); // Create a new TracerBuilder instance. let tracer_builder_block = TracerBuilder::new(Arc::new(&eth_provider)).await.expect("Failed to create tracer_builder_block"); // Get the traces for the block let block_trace = tracer_builder_block .with_block_id(TRACING_BLOCK_NUMBER.into()) .await .expect("Failed to set block number") .with_tracing_options(kakarot_rpc::tracing::builder::TracingOptions::Geth(opts.clone())) .build() .expect("Failed to build block_trace"); // Trace the block and get the block traces. let block_traces = block_trace.debug_block().expect("Failed to trace block by number"); // We expect 1 trace per transaction given the formatting of the debug_traceBlockByNumber response. assert!(block_traces.len() == TRACING_TRANSACTIONS_COUNT); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_debug_trace_transaction(#[future] plain_opcodes: (Katana, KakarotEvmContract), _setup: ()) { let katana = plain_opcodes.0; let plain_opcodes = plain_opcodes.1; tracing(&katana, &plain_opcodes, "createCounterAndInvoke", Box::new(|_| vec![])).await; // Get the block in order to trace a transaction. let block = katana .eth_provider() .block_by_number(TRACING_BLOCK_NUMBER.into(), false) .await .expect("Failed to get block") .unwrap(); let index = TRACING_TRANSACTIONS_COUNT - 2; let tx_hash = block.transactions.as_hashes().unwrap().get(index).unwrap(); let opts: GethDebugTracingOptions = serde_json::from_value(json!({ "tracer": "callTracer", "tracerConfig": { "onlyTopCall": false }, "timeout": "300s" })) .expect("Failed to deserialize tracing options"); // Get the Ethereum provider from the Katana instance. let eth_provider = katana.eth_provider(); // Create a TracerBuilder instance let tracer_builder = TracerBuilder::new(Arc::new(&eth_provider)).await.expect("Failed to create tracer_builder"); // Get the traces for the tx. let trace_with_tx_hash = tracer_builder .clone() .with_transaction_hash(*tx_hash) .await .expect("Failed to set transaction hash") .with_tracing_options(kakarot_rpc::tracing::builder::TracingOptions::Geth(opts.clone())) .build() .expect("Failed to build trace_with_tx_hash"); let trace = trace_with_tx_hash.debug_transaction(*tx_hash).expect("Failed to trace transaction"); // Get the traces for the block let block_trace = tracer_builder .clone() .with_block_id(TRACING_BLOCK_NUMBER.into()) .await .expect("Failed to set block number") .with_tracing_options(kakarot_rpc::tracing::builder::TracingOptions::Geth(opts.clone())) .build() .expect("Failed to build block_trace"); let block_traces = block_trace.debug_block().expect("Failed to trace block by number"); let alloy_rpc_types_trace::geth::TraceResult::Success { result: expected_trace, .. } = block_traces.get(index).cloned().unwrap() else { panic!("Failed to get expected trace") }; // Compare traces assert_eq!(expected_trace, trace); // Get the last trace from the trace vector, which is expected to be out of resources. let run_out_of_resource_trace = block_traces.last().unwrap(); // Asser that the trace matches the expected default GethTrace for a transaction that runs out of resources. match run_out_of_resource_trace { TraceResult::Success { result, .. } => assert_eq!( result.clone(), GethTrace::Default(alloy_rpc_types_trace::geth::DefaultFrame { failed: true, ..Default::default() }) ), TraceResult::Error { .. } => panic!("Expected a success trace result"), }; }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/tests/tests/txpool_api.rs
tests/tests/txpool_api.rs
#![allow(clippy::used_underscore_binding)] #![cfg(feature = "testing")] use crate::tests::mempool::create_sample_transactions; use alloy_consensus::Transaction; use alloy_rpc_types_txpool::{TxpoolContent, TxpoolContentFrom, TxpoolInspect, TxpoolInspectSummary, TxpoolStatus}; use jsonrpsee::server::ServerHandle; use kakarot_rpc::{ providers::eth_provider::database::types::transaction::ExtendedTransaction, test_utils::{ fixtures::{katana_empty, setup}, katana::Katana, rpc::{start_kakarot_rpc_server, RawRpcParamsBuilder}, }, }; use reth_transaction_pool::{TransactionOrigin, TransactionPool}; use rstest::*; use serde::{de::DeserializeOwned, Serialize}; use serde_json::Value; use std::net::SocketAddr; async fn initial_setup(katana: Katana) -> (SocketAddr, ServerHandle, Katana) { // Start the Kakarot RPC server and retrieve the server address and handle let (server_addr, server_handle) = start_kakarot_rpc_server(&katana).await.expect("Error setting up Kakarot RPC server"); (server_addr, server_handle, katana) } async fn request<D: DeserializeOwned, S: Serialize>(method: &str, port: u16, params: Vec<S>) -> D { // Create a reqwest client let reqwest_client = reqwest::Client::new(); // Build the JSON-RPC request body let mut body_builder = RawRpcParamsBuilder::new(method); for p in params { body_builder = body_builder.add_param(p); } let body = body_builder.build(); // Send a POST request to the Kakarot RPC server let res = reqwest_client .post(format!("http://localhost:{port}")) .header("Content-Type", "application/json") .body(body) .send() .await .expect("Failed to call TxPool RPC"); // Extract the response body as text let response = res.text().await.expect("Failed to get response body"); // Deserialize the response body into JSON let raw: Value = serde_json::from_str(&response).expect("Failed to deserialize response body"); // Deserialize the 'result' field of the JSON into a T struct serde_json::from_value(raw["result"].clone()).expect("Failed to deserialize result") } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_txpool_content(#[future] katana_empty: Katana, _setup: ()) { let (server_addr, server_handle, katana_empty) = initial_setup(katana_empty).await; // Create a sample transaction let (transaction, transaction_signed) = create_sample_transactions(&katana_empty, 1) .await .expect("Failed to create sample transaction") .pop() .expect("Expected at least one transaction"); // Insert the transaction into the mempool let _tx_hash = katana_empty .eth_client .mempool() .add_transaction(TransactionOrigin::Local, transaction) .await .expect("Failed to insert transaction into the mempool"); // Fetch the transaction pool content let tx_pool_content: TxpoolContent<ExtendedTransaction> = request("txpool_content", server_addr.port(), Vec::<String>::new()).await; // Get updated mempool size let mempool_size = katana_empty.eth_client.mempool().pool_size(); // Check pending, queued and total transactions assert_eq!(mempool_size.pending, 1); assert_eq!(mempool_size.queued, 0); assert_eq!(mempool_size.total, 1); // Recover the signer from the transaction let transaction_signer = transaction_signed.recover_signer().unwrap(); // Assert that the pool content contains the sender of the first pending transaction assert!(tx_pool_content.pending.contains_key(&transaction_signer)); // Check that the transaction in the pool matches the pending transaction that was inserted assert_eq!( *tx_pool_content .pending .get(&transaction_signer) .unwrap() .get(&transaction_signed.transaction.nonce().to_string()) .unwrap() .hash, transaction_signed.hash() ); // Drop the server handle to shut down the server after the test drop(server_handle); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_txpool_content_from(#[future] katana_empty: Katana, _setup: ()) { let (server_addr, server_handle, katana_empty) = initial_setup(katana_empty).await; // Create a sample transaction let (transaction, transaction_signed) = create_sample_transactions(&katana_empty, 1) .await .expect("Failed to create sample transaction") .pop() .expect("Expected at least one transaction"); // Insert the transaction into the mempool let _tx_hash = katana_empty .eth_client .mempool() .add_transaction(TransactionOrigin::Local, transaction) .await .expect("Failed to insert transaction into the mempool"); // Recover the signer from the transaction let transaction_signer = transaction_signed.recover_signer().unwrap(); // Fetch the transaction pool content from the sender let tx_pool_content: TxpoolContentFrom<ExtendedTransaction> = request("txpool_contentFrom", server_addr.port(), vec![transaction_signer.to_string()]).await; // Assert that we recovered a single pending transaction assert_eq!(tx_pool_content.pending.len(), 1); // Assert that no queued transactions are registered assert!(tx_pool_content.queued.is_empty()); // Assert the validity of the recovered pending transaction assert_eq!( *tx_pool_content.pending.get(&transaction_signed.transaction.nonce().to_string()).unwrap().hash, transaction_signed.hash() ); // Drop the server handle to shut down the server after the test drop(server_handle); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_txpool_status(#[future] katana_empty: Katana, _setup: ()) { let (server_addr, server_handle, katana_empty) = initial_setup(katana_empty).await; // Create a sample transaction let (transaction, _) = create_sample_transactions(&katana_empty, 1) .await .expect("Failed to create sample transaction") .pop() .expect("Expected at least one transaction"); // Insert the transaction into the mempool let _tx_hash = katana_empty .eth_client .mempool() .add_transaction(TransactionOrigin::Local, transaction) .await .expect("Failed to insert transaction into the mempool"); // Fetch the transaction pool status let tx_pool_status: TxpoolStatus = request("txpool_status", server_addr.port(), Vec::<String>::new()).await; // Assert that we recovered the pending transaction assert_eq!(tx_pool_status.pending, 1); // Assert that no queued transactions are registered assert_eq!(tx_pool_status.queued, 0); // Drop the server handle to shut down the server after the test drop(server_handle); drop(katana_empty); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_txpool_inspect(#[future] katana_empty: Katana, _setup: ()) { let (server_addr, server_handle, katana_empty) = initial_setup(katana_empty).await; // Create a sample transaction let (transaction, transaction_signed) = create_sample_transactions(&katana_empty, 1) .await .expect("Failed to create sample transaction") .pop() .expect("Expected at least one transaction"); // Insert the transaction into the mempool let _tx_hash = katana_empty .eth_client .mempool() .add_transaction(TransactionOrigin::Local, transaction) .await .expect("Failed to insert transaction into the mempool"); // Inspect the transaction pool let tx_pool_inspect: TxpoolInspect = request("txpool_inspect", server_addr.port(), Vec::<String>::new()).await; // Assert that we recovered the pending transaction assert_eq!(tx_pool_inspect.pending.len(), 1); // Assert that no queued transactions are registered assert!(tx_pool_inspect.queued.is_empty()); // Recover the signer from the transaction let transaction_signer = transaction_signed.recover_signer().unwrap(); // Assert that the pool content contains the sender of the first pending transaction assert!(tx_pool_inspect.pending.contains_key(&transaction_signer)); // Check that the first transaction in the pool matches the first pending transaction assert_eq!( *tx_pool_inspect .pending .get(&transaction_signer) .unwrap() .get(&transaction_signed.transaction.nonce().to_string()) .unwrap(), TxpoolInspectSummary { to: transaction_signed.to(), value: transaction_signed.value(), gas: transaction_signed.gas_limit().into(), gas_price: transaction_signed.max_fee_per_gas(), } ); // Drop the server handle to shut down the server after the test drop(server_handle); }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/tests/tests/eth_provider.rs
tests/tests/eth_provider.rs
#![allow(clippy::used_underscore_binding)] #![cfg(feature = "testing")] use crate::tests::mempool::create_sample_transactions; use alloy_consensus::{TxEip1559, TxLegacy}; use alloy_eips::{eip2718::Encodable2718, BlockNumberOrTag}; use alloy_primitives::{address, bytes, Address, Bytes, Signature, TxKind, B256, U256, U64}; use alloy_rpc_types::{ request::TransactionInput, serde_helpers::JsonStorageKey, state::{AccountOverride, StateOverride}, Filter, FilterBlockOption, FilterChanges, Log, RpcBlockHash, Topic, TransactionRequest, }; use alloy_sol_types::{sol, SolCall}; use arbitrary::Arbitrary; use kakarot_rpc::{ client::{KakarotTransactions, TransactionHashProvider}, into_via_try_wrapper, models::felt::Felt252Wrapper, providers::eth_provider::{ constant::{MAX_LOGS, STARKNET_MODULUS}, database::{ ethereum::EthereumTransactionStore, filter, filter::EthDatabaseFilterBuilder, types::transaction::{EthStarknetHashes, StoredEthStarknetTransactionHash, StoredTransaction}, }, provider::EthereumProvider, starknet::relayer::Relayer, BlockProvider, ChainProvider, GasProvider, LogProvider, ReceiptProvider, StateProvider, TransactionProvider, }, test_utils::{ eoa::Eoa, evm_contract::{EvmContract, KakarotEvmContract}, fixtures::{contract_empty, counter, katana, katana_empty, plain_opcodes, setup}, katana::Katana, tx_waiter::watch_tx, }, }; use rand::Rng; use reth_primitives::{sign_message, Transaction, TransactionSigned}; use reth_transaction_pool::{TransactionOrigin, TransactionPool}; use rstest::*; use starknet::{ accounts::Account, core::types::{BlockId, BlockTag, Felt}, }; use std::sync::Arc; #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_block_number(#[future] katana: Katana, _setup: ()) { // Given let eth_provider = katana.eth_provider(); // When let block_number = eth_provider.block_number().await.unwrap(); // Then // Catch the most recent block number of the mocked Mongo Database let expected = U64::from(katana.block_number()); assert_eq!(block_number, expected); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_chain_id(#[future] katana: Katana, _setup: ()) { // Given let eth_provider = katana.eth_provider(); // When let chain_id = eth_provider.chain_id().await.unwrap().unwrap_or_default(); // Then // Chain ID should correspond to "kaka_test" % max safe chain id assert_eq!(chain_id, U64::from_str_radix("b615f74ebad2c", 16).unwrap()); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_block_by_hash(#[future] katana: Katana, _setup: ()) { // Given let eth_provider = katana.eth_provider(); let block_hash = katana.most_recent_transaction().unwrap().block_hash.unwrap(); // When let block = eth_provider.block_by_hash(block_hash, false).await.unwrap().unwrap(); // Then assert_eq!(block.inner.header, katana.header_by_hash(block_hash).unwrap()); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_block_by_number(#[future] katana: Katana, _setup: ()) { // Given let eth_provider = katana.eth_provider(); let block_number = katana.block_number(); // When: Retrieving block by specific block number let block = eth_provider.block_by_number(block_number.into(), false).await.unwrap().unwrap(); // Then: Ensure the retrieved block has the expected block number assert_eq!(block.header.number, block_number); // When: Retrieving earliest block let block = eth_provider.block_by_number(BlockNumberOrTag::Earliest, false).await.unwrap().unwrap(); // Then: Ensure the retrieved block has block number zero assert_eq!(block.header.number, 0); // When: Retrieving latest block let block = eth_provider.block_by_number(BlockNumberOrTag::Latest, false).await.unwrap().unwrap(); // Then: Ensure the retrieved block has the same block number as the most recent transaction assert_eq!(block.header.number, block_number); // When: Retrieving finalized block let block = eth_provider.block_by_number(BlockNumberOrTag::Finalized, false).await.unwrap().unwrap(); // Then: Ensure the retrieved block has the same block number as the most recent transaction assert_eq!(block.header.number, block_number); // When: Retrieving safe block let block = eth_provider.block_by_number(BlockNumberOrTag::Safe, false).await.unwrap().unwrap(); // Then: Ensure the retrieved block has the same block number as the most recent transaction assert_eq!(block.header.number, block_number); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_block_transaction_count_by_hash(#[future] katana: Katana, _setup: ()) { // Given let eth_provider = katana.eth_provider(); // Get the header of the first transaction let first_tx = katana.first_transaction().unwrap(); let header = katana.header_by_hash(first_tx.block_hash.unwrap()).unwrap(); // When let count = eth_provider.block_transaction_count_by_hash(header.hash).await.unwrap().unwrap(); // Then assert_eq!(count, U256::from(1)); // When let count = eth_provider .block_transaction_count_by_hash(katana.most_recent_transaction().unwrap().block_hash.unwrap()) .await .unwrap() .unwrap(); // Then assert_eq!(count, U256::from(1)); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_block_transaction_count_by_number(#[future] katana: Katana, _setup: ()) { // Given: Ethereum provider instance let eth_provider = katana.eth_provider(); // Get the header of the first transaction let first_tx = katana.first_transaction().unwrap(); let header = katana.header_by_hash(first_tx.block_hash.unwrap()).unwrap(); // When: Retrieving transaction count for a specific block number let count = eth_provider.block_transaction_count_by_number(header.number.into()).await.unwrap().unwrap(); // Then: Ensure the retrieved transaction count matches the expected value assert_eq!(count, U256::from(1)); // When: Retrieving transaction count for the block of the most recent transaction let block_number = katana.most_recent_transaction().unwrap().block_number.unwrap(); let count = eth_provider.block_transaction_count_by_number(block_number.into()).await.unwrap().unwrap(); // Then: Ensure the retrieved transaction count matches the expected value assert_eq!(count, U256::from(1)); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_balance(#[future] katana: Katana, _setup: ()) { // Given let eth_provider = katana.eth_provider(); let eoa = katana.eoa(); // When let eoa_balance = eth_provider.balance(eoa.evm_address().unwrap(), None).await.unwrap(); // Then assert!(eoa_balance > U256::ZERO); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_storage_at(#[future] counter: (Katana, KakarotEvmContract), _setup: ()) { // Given let katana = counter.0; let counter = counter.1; let eth_provider = katana.eth_provider(); let eoa = katana.eoa(); let counter_address: Felt252Wrapper = counter.evm_address.into(); let counter_address = counter_address.try_into().expect("Failed to convert EVM address"); // When eoa.call_evm_contract(&counter, "inc", &[], 0).await.expect("Failed to increment counter"); // Then let count = eth_provider.storage_at(counter_address, JsonStorageKey::from(U256::from(0)), None).await.unwrap(); assert_eq!(count, B256::left_padding_from(&[0x1])); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_nonce_eoa(#[future] katana: Katana, _setup: ()) { // Given let eth_provider = katana.eth_provider(); // When let nonce = eth_provider.transaction_count(Address::ZERO, None).await.unwrap(); // Then // Zero address shouldn't throw 'ContractNotFound', but return zero assert_eq!(U256::from(0), nonce); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_nonce_contract_account(#[future] counter: (Katana, KakarotEvmContract), _setup: ()) { // Given let katana = counter.0; let counter = counter.1; let eth_provider = katana.eth_provider(); let counter_address: Felt252Wrapper = counter.evm_address.into(); let counter_address = counter_address.try_into().expect("Failed to convert EVM address"); // When let nonce_initial = eth_provider.transaction_count(counter_address, None).await.unwrap(); // Then assert_eq!(nonce_initial, U256::from(1)); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_nonce(#[future] counter: (Katana, KakarotEvmContract), _setup: ()) { // Given let katana: Katana = counter.0; let counter = counter.1; let eth_provider = katana.eth_provider(); let eoa = katana.eoa(); let nonce_before = eth_provider.transaction_count(eoa.evm_address().unwrap(), None).await.unwrap(); // When eoa.call_evm_contract(&counter, "inc", &[], 0).await.expect("Failed to increment counter"); // Then let nonce_after = eth_provider.transaction_count(eoa.evm_address().unwrap(), None).await.unwrap(); assert_eq!(nonce_before + U256::from(1), nonce_after); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_get_code(#[future] counter: (Katana, KakarotEvmContract), _setup: ()) { // Given let katana: Katana = counter.0; let counter = counter.1; let eth_provider = katana.eth_provider(); let counter_address: Felt252Wrapper = counter.evm_address.into(); let counter_address = counter_address.try_into().expect("Failed to convert EVM address"); // When let bytecode = eth_provider.get_code(counter_address, None).await.unwrap(); // Then let counter_bytecode = <KakarotEvmContract as EvmContract>::load_contract_bytecode("Counter") .expect("Failed to load counter bytecode"); let expected = counter_bytecode.deployed_bytecode.unwrap().0; assert_eq!(bytecode, expected); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_get_logs_block_range(#[future] katana: Katana, _setup: ()) { // Given let provider = katana.eth_provider(); // When let logs = provider.get_logs(Filter::default()).await.expect("Failed to get logs"); // Then let FilterChanges::Logs(logs) = logs else { panic!("Expected logs") }; assert!(!logs.is_empty()); } /// Utility function to filter logs using the Ethereum provider. /// Takes a filter and a provider, and returns the corresponding logs. async fn filter_logs(filter: Filter, provider: Arc<dyn EthereumProvider>) -> Vec<Log> { // Call the provider to get logs using the filter. let logs = provider.get_logs(filter).await.expect("Failed to get logs"); // If the result contains logs, return them, otherwise panic with an error. match logs { FilterChanges::Logs(logs) => logs, _ => panic!("Expected logs"), } } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_get_logs_limit(#[future] katana: Katana, _setup: ()) { // Get the Ethereum provider from Katana. let provider = katana.eth_provider(); // Set the limit of logs to be retrieved. std::env::set_var("MAX_LOGS", "500"); // Add mock logs to the Katana instance's database. // The number of logs added is MAX_LOGS + 20, ensuring there are more logs than the limit. katana.add_mock_logs(((*MAX_LOGS).unwrap() + 20) as usize).await; // Assert that the number of logs returned by filter_logs is equal to the limit. // This ensures that the log retrieval respects the MAX_LOGS constraint. assert_eq!(filter_logs(Filter::default(), provider.clone()).await.len(), (*MAX_LOGS).unwrap() as usize); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_get_logs_block_filter(#[future] katana: Katana, _setup: ()) { // Get the Ethereum provider from Katana. let provider = katana.eth_provider(); // Get the first transaction from Katana. let first_transaction = katana.first_transaction().unwrap(); let block_number = first_transaction.block_number.unwrap(); let block_hash = first_transaction.block_hash.unwrap(); // Get logs by block number from Katana. let logs_katana_block_number = katana.logs_by_block_number(block_number); // Get logs for a range of blocks from Katana. let logs_katana_block_range = katana.logs_by_block_range(0..u64::MAX / 2); // Get logs by block hash from Katana. let logs_katana_block_hash = katana.logs_by_block_hash(block_hash); // Get all logs from Katana. let all_logs_katana = katana.all_logs(); // Verify logs filtered by block number. assert_eq!(filter_logs(Filter::default().select(block_number), provider.clone()).await, logs_katana_block_number); // Verify logs filtered by block hash. assert_eq!(filter_logs(Filter::default().select(block_hash), provider.clone()).await, logs_katana_block_hash); // Verify all logs. assert_eq!(filter_logs(Filter::default().select(0..), provider.clone()).await, all_logs_katana); // Verify logs filtered by a range of blocks. assert_eq!( filter_logs(Filter::default().select(..=(u64::MAX / 2) + 1), provider.clone()).await, logs_katana_block_range ); // Verify that filtering by an empty range returns an empty result. // // We skip the 0 block because we hardcoded it via our Mongo Fuzzer and so it can contain logs. assert!(filter_logs(Filter::default().select(1..=2), provider.clone()).await.is_empty()); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_get_logs_address_filter(#[future] katana: Katana, _setup: ()) { // Get the Ethereum provider from Katana. let provider = katana.eth_provider(); // Get all logs from Katana. let all_logs_katana = katana.all_logs(); // Get the first log address, or default address if logs are empty. let first_address = if all_logs_katana.is_empty() { Address::default() } else { all_logs_katana[0].address() }; // Verify logs filtered by the first address. assert_eq!( filter_logs(Filter::new().address(vec![first_address]), provider.clone()).await, katana.logs_by_address(&[first_address]) ); // Create a vector to store a few addresses. let some_addresses: Vec<_> = all_logs_katana.iter().take(2).map(Log::address).collect(); // Verify logs filtered by these few addresses. assert_eq!( filter_logs(Filter::new().address(some_addresses.clone()), provider.clone()).await, katana.logs_by_address(&some_addresses) ); // Create a vector to store all addresses. let all_addresses: Vec<_> = all_logs_katana.iter().map(Log::address).collect(); // Verify that all logs are retrieved when filtered by all addresses. assert_eq!(filter_logs(Filter::new().address(all_addresses), provider.clone()).await, all_logs_katana); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_get_logs_topics(#[future] katana: Katana, _setup: ()) { // Given let provider = katana.eth_provider(); let logs = katana.logs_with_min_topics(3); let topic_one = logs[0].topics()[0]; let topic_two = logs[1].topics()[1]; let topic_three = logs[0].topics()[2]; let topic_four = logs[1].topics()[2]; // Filter on the first topic let filter = Filter { topics: [topic_one.into(), Topic::default(), Topic::default(), Topic::default()], ..Default::default() }; assert_eq!(filter_logs(filter, provider.clone()).await.len(), 1); // Filter on the second topic let filter = Filter { topics: [Topic::default(), topic_two.into(), Topic::default(), Topic::default()], ..Default::default() }; assert_eq!(filter_logs(filter, provider.clone()).await.len(), 1); // Filter on the combination of topics three and four (should return 2 logs) let filter = Filter { topics: [Topic::default(), Topic::default(), vec![topic_three, topic_four].into(), Topic::default()], ..Default::default() }; assert_eq!(filter_logs(filter, provider.clone()).await.len(), 2); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_get_logs_address(#[future] katana: Katana, _setup: ()) { // Given let provider = katana.eth_provider(); let logs = katana.logs_with_min_topics(3); let address_one = logs[0].address(); let address_two = logs[1].address(); // Filter on the first address let filter = Filter { address: address_one.into(), ..Default::default() }; assert_eq!(filter_logs(filter, provider.clone()).await.len(), 1); // Filter on the second address let filter = Filter { address: address_two.into(), ..Default::default() }; assert_eq!(filter_logs(filter, provider.clone()).await.len(), 1); // Filter on the combination of both addresses let filter = Filter { address: vec![address_one, address_two].into(), ..Default::default() }; assert_eq!(filter_logs(filter, provider.clone()).await.len(), 2); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_get_logs_block_hash(#[future] katana: Katana, _setup: ()) { // Given let provider = katana.eth_provider(); let logs = katana.logs_with_min_topics(0); let block_hash = logs[0].block_hash.unwrap(); // Filter on block hash let filter = Filter { block_option: FilterBlockOption::AtBlockHash(block_hash), ..Default::default() }; let filtered_logs = filter_logs(filter, provider.clone()).await; assert!(filtered_logs.iter().all(|log| log.block_hash.unwrap() == block_hash)); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_get_code_empty(#[future] contract_empty: (Katana, KakarotEvmContract), _setup: ()) { // Given let katana: Katana = contract_empty.0; let counter = contract_empty.1; let eth_provider = katana.eth_provider(); let counter_address: Felt252Wrapper = counter.evm_address.into(); let counter_address = counter_address.try_into().expect("Failed to convert EVM address"); // When let bytecode = eth_provider.get_code(counter_address, None).await.unwrap(); // Then assert_eq!(bytecode, Bytes::default()); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_get_code_no_contract(#[future] katana: Katana, _setup: ()) { // Given let eth_provider = katana.eth_provider(); // When let bytecode = eth_provider.get_code(Address::random(), None).await.unwrap(); // Then assert_eq!(bytecode, Bytes::default()); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_estimate_gas(#[future] counter: (Katana, KakarotEvmContract), _setup: ()) { // Given let eoa = counter.0.eoa(); let eth_provider = counter.0.eth_provider(); let counter = counter.1; let chain_id = eth_provider.chain_id().await.unwrap().unwrap_or_default(); let counter_address: Felt252Wrapper = counter.evm_address.into(); let request = TransactionRequest { from: Some(eoa.evm_address().unwrap()), to: Some(TxKind::Call(counter_address.try_into().unwrap())), input: TransactionInput { input: None, data: Some(bytes!("371303c0")) }, // selector of "function inc()" chain_id: Some(chain_id.to::<u64>()), ..Default::default() }; // When let estimate = eth_provider.estimate_gas(request, None).await.unwrap(); // Then assert!(estimate > U256::from(0)); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_fee_history(#[future] katana: Katana, _setup: ()) { // Retrieve the Ethereum provider from the Katana instance. let eth_provider = katana.eth_provider(); // Retrieve the most recent block number. let newest_block = katana.block_number(); // To ensure that the range includes all mocked blocks. let block_count = u64::MAX; // Get the total number of blocks in the database. let nbr_blocks = katana.headers.len(); // Call the fee_history method of the Ethereum provider. let fee_history = eth_provider.fee_history(U64::from(block_count), newest_block.into(), None).await.unwrap(); // Verify that the length of the base_fee_per_gas list in the fee history is equal // to the total number of blocks plus one. assert_eq!(fee_history.base_fee_per_gas.len(), nbr_blocks + 1); // Verify that the length of the gas_used_ratio list in the fee history is equal // to the total number of blocks. assert_eq!(fee_history.gas_used_ratio.len(), nbr_blocks); // Verify that the oldest block in the fee history is equal to zero. assert_eq!(fee_history.oldest_block, 0); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] #[cfg(feature = "hive")] async fn test_predeploy_eoa(#[future] katana: Katana, _setup: ()) { use alloy_primitives::b256; use futures::future::join_all; use kakarot_rpc::test_utils::eoa::KakarotEOA; // Given let one_ether = 1_000_000_000_000_000_000u128; let one_tenth_ether = one_ether / 10; let eoa = katana.eoa(); let eth_provider = katana.eth_provider(); let eth_client = katana.eth_client(); let other_eoa_1 = KakarotEOA::new( b256!("00000000000000012330000000000000000000000000000000000000000abde1"), Arc::new(eth_client.clone()), katana.sequencer.account(), ); let other_eoa_2 = KakarotEOA::new( b256!("00000000000000123123456000000000000000000000000000000000000abde2"), Arc::new(eth_client), katana.sequencer.account(), ); let evm_address = eoa.evm_address().unwrap(); let balance_before = eth_provider.balance(eoa.evm_address().unwrap(), None).await.unwrap(); eoa.transfer(other_eoa_1.evm_address().unwrap(), 2 * one_ether) .await .expect("Failed to transfer funds to other eoa 1"); // Sleep for 2 seconds to let the transaction pass tokio::time::sleep(tokio::time::Duration::from_secs(2)).await; eoa.transfer(other_eoa_2.evm_address().unwrap(), one_ether).await.expect("Failed to transfer funds to other eoa 2"); // Sleep for 2 seconds to let the transaction pass tokio::time::sleep(tokio::time::Duration::from_secs(2)).await; // When let jh1 = tokio::task::spawn(async move { let _ = other_eoa_1 .transfer(evm_address, 17 * one_tenth_ether) .await .expect("Failed to transfer funds back to eoa"); }); let jh2 = tokio::task::spawn(async move { let _ = other_eoa_2.transfer(evm_address, 3 * one_tenth_ether).await.expect("Failed to transfer funds back to eoa"); }); join_all([jh1, jh2]).await; // Then // Await all transactions to pass tokio::time::sleep(tokio::time::Duration::from_secs(2)).await; let balance_after = eth_provider.balance(evm_address, None).await.unwrap(); assert_eq!(balance_after, balance_before - U256::from(one_ether)); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_block_receipts(#[future] katana: Katana, _setup: ()) { // Given: Ethereum provider instance and the most recent transaction let eth_provider = katana.eth_provider(); let transaction = katana.most_recent_transaction().unwrap(); // Then: Retrieve receipts by block number let receipts = eth_provider.block_receipts(Some(transaction.block_number.unwrap().into())).await.unwrap().unwrap(); assert_eq!(receipts.len(), 1); let receipt = receipts.first().unwrap(); assert_eq!(receipt.transaction_index, transaction.transaction_index); assert_eq!(receipt.block_hash, transaction.block_hash); assert_eq!(receipt.block_number, transaction.block_number); // Then: Retrieve receipts by block hash let receipts = eth_provider .block_receipts(Some(alloy_rpc_types::BlockId::Hash(RpcBlockHash::from(transaction.block_hash.unwrap())))) .await .unwrap() .unwrap(); assert_eq!(receipts.len(), 1); let receipt = receipts.first().unwrap(); assert_eq!(receipt.transaction_index, transaction.transaction_index); assert_eq!(receipt.block_hash, transaction.block_hash); assert_eq!(receipt.block_number, transaction.block_number); // Then: Attempt to retrieve receipts for a non-existing block let receipts = eth_provider .block_receipts(Some(alloy_rpc_types::BlockId::Hash(RpcBlockHash::from(B256::from(U256::from(0x00c0_fefe)))))) .await .unwrap(); assert!(receipts.is_none()); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_to_starknet_block_id(#[future] katana: Katana, _setup: ()) { // Given: Ethereum provider instance and the most recent transaction let eth_provider = katana.eth_provider(); let transaction = katana.most_recent_transaction().unwrap(); // When: Convert block number identifier to StarkNet block identifier let pending_starknet_block_id = eth_provider.to_starknet_block_id(Some(transaction.block_number.unwrap().into())).await.unwrap(); // When: Convert block hash identifier to StarkNet block identifier let some_starknet_block_hash = eth_provider.to_starknet_block_id(Some(transaction.block_hash.unwrap().into())).await.unwrap(); // When: Convert block tag identifier to StarkNet block identifier let pending_block_tag_starknet = eth_provider.to_starknet_block_id(Some(BlockNumberOrTag::Pending.into())).await.unwrap(); // When: Attempt to convert an unknown block number identifier to StarkNet block identifier let unknown_starknet_block_number = eth_provider.to_starknet_block_id(Some(u64::MAX.into())).await; // Then: Ensure the converted StarkNet block identifiers match the expected values assert_eq!(pending_starknet_block_id, starknet::core::types::BlockId::Number(transaction.block_number.unwrap())); assert_eq!( some_starknet_block_hash, starknet::core::types::BlockId::Hash(Felt::from_bytes_be( &U256::from_be_slice(transaction.block_hash.unwrap().as_slice()) .wrapping_rem(STARKNET_MODULUS) .to_be_bytes() )) ); assert_eq!(pending_block_tag_starknet, starknet::core::types::BlockId::Tag(BlockTag::Pending)); assert!(unknown_starknet_block_number.is_err()); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_send_raw_transaction(#[future] katana_empty: Katana, _setup: ()) { // Given let katana = katana_empty; let eth_provider = katana.eth_provider(); let eth_client = katana.eth_client(); let chain_id = eth_provider.chain_id().await.unwrap_or_default().unwrap_or_default().to(); // Create a sample transaction let transaction = Transaction::Eip1559(TxEip1559 { chain_id, nonce: 0, gas_limit: 21000, to: TxKind::Call(Address::random()), value: U256::from(1000), input: Bytes::default(), max_fee_per_gas: 875_000_000, max_priority_fee_per_gas: 0, access_list: Default::default(), }); // Sign the transaction let signature = sign_message(katana.eoa().private_key(), transaction.signature_hash()).unwrap(); let transaction_signed = TransactionSigned::from_transaction_and_signature(transaction, signature); // Retrieve the current size of the mempool let mempool_size = eth_client.mempool().pool_size(); // Assert that the number of pending and total transactions in the mempool is 0 assert_eq!(mempool_size.pending, 0); assert_eq!(mempool_size.total, 0); // Send the transaction let _ = eth_client .send_raw_transaction(transaction_signed.encoded_2718().into()) .await .expect("failed to send transaction"); // Prepare the relayer let relayer_balance = eth_client .starknet_provider() .balance_at(katana.eoa.relayer.address(), BlockId::Tag(BlockTag::Latest)) .await .expect("Failed to get relayer balance"); let relayer_balance = into_via_try_wrapper!(relayer_balance).expect("Failed to convert balance"); // Relay the transaction let starknet_hash = Relayer::new( katana.eoa.relayer.address(), relayer_balance, &(*(*eth_client.starknet_provider())), Some(Arc::new(eth_client.eth_provider().database().clone())), ) .relay_transaction(&transaction_signed) .await .expect("Failed to relay transaction"); // Retrieve the hash mapping from the database (Ethereum -> StarkNet) // 1. Prepare the filter let filter = EthDatabaseFilterBuilder::<filter::EthStarknetTransactionHash>::default() .with_tx_hash(&transaction_signed.hash) .build(); // 2. Retrieve the hash mapping let hash_mapping: Option<StoredEthStarknetTransactionHash> = eth_client .eth_provider() .database() .get_one(filter, None) .await .expect("Failed to retrieve updated transaction hash mapping"); // 3. Prepare the transaction hashes let transaction_hashes = EthStarknetHashes { eth_hash: transaction_signed.hash, starknet_hash }; // 4. Assert that the hash mapping was inserted correctly assert_eq!( hash_mapping, Some(StoredEthStarknetTransactionHash::from(transaction_hashes)), "The transaction hash mapping was not inserted correctly" ); // Retrieve the current size of the mempool let mempool_size_after_send = eth_client.mempool().pool_size(); // Assert that the number of pending transactions in the mempool is 1 assert_eq!(mempool_size_after_send.pending, 1); assert_eq!(mempool_size_after_send.total, 1); let tx_in_mempool = eth_client.mempool().get(&transaction_signed.hash()); // Assert that the transaction in the mempool exists assert!(tx_in_mempool.is_some()); // Verify that the hash of the transaction in the mempool matches the expected hash assert_eq!(tx_in_mempool.unwrap().hash(), *transaction_signed.hash()); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_send_raw_transaction_wrong_nonce(#[future] katana_empty: Katana, _setup: ()) { // Given let eth_client = katana_empty.eth_client(); // Create a sample transaction let (_, mut transaction_signed) = create_sample_transactions(&katana_empty, 1) .await .expect("Failed to create sample transaction") .pop() .expect("Expected at least one transaction"); // Retrieve the current size of the mempool let mempool_size = eth_client.mempool().pool_size(); // Assert that the number of pending and total transactions in the mempool is 0 assert_eq!(mempool_size.pending, 0); assert_eq!(mempool_size.total, 0); // Send the transaction let tx_hash = eth_client .send_raw_transaction(transaction_signed.encoded_2718().into()) .await .expect("failed to send transaction"); // Retrieve the current size of the mempool let mempool_size_after_send = eth_client.mempool().pool_size(); // Assert that the number of pending transactions in the mempool is 1 assert_eq!(mempool_size_after_send.pending, 1); assert_eq!(mempool_size_after_send.total, 1); // Remove the transaction from the mempool katana_empty.eth_client.mempool().remove_transactions(vec![tx_hash]); // Check that the transaction is no longer in the mempool assert_eq!(katana_empty.eth_client.mempool().pool_size().total, 0); // Insert a wrong field in the transaction signature to mimic a wrong signature transaction_signed.signature = Signature::from_rs_and_parity(U256::ZERO, transaction_signed.signature.s(), transaction_signed.signature.v()) .unwrap(); // Attempt to send the transaction with the wrong signature and assert that it fails assert!(eth_client.send_raw_transaction(transaction_signed.encoded_2718().into()).await.is_err()); // Retrieve the current size of the mempool let mempool_size_after_wrong_send = eth_client.mempool().pool_size(); // Assert that the number of pending transactions in the mempool is still 1 (wrong_transaction was not added to the mempool) assert_eq!(mempool_size_after_wrong_send.pending, 0); assert_eq!(mempool_size_after_wrong_send.total, 0); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")]
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
true
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/tests/tests/mod.rs
tests/tests/mod.rs
pub mod alchemy_api; pub mod debug_api; pub mod eth_provider; pub mod kakarot_api; pub mod mempool; pub mod trace_api; pub mod tracer; pub mod txpool_api;
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/tests/tests/mempool.rs
tests/tests/mempool.rs
#![allow(clippy::used_underscore_binding)] #![cfg(feature = "testing")] use alloy_consensus::{TxEip1559, EMPTY_ROOT_HASH}; use alloy_eips::eip2718::Encodable2718; use alloy_primitives::{Address, TxKind, B64, U256}; use alloy_rpc_types::Header; use kakarot_rpc::{ constants::KKRT_BLOCK_GAS_LIMIT, pool::mempool::maintain_transaction_pool, providers::eth_provider::{ constant::U64_HEX_STRING_LEN, database::{ filter::{self, format_hex, EthDatabaseFilterBuilder}, types::header::StoredHeader, }, error::SignatureError, ChainProvider, }, test_utils::{ eoa::Eoa, fixtures::{katana, katana_empty, setup}, katana::Katana, }, }; use mongodb::{ bson::doc, options::{UpdateModifications, UpdateOptions}, }; use reth_primitives::{sign_message, Transaction, TransactionSigned, TransactionSignedEcRecovered}; use reth_transaction_pool::{EthPooledTransaction, PoolTransaction, TransactionOrigin, TransactionPool}; use revm_primitives::B256; use rstest::*; use std::{sync::Arc, time::Duration}; #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_mempool_add_transaction(#[future] katana_empty: Katana, _setup: ()) { let katana: Katana = katana_empty; let eth_client = katana.eth_client(); // Create a sample transaction let (transaction, transaction_signed) = create_sample_transactions(&katana, 1) .await .expect("Failed to create sample transaction") .pop() .expect("Expected at least one transaction"); // Check initial pool size assert_eq!(eth_client.mempool().pool_size().total, 0); // Add transaction to mempool let result = eth_client.mempool().add_transaction(TransactionOrigin::Local, transaction.clone()).await; // Ensure the transaction was added successfully assert!(result.is_ok()); // Get updated mempool size let mempool_size = eth_client.mempool().pool_size(); // Check pending, queued and total transactions assert_eq!(mempool_size.pending, 1); assert_eq!(mempool_size.queued, 0); assert_eq!(mempool_size.total, 1); // Get the EOA address let address = katana.eoa().evm_address().expect("Failed to get eoa address"); // get_transactions_by_sender_and_nonce test // Get transactions by sender address and nonce let sender_transaction = eth_client.mempool().get_transaction_by_sender_and_nonce(address, 0); // Check if the returned transaction hash matches assert_eq!(*sender_transaction.unwrap().hash(), transaction_signed.hash()); // get_transactions_by_origin function test // Get transactions by origin let origin_transaction = eth_client.mempool().get_transactions_by_origin(TransactionOrigin::Local); // Check if the returned transaction hash matches assert_eq!(*origin_transaction[0].hash(), transaction_signed.hash()); // get_local_transactions function test // Get local transactions let local_transaction = eth_client.mempool().get_local_transactions(); // Check if the returned transaction hash matches assert_eq!(*local_transaction[0].hash(), transaction_signed.hash()); assert_eq!(*local_transaction[0].hash(), *origin_transaction[0].hash()); // all_transactions function tests // Get all transactions in the mempool let all_transactions = eth_client.mempool().all_transactions(); // Check if the first pending transaction hash matches assert_eq!(*all_transactions.pending[0].hash(), transaction_signed.hash()); // Ensure only one pending transaction is present assert_eq!(all_transactions.pending.len(), 1); // Ensure no queued transactions are present assert_eq!(all_transactions.queued.len(), 0); // remove_transactions function tests // Remove transaction by hash let _ = eth_client.mempool().remove_transactions(vec![transaction_signed.hash()]); // Get updated mempool size let mempool_size = eth_client.mempool().pool_size(); // Check pending, queued and total transactions after remove_transactions assert_eq!(mempool_size.pending, 0); assert_eq!(mempool_size.queued, 0); assert_eq!(mempool_size.total, 0); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_mempool_add_external_transaction(#[future] katana_empty: Katana, _setup: ()) { let katana: Katana = katana_empty; let eth_client = katana.eth_client(); // Create a sample transaction let (transaction, transaction_signed) = create_sample_transactions(&katana, 1) .await .expect("Failed to create sample transaction") .pop() .expect("Expected at least one transaction"); // Add external transaction let result = eth_client.mempool().add_external_transaction(transaction).await; // Ensure the transaction was added successfully assert!(result.is_ok()); // get_pooled_transaction_element function test // Get pooled transaction by hash let hashes = eth_client.mempool().get_pooled_transaction_element(transaction_signed.hash()); // Check if the retrieved hash matches the expected hash assert_eq!(hashes.unwrap().hash(), &transaction_signed.hash()); // Get updated mempool size let mempool_size = eth_client.mempool().pool_size(); // Check pending, queued and total transactions assert_eq!(mempool_size.pending, 1); assert_eq!(mempool_size.queued, 0); assert_eq!(mempool_size.total, 1); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_mempool_add_transactions(#[future] katana_empty: Katana, _setup: ()) { let katana: Katana = katana_empty; let eth_client = katana.eth_client(); // Get the EOA address let address = katana.eoa().evm_address().expect("Failed to get eoa address"); // Set the number of transactions to create let transaction_number = 2; // Create multiple sample transactions let transactions = create_sample_transactions(&katana, transaction_number).await.expect("Failed to create sample transaction"); // Collect pooled transactions let pooled_transactions = transactions.iter().map(|(eth_pooled_transaction, _)| eth_pooled_transaction.clone()).collect::<Vec<_>>(); // Collect signed transactions let signed_transactions = transactions.iter().map(|(_, signed_transactions)| signed_transactions.clone()).collect::<Vec<_>>(); // Add transactions to mempool let _ = eth_client.mempool().add_transactions(TransactionOrigin::Local, pooled_transactions).await; // pending_transactions function tests // Get pending transactions let hashes = eth_client.mempool().pending_transactions(); let expected_hashes = signed_transactions.iter().map(TransactionSigned::hash).collect::<Vec<_>>(); let received_hashes = hashes.iter().map(|tx| *tx.hash()).collect::<Vec<_>>(); assert_eq!(received_hashes, expected_hashes); // get_transactions_by_sender function tests // Get transactions by sender address let sender_transactions = eth_client.mempool().get_transactions_by_sender(address); let received_sender_transactions = sender_transactions.iter().map(|tx| *tx.hash()).collect::<Vec<_>>(); assert_eq!(received_sender_transactions, expected_hashes); // unique_senders function test // Get unique senders from the mempool let unique_senders = eth_client.mempool().unique_senders(); // Ensure the EOA address is in the unique senders assert!(unique_senders.contains(&address)); // contains function test // Check if the first signed transaction is contained let contains = eth_client.mempool().contains(&signed_transactions[0].hash()); assert!(contains); // mempool_size function tests // Get updated mempool size let mempool_size = eth_client.mempool().pool_size(); // Check pending transactions assert_eq!(mempool_size.pending, transaction_number); // Check queued transactions assert_eq!(mempool_size.queued, 0); // Check total transactions assert_eq!(mempool_size.total, transaction_number); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_mempool_add_external_transactions(#[future] katana_empty: Katana, _setup: ()) { let katana: Katana = katana_empty; let eth_client = katana.eth_client(); // Create multiple sample transactions let transactions = create_sample_transactions(&katana, 2).await.expect("Failed to create sample transaction"); // Collect pooled transactions let pooled_transactions = transactions.iter().map(|(eth_pooled_transaction, _)| eth_pooled_transaction.clone()).collect::<Vec<_>>(); // Collect signed transactions let signed_transactions = transactions.iter().map(|(_, signed_transactions)| signed_transactions.clone()).collect::<Vec<_>>(); // Add external transactions to mempool let _ = eth_client.mempool().add_external_transactions(pooled_transactions).await; // pooled_transaction_hashes function tests // Get pooled transaction hashes let hashes = eth_client.mempool().pooled_transaction_hashes(); // Check if the first signed transaction hash is present assert!(hashes.contains(&signed_transactions[0].hash())); // Check if the second signed transaction hash is present assert!(hashes.contains(&signed_transactions[1].hash())); // Ensure the hashes are not empty // pooled_transaction_hashes_max function test // Set maximum number of hashes to retrieve let hashes_max_number = 1; // Get pooled transaction hashes with a limit let hashes_max = eth_client.mempool().pooled_transaction_hashes_max(hashes_max_number); // Check if at least one signed transaction hash is present assert!(hashes_max.contains(&signed_transactions[0].hash()) || hashes_max.contains(&signed_transactions[1].hash())); // Ensure the number of hashes matches the limit assert_eq!(hashes_max.len(), hashes_max_number); // Ensure the hashes are not empty assert!(!hashes_max.is_empty()); // get_external_transactions function test // Get external transactions let external_transactions = eth_client.mempool().get_external_transactions(); // Check if the returned transactions match the expected ones, regardless of order assert_eq!(external_transactions.len(), 2); // Verify that both signed transactions are present in external transactions let external_hashes: Vec<_> = external_transactions.iter().map(|tx| *tx.hash()).collect(); assert!(external_hashes.contains(&signed_transactions[0].hash())); assert!(external_hashes.contains(&signed_transactions[1].hash())); // Get updated mempool size let mempool_size = eth_client.mempool().pool_size(); // Check pending transactions assert_eq!(mempool_size.pending, 2); // Check queued transactions assert_eq!(mempool_size.queued, 0); // Check total transactions assert_eq!(mempool_size.total, 2); assert!(!hashes.is_empty()); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_mempool_transaction_event_listener(#[future] katana_empty: Katana, _setup: ()) { let katana: Katana = katana_empty; let eth_client = katana.eth_client(); // Create a sample transaction let (transaction, transaction_signed) = create_sample_transactions(&katana, 1) .await .expect("Failed to create sample transaction") .pop() .expect("Expected at least one transaction"); // Add transaction to mempool eth_client.mempool().add_transaction(TransactionOrigin::Local, transaction.clone()).await.unwrap(); // Get the transaction event listener let listener = eth_client.mempool().transaction_event_listener(transaction_signed.hash()); // Ensure the listener exists assert!(listener.is_some()); // Check if the listener's hash matches the transaction's hash assert_eq!(listener.unwrap().hash(), transaction_signed.hash()); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_mempool_get_private_transactions(#[future] katana_empty: Katana, _setup: ()) { let katana: Katana = katana_empty; let eth_client = katana.eth_client(); // Create a sample transaction let (transaction, transaction_signed) = create_sample_transactions(&katana, 1) .await .expect("Failed to create sample transaction") .pop() .expect("Expected at least one transaction"); // Add private transaction to mempool eth_client.mempool().add_transaction(TransactionOrigin::Private, transaction.clone()).await.unwrap(); // Get private transactions let private_transaction = eth_client.mempool().get_private_transactions(); // Check if the returned transaction hash matches assert_eq!(*private_transaction[0].hash(), transaction_signed.hash()); } // Helper function to create a sample transaction pub async fn create_sample_transactions( katana: &Katana, num_transactions: usize, ) -> Result<Vec<(EthPooledTransaction, TransactionSigned)>, SignatureError> { // Initialize a vector to hold transactions let mut transactions = Vec::new(); // Get the Ethereum provider let eth_provider = katana.eth_provider(); let signer = katana.eoa().evm_address().expect("Failed to get eoa address"); // Get the chain ID let chain_id = eth_provider.chain_id().await.unwrap_or_default().unwrap_or_default().to(); for counter in 0..num_transactions { // Create a new EIP-1559 transaction let transaction = Transaction::Eip1559(TxEip1559 { chain_id, nonce: counter as u64, gas_limit: 21000, to: TxKind::Call(Address::random()), value: U256::from(1000), max_fee_per_gas: 875_000_000, max_priority_fee_per_gas: 0, ..Default::default() }); // Sign the transaction let signature = sign_message(katana.eoa().private_key(), transaction.signature_hash()).unwrap(); // Create a signed transaction let transaction_signed = TransactionSigned::from_transaction_and_signature(transaction, signature); // Create an EC recovered signed transaction let transaction_signed_ec_recovered = TransactionSignedEcRecovered::from_signed_transaction(transaction_signed.clone(), signer); // Get the encoded length of the transaction let encoded_length = transaction_signed_ec_recovered.clone().encode_2718_len(); // Create a pooled transaction let eth_pooled_transaction = EthPooledTransaction::new(transaction_signed_ec_recovered, encoded_length); // Add the transaction to the vector transactions.push((eth_pooled_transaction, transaction_signed)); } Ok(transactions) } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_maintain_mempool(#[future] katana: Katana, _setup: ()) { let eth_client = Arc::new(katana.eth_client()); // Create two sample transactions at once let transactions = create_sample_transactions(&katana, 2).await.expect("Failed to create sample transactions"); // Extract and ensure we have two valid transactions from the transaction list. let ((transaction1, _), (transaction2, _)) = ( transactions.first().expect("Expected at least one transaction").clone(), transactions.get(1).expect("Expected at least two transactions").clone(), ); // Add transactions to the mempool eth_client.mempool().add_transaction(TransactionOrigin::Private, transaction1.clone()).await.unwrap(); eth_client.mempool().add_transaction(TransactionOrigin::Private, transaction2.clone()).await.unwrap(); // Start maintaining the transaction pool // // This task will periodically prune the mempool based on the given prune_duration. // For testing purposes, we set the prune_duration to 100 milliseconds. let prune_duration = Duration::from_millis(100); let eth_client_clone = Arc::clone(&eth_client); let maintain_task = tokio::spawn(async move { maintain_transaction_pool(eth_client_clone, prune_duration); }); // Initialize the block number based on the current blockchain state from katana. let mut last_block_number = katana.block_number(); // Loop to simulate new blocks being added to the blockchain every 100 milliseconds. for _ in 0..9 { // Sleep for 10 milliseconds to simulate the passage of time between blocks. tokio::time::sleep(Duration::from_millis(10)).await; // Increment the block number to simulate the blockchain progressing. last_block_number += 1; // Format the block number in both padded and unpadded hexadecimal formats. let unpadded_block_number = format_hex(last_block_number, 0); let padded_block_number = format_hex(last_block_number, U64_HEX_STRING_LEN); // Get the block header collection from the database. let header_collection = eth_client.eth_provider().database().collection::<StoredHeader>(); // Build a filter for updating the header based on the new block number. let filter = EthDatabaseFilterBuilder::<filter::Header>::default().with_block_number(last_block_number).build(); // Insert a new header for the new block number in the database. eth_client .eth_provider() .database() .update_one( StoredHeader { header: Header { hash: B256::random(), total_difficulty: Some(U256::default()), mix_hash: Some(B256::default()), nonce: Some(B64::default()), withdrawals_root: Some(EMPTY_ROOT_HASH), base_fee_per_gas: Some(0), blob_gas_used: Some(0), excess_blob_gas: Some(0), number: last_block_number, ..Default::default() }, }, filter, true, ) .await .expect("Failed to update header in database"); // Update the header collection with the padded block number in the database. header_collection .update_one( doc! {"header.number": unpadded_block_number}, UpdateModifications::Document(doc! {"$set": {"header.number": padded_block_number}}), ) .with_options(UpdateOptions::builder().upsert(true).build()) .await .expect("Failed to update block number"); // Check if both transactions are still in the mempool. // We expect them to still be in the mempool until 1 second has elapsed. assert!(eth_client.mempool().contains(transaction1.hash()), "Transaction 1 should still be in the mempool"); assert!(eth_client.mempool().contains(transaction2.hash()), "Transaction 2 should still be in the mempool"); // Check the gas limit for Kakarot blocks assert_eq!(eth_client.mempool().config().gas_limit, KKRT_BLOCK_GAS_LIMIT); } // Sleep for some additional time to allow the pruning to occur. tokio::time::sleep(Duration::from_millis(500)).await; // Verify that both transactions have been pruned from the mempool after the pruning duration. assert!(!eth_client.mempool().contains(transaction1.hash()), "Transaction 1 should be pruned after 1 second"); assert!(!eth_client.mempool().contains(transaction2.hash()), "Transaction 2 should be pruned after 1 second"); // Check the gas limit for Kakarot blocks assert_eq!(eth_client.mempool().config().gas_limit, KKRT_BLOCK_GAS_LIMIT); // Ensure the background task is stopped gracefully. maintain_task.abort(); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] async fn test_mempool_config(#[future] katana: Katana, _setup: ()) { let eth_client = Arc::new(katana.eth_client()); // Check the gas limit for Kakarot blocks assert_eq!(eth_client.mempool().config().gas_limit, KKRT_BLOCK_GAS_LIMIT); }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
kkrt-labs/kakarot-rpc
https://github.com/kkrt-labs/kakarot-rpc/blob/6b48598a85bb2598123e1be7237da9832d0d5eaa/tests/tests/trace_api.rs
tests/tests/trace_api.rs
#![allow(clippy::used_underscore_binding)] #![cfg(feature = "testing")] use alloy_consensus::Transaction; use alloy_dyn_abi::DynSolValue; use alloy_eips::BlockId; use alloy_primitives::{Address, TxKind, B256, U256}; use alloy_rpc_types::{request::TransactionInput, TransactionRequest}; use alloy_rpc_types_trace::geth::{ CallFrame, GethDebugBuiltInTracerType, GethDebugTracerType, GethDebugTracingCallOptions, GethDebugTracingOptions, GethTrace, }; use alloy_serde::{OtherFields, WithOtherFields}; use alloy_sol_types::{sol, SolCall}; use kakarot_rpc::{ providers::eth_provider::ChainProvider, test_utils::{ eoa::Eoa, evm_contract::{EvmContract, KakarotEvmContract, TransactionInfo, TxCommonInfo, TxFeeMarketInfo}, fixtures::{plain_opcodes, setup}, katana::Katana, rpc::{start_kakarot_rpc_server, RawRpcParamsBuilder}, }, }; use rstest::*; use serde_json::Value; use starknet::{core::types::MaybePendingBlockWithTxHashes, providers::Provider}; /// The block number on which tracing will be performed. const TRACING_BLOCK_NUMBER: u64 = 0x3; /// The amount of transactions to be traced. const TRACING_TRANSACTIONS_COUNT: usize = 5; /// Helper to create a header. fn header(block_number: u64, hash: B256, parent_hash: B256, base_fee: u64) -> alloy_rpc_types::Header { alloy_rpc_types::Header { number: block_number, hash, parent_hash, gas_limit: u64::MAX, base_fee_per_gas: Some(base_fee), ..Default::default() } } /// Helper to set up the debug/tracing environment on Katana. pub async fn tracing( katana: &Katana, contract: &KakarotEvmContract, entry_point: &str, get_args: Box<dyn Fn(u64) -> Vec<DynSolValue>>, ) { let eoa = katana.eoa(); let eoa_address = eoa.evm_address().expect("Failed to get eoa address"); let nonce: u64 = eoa.nonce().await.expect("Failed to get nonce").to(); let chain_id = eoa.eth_client().eth_provider().chain_id().await.expect("Failed to get chain id").unwrap_or_default().to(); // Push 10 RPC transactions into the database. let mut txs = Vec::with_capacity(TRACING_TRANSACTIONS_COUNT); let max_fee_per_gas = 10; let max_priority_fee_per_gas = 1; for i in 0..TRACING_TRANSACTIONS_COUNT { let tx = contract .prepare_call_transaction( entry_point, &get_args(nonce + i as u64), &TransactionInfo::FeeMarketInfo(TxFeeMarketInfo { common: TxCommonInfo { nonce: nonce + i as u64, value: 0, chain_id: Some(chain_id) }, max_fee_per_gas, max_priority_fee_per_gas, }), ) .expect("Failed to prepare call transaction"); // Sign the transaction and convert it to a RPC transaction. let tx_signed = eoa.sign_transaction(tx.clone()).expect("Failed to sign transaction"); let tx = alloy_rpc_types::Transaction { transaction_type: Some(2), nonce: tx.nonce(), hash: tx_signed.hash(), to: tx.to(), from: eoa_address, block_number: Some(TRACING_BLOCK_NUMBER), chain_id: tx.chain_id(), gas: tx.gas_limit(), input: tx.input().clone(), signature: Some(alloy_rpc_types::Signature { r: tx_signed.signature().r(), s: tx_signed.signature().s(), v: U256::from(tx_signed.signature().v().to_u64()), y_parity: Some(alloy_rpc_types::Parity(tx_signed.signature().v().y_parity())), }), max_fee_per_gas: Some(max_fee_per_gas), gas_price: Some(max_fee_per_gas), max_priority_fee_per_gas: Some(max_priority_fee_per_gas), value: tx.value(), access_list: Some(Default::default()), ..Default::default() }; let mut tx = WithOtherFields::new(tx); // Add an out of resources field to the last transaction. if i == TRACING_TRANSACTIONS_COUNT - 1 { let mut out_of_resources = std::collections::BTreeMap::new(); out_of_resources .insert(String::from("reverted"), serde_json::Value::String("A custom revert reason".to_string())); tx.other = OtherFields::new(out_of_resources); } txs.push(tx); } // Add a block header pointing to a parent hash header in the database for these transactions. // This is required since tracing will start on the previous block. let maybe_parent_block = katana .eth_provider() .starknet_provider() .get_block_with_tx_hashes(starknet::core::types::BlockId::Number(TRACING_BLOCK_NUMBER - 1)) .await .expect("Failed to get block"); let parent_block_hash = match maybe_parent_block { MaybePendingBlockWithTxHashes::PendingBlock(_) => panic!("Pending block found"), MaybePendingBlockWithTxHashes::Block(block) => block.block_hash, }; let parent_block_hash = B256::from_slice(&parent_block_hash.to_bytes_be()[..]); let parent_header = header(TRACING_BLOCK_NUMBER - 1, parent_block_hash, B256::random(), max_fee_per_gas as u64); let header = header(TRACING_BLOCK_NUMBER, B256::random(), parent_block_hash, max_fee_per_gas as u64); katana.add_transactions_with_header_to_database(vec![], parent_header).await; katana.add_transactions_with_header_to_database(txs, header).await; } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] #[ignore = "failing because of relayer change"] async fn test_trace_call(#[future] plain_opcodes: (Katana, KakarotEvmContract), _setup: ()) { // Setup the Kakarot RPC server. let katana = plain_opcodes.0; let plain_opcodes = plain_opcodes.1; tracing(&katana, &plain_opcodes, "createCounterAndInvoke", Box::new(|_| vec![])).await; let (server_addr, server_handle) = start_kakarot_rpc_server(&katana).await.expect("Error setting up Kakarot RPC server"); // Create the transaction request let request = TransactionRequest { from: Some(katana.eoa().evm_address().expect("Failed to get eoa address")), to: Some(TxKind::Call(Address::ZERO)), gas: Some(21000), gas_price: Some(10), value: Some(U256::ZERO), nonce: Some(2), ..Default::default() }; // Define the call options let call_opts = GethDebugTracingCallOptions { tracing_options: GethDebugTracingOptions::default() .with_tracer(GethDebugTracerType::BuiltInTracer(GethDebugBuiltInTracerType::CallTracer)), state_overrides: Default::default(), block_overrides: Default::default(), }; // Send the trace_call RPC request. let reqwest_client = reqwest::Client::new(); let res = reqwest_client .post(format!("http://localhost:{}", server_addr.port())) .header("Content-Type", "application/json") .body( RawRpcParamsBuilder::new("debug_traceCall") .add_param(request) .add_param(Some(BlockId::Number(TRACING_BLOCK_NUMBER.into()))) .add_param(call_opts) .build(), ) .send() .await .expect("Failed to call Debug RPC"); let response = res.text().await.expect("Failed to get response body"); let raw: Value = serde_json::from_str(&response).expect("Failed to deserialize response body"); let trace: GethTrace = serde_json::from_value(raw["result"].clone()).expect("Failed to deserialize result"); // Assert that the trace contains expected data assert_eq!( trace, GethTrace::CallTracer(CallFrame { from: katana.eoa().evm_address().expect("Failed to get eoa address"), gas: U256::from(21000), gas_used: U256::from(21000), to: Some(Address::ZERO), value: Some(U256::ZERO), typ: "CALL".to_string(), ..Default::default() }) ); drop(server_handle); } #[rstest] #[awt] #[tokio::test(flavor = "multi_thread")] #[ignore = "failing because of relayer change"] async fn test_trace_call_counter(#[future] plain_opcodes: (Katana, KakarotEvmContract), _setup: ()) { // Test function for tracing a call to a counter contract // Extract Katana instance and get the EOA's EVM address let katana = plain_opcodes.0; let evm_address = katana.eoa().evm_address().expect("Failed to get eoa address"); let plain_opcodes = plain_opcodes.1; // Perform tracing setup tracing(&katana, &plain_opcodes, "createCounterAndInvoke", Box::new(|_| vec![])).await; // Start the Kakarot RPC server let (server_addr, server_handle) = start_kakarot_rpc_server(&katana).await.expect("Error setting up Kakarot RPC server"); // Define a Solidity contract interface for the counter sol! { #[sol(rpc)] contract CounterContract { function incForLoop(uint256 iterations) external; } } // Prepare the calldata for invoking the incForLoop function with 5 iterations let calldata = CounterContract::incForLoopCall { iterations: U256::from(5) }.abi_encode(); let contract_address = Address::from_slice(&plain_opcodes.evm_address.to_bytes_be()[12..]); // Define the transaction request let request = TransactionRequest { from: Some(evm_address), to: Some(TxKind::Call(contract_address)), gas: Some(210_000), gas_price: Some(1_000_000_000_000_000_000_000), value: Some(U256::ZERO), nonce: Some(2), input: TransactionInput { input: Some(calldata.clone().into()), data: None }, ..Default::default() }; // Configure tracing options let call_opts = GethDebugTracingCallOptions { tracing_options: GethDebugTracingOptions::default() .with_tracer(GethDebugTracerType::BuiltInTracer(GethDebugBuiltInTracerType::CallTracer)) .with_timeout(std::time::Duration::from_secs(300)) .with_call_config(alloy_rpc_types_trace::geth::CallConfig { only_top_call: Some(false), with_log: None }), state_overrides: Default::default(), block_overrides: Default::default(), }; // Send a trace_call RPC request let reqwest_client = reqwest::Client::new(); let res = reqwest_client .post(format!("http://localhost:{}", server_addr.port())) .header("Content-Type", "application/json") .body( RawRpcParamsBuilder::new("debug_traceCall") .add_param(request) .add_param(Some(BlockId::Number(TRACING_BLOCK_NUMBER.into()))) .add_param(call_opts) .build(), ) .send() .await .expect("Failed to call Debug RPC"); // Process the response let response = res.text().await.expect("Failed to get response body"); let raw: Value = serde_json::from_str(&response).expect("Failed to deserialize response body"); let trace: GethTrace = serde_json::from_value(raw["result"].clone()).expect("Failed to deserialize result from trace"); // Assert that the trace result matches expectations assert_eq!( trace, GethTrace::CallTracer(CallFrame { from: evm_address, gas: U256::from(210_000), gas_used: U256::from(21410), to: Some(contract_address), value: Some(U256::ZERO), typ: "CALL".to_string(), input: calldata.into(), ..Default::default() }) ); // Clean up by dropping the server handle drop(server_handle); }
rust
MIT
6b48598a85bb2598123e1be7237da9832d0d5eaa
2026-01-04T20:20:26.112976Z
false
jwilm/racerd
https://github.com/jwilm/racerd/blob/e3d380b9a1d3f3b67286d60465746bc89fea9098/src/lib.rs
src/lib.rs
//! libracerd provides an http server and set of completion engines for consumption by rust //! developer tools. The http server itself is a few JSON endpoints providing completion, definition //! look-up, and compilation. The endpoints are backed by an object implementing `SemanticEngine` //! //! Documentation for the HTTP endpoints can be found in the http module header. //! //! This project's source code is [available on GitHub](https://github.com/jwilm/racerd). extern crate serde; extern crate serde_json; #[macro_use] extern crate serde_derive; #[macro_use] extern crate router; // Iron routing handler extern crate bodyparser; // Iron body parsing middleware extern crate iron; // http framework extern crate iron_hmac; extern crate logger; // Iron logging middleware extern crate persistent; // Iron storage middleware extern crate rls_span; #[macro_use] extern crate log; // log macros extern crate racer; // rust code analysis extern crate rand; extern crate regex; pub mod engine; pub mod http; pub mod util; use std::fs::File; use std::io::Read; /// Configuration flags and values /// /// This object contains all switches the consumer has control of. #[derive(Debug)] pub struct Config { pub port: u16, pub addr: String, pub secret_file: Option<String>, pub print_http_logs: bool, pub rust_src_path: Option<String>, } impl Default for Config { fn default() -> Config { Config { port: 0, addr: "127.0.0.1".to_owned(), secret_file: None, print_http_logs: false, rust_src_path: None, } } } impl Config { /// Build a default config object pub fn new() -> Config { Default::default() } /// Return contents of secret file /// /// panics if self.secret_file is None or an error is encountered while reading the file. pub fn read_secret_file(&self) -> Vec<u8> { self.secret_file .as_ref() .map(|secret_file_path| { let buf = { let mut f = File::open(secret_file_path).unwrap(); let mut buf = Vec::new(); f.read_to_end(&mut buf).unwrap(); buf }; std::fs::remove_file(secret_file_path).unwrap(); buf }) .unwrap() } }
rust
Apache-2.0
e3d380b9a1d3f3b67286d60465746bc89fea9098
2026-01-04T20:20:43.736802Z
false
jwilm/racerd
https://github.com/jwilm/racerd/blob/e3d380b9a1d3f3b67286d60465746bc89fea9098/src/util/fs.rs
src/util/fs.rs
//! fs utilities (eg. TmpFile) use rand::distributions::Alphanumeric; use std::convert::From; use std::fs::{self, File}; use std::io::Write; use std::path::{Path, PathBuf}; use std::thread; /// A temporary file that is removed on drop /// /// With the new constructor, you provide contents and a file is created based on the name of the /// current task. The with_name constructor allows you to choose a name. Neither forms are secure, /// and both are subject to race conditions. pub struct TmpFile { path_buf: PathBuf, } impl TmpFile { /// Create a temp file with random name and `contents`. pub fn new(contents: &str) -> TmpFile { let tmp = TmpFile { path_buf: TmpFile::mktemp(), }; tmp.write_contents(contents); tmp } /// Create a file with `name` and `contents`. pub fn with_name(name: &str, contents: &str) -> TmpFile { let tmp = TmpFile { path_buf: PathBuf::from(name), }; tmp.write_contents(contents); tmp } fn write_contents(&self, contents: &str) { let mut f = File::create(self.path()).unwrap(); f.write_all(contents.as_bytes()).unwrap(); f.flush().unwrap(); } /// Make path for tmpfile. Stole this from racer's tests. fn mktemp() -> PathBuf { use rand::Rng; let thread = thread::current(); let taskname = thread.name().unwrap(); let s = taskname.replace("::", "_"); let mut p = "tmpfile.".to_string(); p.push_str(&s[..]); // Add some random chars for c in rand::thread_rng().sample_iter(&Alphanumeric).take(5) { p.push(c); } PathBuf::from(p) } /// Get the Path of the TmpFile pub fn path(&self) -> &Path { self.path_buf.as_path() } } impl Drop for TmpFile { fn drop(&mut self) { fs::remove_file(self.path_buf.as_path()).unwrap(); } } #[test] #[allow(unused_variables)] fn tmp_file_works() { fn exists(p: &Path) -> bool { match std::fs::metadata(p) { Ok(_) => true, Err(_) => false, } } use std::fs::File; use std::io::Read; use std::path::Path; let path_str = "test.txt"; let path = &Path::new(path_str); assert!(!exists(path)); let contents = "hello, for a moment"; { let file = TmpFile::with_name(path_str, contents); assert!(exists(path)); let mut f = File::open(path_str).unwrap(); let mut s = String::new(); f.read_to_string(&mut s).unwrap(); assert_eq!(s, contents); } assert!(!exists(path)); }
rust
Apache-2.0
e3d380b9a1d3f3b67286d60465746bc89fea9098
2026-01-04T20:20:43.736802Z
false
jwilm/racerd
https://github.com/jwilm/racerd/blob/e3d380b9a1d3f3b67286d60465746bc89fea9098/src/util/mod.rs
src/util/mod.rs
//! Som misc shared functionality pub mod fs;
rust
Apache-2.0
e3d380b9a1d3f3b67286d60465746bc89fea9098
2026-01-04T20:20:43.736802Z
false
jwilm/racerd
https://github.com/jwilm/racerd/blob/e3d380b9a1d3f3b67286d60465746bc89fea9098/src/bin/racerd.rs
src/bin/racerd.rs
extern crate docopt; extern crate env_logger; extern crate libracerd; #[macro_use] extern crate serde_derive; use libracerd::engine::SemanticEngine; use libracerd::{engine, http, Config}; use std::convert::Into; use docopt::Docopt; const VERSION: &str = env!("CARGO_PKG_VERSION"); const USAGE: &str = " racerd - a JSON/HTTP layer on top of racer Usage: racerd serve [--secret-file=<path>] [--port=<int>] [--addr=<address>] [-l] [--rust-src-path=<path>] racerd (-h | --help) racerd --version Options: -c, --rust-src-path=<path> Use the given path for std library completions -l, --logging Print http logs. -h, --help Show this message. -p, --port=<int> Listen on this port [default: 3048]. -a, --addr=<address> Listen on this address [default: 127.0.0.1]. -s, --secret-file=<path> Path to the HMAC secret file. File will be destroyed after being read. --version Print the version and exit. "; #[derive(Debug, Deserialize)] struct Args { flag_port: u16, flag_addr: String, flag_version: bool, flag_secret_file: Option<String>, flag_logging: bool, flag_rust_src_path: Option<String>, cmd_serve: bool, } impl Into<Config> for Args { fn into(self) -> Config { Config { port: self.flag_port as u16, secret_file: self.flag_secret_file, print_http_logs: self.flag_logging, rust_src_path: self.flag_rust_src_path, addr: self.flag_addr, } } } fn main() { // Start logging env_logger::init(); // Parse arguments let args: Args = Docopt::new(USAGE) .and_then(|d| d.deserialize()) .unwrap_or_else(|e| e.exit()); // Print version and exit if --version was specified if args.flag_version { println!("racerd version {}", VERSION); std::process::exit(0); } // build config object let config: Config = args.into(); // TODO start specified semantic engine. For now, hard coded racer. let racer = engine::Racer::new(); racer.initialize(&config).unwrap(); // Start serving let server = http::serve(&config, racer).unwrap(); println!("racerd listening at {}", server.addr()); }
rust
Apache-2.0
e3d380b9a1d3f3b67286d60465746bc89fea9098
2026-01-04T20:20:43.736802Z
false
jwilm/racerd
https://github.com/jwilm/racerd/blob/e3d380b9a1d3f3b67286d60465746bc89fea9098/src/engine/my_racer.rs
src/engine/my_racer.rs
//! SemanticEngine implementation for [the racer library](https://github.com/phildawes/racer) //! use crate::engine::{Completion, Context, CursorPosition, Definition, SemanticEngine}; use racer::{self, Coordinate, FileCache, Match, Session}; use std::sync::Mutex; use regex::Regex; pub struct Racer { cache: Mutex<FileCache>, } impl Racer { pub fn new() -> Racer { Racer { cache: Mutex::new(FileCache::default()), } } } // Racer's FileCache uses Rc and RefCell internally. We wrap everything in a // Mutex, and the Rcs aren't possible to leak, so these should be ok. Correct // solution is to make racer threadsafe. unsafe impl Sync for Racer {} unsafe impl Send for Racer {} use super::Result; use crate::Config; impl SemanticEngine for Racer { fn initialize(&self, config: &Config) -> Result<()> { if let Some(ref src_path) = config.rust_src_path { std::env::set_var("RUST_SRC_PATH", src_path); } Ok(()) } fn find_definition(&self, ctx: &Context) -> Result<Option<Definition>> { let cache = match self.cache.lock() { Ok(guard) => guard, Err(poisoned) => poisoned.into_inner(), }; let session = Session::new(&cache, Some(ctx.query_path())); for buffer in &ctx.buffers { session.cache_file_contents(buffer.path(), &*buffer.contents) } // TODO catch_panic: apparently this can panic! in a string operation. Something about pos // not landing on a character boundary. Ok( racer::find_definition(ctx.query_path(), ctx.query_cursor, &session).and_then(|m| { m.coords.map(|Coordinate { row, col }| Definition { position: CursorPosition { line: row.0 as usize, col: col.0 as usize, }, dtype: format!("{:?}", m.mtype), file_path: m.filepath.to_str().unwrap().to_string(), text: m.matchstr.clone(), text_context: m.contextstr.clone(), docs: m.docs.clone(), }) }), ) } fn list_completions(&self, ctx: &Context) -> Result<Option<Vec<Completion>>> { let cache = match self.cache.lock() { Ok(guard) => guard, Err(poisoned) => poisoned.into_inner(), }; let session = Session::new(&cache, Some(ctx.query_path())); for buffer in &ctx.buffers { session.cache_file_contents(buffer.path(), &*buffer.contents) } let completions = racer::complete_from_file(ctx.query_path(), ctx.query_cursor, &session) .filter_map( |Match { matchstr, contextstr, mtype, filepath, coords, .. }| { coords.map(|Coordinate { row, col }| Completion { position: CursorPosition { line: row.0 as usize, col: col.0 as usize, }, text: matchstr, context: collapse_whitespace(&contextstr), kind: format!("{:?}", mtype), file_path: filepath.to_str().unwrap().to_string(), }) }, ) .collect::<Vec<_>>(); if !completions.is_empty() { Ok(Some(completions)) } else { Ok(None) } } } pub fn collapse_whitespace(text: &str) -> String { Regex::new(r"\s+") .unwrap() .replace_all(text, " ") .to_string() } #[cfg(test)] mod tests { use super::*; use crate::engine::{Buffer, Context, CursorPosition, SemanticEngine}; use crate::util::fs::TmpFile; #[test] #[allow(unused_variables)] fn find_definition() { // FIXME this is just here for side effects. let src2 = TmpFile::with_name( "src2.rs", " /// myfn docs pub fn myfn() {} pub fn foo() {} ", ); let src = " use src2::*; mod src2; fn main() { myfn(); }"; let buffers = vec![Buffer { contents: src.to_string(), file_path: "src.rs".to_string(), }]; let ctx = Context::new(buffers, CursorPosition { line: 5, col: 17 }, "src.rs"); let racer = Racer::new(); let def = racer.find_definition(&ctx).unwrap().unwrap(); assert_eq!(def.text, "myfn"); assert_eq!(def.docs, "myfn docs"); } #[test] #[allow(unused_variables)] fn find_completion() { let src = " mod mymod { /// myfn is a thing pub fn myfn<T>(reader: T) where T: ::std::io::Read {} } fn main() { mymod::my }"; let buffers = vec![Buffer { contents: src.to_string(), file_path: "src.rs".to_string(), }]; let ctx = Context::new(buffers, CursorPosition { line: 8, col: 25 }, "src.rs"); let racer = Racer::new(); let completions = racer.list_completions(&ctx).unwrap().unwrap(); assert_eq!(completions.len(), 1); let completion = &completions[0]; assert_eq!(completion.text, "myfn"); assert_eq!(completion.position.line, 4); assert_eq!(completion.file_path, "src.rs"); } #[test] fn find_completion_collapsing_whitespace() { let src = " struct foo {} impl foo { fn format( &self ) -> u32 { } } fn main() { let x = foo{}; x. }"; let buffers = vec![Buffer { contents: src.to_string(), file_path: "src.rs".to_string(), }]; let ctx = Context::new(buffers, CursorPosition { line: 12, col: 16 }, "src.rs"); let racer = Racer::new(); let completions = racer.list_completions(&ctx).unwrap().unwrap(); assert_eq!(completions.len(), 1); let completion = &completions[0]; assert_eq!(completion.context, "fn format( &self ) -> u32"); } #[test] fn collapse_whitespace_test() { assert_eq!(collapse_whitespace("foo foo"), "foo foo"); assert_eq!(collapse_whitespace(" "), " "); assert_eq!(collapse_whitespace("\n\t \n"), " "); assert_eq!(collapse_whitespace("foo\nbar"), "foo bar"); assert_eq!( collapse_whitespace("fn foo( &self )\n -> u32"), "fn foo( &self ) -> u32" ); } }
rust
Apache-2.0
e3d380b9a1d3f3b67286d60465746bc89fea9098
2026-01-04T20:20:43.736802Z
false
jwilm/racerd
https://github.com/jwilm/racerd/blob/e3d380b9a1d3f3b67286d60465746bc89fea9098/src/engine/error.rs
src/engine/error.rs
use std::error; use std::fmt; use std::io; /// Error type for semantic engine module #[derive(Debug)] pub enum Error { IoError(io::Error), Racer, } impl error::Error for Error { fn description(&self) -> &str { match *self { Error::IoError(_) => "io::Error during engine operation", Error::Racer => "Internal racer error", } } fn cause(&self) -> Option<&dyn error::Error> { match *self { Error::IoError(ref err) => Some(err), Error::Racer => None, } } } impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { Error::IoError(ref e) => write!(fmt, "io::Error({})", e), Error::Racer => write!(fmt, "Internal racer error"), } } } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::IoError(err) } } /// Result type for semantic engine module pub type Result<T> = std::result::Result<T, Error>;
rust
Apache-2.0
e3d380b9a1d3f3b67286d60465746bc89fea9098
2026-01-04T20:20:43.736802Z
false
jwilm/racerd
https://github.com/jwilm/racerd/blob/e3d380b9a1d3f3b67286d60465746bc89fea9098/src/engine/mod.rs
src/engine/mod.rs
use std::path::Path; /// This module's Error and Result types mod error; pub use self::error::{Error, Result}; use crate::Config; /// Provide completions, definitions, and analysis of rust source code pub trait SemanticEngine: Send + Sync { /// Perform any necessary initialization. /// /// Only needs to be called once when an engine is created. fn initialize(&self, config: &Config) -> Result<()>; /// Find the definition for the item under the cursor fn find_definition(&self, context: &Context) -> Result<Option<Definition>>; /// Get a list of completions for the item under the cursor fn list_completions(&self, context: &Context) -> Result<Option<Vec<Completion>>>; } /// A possible completion for a location #[derive(Debug)] pub struct Completion { pub text: String, pub context: String, pub kind: String, pub file_path: String, pub position: CursorPosition, } /// Source file and type information for a found definition #[derive(Debug)] pub struct Definition { pub position: CursorPosition, pub text: String, pub text_context: String, pub dtype: String, pub file_path: String, pub docs: String, } /// Context for a given operation. /// /// All operations require a buffer holding the contents of a file, the file's absolute path, and a /// cursor position to fully specify the request. This object holds all of those items. #[derive(Debug)] pub struct Context { pub buffers: Vec<Buffer>, pub query_cursor: CursorPosition, pub query_file: String, } impl Context { pub fn new<T>(buffers: Vec<Buffer>, position: CursorPosition, file_path: T) -> Context where T: Into<String>, { Context { buffers, query_cursor: position, query_file: file_path.into(), } } pub fn query_path(&self) -> &Path { &Path::new(&self.query_file[..]) } } /// Position of the cursor in a text file /// /// Similar to a point, it has two coordinates `line` and `col`. #[derive(Debug, Copy, Clone)] pub struct CursorPosition { pub line: usize, pub col: usize, } impl Into<racer::Location> for CursorPosition { fn into(self) -> racer::Location { racer::Location::Coords(racer::Coordinate { row: rls_span::Row::new_one_indexed(self.line as u32), col: rls_span::Column::new_zero_indexed(self.col as u32), }) } } pub mod my_racer; pub use self::my_racer::Racer; #[derive(Debug, Deserialize, Clone)] pub struct Buffer { pub file_path: String, pub contents: String, } impl Buffer { pub fn path(&self) -> &Path { &Path::new(&self.file_path[..]) } }
rust
Apache-2.0
e3d380b9a1d3f3b67286d60465746bc89fea9098
2026-01-04T20:20:43.736802Z
false
jwilm/racerd
https://github.com/jwilm/racerd/blob/e3d380b9a1d3f3b67286d60465746bc89fea9098/src/http/completion.rs
src/http/completion.rs
use iron::mime::Mime; use iron::prelude::*; use iron::status; use serde_json::to_string; use super::EngineProvider; use crate::engine::{Buffer, Completion, Context, CursorPosition}; /// Given a location, return a list of possible completions pub fn list(req: &mut Request) -> IronResult<Response> { let lcr = match req.get::<::bodyparser::Struct<ListCompletionsRequest>>() { Ok(Some(s)) => { trace!("parsed ListCompletionsRequest"); s } Ok(None) => { trace!("failed parsing ListCompletionsRequest"); return Ok(Response::with(status::BadRequest)); } Err(err) => { trace!("error while parsing ListCompletionsRequest"); return Err(IronError::new(err, status::InternalServerError)); } }; let mutex = req.get::<::persistent::Write<EngineProvider>>().unwrap(); let engine = mutex.lock().unwrap_or_else(|e| e.into_inner()); match engine.list_completions(&lcr.context()) { // 200 OK; found the definition Ok(Some(completions)) => { trace!("got a match"); let res = completions .into_iter() .map(CompletionResponse::from) .collect::<Vec<_>>(); let content_type = "application/json".parse::<Mime>().unwrap(); Ok(Response::with(( content_type, status::Ok, to_string(&res).unwrap(), ))) } // 204 No Content; Everything went ok, but the definition was not found. Ok(None) => { trace!("did not find any match"); Ok(Response::with(status::NoContent)) } // 500 Internal Server Error; Error occurred while searching for the definition Err(err) => { trace!("encountered an error"); Err(IronError::new(err, status::InternalServerError)) } } } #[derive(Debug, Deserialize, Clone)] struct ListCompletionsRequest { pub buffers: Vec<Buffer>, pub file_path: String, pub column: usize, pub line: usize, } impl ListCompletionsRequest { pub fn context(self) -> Context { let cursor = CursorPosition { line: self.line, col: self.column, }; Context::new(self.buffers, cursor, self.file_path) } } #[derive(Debug, Serialize)] struct CompletionResponse { text: String, context: String, kind: String, file_path: String, line: usize, column: usize, } impl From<Completion> for CompletionResponse { fn from(c: Completion) -> CompletionResponse { CompletionResponse { text: c.text, context: c.context, kind: c.kind, file_path: c.file_path, line: c.position.line, column: c.position.col, } } }
rust
Apache-2.0
e3d380b9a1d3f3b67286d60465746bc89fea9098
2026-01-04T20:20:43.736802Z
false
jwilm/racerd
https://github.com/jwilm/racerd/blob/e3d380b9a1d3f3b67286d60465746bc89fea9098/src/http/ping.rs
src/http/ping.rs
use iron::prelude::*; use iron::status; /// Check if the server is accepting requests pub fn pong(_: &mut Request) -> IronResult<Response> { Ok(Response::with((status::Ok, "{\"pong\": true}"))) }
rust
Apache-2.0
e3d380b9a1d3f3b67286d60465746bc89fea9098
2026-01-04T20:20:43.736802Z
false
jwilm/racerd
https://github.com/jwilm/racerd/blob/e3d380b9a1d3f3b67286d60465746bc89fea9098/src/http/file.rs
src/http/file.rs
use iron::prelude::*; /// Parse a file and return a list of issues (warnings, errors) encountered pub fn parse(_: &mut Request) -> IronResult<Response> { unimplemented!(); }
rust
Apache-2.0
e3d380b9a1d3f3b67286d60465746bc89fea9098
2026-01-04T20:20:43.736802Z
false
jwilm/racerd
https://github.com/jwilm/racerd/blob/e3d380b9a1d3f3b67286d60465746bc89fea9098/src/http/mod.rs
src/http/mod.rs
//! http server for semantic engines use iron::prelude::*; use crate::Config; mod completion; mod definition; mod file; mod ping; use crate::engine::SemanticEngine; use iron::typemap::Key; use iron_hmac::Hmac256Authentication; use iron_hmac::SecretKey; use std::sync::{Arc, Mutex}; /// Errors occurring in the http module #[derive(Debug)] pub enum Error { /// Error occurred in underlying http server lib HttpServer(iron::error::HttpError), } impl From<iron::error::HttpError> for Error { fn from(err: iron::error::HttpError) -> Error { Error::HttpServer(err) } } pub type Result<T> = std::result::Result<T, Error>; // ------------------------------------------------------------------------------------------------- /// Iron middleware responsible for attaching a semantic engine to each request #[derive(Debug, Clone)] pub struct EngineProvider; impl Key for EngineProvider { type Value = Box<dyn SemanticEngine + Send + Sync + 'static>; } // ------------------------------------------------------------------------------------------------- /// Start the http server using the given configuration /// /// `serve` is non-blocking. /// /// # Example /// /// ```no_run /// # use libracerd::{Config}; /// let mut cfg = Config::new(); /// cfg.port = 3000; /// /// let engine = libracerd::engine::Racer::new(); /// /// let mut server = libracerd::http::serve(&cfg, engine).unwrap(); /// // ... later /// server.close().unwrap(); /// ``` /// pub fn serve<E: SemanticEngine + Send + Sync + 'static>( config: &Config, engine: E, ) -> Result<Server> { use logger::Format; use logger::Logger; use persistent::{Read, Write}; let mut chain = Chain::new(router!( parse: post "/parse_file" => file::parse, find: post "/find_definition" => definition::find, list: post "/list_completions" => completion::list, ping: get "/ping" => ping::pong)); // Logging middleware let log_fmt = Format::new("{method} {uri} -> {status} ({response-time})"); let (log_before, log_after) = Logger::new(log_fmt); // log_before must be first middleware in before chain if config.print_http_logs { chain.link_before(log_before); } // Get HMAC Middleware let (hmac_before, hmac_after) = if config.secret_file.is_some() { let secret = SecretKey::new(&config.read_secret_file()); let hmac_header = "x-racerd-hmac"; let (before, after) = Hmac256Authentication::middleware(secret, hmac_header); (Some(before), Some(after)) } else { (None, None) }; // This middleware provides a semantic engine to the request handlers // where Box<E>: PersistentInto<Arc<Mutex<Box<SemanticEngine + Sync + Send + 'static>>>> let x: Arc<Mutex<Box<dyn SemanticEngine + Sync + Send + 'static>>> = Arc::new(Mutex::new(Box::new(engine))); chain.link_before(Write::<EngineProvider>::one(x)); // Body parser middlerware chain.link_before(Read::<::bodyparser::MaxBodyLength>::one(1024 * 1024 * 10)); // Maybe link hmac middleware if let Some(hmac) = hmac_before { chain.link_before(hmac); } if let Some(hmac) = hmac_after { chain.link_after(hmac); } // log_after must be last middleware in after chain if config.print_http_logs { chain.link_after(log_after); } let app = Iron::new(chain); Ok(Server { inner: app.http((&config.addr[..], config.port))?, }) } /// Wrapper type with information and control of the underlying HTTP server /// /// This type can only be created via the [`serve`](fn.serve.html) function. #[derive(Debug)] pub struct Server { inner: iron::Listening, } impl Server { /// Stop accepting connections pub fn close(&mut self) -> Result<()> { self.inner.close().map_err(|e| e.into()) } /// Get listening address of server (eg. "127.0.0.1:59369") /// /// # Example /// ```no_run /// let mut config = ::libracerd::Config::new(); /// config.port = 3000; /// /// let engine = ::libracerd::engine::Racer::new(); /// let server = ::libracerd::http::serve(&config, engine).unwrap(); /// /// assert_eq!(server.addr(), "0.0.0.0:3000"); /// ``` pub fn addr(&self) -> String { format!("{}", self.inner.socket) } }
rust
Apache-2.0
e3d380b9a1d3f3b67286d60465746bc89fea9098
2026-01-04T20:20:43.736802Z
false
jwilm/racerd
https://github.com/jwilm/racerd/blob/e3d380b9a1d3f3b67286d60465746bc89fea9098/src/http/definition.rs
src/http/definition.rs
use iron::mime::Mime; use iron::prelude::*; use iron::status; use serde_json::to_string; use super::EngineProvider; use crate::engine::{Buffer, Context, CursorPosition, Definition}; /// Given a location, return where the identifier is defined /// /// Possible responses include /// /// - `200 OK` the request was successful and a JSON object is returned. /// - `204 No Content` the request was successful, but no match was found. /// - `400 Bad Request` the request payload was malformed /// - `500 Internal Server Error` some unexpected error occurred pub fn find(req: &mut Request) -> IronResult<Response> { // Parse the request. If the request doesn't parse properly, the request is invalid, and a 400 // BadRequest is returned. let fdr = match req.get::<::bodyparser::Struct<FindDefinitionRequest>>() { Ok(Some(s)) => { trace!("definition::find parsed FindDefinitionRequest"); s } Ok(None) => { trace!("definition::find failed parsing FindDefinitionRequest"); return Ok(Response::with(status::BadRequest)); } Err(err) => { trace!("definition::find received error while parsing FindDefinitionRequest"); return Err(IronError::new(err, status::InternalServerError)); } }; let mutex = req.get::<::persistent::Write<EngineProvider>>().unwrap(); let engine = mutex.lock().unwrap_or_else(|e| e.into_inner()); match engine.find_definition(&fdr.context()) { // 200 OK; found the definition Ok(Some(definition)) => { trace!("definition::find got a match"); let res = FindDefinitionResponse::from(definition); let content_type = "application/json".parse::<Mime>().unwrap(); Ok(Response::with(( content_type, status::Ok, to_string(&res).unwrap(), ))) } // 204 No Content; Everything went ok, but the definition was not found. Ok(None) => { trace!("definition::find did not find a match"); Ok(Response::with(status::NoContent)) } // 500 Internal Server Error; Error occurred while searching for the definition Err(err) => { trace!("definition::find encountered an error"); Err(IronError::new(err, status::InternalServerError)) } } } impl From<Definition> for FindDefinitionResponse { fn from(def: Definition) -> FindDefinitionResponse { FindDefinitionResponse { file_path: def.file_path, column: def.position.col, line: def.position.line, text: def.text, context: def.text_context, kind: def.dtype, docs: def.docs, } } } #[derive(Debug, Deserialize, Clone)] struct FindDefinitionRequest { pub buffers: Vec<Buffer>, pub file_path: String, pub column: usize, pub line: usize, } impl FindDefinitionRequest { pub fn context(self) -> Context { let cursor = CursorPosition { line: self.line, col: self.column, }; Context::new(self.buffers, cursor, self.file_path) } } #[test] fn find_definition_request_from_json() { let s = stringify!({ "file_path": "src.rs", "buffers": [{ "file_path": "src.rs", "contents": "fn foo() {}\nfn bar() {}\nfn main() {\nfoo();\n}" }], "line": 4, "column": 3 }); let req: FindDefinitionRequest = serde_json::from_str(s).unwrap(); assert_eq!(req.file_path, "src.rs"); assert_eq!(req.line, 4); assert_eq!(req.column, 3); } #[derive(Debug, Deserialize, Serialize)] struct FindDefinitionResponse { pub file_path: String, pub column: usize, pub line: usize, pub text: String, pub context: String, pub kind: String, pub docs: String, }
rust
Apache-2.0
e3d380b9a1d3f3b67286d60465746bc89fea9098
2026-01-04T20:20:43.736802Z
false
jwilm/racerd
https://github.com/jwilm/racerd/blob/e3d380b9a1d3f3b67286d60465746bc89fea9098/tests/lib.rs
tests/lib.rs
#![deny(warnings)] extern crate libracerd; extern crate rustc_serialize; #[macro_use] extern crate hyper; extern crate crypto; mod util; /// Although the value is not used, running env! for RUST_SRC_PATH checks, before running the tests, /// that the required environment variable is defined. const _RUST_SRC_PATH: &'static str = env!("RUST_SRC_PATH"); macro_rules! init_logging { () => {}; } #[test] #[should_panic] #[cfg(not(windows))] fn panics_when_invalid_secret_given() { use libracerd::engine::{Racer, SemanticEngine}; use libracerd::http::serve; use libracerd::Config; init_logging!(); let config = Config { secret_file: Some("a.file.that.does.not.exist".to_owned()), print_http_logs: true, ..Default::default() }; let engine = Racer::new(); engine.initialize(&config).unwrap(); serve(&config, engine).unwrap(); } mod http { use hyper::header::ContentType; use hyper::Client; use std::io::Read; header! { (XRacerdHmac, "x-racerd-hmac") => [String] } use crate::util::http::{self, request_str, UrlBuilder}; use libracerd::util::fs::TmpFile; use rustc_serialize::json::Json; use hyper::method::Method; /// Checks that /find_definition works within a single buffer #[test] fn find_definition() { init_logging!(); http::with_server(|server| { // Build request args let url = server.url("/find_definition"); let request_obj = stringify!({ "buffers": [{ "file_path": "src.rs", "contents": "fn foo() {}\nfn bar() {}\nfn main() {\nfoo();\n}" }], "file_path": "src.rs", "line": 4, "column": 3 }); // Make request let res = request_str(Method::Post, &url[..], Some(request_obj)) .unwrap() .unwrap(); // Build actual/expected objects let actual = Json::from_str(&res[..]).unwrap(); let expected = Json::from_str(stringify!({ "text": "foo", "line": 1, "column": 3, "file_path": "src.rs", "context": "fn foo()", "kind": "Function", "docs": "" })) .unwrap(); // They should be equal assert_eq!(actual, expected); }); } /// Checks that /find_definition correctly resolves cross file definitions when the buffers have /// not been written to disk. #[test] fn find_definition_multiple_dirty_buffers() { init_logging!(); // Build request args let request_obj = stringify!({ "buffers": [{ "file_path": "src.rs", "contents": "mod src2;\nuse src2::{foo,myfn};\nfn main() {\n myfn();\n}\n" }, { "file_path": "src2.rs", "contents": "\npub fn myfn()\npub fn foo() {}\n" }], "file_path": "src.rs", "line": 4, "column": 7 }); // Create an *empty* temporary file. The request contains unsaved file contents. For rust // module inclusions to work, the compiler checks certain locations on the file system where // a module file could be located. It simply doesn't work with unnamed files. let _f = TmpFile::with_name("src2.rs", ""); http::with_server(|server| { // Make request let url = server.url("/find_definition"); let res = request_str(Method::Post, &url[..], Some(request_obj)) .unwrap() .unwrap(); // Build actual/expected objects let actual = Json::from_str(&res[..]).unwrap(); let expected = Json::from_str(stringify!({ "text": "myfn", "line": 2, "column": 7, "file_path": "src2.rs", "context": "pub fn myfn() pub fn foo()", "kind": "Function", "docs": "" })) .unwrap(); // They should be equal assert_eq!(actual, expected); }); } macro_rules! assert_str_prop_on_obj_in_list { ($prop:expr, $val:expr, $list:expr) => { assert!($list.as_array().unwrap().iter().any(|c| { $val == c .as_object() .unwrap() .get($prop) .unwrap() .as_string() .unwrap() })); }; } #[test] fn find_definition_in_std_library() { init_logging!(); // Build request args let request_obj = stringify!({ "buffers": [{ "file_path": "src.rs", "contents": "use std::borrow::Cow;\nfn main() {\nlet p = Cow::Borrowed(\"arst\");\n}\n" }], "file_path": "src.rs", "line": 3, "column": 17 }); http::with_server(|server| { // Make request let url = server.url("/find_definition"); let res = request_str(Method::Post, &url[..], Some(request_obj)) .unwrap() .unwrap(); // Build actual/expected objects let actual = Json::from_str(&res[..]).expect("response is json"); // We don't know exactly how the result is going to look in this case. let obj = actual.as_object().unwrap(); // Check that `file_path` ends_with "path.rs" let found_path = obj.get("file_path").unwrap().as_string().unwrap(); assert!(found_path.ends_with("borrow.rs")); // Check that we found a thing called "new" let found_text = obj.get("text").unwrap().as_string().unwrap(); assert_eq!(found_text, "Borrowed"); }); } #[test] fn list_path_completions_std_library() { use rustc_serialize::json; init_logging!(); // Build request args let request_obj = stringify!({ "buffers": [{ "file_path": "src.rs", "contents": "use std::path;\nfn main() {\nlet p = &path::\n}\n" }], "file_path": "src.rs", "line": 3, "column": 15 }); http::with_server(|server| { // Make request let url = server.url("/list_completions"); let res = request_str(Method::Post, &url[..], Some(request_obj)) .unwrap() .unwrap(); let list = Json::from_str(&res[..]).unwrap(); println!("{}", json::as_pretty_json(&list)); // Check that the "Path" completion is available assert_str_prop_on_obj_in_list!("text", "Path", list); assert_str_prop_on_obj_in_list!("text", "PathBuf", list); }); } #[test] fn ping_pong() { init_logging!(); http::with_server(|server| { let url = server.url("/ping"); let res = request_str(Method::Get, &url[..], None).unwrap().unwrap(); let actual = Json::from_str(&res[..]).unwrap(); let expected = Json::from_str(stringify!({ "pong": true })) .unwrap(); assert_eq!(actual, expected); }); } #[test] fn ping_pong_hmac_with_correct_secret() { init_logging!(); let secret = "hello hmac ping pong"; http::with_hmac_server(secret, |server| { // The request hmac in this case should be let hmac = crate::util::request_hmac(secret, "GET", "/ping", ""); let url = server.url("/ping"); let client = Client::new(); let mut res = client .get(&url[..]) .header(XRacerdHmac(hmac)) .header(ContentType::json()) .send() .unwrap(); assert_eq!(res.status, ::hyper::status::StatusCode::Ok); let mut body = String::new(); res.read_to_string(&mut body).unwrap(); let actual = Json::from_str(&body[..]).unwrap(); let expected = Json::from_str(stringify!({ "pong": true })) .unwrap(); assert_eq!(actual, expected); }); } #[test] fn ping_pong_hmac_wrong_secret() { init_logging!(); let secret = "hello hmac ping pong"; http::with_hmac_server(secret, |server| { // The request hmac in this case should be let hmac = crate::util::request_hmac("different secret", "GET", "/ping", ""); let url = server.url("/ping"); let client = Client::new(); let res = client .get(&url[..]) .header(XRacerdHmac(hmac)) .header(ContentType::json()) .send() .unwrap(); assert_eq!(res.status, ::hyper::status::StatusCode::Forbidden); }); } }
rust
Apache-2.0
e3d380b9a1d3f3b67286d60465746bc89fea9098
2026-01-04T20:20:43.736802Z
false
jwilm/racerd
https://github.com/jwilm/racerd/blob/e3d380b9a1d3f3b67286d60465746bc89fea9098/tests/util/http.rs
tests/util/http.rs
use std::fs::File; use std::io::{Read, Write}; use std::ops::Deref; use libracerd::engine::{Racer, SemanticEngine}; use libracerd::Config; use hyper::method::Method; /// Smart pointer for libracerd http server. /// /// TestServer automatically closes the underlying server when going out of scope. pub struct TestServer { inner: ::libracerd::http::Server, } impl TestServer { pub fn new(secret_file: Option<String>) -> TestServer { let engine = Racer::new(); let config = Config { secret_file: secret_file, print_http_logs: true, ..Default::default() }; engine.initialize(&config).unwrap(); TestServer { inner: ::libracerd::http::serve(&config, engine).unwrap(), } } } impl Deref for TestServer { type Target = ::libracerd::http::Server; fn deref(&self) -> &::libracerd::http::Server { &self.inner } } impl Drop for TestServer { fn drop(&mut self) { self.inner.close().unwrap(); } } pub trait UrlBuilder { /// Given a /url/path, return a full http URL. fn url(&self, path: &str) -> String; } impl UrlBuilder for TestServer { fn url(&self, path: &str) -> String { format!("http://{}{}", self.addr(), path) } } pub fn with_server<F>(mut func: F) where F: FnMut(&TestServer) -> (), { func(&TestServer::new(None)); } pub fn with_hmac_server<F>(secret: &str, mut func: F) where F: FnMut(&TestServer) -> (), { // Make a temp file unique to this test let thread = ::std::thread::current(); let taskname = thread.name().unwrap(); let s = taskname.replace("::", "_"); let mut p = "secretfile.".to_string(); p.push_str(&s[..]); { let mut f = File::create(&p[..]).unwrap(); f.write_all(secret.as_bytes()).unwrap(); f.flush().unwrap(); } func(&TestServer::new(Some(p))); } pub fn request_str( method: Method, url: &str, data: Option<&str>, ) -> ::hyper::Result<Option<String>> { use hyper::header; use hyper::status::StatusClass; use hyper::Client; let mut body = String::new(); let client = Client::new(); println!("url: {}", url); let mut res = match data { Some(inner) => { let builder = client .request(method, url) .header(header::Connection::close()) .header(header::ContentType::json()) .body(inner); builder.send()? } None => { let builder = client .request(method, url) .header(header::Connection::close()); builder.send()? } }; Ok(match res.status.class() { StatusClass::Success => { res.read_to_string(&mut body)?; Some(body) } _ => None, }) } #[test] fn server_url_builder() { with_server(|server| { let url = server.url("/definition"); assert!(url.starts_with("http://")); assert!(url.ends_with("/definition")); }); }
rust
Apache-2.0
e3d380b9a1d3f3b67286d60465746bc89fea9098
2026-01-04T20:20:43.736802Z
false
jwilm/racerd
https://github.com/jwilm/racerd/blob/e3d380b9a1d3f3b67286d60465746bc89fea9098/tests/util/mod.rs
tests/util/mod.rs
use rustc_serialize::hex::ToHex; use crypto::hmac::Hmac; use crypto::mac::Mac; use crypto::sha2::Sha256; #[macro_use] pub mod http; pub fn hmac256(secret: &[u8], data: &[u8]) -> Vec<u8> { let mut hmac = Hmac::new(Sha256::new(), secret); let len = hmac.output_bytes(); let mut result = Vec::with_capacity(len); for _ in 0..len { result.push(0); } hmac.input(data); hmac.raw_result(&mut result[..]); result } pub fn request_hmac(secret_str: &str, method: &str, path: &str, body: &str) -> String { // hmac(hmac(GET) + hmac(/ping) + hmac()) let secret = secret_str.as_bytes(); let method_hmac = hmac256(secret, method.as_bytes()); let path_hmac = hmac256(secret, path.as_bytes()); let body_hmac = hmac256(secret, body.as_bytes()); let mut meta = Hmac::new(Sha256::new(), secret); meta.input(&method_hmac[..]); meta.input(&path_hmac[..]); meta.input(&body_hmac[..]); let len = meta.output_bytes(); let mut result = Vec::with_capacity(len); for _ in 0..len { result.push(0); } meta.raw_result(&mut result[..]); result.to_hex() }
rust
Apache-2.0
e3d380b9a1d3f3b67286d60465746bc89fea9098
2026-01-04T20:20:43.736802Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/tools/benchmarks/3em/evm.rs
tools/benchmarks/3em/evm.rs
use three_em_arweave::arweave::Arweave; use three_em_arweave::cache::ArweaveCache; use three_em_arweave::cache::CacheExt; use three_em_executor::execute_contract; #[tokio::main] async fn main() { let arweave = Arweave::new( 443, "arweave.net".to_string(), String::from("https"), ArweaveCache::new(), ); execute_contract( "_233QEbUxpTpxa_CUbGi3TVEEh2Qao5i_xzp4Lusv8I".to_string(), None, true, false, None, None, &arweave, ) .await .unwrap(); }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/tools/benchmarks/3em/js_mem.rs
tools/benchmarks/3em/js_mem.rs
use std::time::Instant; use three_em_arweave::arweave::Arweave; use three_em_arweave::cache::CacheExt; use three_em_arweave::lru_cache::ArweaveLruCache; use three_em_executor::execute_contract; #[tokio::main] async fn main() { let arweave = Arweave::new( 443, "arweave.net".to_string(), String::from("https"), ArweaveLruCache::new(), ); let mut sum: u128 = 0; const NUM_ITERATIONS: isize = 1_000_000; for i in 0..NUM_ITERATIONS { let now = Instant::now(); execute_contract( "t9T7DIOGxx4VWXoCEeYYarFYeERTpWIC1V3y-BPZgKE".to_string(), Some(749180), true, false, None, None, &arweave, ) .await .unwrap(); let elapsed = now.elapsed(); sum += elapsed.as_nanos(); } let mean = sum / NUM_ITERATIONS as u128; println!("Mean: {:.2} nanoseconds", mean); }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/tools/benchmarks/3em/main_fh.rs
tools/benchmarks/3em/main_fh.rs
use three_em_arweave::arweave::Arweave; use three_em_arweave::cache::ArweaveCache; use three_em_arweave::cache::CacheExt; use three_em_executor::execute_contract; #[tokio::main] async fn main() { let arweave = Arweave::new( 443, "arweave.net".to_string(), String::from("https"), ArweaveCache::new(), ); execute_contract( "t9T7DIOGxx4VWXoCEeYYarFYeERTpWIC1V3y-BPZgKE".to_string(), Some(749180), true, false, None, None, &arweave, ) .await .unwrap(); }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/tools/benchmarks/3em/main.rs
tools/benchmarks/3em/main.rs
use three_em_arweave::arweave::Arweave; use three_em_arweave::cache::ArweaveCache; use three_em_arweave::cache::CacheExt; use three_em_executor::execute_contract; #[tokio::main] async fn main() { let arweave = Arweave::new( 443, "arweave.net".to_string(), String::from("https"), ArweaveCache::new(), ); execute_contract( "t9T7DIOGxx4VWXoCEeYYarFYeERTpWIC1V3y-BPZgKE".to_string(), None, true, false, None, None, &arweave, ) .await .unwrap(); }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/tools/benchmarks/3em/wasm.rs
tools/benchmarks/3em/wasm.rs
use three_em_arweave::arweave::Arweave; use three_em_arweave::cache::ArweaveCache; use three_em_arweave::cache::CacheExt; use three_em_executor::execute_contract; #[tokio::main] async fn main() { let arweave = Arweave::new( 443, "arweave.net".to_string(), String::from("https"), ArweaveCache::new(), ); execute_contract( "KfU_1Uxe3-h2r3tP6ZMfMT-HBFlM887tTFtS-p4edYQ".to_string(), None, true, false, None, None, &arweave, ) .await .unwrap(); }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/benches/wasm.rs
benches/wasm.rs
#[macro_use] extern crate three_em; use std::cell::Cell; use three_em::runtime::smartweave::ContractInfo; use criterion::black_box; use criterion::criterion_group; use criterion::criterion_main; use criterion::Criterion; use deno_core::serde_json; use deno_core::serde_json::json; use std::time::Duration; use three_em::runtime::wasm::WasmRuntime; use wasmer::Universal; use wasmer::{ imports, Function, FunctionType, Instance, MemoryView, Module, Store, Type, }; fn wasmer_bench( instance: Instance, state: &mut [u8], ) -> Result<Vec<u8>, Box<dyn std::error::Error>> { let handle = instance .exports .get_function("handle")? .native::<(u32, u32, u32, u32, u32, u32), u32>()?; let alloc = instance .exports .get_function("_alloc")? .native::<u32, u32>()?; let get_len = instance .exports .get_function("get_len")? .native::<(), u32>()?; let ptr = alloc.call(state.len() as u32)?; let memory = instance.exports.get_memory("memory")?; let mut raw_mem = unsafe { memory.data_unchecked_mut() }; raw_mem[ptr as usize..ptr as usize + state.len()].swap_with_slice(state); let mut info = deno_core::serde_json::to_vec(&ContractInfo::default()).unwrap(); let info_ptr = alloc.call(info.len() as u32)?; let mut action = deno_core::serde_json::to_vec(&deno_core::serde_json::json!({})).unwrap(); let action_ptr = alloc.call(action.len() as u32)?; raw_mem[info_ptr as usize..info_ptr as usize + info.len()] .swap_with_slice(&mut info); raw_mem[action_ptr as usize..action_ptr as usize + action.len()] .swap_with_slice(&mut action); let result_ptr = handle.call( ptr, state.len() as u32, action_ptr, action.len() as u32, info_ptr, info.len() as u32, )? as usize; let view: MemoryView<u8> = memory.view(); let result_len = get_len.call()? as usize; let result = view[result_ptr..result_ptr + result_len] .iter() .map(Cell::get) .collect(); Ok(result) } static BENCH_CONTRACT1: &[u8] = include_bytes!("../wasm_tools/rust/example/contract.wasm"); fn setup_wasmer(store: Store) -> Result<Instance, Box<dyn std::error::Error>> { let module = Module::new(&store, BENCH_CONTRACT1)?; let read_state = FunctionType::new(vec![Type::I32, Type::I32, Type::I32], vec![Type::I32]); let read_state_function = Function::new(&store, &read_state, |_args| { // TODO: How do I even access memory from here? Ok(vec![wasmer::Value::I32(0)]) }); let abort = FunctionType::new(vec![Type::I32, Type::I32, Type::I32, Type::I32], vec![]); let abort = Function::new(&store, &abort, |_args| Ok(vec![])); let import_object = imports! { "3em" => { "smartweave_read_state" => read_state_function, }, "env" => { "abort" => abort, } }; let instance = Instance::new(&module, &import_object)?; Ok(instance) } fn wasm_benchmark(c: &mut Criterion) { let rt = tokio::runtime::Runtime::new().unwrap(); let mut group = c.benchmark_group("WASM"); group.measurement_time(Duration::from_secs(20)); group.bench_function("wasmer (default)", |b| { b.to_async(&rt).iter_with_setup( || { let mut state = json!({ "counter": 0, }); let store = Store::default(); (deno_core::serde_json::to_vec(&state).unwrap(), store) }, |(state_bytes, store)| async { let mut state = state_bytes; let instance = setup_wasmer(store).unwrap(); black_box(wasmer_bench(instance, &mut state).unwrap()); }, ) }); group.bench_function("wasmer (singlepass)", |b| { b.to_async(&rt).iter_with_setup( || { let mut state = json!({ "counter": 0, }); let compiler = wasmer_compiler_singlepass::Singlepass::new(); let store = Store::new(&Universal::new(compiler).engine()); (deno_core::serde_json::to_vec(&state).unwrap(), store) }, |(state_bytes, store)| async { let mut state = state_bytes; let instance = setup_wasmer(store).unwrap(); black_box(wasmer_bench(instance, &mut state).unwrap()); }, ) }); group.bench_function("v8", |b| { b.to_async(&rt).iter_with_setup( || { let state = json!({ "counter": 0, }); let state_bytes = serde_json::to_vec(&state).unwrap(); let action = json!({}); let action_bytes = serde_json::to_vec(&action).unwrap(); let mut rt = WasmRuntime::new(BENCH_CONTRACT1, Default::default()).unwrap(); (state_bytes, action_bytes, rt) }, |(state_bytes, action_bytes, mut rt)| async move { let mut state = state_bytes; let mut action = action_bytes; black_box(rt.call(&mut state, &mut action).unwrap()); }, ) }); group.finish(); } criterion_group!(benches, wasm_benchmark); criterion_main!(benches);
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/wasm_tools/rust/src/lib.rs
wasm_tools/rust/src/lib.rs
use std::panic; pub use three_em_macro::*; pub mod alloc; #[link(wasm_import_module = "3em")] extern "C" { fn throw_error(ptr: *const u8, len: usize); } #[no_mangle] pub fn panic_hook(info: &panic::PanicInfo) { let payload = info.payload(); let payload_str = match payload.downcast_ref::<&str>() { Some(s) => s, None => match payload.downcast_ref::<String>() { Some(s) => s, None => "Box<Any>", }, }; let msg = format!("{}", payload_str); let msg_ptr = msg.as_ptr(); let msg_len = msg.len(); unsafe { throw_error(msg_ptr, msg_len); } std::mem::forget(msg); }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/wasm_tools/rust/src/alloc.rs
wasm_tools/rust/src/alloc.rs
//! Allocator APIs exposed to the host. use ::std::alloc::alloc; use ::std::alloc::dealloc; use ::std::alloc::Layout; use ::std::mem::align_of; #[no_mangle] pub unsafe fn contract_alloc(len: usize) -> *mut u8 { let align = align_of::<usize>(); let layout = Layout::from_size_align_unchecked(len, align); alloc(layout) } #[no_mangle] pub unsafe fn contract_dealloc(ptr: *mut u8, size: usize) { let align = align_of::<usize>(); let layout = Layout::from_size_align_unchecked(size, align); dealloc(ptr, layout); }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/wasm_tools/rust/proc_macro/src/lib.rs
wasm_tools/rust/proc_macro/src/lib.rs
use proc_macro::TokenStream; use syn::ItemFn; use quote::quote; #[proc_macro_attribute] pub fn handler(_attr: TokenStream, input: TokenStream) -> TokenStream { let func = syn::parse::<ItemFn>(input).unwrap(); let fn_inputs = &func.sig.inputs; let fn_output = &func.sig.output; let fn_generics = &func.sig.generics; let fn_block = &func.block; TokenStream::from(quote! { use ::std::panic; use ::std::sync::Once; use ::three_em::alloc::*; use ::three_em::*; #[link(wasm_import_module = "3em")] extern "C" { fn smartweave_read_state( // `ptr` is the pointer to the base64 URL encoded sha256 txid. ptr: *const u8, ptr_len: usize, // Pointer to the 4 byte array to store the length of the state. result_len_ptr: *mut u8, ) -> *mut u8; } static mut LEN: usize = 0; #[no_mangle] pub unsafe fn _alloc(len: usize) -> *mut u8 { contract_alloc(len) } #[no_mangle] pub unsafe fn _dealloc(ptr: *mut u8, size: usize) { contract_dealloc(ptr, size) } #[no_mangle] pub extern "C" fn get_len() -> usize { unsafe { LEN } } #[no_mangle] pub extern "C" fn handle( state: *mut u8, state_size: usize, action: *mut u8, action_size: usize, contract_info: *mut u8, contract_info_size: usize, ) -> *const u8 { static SET_HOOK: Once = Once::new(); SET_HOOK.call_once(|| { panic::set_hook(Box::new(panic_hook)); }); let state_buf = unsafe { Vec::from_raw_parts(state, state_size, state_size) }; let action_buf = unsafe { Vec::from_raw_parts(action, action_size, action_size) }; fn __inner_handler #fn_generics (#fn_inputs) #fn_output #fn_block let output_state = __inner_handler( serde_json::from_slice(&state_buf).unwrap(), serde_json::from_slice(&action_buf).unwrap(), ); let output_buf = serde_json::to_vec(&output_state).unwrap(); let output = output_buf.as_slice().as_ptr(); unsafe { LEN = output_buf.len(); } ::std::mem::forget(state_buf); output } }) }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/wasm_tools/rust/example/contract.rs
wasm_tools/rust/example/contract.rs
use serde::Deserialize; use serde::Serialize; use three_em::handler; #[derive(Serialize, Deserialize)] pub struct State { counter: i32, } #[derive(Deserialize)] pub struct Action {} #[handler] pub fn handle(state: State, _action: Action) -> State { State { counter: state.counter + 1, } }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/js/evm/lib.rs
js/evm/lib.rs
use evm::Instruction; use evm::Machine; use evm::U256; use std::alloc::Layout; fn dummy_cost_fn(_: &Instruction) -> U256 { U256::zero() } #[no_mangle] pub extern "C" fn machine_new() -> *mut Machine<'static> { Box::into_raw(Box::new(Machine::new(dummy_cost_fn))) } #[no_mangle] pub extern "C" fn machine_new_with_data( data: *mut u8, data_len: usize, ) -> *mut Machine<'static> { let data = unsafe { Vec::from_raw_parts(data, data_len, data_len) }; Box::into_raw(Box::new(Machine::new_with_data(dummy_cost_fn, data))) } #[no_mangle] pub extern "C" fn machine_free(machine: *mut Machine) { unsafe { Box::from_raw(machine); } } #[no_mangle] pub extern "C" fn machine_result(machine: *mut Machine) -> *const u8 { let machine = unsafe { Box::from_raw(machine) }; let ptr = machine.result.as_ptr(); Box::leak(machine); ptr } #[no_mangle] pub extern "C" fn machine_result_len(machine: *mut Machine) -> usize { let machine = unsafe { Box::from_raw(machine) }; let length = machine.result.len(); Box::leak(machine); length } #[no_mangle] pub extern "C" fn machine_execute( machine: *mut Machine, ptr: *const u8, length: usize, ) -> *mut Machine { let mut machine = unsafe { Box::from_raw(machine) }; let bytecode = unsafe { std::slice::from_raw_parts(ptr, length) }; let status = machine.execute(bytecode, Default::default()); if status != evm::ExecutionState::Ok { panic!("Execution failed"); } Box::into_raw(machine) } #[no_mangle] pub unsafe fn alloc(len: usize) -> *mut u8 { let align = std::mem::align_of::<usize>(); let layout = Layout::from_size_align_unchecked(len, align); std::alloc::alloc(layout) }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/js/napi/build.rs
js/napi/build.rs
fn main() { napi_build::setup(); }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/js/napi/src/lib.rs
js/napi/src/lib.rs
use napi::bindgen_prelude::*; use napi::sys::{napi_env, napi_value}; use napi_derive::napi; use serde_json::Value; use std::collections::HashMap; use std::panic; use three_em_arweave::arweave::{Arweave, ManualLoadedContract}; use three_em_arweave::cache::ArweaveCache; use three_em_arweave::cache::CacheExt; use three_em_arweave::gql_result::{GQLEdgeInterface, GQLTagInterface}; use three_em_arweave::miscellaneous::ContractType; use three_em_executor::execute_contract as execute; use three_em_executor::simulate_contract as simulate; use three_em_executor::utils::create_simulated_transaction; use three_em_executor::ExecuteResult; use three_em_executor::ValidityTable; use tokio::runtime::Handle; #[cfg(target_os = "macos")] #[global_allocator] static GLOBAL: jemallocator::Jemalloc = jemallocator::Jemalloc; #[napi(object)] pub struct ExecuteContractResult { pub state: serde_json::Value, pub result: serde_json::Value, pub validity: HashMap<String, serde_json::Value>, pub exm_context: serde_json::Value, pub updated: bool, pub errors: HashMap<String, String>, } #[napi(object)] pub struct ExecuteConfig { pub host: String, pub port: i32, pub protocol: String, } #[napi(object)] pub struct Tag { pub name: String, pub value: String, } #[napi(object)] pub struct Block { pub height: String, pub indep_hash: String, pub timestamp: String, } #[napi(object)] pub struct SimulateInput { pub id: String, pub owner: String, pub quantity: String, pub reward: String, pub target: Option<String>, pub tags: Vec<Tag>, pub block: Option<Block>, pub input: String, } #[napi(object)] pub enum SimulateContractType { JAVASCRIPT, WASM, } #[napi(object)] pub struct ContractSource { pub contract_src: Buffer, pub contract_type: SimulateContractType, } #[napi(object)] pub struct SimulateExecutionContext { pub contract_id: String, pub maybe_contract_source: Option<ContractSource>, pub interactions: Vec<SimulateInput>, pub contract_init_state: Option<String>, pub maybe_config: Option<ExecuteConfig>, pub maybe_cache: Option<bool>, pub maybe_bundled_contract: Option<bool>, pub maybe_settings: Option<HashMap<String, serde_json::Value>>, pub maybe_exm_context: Option<String>, } // Convert the ValidityTable from an IndexMap to HashMap #[inline] fn validity_to_hashmap( table: ValidityTable, ) -> HashMap<String, serde_json::Value> { let mut map = HashMap::new(); for (k, v) in table { map.insert(k, v); } map } fn get_gateway( maybe_config: Option<ExecuteConfig>, use_cache: Option<bool>, ) -> Arweave { let arweave_gateway = maybe_config .as_ref() .map(|item| item.host.to_owned()) .unwrap_or("arweave.net".to_string()); let arweave_protocol = maybe_config .as_ref() .map(|item| item.protocol.to_owned()) .unwrap_or("https".to_string()); let arweave_port = maybe_config .as_ref() .map(|item| item.port) .unwrap_or(443 as i32); let use_cache_bool = use_cache.unwrap_or(true); if use_cache_bool { Arweave::new( arweave_port, arweave_gateway, arweave_protocol, ArweaveCache::new(), ) } else { Arweave::new_no_cache(arweave_port, arweave_gateway, arweave_protocol) } } fn get_result( process_result: std::result::Result< ExecuteResult, three_em_arweave::miscellaneous::CommonError, >, ) -> Option<ExecuteContractResult> { if process_result.is_ok() { match process_result.unwrap() { ExecuteResult::V8(data) => { let (state, result, validity, exm_context, errors) = ( data.state, data.result.unwrap_or(Value::Null), data.validity, data.context, data.errors, ); Some(ExecuteContractResult { state, result, validity: validity_to_hashmap(validity), exm_context: serde_json::to_value(exm_context).unwrap(), updated: data.updated, errors, }) } ExecuteResult::Evm(..) => todo!(), } } else { process_result.unwrap(); None } } #[napi] async fn simulate_contract( context: SimulateExecutionContext, ) -> Result<ExecuteContractResult> { let SimulateExecutionContext { contract_id, interactions, contract_init_state, maybe_config, maybe_cache, maybe_bundled_contract, maybe_settings, maybe_exm_context, maybe_contract_source, } = context; let result = tokio::task::spawn_blocking(move || { panic::catch_unwind(|| { Handle::current().block_on(async move { let arweave = get_gateway(maybe_config, maybe_cache.clone()); let real_interactions: Vec<GQLEdgeInterface> = interactions .into_iter() .map(|data| { let tags: Vec<GQLTagInterface> = data .tags .into_iter() .map(|tag| GQLTagInterface { name: tag.name.to_string(), value: tag.value.to_string(), }) .collect::<Vec<GQLTagInterface>>(); let (height, timestamp, indep_hash) = if let Some(block_data) = data.block { ( Some(block_data.height), Some(block_data.timestamp), Some(block_data.indep_hash), ) } else { (None, None, None) }; let transaction = create_simulated_transaction( data.id, data.owner, data.quantity, data.reward, data.target, tags, height, indep_hash, timestamp, data.input, ); transaction }) .collect(); let manual_loaded_contract = { if let Some(contract_source) = maybe_contract_source { let loaded_contract = ManualLoadedContract { contract_src: contract_source.contract_src.into(), contract_type: match contract_source.contract_type { SimulateContractType::JAVASCRIPT => ContractType::JAVASCRIPT, SimulateContractType::WASM => ContractType::WASM, }, }; Some(loaded_contract) } else { None } }; let result = simulate( contract_id, contract_init_state, real_interactions, &arweave, maybe_cache, maybe_bundled_contract, maybe_settings, maybe_exm_context, manual_loaded_contract, ) .await; get_result(result) }) }) }) .await; if let Ok(catcher) = result { if let Ok(processing) = catcher { if let Some(result) = processing { return Ok(result); } } } return Err(Error::new( Status::Unknown, "Contract could not be processed".to_string(), )); } #[napi] async fn execute_contract( tx: String, maybe_height: Option<u32>, maybe_config: Option<ExecuteConfig>, ) -> Result<ExecuteContractResult> { let result = tokio::task::spawn_blocking(move || { Handle::current().block_on(async move { let arweave = get_gateway(maybe_config, None); let result = execute( tx, maybe_height.map(|h| h as usize), true, false, None, None, &arweave, ) .await; get_result(result) }) }) .await .unwrap(); if let Some(result) = result { Ok(result) } else { Err(Error::new( Status::Unknown, "Contract could not be processed".to_string(), )) } } #[cfg(test)] mod tests { use crate::{ execute_contract, get_gateway, simulate_contract, ContractSource, ExecuteConfig, SimulateContractType, SimulateExecutionContext, SimulateInput, }; use std::collections::HashMap; use three_em_arweave::arweave::get_cache; // #[tokio::test(flavor = "multi_thread", worker_threads = 1)] // #[should_panic] // pub async fn no_cache_test() { // get_gateway(None, Some(false)); // get_cache(); // } #[tokio::test] pub async fn with_cache_test() { get_gateway(None, None); get_cache(); } // #[tokio::test] // pub async fn test_execute_contract() { // let contract = execute_contract( // String::from("yAovBvlYWiIBx6i7hPSo2f5hNJpG6Wdq4eDyiudm1_M"), // None, // Some(ExecuteConfig { // host: String::from("www.arweave.run"), // port: 443, // protocol: String::from("https"), // }), // ) // .await; // let contract_result = contract.unwrap().state; // println!("{}", contract_result); // assert_eq!( // contract_result.get("name").unwrap().as_str().unwrap(), // "VERTO" // ); // } #[tokio::test] pub async fn simulate_contract_test() { let execution_context: SimulateExecutionContext = SimulateExecutionContext { contract_id: "KfU_1Uxe3-h2r3tP6ZMfMT-HBFlM887tTFtS-p4edYQ".into(), interactions: vec![SimulateInput { id: String::from("abcd"), owner: String::from("210392sdaspd-asdm-asd_sa0d1293-lc"), quantity: String::from("12301"), reward: String::from("12931293"), target: None, tags: vec![], block: None, input: serde_json::json!({}).to_string(), }], contract_init_state: Some(r#"{"counter": 2481}"#.into()), maybe_config: None, maybe_cache: Some(false), maybe_bundled_contract: None, maybe_settings: None, maybe_exm_context: None, maybe_contract_source: None, }; let contract = simulate_contract(execution_context).await.unwrap(); let contract_result = contract.state; println!("{}", contract_result); assert_eq!(contract_result.get("counter").unwrap(), 2482); } #[tokio::test] pub async fn simulate_counter_failure() { let contract_source_bytes = include_bytes!("../../../testdata/contracts/counter_error.js"); let contract_source_vec = contract_source_bytes.to_vec(); let execution_context: SimulateExecutionContext = SimulateExecutionContext { contract_id: String::new(), interactions: vec![ SimulateInput { id: String::from("abcd"), owner: String::from("210392sdaspd-asdm-asd_sa0d1293-lc"), quantity: String::from("12301"), reward: String::from("12931293"), target: None, tags: vec![], block: None, input: serde_json::json!({}).to_string(), }, SimulateInput { id: String::from("abcd"), owner: String::from("210392sdaspd-asdm-asd_sa0d1293-lc"), quantity: String::from("12301"), reward: String::from("12931293"), target: None, tags: vec![], block: None, input: serde_json::json!({}).to_string(), }, ], contract_init_state: Some(r#"{"counts": 0}"#.into()), maybe_config: None, maybe_cache: Some(false), maybe_bundled_contract: None, maybe_settings: None, maybe_exm_context: None, maybe_contract_source: Some(ContractSource { contract_src: contract_source_vec.into(), contract_type: SimulateContractType::JAVASCRIPT, }), }; let contract = simulate_contract(execution_context).await.unwrap(); assert_eq!(contract.errors.len(), 1); } #[tokio::test] pub async fn simulate_contract_test_bundled() { let execution_context: SimulateExecutionContext = SimulateExecutionContext { contract_id: "RadpzdYtVrQiS25JR1hGxZppwCXVCel_nfXk-noyFmc".into(), interactions: vec![ SimulateInput { id: String::from("abcd"), owner: String::from("210392sdaspd-asdm-asd_sa0d1293-lc"), quantity: String::from("12301"), reward: String::from("12931293"), target: None, tags: vec![], block: None, input: serde_json::json!({}).to_string(), }, SimulateInput { id: String::from("abcd"), owner: String::from("210392sdaspd-asdm-asd_sa0d1293-lc"), quantity: String::from("12301"), reward: String::from("12931293"), target: None, tags: vec![], block: None, input: serde_json::json!({}).to_string(), }, ], contract_init_state: Some(r#"2"#.into()), maybe_config: None, maybe_cache: Some(false), maybe_bundled_contract: Some(true), maybe_settings: None, maybe_exm_context: None, maybe_contract_source: None, }; let contract = simulate_contract(execution_context).await.unwrap(); let contract_result = contract.state; println!("{}", contract_result); assert_eq!(contract_result, 4); } #[tokio::test] pub async fn simulate_contract_test_custom_source() { let contract_source_bytes = include_bytes!("../../../testdata/contracts/user-registry2.js"); let contract_source_vec = contract_source_bytes.to_vec(); let execution_context: SimulateExecutionContext = SimulateExecutionContext { contract_id: String::new(), interactions: vec![SimulateInput { id: String::from("abcd"), owner: String::from("210392sdaspd-asdm-asd_sa0d1293-lc"), quantity: String::from("12301"), reward: String::from("12931293"), target: None, tags: vec![], block: None, input: serde_json::json!({ "username": "Andres" }) .to_string(), }], contract_init_state: Some(r#"{"users": []}"#.into()), maybe_config: None, maybe_cache: Some(false), maybe_bundled_contract: None, maybe_settings: None, maybe_exm_context: None, maybe_contract_source: Some(ContractSource { contract_src: contract_source_vec.into(), contract_type: SimulateContractType::JAVASCRIPT, }), }; let contract = simulate_contract(execution_context).await.unwrap(); let contract_result = contract.state; println!("{}", contract_result); assert_eq!( contract_result.get("users").unwrap(), &serde_json::json!([{"username": "Andres"}]) ); assert_eq!(contract.result.as_str().unwrap(), "Hello World"); assert_eq!(contract.updated, true); } //NOTE: Fix assert statements within _validateMintingFeeTest in ans.js #[tokio::test] pub async fn simulate_contract_ans() { let contract_source_bytes = include_bytes!("../../../testdata/contracts/ans.js"); let contract_source_vec = contract_source_bytes.to_vec(); let execution_context: SimulateExecutionContext = SimulateExecutionContext { contract_id: String::new(), interactions: vec![SimulateInput { id: String::from("abcd"), owner: String::from("210392sdaspd-asdm-asd_sa0d1293-lc"), quantity: String::from("12301"), reward: String::from("12931293"), target: None, tags: vec![], block: None, input: serde_json::json!({"jwk_n":"iwLlbpT6b7rYOV6aJTTeSD5wXdqZYwYBGphdOclGeftR3wJcLp5OzWrQqexbfpvi-CBkxz0yroX4Of9Ikv_qoakIoz1qQsQztD2UR2MI6SAvbGPn8swKL7QId2OtyRtOJ3TAEuULt1lpA0nj67dOKNq-2HyhDyuCaZ6TTC2Luk5QUrqWKs9ix8xBNM_O20lmRGgDsrhNtTMca2tnkCk4JffGrEDVsF6iRM4Ls_KOcrAJlsrpSypi2M7O4rQkcyWaBerXomtkj4I5KBXnr5J9_sdLS-2esAHzpArNA2gnYi8aqtlJgSYWAX9TTItqjszK6kIIBlPJCMn7K1a4p2kJilJpOsPY9VFaPP5B5_ie2V87_6xpqgmMMjBzc2zS9MBkg55JP-sImXBMJQAvL89muSYIDAdqh8Z6dIEiwIGnnWHCbZKsPjkDV3Cmx1br4zx73Kp6fYD7lTNuFriKcRo7z7rcfdE5qJ-pamSpXZhEo1q4J08ZihOuA1LrvDuLrTwVMam_r0E5WJKHg28w2LD7pMgSUb7vhbMLTNSLMcvC19Tip2bBosfmX79tPoW0UQ5lUx1IykdIuARp6LTV5g8nESnxoAnRiBEQgJffXuMhnDbLu6lW_aoYRWM_uwGEu2So4a584mCc0ziNKb9ZfvmLxWS4M1NJd6Lnt9hHTkBxq-8","sig":"GZ0vreib6rUv/rG488ZdzFtIFiLWes2gptzRlX1p4fBebORurdShCPtQWvgXn3J9wTncnveuDLO2nK57gcliwqXYxSetWoJnyn5y4KeKWU3+zA+QUKoMntOu66XY3SF09taUMAfpDi73wOtBbN2vo+SR3NVjsxx3ibit2zannAOOf49CZABH6B2EujaVklv1pczfAzrVQPVU1z+XpGb7O1ydv380vc/gWT3yBduIjZLCvD3d8BK+6x3kLji8NsnqfFDTPCSVR11mZwedUGEVvG1ONYmxt7y8a5RZLWbdI2GeUroeOuimsUBqzPVORZ0ZH9vzpQ1lbHORYEvbpmq0wVn8w+kA5s9Z03S15y86ZX1260PangBLCOTUi8gZneKdByUkp18rl37XeH2CdBlkRrANdJZH/X3g0WUOkYEqSaVkw9zXO+a/sUmoDVGW6cqmdxN0ltJpLNd98nuDCHbS0FIIa9ksNwsQlnK5V/tZP+9Skw/lCBip6R8HKoRZhLuAsmh6k0eOKUFXJ7Objf40/+GvUGyNDJRxwtIvzQkTdALKNRDKNhhS4Kk8RH0ZhUIOhQHufg3HNaO3HmZeIOuo4pIOe1rma6oE4kiB8o7Je59I05d9PYIBgx619qMIWrRnc9z3sm/oPZvTNeLEL1G+46UVLe5MPkYpcXuQBzNe8ps=","txid":"0x7d07008ae820b889ad406142e5043dfd8d9ba6d9723fbef78a4c69ed294a65eb","mint_domain":"wearemintingyes", "function": "mint"}) .to_string(), }], contract_init_state: Some(String::from(include_str!("../../../testdata/contracts/ans.json"))), maybe_config: None, maybe_cache: Some(false), maybe_bundled_contract: None, maybe_settings: None, maybe_exm_context: None, maybe_contract_source: Some(ContractSource { contract_src: contract_source_vec.into(), contract_type: SimulateContractType::JAVASCRIPT, }), }; let contract = simulate_contract(execution_context).await.unwrap(); let contract_result = contract.state; let str_state = contract_result.to_string(); //println!("STATUS::::: {:#?}", str_state.contains("wearemintingyes")); assert!(str_state.contains("wearemintingyes")); } #[tokio::test] pub async fn simulate_contract_ark() { let contract_source_bytes = include_bytes!("../../../testdata/contracts/ark.js"); let contract_source_vec = contract_source_bytes.to_vec(); let execution_context: SimulateExecutionContext = SimulateExecutionContext { contract_id: String::new(), interactions: vec![SimulateInput { id: String::from("abcd"), owner: String::from("210392sdaspd-asdm-asd_sa0d1293-lc"), quantity: String::from("12301"), reward: String::from("12931293"), target: None, tags: vec![], block: None, input: serde_json::json!({ "function": "createContainer", "caller_address": "0x197f818c1313dc58b32d88078ecdfb40ea822614", "type": "evm", "label": "test-evm", "sig": "0x0e8cda3652185efcb9e68cbd932836c46df14dcf3b052931f463f0cd189a0fdd619206accafbb44afc155ce1c629da2eda4370fd71376ad250f28b50711b112b1c" }).to_string(), }], contract_init_state: Some(String::from(include_str!("../../../testdata/contracts/ark.json"))), maybe_config: None, maybe_cache: Some(false), maybe_bundled_contract: None, maybe_settings: None, maybe_exm_context: None, maybe_contract_source: Some(ContractSource { contract_src: contract_source_vec.into(), contract_type: SimulateContractType::JAVASCRIPT, }), }; let contract = simulate_contract(execution_context).await.unwrap(); assert_eq!(contract.errors.len(), 0); let contract_result = contract.state; let str_state = contract_result.to_string(); } #[tokio::test] pub async fn simulate_deterministic_fetch_lazy() { let mut sets: HashMap<String, serde_json::Value> = HashMap::new(); sets.insert("LAZY_EVALUATION".to_string(), serde_json::Value::Bool(true)); let contract_source_bytes = include_bytes!("../../../testdata/contracts/deterministic-fetch.js"); let contract_source_vec = contract_source_bytes.to_vec(); let execution_context: SimulateExecutionContext = SimulateExecutionContext { contract_id: String::new(), interactions: vec![SimulateInput { id: String::from("abcd"), owner: String::from("210392sdaspd-asdm-asd_sa0d1293-lc"), quantity: String::from("12301"), reward: String::from("12931293"), target: None, tags: vec![], block: None, input: serde_json::json!({"id":"8f39fb4940c084460da00a876a521ef2ba84ad6ea8d2f5628c9f1f8aeb395342"}).to_string(), }], contract_init_state: Some(String::from(include_str!("../../../testdata/contracts/deterministic-fetch.json"))), maybe_config: None, maybe_cache: Some(false), maybe_bundled_contract: None, maybe_settings: Some(sets), maybe_exm_context: Some((r#"{"requests":{"d1b57dac5f734a8831b808bdd5dfdb9cd0d12a56014190982ce744d99a9a661c":{"type":"basic","url":"https://api.blockcypher.com/v1/eth/main/txs/8f39fb4940c084460da00a876a521ef2ba84ad6ea8d2f5628c9f1f8aeb395342","statusText":"OK","status":127,"redirected":false,"ok":true,"headers":{"x-ratelimit-remaining":"99","access-control-allow-methods":"GET, POST, PUT, DELETE","server":"cloudflare","cf-cache-status":"DYNAMIC","access-control-allow-origin":"*","content-type":"application/json","date":"Tue, 21 Mar 2023 18:14:43 GMT","access-control-allow-headers":"Origin, X-Requested-With, Content-Type, Accept","cf-ray":"7ab82d1aed372937-ORD-X"},"vector":[123,10,32,32,34,98,108,111,99,107,95,104,97,115,104,34,58,32,34,98,51,53,50,54,53,57,54,53,102,54,102,49,52,99,53,100,54,57,50,98,50,48,51,48,57,50,50,102,99,101,53,51,48,54,55,102,99,48,101,57,100,56,99,56,52,57,48,99,51,49,100,52,101,99,100,51,101,52,54,53,48,48,99,34,44,10,32,32,34,98,108,111,99,107,95,104,101,105,103,104,116,34,58,32,49,53,54,52,48,52,48,44,10,32,32,34,98,108,111,99,107,95,105,110,100,101,120,34,58,32,48,44,10,32,32,34,104,97,115,104,34,58,32,34,56,102,51,57,102,98,52,57,52,48,99,48,56,52,52,54,48,100,97,48,48,97,56,55,54,97,53,50,49,101,102,50,98,97,56,52,97,100,54,101,97,56,100,50,102,53,54,50,56,99,57,102,49,102,56,97,101,98,51,57,53,51,52,50,34,44,10,32,32,34,97,100,100,114,101,115,115,101,115,34,58,32,91,10,32,32,32,32,34,52,101,57,100,56,98,52,102,49,56,100,57,56,52,102,54,102,48,99,56,56,100,48,55,101,52,98,51,57,50,48,49,101,56,50,53,99,100,49,55,34,44,10,32,32,32,32,34,55,51,56,100,49,52,53,102,97,97,98,98,49,101,48,48,99,102,53,97,48,49,55,53,56,56,97,57,99,48,102,57,57,56,51,49,56,48,49,50,34,10,32,32,93,44,10,32,32,34,116,111,116,97,108,34,58,32,49,48,49,53,51,49,53,51,51,53,57,52,51,55,51,50,54,44,10,32,32,34,102,101,101,115,34,58,32,49,53,57,53,53,56,48,48,48,48,48,48,48,48,48,48,44,10,32,32,34,115,105,122,101,34,58,32,49,49,54,44,10,32,32,34,103,97,115,95,108,105,109,105,116,34,58,32,53,48,48,48,48,48,44,10,32,32,34,103,97,115,95,117,115,101,100,34,58,32,55,57,55,55,57,44,10,32,32,34,103,97,115,95,112,114,105,99,101,34,58,32,50,48,48,48,48,48,48,48,48,48,48,44,10,32,32,34,103,97,115,95,116,105,112,95,99,97,112,34,58,32,50,48,48,48,48,48,48,48,48,48,48,44,10,32,32,34,103,97,115,95,102,101,101,95,99,97,112,34,58,32,50,48,48,48,48,48,48,48,48,48,48,44,10,32,32,34,99,111,110,102,105,114,109,101,100,34,58,32,34,50,48,49,54,45,48,53,45,50,50,84,49,50,58,52,51,58,48,48,90,34,44,10,32,32,34,114,101,99,101,105,118,101,100,34,58,32,34,50,48,49,54,45,48,53,45,50,50,84,49,50,58,52,51,58,48,48,90,34,44,10,32,32,34,118,101,114,34,58,32,48,44,10,32,32,34,100,111,117,98,108,101,95,115,112,101,110,100,34,58,32,102,97,108,115,101,44,10,32,32,34,118,105,110,95,115,122,34,58,32,49,44,10,32,32,34,118,111,117,116,95,115,122,34,58,32,49,44,10,32,32,34,105,110,116,101,114,110,97,108,95,116,120,105,100,115,34,58,32,91,10,32,32,32,32,34,100,100,49,48,55,99,56,52,56,56,56,54,55,102,100,53,51,99,48,97,97,51,98,102,49,100,56,97,52,55,56,97,48,55,55,101,99,54,55,97,102,55,53,56,52,50,100,50,52,102,49,97,54,52,101,98,52,52,101,52,100,57,48,50,34,44,10,32,32,32,32,34,57,97,57,56,54,55,56,100,50,48,57,57,49,48,102,55,48,98,100,101,100,54,50,52,102,50,99,53,99,49,56,101,100,49,55,100,52,49,55,55,53,50,48,55,50,100,52,49,99,53,100,54,49,98,52,50,99,50,55,55,51,52,56,99,34,44,10,32,32,32,32,34,97,100,57,53,57,57,54,49,102,52,54,54,54,51,102,55,56,53,101,49,101,48,97,48,98,50,54,53,54,57,54,48,98,53,100,50,55,48,54,49,48,57,55,99,53,48,57,50,99,52,101,54,56,57,54,52,98,102,97,102,48,48,52,49,34,44,10,32,32,32,32,34,53,97,50,51,100,55,52,97,52,56,52,101,99,53,56,98,50,49,49,50,54,52,56,56,56,56,52,54,98,101,54,100,55,52,50,56,99,51,51,98,101,57,51,50,50,51,51,57,54,101,102,102,51,54,50,54,101,48,51,54,97,55,102,52,34,44,10,32,32,32,32,34,55,51,57,48,54,98,50,102,49,97,49,100,55,102,100,49,55,99,55,55,54,56,52,101,53,101,56,49,49,97,101,56,55,49,48,101,52,97,48,51,50,53,48,49,48,57,48,100,97,50,54,52,55,49,50,100,98,55,97,52,56,101,55,97,34,44,10,32,32,32,32,34,53,51,99,101,56,56,101,49,99,102,57,56,98,51,55,102,98,54,52,99,49,54,49,50,49,98,52,54,52,49,100,100,101,54,53,50,57,48,56,51,56,99,101,48,98,100,101,54,99,98,49,99,51,49,57,100,102,51,101,102,56,102,102,57,34,44,10,32,32,32,32,34,50,57,98,99,52,101,55,102,97,50,100,98,50,56,98,48,97,50,101,102,57,101,55,97,53,101,48,55,51,99,99,55,53,51,50,101,54,48,57,102,55,53,50,98,50,101,98,48,98,53,55,51,49,98,48,99,54,98,57,50,54,97,50,99,34,44,10,32,32,32,32,34,52,97,57,97,102,99,53,97,54,56,48,57,49,55,57,53,53,101,55,56,49,98,56,57,48,54,56,56,49,52,51,102,53,54,98,97,100,99,55,54,55,56,53,97,102,57,56,55,53,51,100,53,50,54,55,50,55,48,100,55,100,56,48,57,34,10,32,32,93,44,10,32,32,34,99,111,110,102,105,114,109,97,116,105,111,110,115,34,58,32,49,53,51,49,51,54,56,48,44,10,32,32,34,99,111,110,102,105,100,101,110,99,101,34,58,32,49,44,10,32,32,34,105,110,112,117,116,115,34,58,32,91,10,32,32,32,32,123,10,32,32,32,32,32,32,34,115,101,113,117,101,110,99,101,34,58,32,50,55,51,44,10,32,32,32,32,32,32,34,97,100,100,114,101,115,115,101,115,34,58,32,91,10,32,32,32,32,32,32,32,32,34,55,51,56,100,49,52,53,102,97,97,98,98,49,101,48,48,99,102,53,97,48,49,55,53,56,56,97,57,99,48,102,57,57,56,51,49,56,48,49,50,34,10,32,32,32,32,32,32,93,10,32,32,32,32,125,10,32,32,93,44,10,32,32,34,111,117,116,112,117,116,115,34,58,32,91,10,32,32,32,32,123,10,32,32,32,32,32,32,34,118,97,108,117,101,34,58,32,49,48,49,53,51,49,53,51,51,53,57,52,51,55,51,50,54,44,10,32,32,32,32,32,32,34,115,99,114,105,112,116,34,58,32,34,52,101,55,49,100,57,50,100,34,44,10,32,32,32,32,32,32,34,97,100,100,114,101,115,115,101,115,34,58,32,91,10,32,32,32,32,32,32,32,32,34,52,101,57,100,56,98,52,102,49,56,100,57,56,52,102,54,102,48,99,56,56,100,48,55,101,52,98,51,57,50,48,49,101,56,50,53,99,100,49,55,34,10,32,32,32,32,32,32,93,10,32,32,32,32,125,10,32,32,93,10,125]}}}"#).to_string()), maybe_contract_source: Some(ContractSource { contract_src: contract_source_vec.into(), contract_type: SimulateContractType::JAVASCRIPT, }), }; let contract = simulate_contract(execution_context).await.unwrap(); //println!("{}", contract.state); } #[tokio::test] pub async fn simulate_kv() { let contract_source_bytes = include_bytes!("../../../testdata/contracts/kv.js"); let contract_source_vec = contract_source_bytes.to_vec(); let execution_context: SimulateExecutionContext = SimulateExecutionContext { contract_id: String::new(), interactions: vec![SimulateInput { id: String::from("abcd"), owner: String::from("210392sdaspd-asdm-asd_sa0d1293-lc"), quantity: String::from("12301"), reward: String::from("12931293"), target: None, tags: vec![], block: None, input: serde_json::json!({ "key": "Name", "value": "Andres" }) .to_string(), }], contract_init_state: Some(r#"{"users": []}"#.into()), maybe_config: None, maybe_cache: Some(false), maybe_bundled_contract: None, maybe_settings: None, maybe_exm_context: Some(r#"{"requests": {}, "kv": {"Pre-key": "prevalue"}}"#.into()), maybe_contract_source: Some(ContractSource { contract_src: contract_source_vec.into(), contract_type: SimulateContractType::JAVASCRIPT, }), }; let contract = simulate_contract(execution_context).await.unwrap(); //println!("{}", contract.exm_context); assert_eq!(contract.exm_context.to_string().contains("Name"), true); } #[tokio::test] pub async fn simulate_kv_del() { let contract_source_bytes = include_bytes!("../../../testdata/contracts/delKv.js"); let contract_source_vec = contract_source_bytes.to_vec(); let execution_context: SimulateExecutionContext = SimulateExecutionContext { contract_id: String::new(), interactions: vec![SimulateInput { id: String::from("abcd"), owner: String::from("210392sdaspd-asdm-asd_sa0d1293-lc"), quantity: String::from("12301"), reward: String::from("12931293"), target: None, tags: vec![], block: None, input: serde_json::json!({ "key": "Name", "value": "" }) .to_string(), }], contract_init_state: Some(r#"{"users": []}"#.into()), maybe_config: None, maybe_cache: Some(false), maybe_bundled_contract: None, maybe_settings: None, maybe_exm_context: Some(r#"{"requests": {}, "kv": {"Nile": "River", "Name": "Mickey", "Amazon": "River"}, "initiated":[]}"#.into()), maybe_contract_source: Some(ContractSource { contract_src: contract_source_vec.into(), contract_type: SimulateContractType::JAVASCRIPT, }), }; let contract = simulate_contract(execution_context).await.unwrap(); //println!("{}", contract.exm_context); assert_eq!(contract.exm_context.to_string().contains("Name"), false); } #[tokio::test] pub async fn simulate_kv_map() { let contract_source_bytes = include_bytes!("../../../testdata/contracts/kvMap.js"); let contract_source_vec = contract_source_bytes.to_vec(); let execution_context: SimulateExecutionContext = SimulateExecutionContext { contract_id: String::new(), interactions: vec![SimulateInput { id: String::from("abcd"), owner: String::from("210392sdaspd-asdm-asd_sa0d1293-lc"), quantity: String::from("12301"), reward: String::from("12931293"), target: None, tags: vec![], block: None, input: serde_json::json!({ "gte": "1", "lt": "4", "reverse": false, "limit": "2" }) .to_string(), }], contract_init_state: Some(r#"{"users": []}"#.into()), maybe_config: None, maybe_cache: Some(false), maybe_bundled_contract: None, maybe_settings: None, maybe_exm_context: Some(r#"{"requests": {}, "kv": {"Nile": "River1", "Yangtze": "River2", "Amazon": "River3", "Mississippi": "River4", "Name": "Buccees"}, "initiated":[]}"#.into()), maybe_contract_source: Some(ContractSource { contract_src: contract_source_vec.into(), contract_type: SimulateContractType::JAVASCRIPT, }), }; let contract = simulate_contract(execution_context).await.unwrap(); assert_eq!(contract.result, "[\"Yangtze\",\"Amazon\"]"); } #[tokio::test] pub async fn simulate_sha256() { let contract_source_bytes = include_bytes!("../../../testdata/contracts/sha256.js"); let contract_source_vec = contract_source_bytes.to_vec(); let execution_context: SimulateExecutionContext = SimulateExecutionContext { contract_id: String::new(), interactions: vec![SimulateInput { id: String::from("abcd"), owner: String::from("210392sdaspd-asdm-asd_sa0d1293-lc"), quantity: String::from("12301"), reward: String::from("12931293"), target: None, tags: vec![], block: None, input: serde_json::json!({ "act": "1", }) .to_string(), }], contract_init_state: Some(r#"{}"#.into()), maybe_config: None, maybe_cache: Some(false), maybe_bundled_contract: None,
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
true
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/evm/lib.rs
crates/evm/lib.rs
pub use primitive_types::H128; pub use primitive_types::U256; use tiny_keccak::Hasher; use tiny_keccak::Keccak; pub mod storage; pub use storage::Storage; macro_rules! repr_u8 { ($(#[$meta:meta])* $vis:vis enum $name:ident { $($(#[$vmeta:meta])* $vname:ident $(= $val:expr)?,)* }) => { $(#[$meta])* $vis enum $name { $($(#[$vmeta])* $vname $(= $val)?,)* } impl std::convert::TryFrom<u8> for $name { type Error = (); fn try_from(v: u8) -> Result<Self, Self::Error> { match v { $(x if x == $name::$vname as u8 => Ok($name::$vname),)* _ => Err(()), } } } } } fn to_signed(value: U256) -> U256 { match value.bit(255) { true => (!value).overflowing_add(U256::one()).0, false => value, } } fn get_window_data( data: &Vec<u8>, window_size: usize, offset: usize, ) -> Vec<u8> { let start_index = offset % data.len(); let end_index = start_index + window_size; // Ensure the end index doesn't go beyond the length of the data let end_index = if end_index > data.len() { data.len() } else { end_index }; // Return the data within the specified window data[start_index..end_index].to_vec() } fn filter_left_zeros(data: Vec<u8>) -> Vec<u8> { let mut result = Vec::new(); let mut found_non_zero = false; for &value in &data { if value > 0 { found_non_zero = true; } if found_non_zero || value > 0 { result.push(value); } } result } repr_u8! { // EVM instructions #[repr(u8)] #[derive(Debug, Eq, PartialEq)] pub enum Instruction { Stop = 0x00, Add = 0x01, Mul = 0x02, Sub = 0x03, Div = 0x04, SDiv = 0x05, Mod = 0x06, SMod = 0x07, AddMod = 0x08, MulMod = 0x09, Exp = 0x0a, SignExtend = 0x0b, // 0x0c - 0x0f reserved Lt = 0x10, Gt = 0x11, SLt = 0x12, SGt = 0x13, Eq = 0x14, IsZero = 0x15, And = 0x16, Or = 0x17, Xor = 0x18, Not = 0x19, Byte = 0x1a, // EIP145 // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-145.md Shl = 0x1b, Shr = 0x1c, Sar = 0x1d, Keccak256 = 0x20, // 0x21 - 0x2f reserved Address = 0x30, Balance = 0x31, Origin = 0x32, Caller = 0x33, CallValue = 0x34, CallDataLoad = 0x35, CallDataSize = 0x36, CallDataCopy = 0x37, CodeSize = 0x38, CodeCopy = 0x39, GasPrice = 0x3a, ExtCodeSize = 0x3b, ExtCodeCopy = 0x3c, ReturnDataSize = 0x3d, ReturnDataCopy = 0x3e, BlockHash = 0x40, Coinbase = 0x41, Timestamp = 0x42, Number = 0x43, Difficulty = 0x44, GasLimit = 0x45, // EIP 1344 // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1344.md ChainId = 0x46, // 0x47 - 0x4f reserved // EIP-3198 BaseFee = 0x48, Pop = 0x50, MLoad = 0x51, MStore = 0x52, MStore8 = 0x53, SLoad = 0x54, SStore = 0x55, Jump = 0x56, JumpI = 0x57, GetPc = 0x58, MSize = 0x59, Gas = 0x5a, JumpDest = 0x5b, Push0 = 0x5f, // Newly Added Opcode Push1 = 0x60, Push2 = 0x61, Push3 = 0x62, Push4 = 0x63, Push5 = 0x64, Push6 = 0x65, Push7 = 0x66, Push8 = 0x67, Push9 = 0x68, Push10 = 0x69, Push11 = 0x6a, Push12 = 0x6b, Push13 = 0x6c, Push14 = 0x6d, Push15 = 0x6e, Push16 = 0x6f, Push17 = 0x70, Push18 = 0x71, Push19 = 0x72, Push20 = 0x73, Push21 = 0x74, Push22 = 0x75, Push23 = 0x76, Push24 = 0x77, Push25 = 0x78, Push26 = 0x79, Push27 = 0x7a, Push28 = 0x7b, Push29 = 0x7c, Push30 = 0x7d, Push31 = 0x7e, Push32 = 0x7f, Dup1 = 0x80, Dup2 = 0x81, Dup3 = 0x82, Dup4 = 0x83, Dup5 = 0x84, Dup6 = 0x85, Dup7 = 0x86, Dup8 = 0x87, Dup9 = 0x88, Dup10 = 0x89, Dup11 = 0x8a, Dup12 = 0x8b, Dup13 = 0x8c, Dup14 = 0x8d, Dup15 = 0x8e, Dup16 = 0x8f, Swap1 = 0x90, Swap2 = 0x91, Swap3 = 0x92, Swap4 = 0x93, Swap5 = 0x94, Swap6 = 0x95, Swap7 = 0x96, Swap8 = 0x97, Swap9 = 0x98, Swap10 = 0x99, Swap11 = 0x9a, Swap12 = 0x9b, Swap13 = 0x9c, Swap14 = 0x9d, Swap15 = 0x9e, Swap16 = 0x9f, Log0 = 0xa0, Log1 = 0xa1, Log2 = 0xa2, Log3 = 0xa3, Log4 = 0xa4, // 0xa5 - 0xaf reserved Create = 0xf0, Call = 0xf1, CallCode = 0xf2, Return = 0xf3, DelegateCall = 0xf4, Create2 = 0xfb, Revert = 0xfd, StaticCall = 0xfa, Invalid = 0xfe, SelfDestruct = 0xff, } } pub const MAX_STACK_SIZE: usize = 1024; #[derive(Debug)] pub struct Stack { pub data: Vec<U256>, } impl Default for Stack { fn default() -> Self { let data = Vec::with_capacity(MAX_STACK_SIZE); Stack { data } } } impl Stack { pub fn push(&mut self, value: U256) { self.data.push(value); } pub fn pop(&mut self) -> U256 { self.data.pop().unwrap() } pub fn peek(&self) -> U256 { self.data[self.data.len() - 1] } pub fn peek_step(&self, step: usize) -> U256 { self.data[self.data.len() - step] } pub fn swap(&mut self, index: usize) { let ptr = self.data.len() - 1; // dbg!("Attempting swap ptr = {}, value = {}", ptr, self.data[ptr]); if ptr < index { return; } self.data.swap(ptr, ptr - index); // dbg!("Swapped {}", self.data[ptr]); } pub fn dup(&mut self, index: usize) { self.push(self.data[self.data.len() - index]); } } pub struct Machine<'a> { pub stack: Stack, state: U256, memory: Vec<u8>, pub result: Vec<u8>, // The cost function. cost_fn: Box<dyn Fn(&Instruction) -> U256>, fetch_contract: Box<dyn Fn(&U256) -> Option<ContractInfo> + 'a>, // Total gas used so far. // gas_used += cost_fn(instruction) gas_used: U256, // The input data. data: Vec<u8>, pub storage: Storage, owner: U256, } #[derive(PartialEq, Debug)] pub enum AbortError { DivZero, InvalidOpcode, } #[derive(PartialEq, Debug)] pub enum ExecutionState { Abort(AbortError), Revert, Ok, } #[derive(Default, Clone)] pub struct BlockInfo { pub timestamp: U256, pub difficulty: U256, pub block_hash: U256, pub number: U256, } pub struct ContractInfo { pub store: Storage, pub bytecode: Vec<u8>, } impl<'a> Machine<'a> { pub fn new<T>(cost_fn: T) -> Self where T: Fn(&Instruction) -> U256 + 'static, { Machine { stack: Stack::default(), state: U256::zero(), memory: Vec::new(), result: Vec::new(), cost_fn: Box::new(cost_fn), fetch_contract: Box::new(|_| None), gas_used: U256::zero(), data: Vec::new(), storage: Storage::new(U256::zero()), owner: U256::zero(), } } pub fn new_with_data<T>(cost_fn: T, data: Vec<u8>) -> Self where T: Fn(&Instruction) -> U256 + 'static, { Machine { stack: Stack::default(), state: U256::zero(), memory: Vec::new(), result: Vec::new(), cost_fn: Box::new(cost_fn), gas_used: U256::zero(), data, fetch_contract: Box::new(|_| None), storage: Storage::new(U256::zero()), owner: U256::zero(), } } pub fn set_storage(&mut self, storage: Storage) { self.storage = storage; } pub fn set_fetcher( &mut self, fetcher: Box<dyn Fn(&U256) -> Option<ContractInfo> + 'a>, ) { self.fetch_contract = fetcher; } pub fn execute( &mut self, bytecode: &[u8], block_info: BlockInfo, ) -> ExecutionState { let mut pc = 0; let len = bytecode.len(); let mut counter = 0; while pc < len { let opcode = bytecode[pc]; let inst = match Instruction::try_from(opcode) { Ok(inst) => inst, Err(_) => { return ExecutionState::Abort(AbortError::InvalidOpcode); } }; let cost = (self.cost_fn)(&inst); pc += 1; counter += 1; if counter == 400 { break; } println!("{:#?}", inst); println!("OPCODE: {:#?}", opcode); println!("Position: {:#?}", pc - 1); println!("Counter: {:#?}", counter); println!("==================="); match inst { Instruction::Stop => {} Instruction::Add => { let lhs = self.stack.pop(); let rhs = self.stack.pop(); let lhs16: u16 = lhs.as_u64() as u16; let rhs16: u16 = rhs.as_u64() as u16; let sum = U256::from(lhs16.overflowing_add(rhs16).0); self.stack.push(sum); } Instruction::Sub => { let lhs = self.stack.pop(); let rhs = self.stack.pop(); let lhs16: u16 = lhs.as_u64() as u16; // culprits causing an issue let rhs16: u16 = rhs.as_u64() as u16; // Should wallet be converted to base16? We need to see what obj truth offers wallet conversion let difference = U256::from(lhs16.overflowing_sub(rhs16).0); self.stack.push(difference); } Instruction::Mul => { let lhs = self.stack.pop(); let rhs = self.stack.pop(); let lhs16: u16 = lhs.as_u64() as u16; let rhs16: u16 = rhs.as_u64() as u16; let product = U256::from(lhs16.overflowing_mul(rhs16).0); self.stack.push(product); } Instruction::Div => { let lhs = self.stack.pop(); let rhs = self.stack.pop(); let lhs16: u16 = lhs.as_u64() as u16; let rhs16: u16 = rhs.as_u64() as u16; let quotient = U256::from(lhs16.overflowing_div(rhs16).0); if rhs == U256::zero() { return ExecutionState::Abort(AbortError::DivZero); } self.stack.push(quotient); } Instruction::SDiv => { let dividend = to_signed(self.stack.pop()); let divisor = to_signed(self.stack.pop()); const U256_ZERO: U256 = U256::zero(); let quotient = if divisor == U256_ZERO { U256_ZERO } else { let min = (U256::one() << 255) - U256::one(); if dividend == min && divisor == !U256::one() { min } else { let sign = dividend.bit(255) ^ divisor.bit(255); match sign { true => !(dividend / divisor), false => dividend / divisor, } } }; self.stack.push(quotient); } Instruction::Mod => { let lhs = self.stack.pop(); let rhs = self.stack.pop(); let res = match lhs.checked_rem(rhs) { Some(res) => res, None => U256::zero(), }; self.stack.push(res); } Instruction::SMod => { fn to_signed(value: U256) -> U256 { match value.bit(255) { true => (!value).overflowing_add(U256::one()).0, false => value, } } let lhs = self.stack.pop(); let signed_lhs = to_signed(lhs); let sign = lhs.bit(255); let rhs = to_signed(self.stack.pop()); if rhs == U256::zero() { self.stack.push(U256::zero()); } else { let value = signed_lhs % rhs; self.stack.push(match sign { true => (!value).overflowing_add(U256::one()).0, false => value, }); } } Instruction::AddMod => { let a = self.stack.pop(); let b = self.stack.pop(); let c = self.stack.pop(); let res = match a.checked_add(b) { Some(res) => res % c, None => U256::zero(), }; self.stack.push(res); } Instruction::MulMod => { let a = self.stack.pop(); let b = self.stack.pop(); let c = self.stack.pop(); let res = match a.checked_mul(b) { Some(res) => res % c, None => U256::zero(), }; self.stack.push(res); } Instruction::Exp => { let lhs = self.stack.pop(); let rhs = self.stack.pop(); self.stack.push(lhs.overflowing_pow(rhs).0) } Instruction::SignExtend => { let pos = self.stack.pop(); let value = self.stack.pop(); if pos > U256::from(32) { self.stack.push(value); } else { let bit_pos = (pos.low_u64() * 8 + 7) as usize; let bit = value.bit(bit_pos); let mask = (U256::one() << bit_pos) - U256::one(); let result = if bit { value | !mask } else { value & mask }; self.stack.push(result); } } Instruction::Lt => { let lhs = self.stack.pop(); let rhs = self.stack.pop(); self .stack .push(if lhs < rhs { U256::one() } else { U256::zero() }); } Instruction::Gt => { let lhs = self.stack.pop(); let rhs = self.stack.pop(); self .stack .push(if lhs > rhs { U256::one() } else { U256::zero() }); } Instruction::SLt => { let (lhs, l_sign) = { let lhs = self.stack.pop(); let l_sign = lhs.bit(255); (to_signed(lhs), l_sign) }; let (rhs, r_sign) = { let rhs = self.stack.pop(); let r_sign = rhs.bit(255); (to_signed(rhs), r_sign) }; let result = match (l_sign, r_sign) { (false, false) => lhs < rhs, (true, true) => lhs > rhs, (true, false) => true, (false, true) => false, }; self .stack .push(if result { U256::one() } else { U256::zero() }); } Instruction::SGt => { let (lhs, l_sign) = { let lhs = self.stack.pop(); let l_sign = lhs.bit(255); (to_signed(lhs), l_sign) }; let (rhs, r_sign) = { let rhs = self.stack.pop(); let r_sign = rhs.bit(255); (to_signed(rhs), r_sign) }; let result = match (l_sign, r_sign) { (false, false) => lhs > rhs, (true, true) => lhs < rhs, (true, false) => false, (false, true) => true, }; self .stack .push(if result { U256::one() } else { U256::zero() }); } Instruction::Shr => { let rhs = self.stack.pop(); let lhs = self.stack.pop(); if rhs < U256::from(256) { self.stack.push(lhs >> rhs); } else { self.stack.push(U256::zero()); } } Instruction::Shl => { let rhs = self.stack.pop(); let lhs = self.stack.pop(); if rhs < U256::from(256) { self.stack.push(lhs << rhs); } else { self.stack.push(U256::zero()); } } Instruction::Eq => { let lhs = self.stack.pop(); let rhs = self.stack.pop(); self.stack.push(if lhs == rhs { U256::one() } else { U256::zero() }); } Instruction::IsZero => { let val = self.stack.pop(); self.stack.push(if val == U256::zero() { U256::one() } else { U256::zero() }); } Instruction::And => { let lhs = self.stack.pop(); let rhs = self.stack.pop(); self.stack.push(lhs & rhs); } Instruction::Or => { let lhs = self.stack.pop(); let rhs = self.stack.pop(); self.stack.push(lhs | rhs); } Instruction::Xor => { let lhs = self.stack.pop(); let rhs = self.stack.pop(); self.stack.push(lhs ^ rhs); } Instruction::Not => { let val = self.stack.pop(); let val16: u16 = val.as_u64() as u16; let not_val16 = U256::from(!val16); self.stack.push(not_val16); } Instruction::Byte => { let rhs = self.stack.pop(); let lhs = self.stack.pop(); match rhs > U256::from(32) { true => { self.stack.push(U256::zero()); } false => { let byte = lhs.byte(rhs.as_u64() as usize); self.stack.push(U256::from(byte)); } } } Instruction::Keccak256 => { let offset = self.stack.pop().low_u64() as usize; let size = self.stack.pop().low_u64() as usize; let data = &self.memory[offset..offset + size]; let mut result = [0u8; 32]; let mut keccak = Keccak::v256(); keccak.update(data); keccak.finalize(&mut result); self.stack.push(U256::from(result)); } Instruction::Address => { self.stack.push(self.owner); } Instruction::Balance => { let _addr = self.stack.pop(); // TODO: balance self.stack.push(U256::zero()); } Instruction::Origin => { // TODO: origin self.stack.push(U256::zero()); } Instruction::Caller => { // TODO: caller self.stack.push(U256::zero()); } Instruction::CallValue => { self.stack.push(self.state); } Instruction::CallDataLoad => { let offset = self.stack.pop(); let offset = match offset > usize::max_value().into() { true => self.data.len(), false => offset.low_u64() as usize, }; let end = std::cmp::min(offset + 32, self.data.len()); let mut data = self.data[offset..end].to_vec(); data.resize(32, 0u8); self.stack.push(U256::from(data.as_slice())); } Instruction::CallDataSize => { self.stack.push(U256::from(self.data.len())); } Instruction::CallDataCopy => { let mem_offset = self.stack.pop(); let offset = self.stack.pop(); let size = self.stack.pop(); if offset > U256::from(self.data.len()) || offset.overflowing_add(size).1 { return ExecutionState::Ok; } let offset = offset.low_u64() as usize; let size = size.low_u64() as usize; let end = std::cmp::min(offset + size, self.data.len()); let mut data = self.data[offset..end].to_vec(); data.resize(32, 0u8); let mem_offset = mem_offset.low_u64() as usize; self.memory[mem_offset..mem_offset + 32] .copy_from_slice(data.as_slice()); } Instruction::CodeSize => { self.stack.push(U256::from(len)); } Instruction::CodeCopy => { let mem_offset = self.stack.pop().low_u64() as usize; let code_offset = self.stack.pop(); let len = self.stack.pop().low_u64() as usize; if code_offset > usize::max_value().into() { dbg!("CODECOPY: offset too large"); } let code_offset = code_offset.low_u64() as usize; let code: &[u8]; // Needed for testing parts of bytecode to avoid out of bound errors in &bytecode[code_offset..code_offset + len] let mut temp_vec: Vec<u8> = vec![]; //println!("mem_offset: {:#?}", mem_offset); //println!("code_offset: {:#?}", code_offset); //println!("len: {:#?}", len); //println!("Memory Size: {:#?}", self.memory.len()); if self.memory.len() < (mem_offset + len) { self.memory.extend( std::iter::repeat(0).take(mem_offset + len - self.memory.len()), ); } code = &bytecode[code_offset..code_offset + len]; //println!("Grabbed Code: {:#?}", code); //Calculate new space of zeroes for i in 0..=code.len() - 1 { self.memory[mem_offset + i] = code[i]; } } Instruction::ExtCodeSize => { // Fetch the `Contract-Src` from Arweave for the contract. } Instruction::ExtCodeCopy => { // Fetch the `Contract-Src` from Arweave for the contract. } Instruction::ReturnDataSize => { self.stack.push(U256::from(self.result.len())); } Instruction::ReturnDataCopy => { let mem_offset = self.stack.pop().low_u64() as usize; let data_offset = self.stack.pop().low_u64() as usize; let length = self.stack.pop().low_u64() as usize; if self.result.len() < data_offset + length { panic!("Return data out of bounds"); } let data = &self.result[data_offset..data_offset + length]; if self.memory.len() < mem_offset + 32 { self.memory.resize(mem_offset + 32, 0); } for i in 0..32 { if i > data.len() { self.memory[mem_offset + i] = 0; } else { self.memory[mem_offset + i] = data[i]; } } } Instruction::BlockHash => { self.stack.push(block_info.block_hash); } Instruction::Timestamp => { self.stack.push(block_info.timestamp); } Instruction::Number => { self.stack.push(block_info.number); } Instruction::Difficulty => { self.stack.push(block_info.difficulty); } Instruction::GasLimit => { self.stack.push(U256::MAX); } Instruction::Pop => { self.stack.pop(); } Instruction::MLoad => { let offset = self.stack.pop(); if offset > usize::max_value().into() { dbg!("MLOAD: offset too large"); } let len = offset.low_u64() as usize; // Calcuate bytes to add to memory based on offset let num_memory_rows = self.memory.len() / 32; let offset_needed_rows = ((len + 32) as f64 / 32.0).ceil() as usize; //println!("OFFSET: {:#?}", len); //println!("num_memory_rows: {:#?}", num_memory_rows); //println!("offset_needed_row {:#?}", offset_needed_rows); let rows_to_add = offset_needed_rows as i32 - num_memory_rows as i32; //println!("rows_to_add {:#?}", rows_to_add); if rows_to_add > 0 { for _ in 0..=rows_to_add - 1 { self.memory.extend(std::iter::repeat(0).take(32)); } } let word = get_window_data(&self.memory, 32, len); let filtered_word = filter_left_zeros(word); let filtered_hex: Vec<String> = filtered_word .iter() .map(|u256| format!("{:02x}", u256)) .collect(); let joined_filtered: String = filtered_hex .into_iter() .map(|byte| byte.to_string()) .collect(); let word_u256 = U256::from_str_radix(joined_filtered.as_str(), 16).unwrap(); self.stack.push(U256::from(word_u256)); } Instruction::MStore => { let offset = self.stack.pop(); let val = self.stack.pop(); if offset > usize::max_value().into() { dbg!("MStore: offset too large"); } let offset = offset.low_u64() as usize; if self.memory.len() <= offset + 32 { self.memory.resize(offset + 32, 0); } for i in 0..32 { let mem_ptr = offset + i; // Big endian byte let index = 4 * 8 - 1 - i; self.memory[mem_ptr] = val.byte(index); } } Instruction::MStore8 => { let offset = self.stack.pop(); let val = self.stack.pop(); if offset > usize::max_value().into() { dbg!("MStore8: offset too large"); } let mem_ptr = offset.low_u64() as usize; if mem_ptr >= self.memory.len() { self.memory.resize(mem_ptr + 32, 0); } self.memory[mem_ptr] = val.byte(0); } Instruction::SLoad => { let offset = self.stack.pop(); let data = self.storage.get(&self.owner, &offset); self.stack.push(data); } Instruction::SStore => { let offset = self.stack.pop(); let val = self.stack.pop(); self.storage.insert(&self.owner, offset, val); } Instruction::Jump => { let offset = self.stack.pop(); pc = offset.low_u64() as usize; } Instruction::JumpI => { let offset = self.stack.pop(); let condition = self.stack.pop(); if condition != U256::zero() { pc = offset.low_u64() as usize; } } Instruction::GetPc => { self.stack.push(U256::from(pc)); } Instruction::MSize | Instruction::Gas | Instruction::GasPrice | Instruction::Coinbase => { self.stack.push(U256::zero()); } Instruction::JumpDest => {} Instruction::Push0 => { self.stack.push(U256::from(0x00)); } Instruction::Push1 | Instruction::Push2 | Instruction::Push3 | Instruction::Push4 | Instruction::Push5 | Instruction::Push6 | Instruction::Push7 | Instruction::Push8 | Instruction::Push9 | Instruction::Push10 | Instruction::Push11 | Instruction::Push12 | Instruction::Push13 | Instruction::Push14 | Instruction::Push15 | Instruction::Push16 | Instruction::Push17 | Instruction::Push18 | Instruction::Push19 | Instruction::Push20 | Instruction::Push21 | Instruction::Push22 | Instruction::Push23 | Instruction::Push24 | Instruction::Push25 | Instruction::Push26 | Instruction::Push27 | Instruction::Push28 | Instruction::Push29 | Instruction::Push30 | Instruction::Push31 | Instruction::Push32 => { let value_size = (opcode - 0x60 + 1) as usize; let value = &bytecode[pc..pc + value_size]; println!("VALUE ADDED {:#?} :", value); pc += value_size; self.stack.push(U256::from(value)); } Instruction::Dup1 | Instruction::Dup2 | Instruction::Dup3 | Instruction::Dup4 | Instruction::Dup5 | Instruction::Dup6 | Instruction::Dup7 | Instruction::Dup8 | Instruction::Dup9 | Instruction::Dup10 | Instruction::Dup11 | Instruction::Dup12 | Instruction::Dup13 | Instruction::Dup14 | Instruction::Dup15 | Instruction::Dup16 => { let size = (opcode - 0x80 + 1) as usize; self.stack.dup(size); } Instruction::Swap1 | Instruction::Swap2 | Instruction::Swap3 | Instruction::Swap4 | Instruction::Swap5 | Instruction::Swap6 | Instruction::Swap7 | Instruction::Swap8 | Instruction::Swap9 | Instruction::Swap10 | Instruction::Swap11 | Instruction::Swap12 | Instruction::Swap13 | Instruction::Swap14 | Instruction::Swap15 | Instruction::Swap16 => { let size = (opcode - 0x90 + 1) as usize; self.stack.swap(size); } Instruction::Log0 | Instruction::Log1 | Instruction::Log2 | Instruction::Log3 | Instruction::Log4 => {} Instruction::Create => { // TODO } Instruction::Call => { // Call parameters let _gas = self.stack.pop(); let addr = self.stack.pop(); let _value = self.stack.pop(); let in_offset = self.stack.pop().low_u64() as usize; let in_size = self.stack.pop().low_u64() as usize; let out_offset = self.stack.pop().low_u64() as usize; let out_size = self.stack.pop().low_u64() as usize; let input = &bytecode[in_offset..in_offset + in_size]; let mut evm = Self::new_with_data(|_| U256::zero(), input.to_vec()); let contract = (self.fetch_contract)(&addr) .expect("No fetch contract handler provided."); evm.set_storage(contract.store); evm.execute(&contract.bytecode, block_info.clone()); self.memory[out_offset..out_offset + out_size] .copy_from_slice(&evm.result); } Instruction::CallCode | Instruction::DelegateCall => { // Call parameters let _gas = self.stack.pop(); let addr = self.stack.pop(); let in_offset = self.stack.pop().low_u64() as usize; let in_size = self.stack.pop().low_u64() as usize; let out_offset = self.stack.pop().low_u64() as usize; let out_size = self.stack.pop().low_u64() as usize; let input = &bytecode[in_offset..in_offset + in_size]; let mut evm = Self::new_with_data(|_| U256::zero(), input.to_vec()); let contract = (self.fetch_contract)(&addr) .expect("No fetch contract handler provided."); evm.set_storage(contract.store); evm.execute(&contract.bytecode, block_info.clone()); self.memory[out_offset..out_offset + out_size] .copy_from_slice(&evm.result); } Instruction::Return => { let offset = self.stack.pop(); if offset > usize::max_value().into() { dbg!("Return: offset too large"); } let offset = offset.low_u64() as usize; let size = self.stack.pop().low_u64() as usize; let mut data = vec![]; for idx in offset..offset + size { if idx >= self.memory.len() { data.push(0); } else { data.push(self.memory[idx]); } } self.result = data; break; } Instruction::Revert => { return ExecutionState::Revert; } Instruction::Invalid => { // revisit this logic. Similar to Revert but must consume all gas return ExecutionState::Revert; } _ => unimplemented!(), } self.gas_used += cost; } ExecutionState::Ok } } #[cfg(test)] mod tests { use crate::storage::Storage; use crate::ExecutionState; use crate::Instruction; use crate::Machine; use crate::Stack; use hex_literal::hex; use primitive_types::U256; fn test_cost_fn(_: &Instruction) -> U256 { U256::zero() } /* #[allow(dead_code)] fn print_vm_memory(vm: &Machine) { let mem = &vm.memory; //println!("{:?}", mem); for (i, cell) in mem.iter().enumerate() { if i % 16 == 0 { print!("\n{:x}: ", i); } print!("{:#04x} ", cell); } } */ /* #[test] fn test_basic() { let mut machine = Machine::new(test_cost_fn); let status = machine.execute( &[ Instruction::Push1 as u8, 0x01, Instruction::Push1 as u8, 0x02, Instruction::Add as u8, ], Default::default(), ); assert_eq!(status, ExecutionState::Ok); assert_eq!(machine.stack.pop(), U256::from(0x03)); } #[test] fn test_stack_swap() { let mut stack = Stack::default(); stack.push(U256::from(0x01)); stack.push(U256::from(0x02)); stack.swap(1); stack.pop(); stack.swap(1); assert_eq!(stack.pop(), U256::from(0x02)); } #[test] fn test_swap_jump() { let mut machine = Machine::new(test_cost_fn); let status = machine.execute( &[ Instruction::Push1 as u8, 0x00, Instruction::Push1 as u8, 0x03, Instruction::Swap1 as u8, Instruction::Pop as u8, Instruction::Swap1 as u8, ], Default::default(), ); assert_eq!(status, ExecutionState::Ok); assert_eq!(machine.stack.pop(), U256::from(0x03)); } #[test] fn test_sdiv() { let mut machine = Machine::new(test_cost_fn); let status = machine.execute( &[ Instruction::Push1 as u8, 0x02, Instruction::Push1 as u8, 0x04, Instruction::SDiv as u8, ],
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
true
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/evm/storage.rs
crates/evm/storage.rs
// Contract storage use primitive_types::U256; use std::collections::HashMap; macro_rules! extend_u256 { ($vec:ident, $val:expr) => { let array: [u8; 32] = $val.into(); $vec.extend_from_slice(&array); }; } #[derive(Debug, Clone)] pub struct Storage { pub inner: HashMap<U256, HashMap<U256, U256>>, } /// Storage is the EVM account cum storage implementation. impl Storage { pub fn new(owner: U256) -> Self { let mut inner = HashMap::new(); inner.insert(owner, HashMap::new()); Storage { inner } } pub fn insert(&mut self, account: &U256, key: U256, value: U256) { let account = self.inner.get_mut(account).unwrap(); account.insert(key, value); } pub fn get(&self, account: &U256, key: &U256) -> U256 { let account = self.inner.get(account).unwrap(); *account.get(key).unwrap_or(&U256::zero()) } /// Decode storage bytes. pub fn from_raw(raw: &[u8]) -> Self { let mut storage = Storage::new(U256::zero()); let mut offset = 0; while offset < raw.len() { let account = U256::from(&raw[offset..offset + 32]); offset += 32; let mut account_storage = HashMap::new(); let key_count = U256::from(&raw[offset..offset + 32]); offset += 32; for _ in 0..key_count.as_usize() { let key = U256::from(&raw[offset..offset + 32]); offset += 32; let value = U256::from(&raw[offset..offset + 32]); offset += 32; account_storage.insert(key, value); } storage.inner.insert(account, account_storage); } storage } pub fn raw(&self) -> Vec<u8> { let mut raw: Vec<u8> = Vec::new(); for (account, account_storage) in self.inner.iter() { extend_u256!(raw, *account); extend_u256!(raw, U256::from(account_storage.len())); for (key, value) in account_storage.iter() { extend_u256!(raw, *key); extend_u256!(raw, *value); } } raw } } #[cfg(test)] mod tests { use crate::storage::Storage; use primitive_types::U256; #[test] fn test_storage_decode() { let account = U256::zero(); let encoded: [[u8; 32]; 6] = [ // Account account.into(), // Key count U256::from(0x02u8).into(), // Key 1 U256::zero().into(), // Value 1 U256::one().into(), // Key 2 U256::one().into(), // Value 2 U256::from(0x02u8).into(), ]; let store = Storage::from_raw(&encoded.concat()); assert_eq!(store.get(&account, &U256::zero()), U256::one()); assert_eq!(store.get(&account, &U256::one()), U256::from(0x02u8)); } }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/arweave/lib.rs
crates/arweave/lib.rs
pub mod arweave; pub mod cache; pub mod gql_result; pub mod lru_cache; pub mod miscellaneous; mod utils;
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/arweave/utils.rs
crates/arweave/utils.rs
use crate::gql_result::GQLNodeInterface; use sha2::Digest; pub fn decode_base_64(data: String) -> String { String::from_utf8(base64::decode(data).unwrap_or_else(|_| vec![])) .unwrap_or_else(|_| String::from("")) } pub fn hasher(data: &[u8]) -> Vec<u8> { let mut hasher = sha2::Sha256::new(); hasher.update(data); hasher.finalize()[..].to_vec() } pub fn get_tags(tags_tx: &GQLNodeInterface, name: &str) -> Option<String> { let tag = &tags_tx.tags.iter().find(|data| &data.name == name); tag.map(|x| x.value.clone()) }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/arweave/gql_result.rs
crates/arweave/gql_result.rs
use serde::Deserialize; use serde::Serialize; #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct GQLPageInfoInterface { pub has_next_page: bool, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct GQLOwnerInterface { pub address: String, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] pub key: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct GQLAmountInterface { #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] pub winston: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] pub ar: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct GQLMetaDataInterface { #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] pub size: Option<usize>, #[serde(rename = "type")] #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] pub ty: Option<String>, } #[derive(Serialize, Deserialize, Default, Debug, Clone)] pub struct GQLTagInterface { pub name: String, pub value: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct GQLBlockInterface { pub id: String, pub timestamp: usize, pub height: usize, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] pub previous: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct GQLNodeParent { pub id: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct GQLBundled { pub id: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct GQLNodeInterface { pub id: String, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] pub anchor: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] pub signature: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] pub recipient: Option<String>, pub owner: GQLOwnerInterface, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] pub fee: Option<GQLAmountInterface>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] pub quantity: Option<GQLAmountInterface>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] pub data: Option<GQLMetaDataInterface>, pub tags: Vec<GQLTagInterface>, pub block: GQLBlockInterface, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] pub parent: Option<GQLNodeParent>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] pub bundledIn: Option<GQLBundled>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct GQLEdgeInterface { pub cursor: String, pub node: GQLNodeInterface, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct GQLTransactionsResultInterface { pub page_info: GQLPageInfoInterface, pub edges: Vec<GQLEdgeInterface>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct GQLDataResultInterface { pub transactions: GQLTransactionsResultInterface, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct GQLResultInterface { pub data: GQLDataResultInterface, }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/arweave/miscellaneous.rs
crates/arweave/miscellaneous.rs
use crate::arweave::TransactionData; use crate::utils::hasher; use deno_core::error::AnyError; use serde::Deserialize; use serde::Serialize; pub type CommonError = AnyError; #[derive(Deserialize, Serialize, Clone, Debug, Default)] pub enum ContractType { #[default] JAVASCRIPT, WASM, EVM, } // impl Default for ContractType { // fn default() -> ContractType { // ContractType::JAVASCRIPT // } // } pub fn get_contract_type_raw(contract_type: String) -> ContractType { match &(contract_type.to_lowercase())[..] { "application/javascript" => ContractType::JAVASCRIPT, "application/wasm" => ContractType::WASM, "application/octet-stream" => ContractType::EVM, _ => ContractType::JAVASCRIPT, } } pub fn get_contract_type( maybe_content_type: Option<String>, contract_transaction: &TransactionData, source_transaction: &TransactionData, ) -> Result<ContractType, AnyError> { let contract_type = maybe_content_type .or_else(|| source_transaction.get_tag("Content-Type").ok()) .or_else(|| contract_transaction.get_tag("Content-Type").ok()) .ok_or_else(|| { AnyError::msg("Contract-Src tag not found in transaction") })?; let ty = get_contract_type_raw(contract_type); Ok(ty) } pub fn get_sort_key( block_height: &usize, block_id: &str, transaction_id: &str, ) -> String { let mut hasher_bytes = base64::decode_config(block_id, base64::URL_SAFE_NO_PAD).unwrap(); let mut tx_id = base64::decode_config(transaction_id, base64::URL_SAFE_NO_PAD).unwrap(); hasher_bytes.append(&mut tx_id); let hashed = hex::encode(hasher(&hasher_bytes[..])); let height = format!("000000{}", *block_height); let start = height.len() - std::cmp::min(height.len(), 12); format!("{},{}", &height[start..], hashed) } #[cfg(test)] mod tests { use crate::arweave::{Tag, TransactionData}; use crate::miscellaneous::{get_contract_type, ContractType}; #[tokio::test] async fn get_contract_type_test() { let contract_type = get_contract_type( Some(String::from("invalid")), &get_fake_transaction("whatever"), &get_fake_transaction("whatever"), ) .unwrap(); assert!(matches!(contract_type, ContractType::JAVASCRIPT)); let contract_type = get_contract_type( None, &get_fake_transaction("whatever"), &get_fake_transaction("whatever"), ) .unwrap(); assert!(matches!(contract_type, ContractType::JAVASCRIPT)); let contract_type = get_contract_type( None, &get_fake_transaction(""), &get_fake_transaction("whatever"), ) .unwrap(); assert!(matches!(contract_type, ContractType::JAVASCRIPT)); let contract_type = get_contract_type( None, &get_fake_transaction("whatever"), &get_fake_transaction("application/wasm"), ) .unwrap(); assert!(matches!(contract_type, ContractType::WASM)); let contract_type = get_contract_type( None, &get_fake_transaction(""), &get_fake_transaction("application/octet-stream"), ) .unwrap(); assert!(matches!(contract_type, ContractType::EVM)); let contract_type = get_contract_type( None, &get_fake_transaction(""), &get_fake_transaction(""), ) .unwrap(); assert!(matches!(contract_type, ContractType::JAVASCRIPT)); } fn get_fake_transaction(content_type: &str) -> TransactionData { TransactionData { format: 1_usize, id: String::from(""), last_tx: String::from(""), owner: String::from(""), tags: vec![Tag { name: String::from("Q29udGVudC1UeXBl"), value: base64::encode(String::from(content_type)), }], target: String::from(""), quantity: String::from(""), data: String::from(""), reward: String::from(""), signature: String::from(""), data_size: String::from(""), data_root: String::from(""), } } }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/arweave/arweave.rs
crates/arweave/arweave.rs
use crate::cache::CacheExt; use crate::gql_result::GQLNodeParent; use crate::gql_result::GQLResultInterface; use crate::gql_result::GQLTransactionsResultInterface; use crate::gql_result::{GQLBundled, GQLEdgeInterface}; use crate::miscellaneous::ContractType; use crate::miscellaneous::{get_contract_type, get_contract_type_raw}; use crate::utils::{decode_base_64, get_tags}; use deno_core::error::AnyError; use deno_core::futures::stream; use deno_core::futures::StreamExt; use once_cell::sync::OnceCell; use reqwest::Client; use serde::Deserialize; use serde::Serialize; use std::fmt::Debug; use std::sync::Arc; use std::sync::Mutex; #[derive(Deserialize, Serialize, Default, Clone)] pub struct BundledContract { pub contractSrc: Vec<u8>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] pub contentType: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] pub initState: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] pub contractOwner: Option<String>, } #[derive(Deserialize, Serialize, Clone)] pub struct NetworkInfo { pub network: String, pub version: usize, pub release: usize, pub height: usize, pub current: String, pub blocks: usize, pub peers: usize, pub queue_length: usize, pub node_state_latency: usize, } #[derive(Deserialize, Serialize, Default, Clone, Debug)] pub struct Tag { pub name: String, pub value: String, } #[derive(Deserialize, Serialize, Default, Clone)] pub struct TransactionData { pub format: usize, pub id: String, pub last_tx: String, pub owner: String, pub tags: Vec<Tag>, pub target: String, pub quantity: String, pub data: String, pub reward: String, pub signature: String, pub data_size: String, pub data_root: String, } #[derive(Deserialize, Serialize, Default, Clone)] pub struct BlockInfo { pub timestamp: u64, pub diff: String, pub indep_hash: String, pub height: u64, } #[derive(Deserialize, Serialize, Default, Clone)] pub struct TransactionStatus { pub block_indep_hash: String, } impl TransactionData { pub fn get_tag(&self, tag: &str) -> Result<String, AnyError> { // Encodes the tag instead of decoding the keys. let encoded_tag = base64::encode_config(tag, base64::URL_SAFE_NO_PAD); self .tags .iter() .find(|t| t.name == encoded_tag) .map(|t| Ok(String::from_utf8(base64::decode(&t.value)?)?)) .ok_or_else(|| AnyError::msg(format!("{} tag not found", tag)))? } } #[derive(Clone)] pub enum ArweaveProtocol { HTTP, HTTPS, } #[derive(Clone)] pub struct Arweave { pub host: String, pub port: i32, pub protocol: ArweaveProtocol, client: Client, } #[derive(Deserialize, Serialize, Clone)] pub struct TagFilter { name: String, values: Vec<String>, } #[derive(Deserialize, Serialize, Clone)] pub struct BlockFilter { max: usize, } #[derive(Deserialize, Serialize, Clone)] #[serde(rename_all = "camelCase")] pub struct InteractionVariables { tags: Vec<TagFilter>, block_filter: BlockFilter, first: usize, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] after: Option<String>, } #[derive(Deserialize, Serialize)] pub struct GraphqlQuery { query: String, variables: InteractionVariables, } #[derive(Deserialize, Serialize, Clone, Default)] pub struct LoadedContract { pub id: String, pub contract_src_tx_id: String, pub contract_src: Vec<u8>, pub contract_type: ContractType, pub init_state: String, pub min_fee: Option<String>, pub contract_transaction: TransactionData, } #[derive(Deserialize, Serialize, Clone)] pub struct ManualLoadedContract { pub contract_src: Vec<u8>, pub contract_type: ContractType, } enum State { Next(Option<String>, InteractionVariables), #[allow(dead_code)] End, } pub static MAX_REQUEST: usize = 100; static ARWEAVE_CACHE: OnceCell<Arc<Mutex<dyn CacheExt + Send + Sync>>> = OnceCell::new(); pub fn get_cache() -> &'static Arc<Mutex<dyn CacheExt + Send + Sync>> { ARWEAVE_CACHE.get().expect("cache is not initialized") } impl Arweave { pub fn new<T>(port: i32, host: String, protocol: String, cache: T) -> Arweave where T: CacheExt + Send + Sync + Debug + 'static, { ARWEAVE_CACHE.set(Arc::new(Mutex::new(cache))); Arweave { port, host, protocol: match &protocol[..] { "http" => ArweaveProtocol::HTTP, "https" | _ => ArweaveProtocol::HTTPS, }, client: Client::new(), } } pub fn new_no_cache(port: i32, host: String, protocol: String) -> Arweave { Arweave { port, host, protocol: match &protocol[..] { "http" => ArweaveProtocol::HTTP, "https" | _ => ArweaveProtocol::HTTPS, }, client: Client::new(), } } pub async fn get_transaction( &self, transaction_id: &str, ) -> reqwest::Result<TransactionData> { let request = self .client .get(format!("{}/tx/{}", self.get_host(), transaction_id)) .send() .await .unwrap(); let transaction = request.json::<TransactionData>().await; transaction } pub async fn get_bundled_contract( &self, transaction_id: &str, ) -> reqwest::Result<BundledContract> { let request = self .client .get(format!("{}/{}", self.get_host(), transaction_id)) .send() .await .unwrap(); let transaction = request.json::<BundledContract>().await; transaction } pub async fn get_transaction_data(&self, transaction_id: &str) -> Vec<u8> { let request = self .client .get(format!("{}/{}", self.get_host(), transaction_id)) .send() .await .unwrap(); request.bytes().await.unwrap().to_vec() } pub async fn get_transaction_block( &self, transaction_id: &str, ) -> reqwest::Result<BlockInfo> { let request = self .client .get(format!("{}/tx/{}/status", self.get_host(), transaction_id)) .send() .await?; let status = request.json::<TransactionStatus>().await?; let block_hash = status.block_indep_hash; let request = self .client .get(format!("{}/block/hash/{}", self.get_host(), block_hash)) .send() .await?; request.json::<BlockInfo>().await } pub async fn get_network_info(&self) -> NetworkInfo { let info = self .client .get(format!("{}/info", self.get_host())) .send() .await .unwrap() .json::<NetworkInfo>() .await .unwrap(); info } pub async fn get_interactions( &self, contract_id: String, height: Option<usize>, cache: bool, ) -> Result<(Vec<GQLEdgeInterface>, usize, bool), AnyError> { let mut interactions: Option<Vec<GQLEdgeInterface>> = None; let height_result = match height { Some(size) => size, None => self.get_network_info().await.height, }; if cache { if let Some(cache_interactions) = get_cache() .lock() .unwrap() .find_interactions(contract_id.to_owned()) { if !cache_interactions.is_empty() { if height.is_some() { return Ok((cache_interactions, 0, false)); } interactions = Some(cache_interactions); } } } let variables = self .get_default_gql_variables(contract_id.to_owned(), height_result) .await; let mut final_result: Vec<GQLEdgeInterface> = Vec::new(); let mut new_transactions = false; let mut new_interactions_index: usize = 0; if let Some(mut cache_interactions) = interactions { let last_transaction_edge = cache_interactions.last().unwrap(); let has_more_from_last_interaction = self .has_more(&variables, last_transaction_edge.cursor.to_owned()) .await?; if has_more_from_last_interaction { // Start from what's going to be the next interaction. if doing len - 1, that would mean we will also include the last interaction cached: not ideal. new_interactions_index = cache_interactions.len(); let fetch_more_interactions = self .stream_interactions( Some(last_transaction_edge.cursor.to_owned()), variables.to_owned(), ) .await; for result in fetch_more_interactions { let mut new_tx_infos = result.edges.clone(); cache_interactions.append(&mut new_tx_infos); } new_transactions = true; } final_result.append(&mut cache_interactions); } else { let transactions = self .get_next_interaction_page(variables.clone(), false, None) .await?; let mut tx_infos = transactions.edges.clone(); let mut cursor: Option<String> = None; let max_edge = self.get_max_edges(&transactions.edges); let maybe_edge = transactions.edges.get(max_edge); if let Some(data) = maybe_edge { let owned = data; cursor = Some(owned.cursor.to_owned()); } let results = self.stream_interactions(cursor, variables).await; for result in results { let mut new_tx_infos = result.edges.clone(); tx_infos.append(&mut new_tx_infos); } final_result.append(&mut tx_infos); new_transactions = true; } let to_return: Vec<GQLEdgeInterface>; if new_transactions { let filtered: Vec<GQLEdgeInterface> = final_result .into_iter() .filter(|p| { (p.node.parent.is_none()) || p .node .parent .as_ref() .unwrap_or(&GQLNodeParent { id: None }) .id .is_none() || (p.node.bundledIn.is_none()) || p .node .bundledIn .as_ref() .unwrap_or(&GQLBundled { id: None }) .id .is_none() }) .collect(); if cache { get_cache() .lock() .unwrap() .cache_interactions(contract_id, &filtered); } to_return = filtered; } else { to_return = final_result; } let are_there_new_interactions = cache && new_transactions; Ok(( to_return, new_interactions_index, are_there_new_interactions, )) } async fn get_next_interaction_page( &self, mut variables: InteractionVariables, from_last_page: bool, max_results: Option<usize>, ) -> Result<GQLTransactionsResultInterface, AnyError> { let mut query = String::from( r#"query Transactions($tags: [TagFilter!]!, $blockFilter: BlockFilter!, $first: Int!, $after: String) { transactions(tags: $tags, block: $blockFilter, first: $first, sort: HEIGHT_ASC, after: $after) { pageInfo { hasNextPage } edges { node { id owner { address } recipient tags { name value } block { height id timestamp } fee { winston } quantity { winston } parent { id } } cursor } } }"#, ); if from_last_page { query = query.replace("HEIGHT_ASC", "HEIGHT_DESC"); variables.first = max_results.unwrap_or(100); } let graphql_query = GraphqlQuery { query, variables }; let req_url = format!("{}/graphql", self.get_host()); let result = self .client .post(req_url) .json(&graphql_query) .send() .await .unwrap(); let data = result.json::<GQLResultInterface>().await?; Ok(data.data.transactions) } pub async fn load_contract( &self, contract_id: String, contract_src_tx_id: Option<String>, contract_type: Option<String>, contract_init_state: Option<String>, cache: bool, simulated: bool, is_contract_in_bundled: bool, ) -> Result<LoadedContract, AnyError> { let mut result: Option<LoadedContract> = None; if is_contract_in_bundled { if let Ok(bundle_tx_search) = self.get_bundled_contract(&contract_id.clone()).await { let owner = bundle_tx_search .contractOwner .unwrap_or_else(|| String::new()); let content_type = bundle_tx_search .contentType .unwrap_or_else(|| String::new()); let mut init_state = bundle_tx_search.initState.unwrap_or_else(|| String::new()); let contract_data = bundle_tx_search.contractSrc; if simulated { if let Some(user_init_state) = contract_init_state { init_state = user_init_state; } } return Ok(LoadedContract { id: contract_id.clone(), contract_src_tx_id: contract_id.clone(), contract_src: contract_data, contract_type: get_contract_type_raw(content_type), init_state, min_fee: None, contract_transaction: TransactionData { format: 2, id: contract_id, last_tx: String::new(), owner, tags: vec![], target: String::new(), quantity: String::new(), data: String::new(), reward: String::new(), signature: String::new(), data_size: String::new(), data_root: String::new(), }, }); } else { panic!("Bundled contract was not found during query") } } if cache { result = get_cache() .lock() .unwrap() .find_contract(contract_id.to_owned()); } if result.is_some() { let mut cached_result = result.unwrap(); if simulated { if let Some(init_state) = contract_init_state { cached_result.init_state = init_state; } } Ok(cached_result) } else { let contract_transaction = self.get_transaction(&contract_id).await?; let contract_src = contract_src_tx_id .or_else(|| contract_transaction.get_tag("Contract-Src").ok()) .ok_or_else(|| { AnyError::msg("Contract-Src tag not found in transaction") })?; let min_fee = contract_transaction.get_tag("Min-Fee").ok(); let contract_src_tx = self.get_transaction(&contract_src).await?; let contract_src_data = self.get_transaction_data(&contract_src_tx.id).await; let mut state: String; if let Some(manual_init_state) = contract_init_state { state = manual_init_state; } else { if let Ok(init_state_tag) = contract_transaction.get_tag("Init-State") { state = init_state_tag; } else if let Ok(init_state_tag_txid) = contract_transaction.get_tag("Init-State-TX") { let init_state_tx = self.get_transaction(&init_state_tag_txid).await?; state = decode_base_64(init_state_tx.data); } else { state = decode_base_64(contract_transaction.data.to_owned()); if state.is_empty() { state = String::from_utf8( self.get_transaction_data(&contract_transaction.id).await, ) .unwrap(); } } } let contract_type = get_contract_type( contract_type, &contract_transaction, &contract_src_tx, )?; let final_result = LoadedContract { id: contract_id, contract_src_tx_id: contract_src, contract_src: contract_src_data, contract_type, init_state: state, min_fee, contract_transaction, }; if cache { get_cache().lock().unwrap().cache_contract(&final_result); } Ok(final_result) } } fn get_host(&self) -> String { let protocol = match self.protocol { ArweaveProtocol::HTTP => "http", ArweaveProtocol::HTTPS => "https", }; if self.port == 80 { format!("{}://{}", protocol, self.host) } else { format!("{}://{}:{}", protocol, self.host, self.port) } } async fn get_default_gql_variables( &self, contract_id: String, height: usize, ) -> InteractionVariables { let app_name_tag: TagFilter = TagFilter { name: "App-Name".to_owned(), values: vec!["SmartWeaveAction".to_owned()], }; let contract_tag: TagFilter = TagFilter { name: "Contract".to_owned(), values: vec![contract_id], }; let variables: InteractionVariables = InteractionVariables { tags: vec![app_name_tag, contract_tag], block_filter: BlockFilter { max: height }, first: MAX_REQUEST, after: None, }; variables } async fn stream_interactions( &self, cursor: Option<String>, variables: InteractionVariables, ) -> Vec<GQLTransactionsResultInterface> { stream::unfold(State::Next(cursor, variables), |state| async move { match state { State::End => None, State::Next(cursor, variables) => { let mut new_variables: InteractionVariables = variables.clone(); new_variables.after = cursor; let tx = self .get_next_interaction_page(new_variables, false, None) .await .unwrap(); if tx.edges.is_empty() { None } else { let max_requests = self.get_max_edges(&tx.edges); let edge = tx.edges.get(max_requests); if let Some(result_edge) = edge { let cursor = result_edge.cursor.to_owned(); Some((tx, State::Next(Some(cursor), variables))) } else { None } } } } }) .collect::<Vec<GQLTransactionsResultInterface>>() .await } fn get_max_edges(&self, data: &[GQLEdgeInterface]) -> usize { let len = data.len(); if len == MAX_REQUEST { MAX_REQUEST - 1 } else if len == 0 { len } else { len - 1 } } async fn has_more( &self, variables: &InteractionVariables, cursor: String, ) -> Result<bool, AnyError> { let mut variables = variables.to_owned(); variables.after = Some(cursor); variables.first = 1; let load_transactions = self .get_next_interaction_page(variables, false, None) .await?; Ok(!load_transactions.edges.is_empty()) } } #[cfg(test)] mod tests { use crate::arweave::Arweave; use crate::cache::ArweaveCache; use crate::cache::CacheExt; #[tokio::test] pub async fn test_build_host() { let arweave = Arweave::new( 80, String::from("arweave.net"), String::from("http"), ArweaveCache::new(), ); assert_eq!(arweave.get_host(), "http://arweave.net"); let arweave = Arweave::new( 443, String::from("arweave.net"), String::from("https"), ArweaveCache::new(), ); assert_eq!(arweave.get_host(), "https://arweave.net:443"); let arweave = Arweave::new( 500, String::from("arweave.net"), String::from("adksad"), ArweaveCache::new(), ); assert_eq!(arweave.get_host(), "https://arweave.net:500"); } }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/arweave/cache.rs
crates/arweave/cache.rs
use crate::arweave::LoadedContract; use crate::gql_result::GQLEdgeInterface; use deno_core::serde_json::Value; use indexmap::map::IndexMap; use serde::{Deserialize, Serialize}; use std::fmt::Debug; use std::fs::{create_dir_all, remove_file, File}; use std::io::BufReader; use std::path::PathBuf; pub trait CacheExt: Debug { fn new() -> Self where Self: Sized; fn find_contract(&mut self, contract_id: String) -> Option<LoadedContract>; fn find_interactions( &mut self, contract_id: String, ) -> Option<Vec<GQLEdgeInterface>>; fn find_state(&mut self, contract_id: String) -> Option<StateResult>; fn cache_contract(&mut self, loaded_contract: &LoadedContract); fn cache_interactions( &mut self, contract_id: String, interactions: &[GQLEdgeInterface], ); fn cache_states(&mut self, contract_id: String, state: StateResult); } #[derive(Debug)] pub struct ArweaveCache { pub contracts_cache_folder: PathBuf, pub interactions_cache_folder: PathBuf, pub states_cache_folder: PathBuf, } #[derive(Serialize, Deserialize, Clone)] pub struct StateResult { pub state: Value, pub validity: IndexMap<String, Value>, } impl Default for ArweaveCache { fn default() -> Self { Self::new() } } impl CacheExt for ArweaveCache { fn new() -> ArweaveCache { if let Some(cache_dir) = dirs::cache_dir() { let root_cache_dir = cache_dir.join("3em").join("contracts"); let interactions_cache_dir = cache_dir.join("3em").join("interactions"); let states_cache_dir = cache_dir.join("3em").join("states"); create_dir_all(&root_cache_dir).unwrap(); create_dir_all(&interactions_cache_dir).unwrap(); create_dir_all(&states_cache_dir).unwrap(); ArweaveCache { contracts_cache_folder: root_cache_dir, interactions_cache_folder: interactions_cache_dir, states_cache_folder: states_cache_dir, } } else { panic!("Cache folder could not be set"); } } fn find_contract(&mut self, contract_id: String) -> Option<LoadedContract> { let cache_file = self.get_cache_file(contract_id); let file = File::open(cache_file); match file { Ok(data) => { let reader = BufReader::new(data); let loaded_contract: LoadedContract = deno_core::serde_json::from_reader(reader).unwrap(); Some(loaded_contract) } Err(_) => None, } } fn find_interactions( &mut self, contract_id: String, ) -> Option<Vec<GQLEdgeInterface>> { let cache_file = self.get_cache_interaction_file(contract_id); let file = File::open(cache_file); match file { Ok(data) => { let reader = BufReader::new(data); let interactions: Vec<GQLEdgeInterface> = deno_core::serde_json::from_reader(reader).unwrap(); Some(interactions) } Err(_) => None, } } fn find_state(&mut self, contract_id: String) -> Option<StateResult> { let cache_file = self.get_cache_state_file(contract_id); let file = File::open(cache_file); match file { Ok(data) => { let reader = BufReader::new(data); let state: StateResult = deno_core::serde_json::from_reader(reader).unwrap(); Some(state) } Err(_) => None, } } fn cache_contract(&mut self, loaded_contract: &LoadedContract) { let cache_file = self.get_cache_file(loaded_contract.id.to_owned()); deno_core::serde_json::to_writer( &File::create(cache_file).unwrap(), loaded_contract, ) .unwrap(); } fn cache_interactions( &mut self, contract_id: String, interactions: &[GQLEdgeInterface], ) { let cache_file = self.get_cache_interaction_file(contract_id); deno_core::serde_json::to_writer( &File::create(cache_file).unwrap(), interactions, ) .unwrap(); } fn cache_states(&mut self, contract_id: String, state: StateResult) { let cache_file = self.get_cache_state_file(contract_id); deno_core::serde_json::to_writer( &File::create(cache_file).unwrap(), &state, ) .unwrap(); } } impl ArweaveCache { pub async fn delete_cache_interactions(&self, contract_id: String) { let cache_file = self.get_cache_interaction_file(contract_id); remove_file(cache_file).unwrap(); } fn get_cache_file(&self, contract_id: String) -> PathBuf { let mut cache_file = self.contracts_cache_folder.to_owned(); cache_file.push(format!("{}.json", contract_id)); cache_file } fn get_cache_interaction_file(&self, contract_id: String) -> PathBuf { let mut cache_file = self.interactions_cache_folder.to_owned(); cache_file.push(format!("{}.json", contract_id)); cache_file } fn get_cache_state_file(&self, contract_id: String) -> PathBuf { let mut cache_file = self.states_cache_folder.to_owned(); cache_file.push(format!("{}_result.json", contract_id)); cache_file } }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/arweave/lru_cache.rs
crates/arweave/lru_cache.rs
use crate::arweave::LoadedContract; use crate::cache::CacheExt; use crate::cache::StateResult; use crate::gql_result::GQLEdgeInterface; use lru::LruCache; #[derive(Debug)] pub struct ArweaveLruCache { contracts: LruCache<String, LoadedContract>, interactions: LruCache<String, Vec<GQLEdgeInterface>>, states: LruCache<String, StateResult>, } impl CacheExt for ArweaveLruCache { fn new() -> ArweaveLruCache { ArweaveLruCache { contracts: LruCache::unbounded(), interactions: LruCache::unbounded(), states: LruCache::unbounded(), } } fn find_contract(&mut self, contract_id: String) -> Option<LoadedContract> { self.contracts.get_mut(&contract_id).cloned() } fn find_interactions( &mut self, contract_id: String, ) -> Option<Vec<GQLEdgeInterface>> { self.interactions.get_mut(&contract_id).cloned() } fn find_state(&mut self, contract_id: String) -> Option<StateResult> { self.states.get_mut(&contract_id).cloned() } fn cache_contract(&mut self, loaded_contract: &LoadedContract) { self .contracts .put(loaded_contract.id.to_owned(), loaded_contract.clone()); } fn cache_interactions( &mut self, contract_id: String, interactions: &[GQLEdgeInterface], ) { self.interactions.put(contract_id, interactions.to_vec()); } fn cache_states(&mut self, contract_id: String, state: StateResult) { self.states.put(contract_id, state); } }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/wasm/lib.rs
crates/wasm/lib.rs
use deno_core::error::AnyError; use deno_core::serde_json::Value; use deno_core::JsRuntime; use deno_core::RuntimeOptions; use std::cell::Cell; use three_em_js::{snapshot, Error}; use three_em_smartweave::{read_contract_state, InteractionContext}; macro_rules! wasm_alloc { ($scope: expr, $alloc: expr, $this: expr, $len: expr) => { $alloc.call($scope, $this.into(), &[$len.into()]).unwrap() }; } pub struct WasmRuntime { rt: JsRuntime, /// The contract handler. /// `handle(state_ptr, state_len, action_ptr, action_len) -> result_ptr` /// Length of the result can be obtained by calling `WasmRuntime::result_len`. handle: v8::Global<v8::Function>, /// The length of the updated state. /// `get_len() -> usize` result_len: v8::Global<v8::Function>, /// Memory allocator for the contract. /// `_alloc(size) -> ptr` allocator: v8::Global<v8::Function>, /// `WebAssembly.Instance.exports` object. exports: v8::Global<v8::Object>, } impl WasmRuntime { pub fn new(wasm: &[u8]) -> Result<WasmRuntime, AnyError> { let mut rt = JsRuntime::new(RuntimeOptions { startup_snapshot: Some(snapshot::snapshot()), ..Default::default() }); // Get hold of the WebAssembly object. let wasm_obj = rt.execute_script("<anon>", "WebAssembly").unwrap(); let (exports, handle, allocator, result_len) = { let scope = &mut rt.handle_scope(); let buf = v8::ArrayBuffer::new_backing_store_from_boxed_slice(wasm.into()); let buf = v8::SharedRef::from(buf); let buf = v8::ArrayBuffer::with_backing_store(scope, &buf); let wasm_obj = wasm_obj.open(scope).to_object(scope).unwrap(); // Create a new WebAssembly.Instance object. let module_str = v8::String::new(scope, "Module").unwrap(); let module_value = wasm_obj.get(scope, module_str.into()).unwrap(); let module_constructor = v8::Local::<v8::Function>::try_from(module_value)?; let module = module_constructor .new_instance(scope, &[buf.into()]) .unwrap(); // Create a new WebAssembly.Instance object. let instance_str = v8::String::new(scope, "Instance").unwrap(); let instance_value = wasm_obj.get(scope, instance_str.into()).unwrap(); let instance_constructor = v8::Local::<v8::Function>::try_from(instance_value)?; let imports = v8::Object::new(scope); // AssemblyScript needs `abort` to be defined. let env = v8::Object::new(scope); let abort_str = v8::String::new(scope, "abort").unwrap(); let function_callback = |_: &mut v8::HandleScope, _: v8::FunctionCallbackArguments, _: v8::ReturnValue| { // No-op. }; let abort_callback = v8::Function::new(scope, function_callback).unwrap(); env.set(scope, abort_str.into(), abort_callback.into()); let env_str = v8::String::new(scope, "env").unwrap(); imports.set(scope, env_str.into(), env.into()); let ns = v8::Object::new(scope); let read_state_str = v8::String::new(scope, "smartweave_read_state").unwrap(); let read_state = |scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue| { let ctx = scope.get_current_context(); let global = ctx.global(scope); let exports_str = v8::String::new(scope, "exports").unwrap(); let exports = global.get(scope, exports_str.into()).unwrap(); let exports = v8::Local::<v8::Object>::try_from(exports).unwrap(); let mem_str = v8::String::new(scope, "memory").unwrap(); let mem_obj = exports.get(scope, mem_str.into()).unwrap(); let mem_obj = v8::Local::<v8::Object>::try_from(mem_obj).unwrap(); let buffer_str = v8::String::new(scope, "buffer").unwrap(); let buffer_obj = mem_obj.get(scope, buffer_str.into()).unwrap(); let alloc_str = v8::String::new(scope, "_alloc").unwrap(); let alloc_obj = exports.get(scope, alloc_str.into()).unwrap(); let alloc = v8::Local::<v8::Function>::try_from(alloc_obj).unwrap(); let undefined = v8::undefined(scope); let mem_buf = v8::Local::<v8::ArrayBuffer>::try_from(buffer_obj).unwrap(); let store = mem_buf.get_backing_store(); let tx_id_ptr = args .get(0) .to_number(scope) .unwrap() .int32_value(scope) .unwrap(); let tx_id_len = args .get(1) .to_number(scope) .unwrap() .int32_value(scope) .unwrap(); let tx_bytes = unsafe { get_backing_store_slice_mut( &store, tx_id_ptr as usize, tx_id_len as usize, ) }; let length_ptr = args .get(2) .to_number(scope) .unwrap() .int32_value(scope) .unwrap(); let len_bytes = unsafe { get_backing_store_slice_mut(&store, length_ptr as usize, 4) }; let tx_id = String::from_utf8_lossy(tx_bytes).to_string(); let state = read_contract_state(tx_id); let mut state = deno_core::serde_json::to_vec(&state).unwrap(); let mut state_len = (state.len() as u32).to_le_bytes(); len_bytes.swap_with_slice(&mut state_len); let state_len = v8::Number::new(scope, state.len() as f64); let state_ptr = wasm_alloc!(scope, alloc, undefined, state_len); let state_region = unsafe { get_backing_store_slice_mut( &store, state_ptr.uint32_value(scope).unwrap() as usize, state.len(), ) }; state_region.swap_with_slice(&mut state); rv.set(state_ptr); }; let read_state_callback = v8::Function::new(scope, read_state).unwrap(); ns.set(scope, read_state_str.into(), read_state_callback.into()); let consume_gas_str = v8::String::new(scope, "consumeGas").unwrap(); let consume_gas = |scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, _: v8::ReturnValue| { let inc = args .get(0) .to_number(scope) .unwrap() .int32_value(scope) .unwrap(); let ctx = scope.get_current_context(); let global = ctx.global(scope); let cost_str = v8::String::new(scope, "COST").unwrap(); let cost = global.get(scope, cost_str.into()).unwrap(); let cost = cost.int32_value(scope).unwrap(); let cost = cost + inc; let cost = v8::Number::new(scope, cost as f64); global.set(scope, cost_str.into(), cost.into()).unwrap(); }; let consume_gas_callback = v8::Function::new(scope, consume_gas).unwrap(); ns.set(scope, consume_gas_str.into(), consume_gas_callback.into()); let ctx = scope.get_current_context(); let global = ctx.global(scope); // >> throw_error let throw_error_str = v8::String::new(scope, "throw_error").unwrap(); let throw_error = |scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, _: v8::ReturnValue| { let ctx = scope.get_current_context(); let global = ctx.global(scope); let exports_str = v8::String::new(scope, "exports").unwrap(); let exports = global.get(scope, exports_str.into()).unwrap(); let exports = v8::Local::<v8::Object>::try_from(exports).unwrap(); let mem_str = v8::String::new(scope, "memory").unwrap(); let mem_obj = exports.get(scope, mem_str.into()).unwrap(); let mem_obj = v8::Local::<v8::Object>::try_from(mem_obj).unwrap(); let buffer_str = v8::String::new(scope, "buffer").unwrap(); let buffer_obj = mem_obj.get(scope, buffer_str.into()).unwrap(); let mem_buf = v8::Local::<v8::ArrayBuffer>::try_from(buffer_obj).unwrap(); let store = mem_buf.get_backing_store(); let error_ptr = args .get(0) .to_number(scope) .unwrap() .int32_value(scope) .unwrap(); let error_len = args .get(1) .to_number(scope) .unwrap() .int32_value(scope) .unwrap(); let error_bytes = unsafe { get_backing_store_slice_mut( &store, error_ptr as usize, error_len as usize, ) }; // throw error let error_str = String::from_utf8_lossy(error_bytes).to_string(); let error_str = v8::String::new(scope, &error_str).unwrap(); let error = v8::Exception::error(scope, error_str); scope.throw_exception(error.into()); }; let throw_error_callback = v8::Function::new(scope, throw_error).unwrap(); ns.set(scope, throw_error_str.into(), throw_error_callback.into()); let ns_str = v8::String::new(scope, "3em").unwrap(); imports.set(scope, ns_str.into(), ns.into()); // wasi_snapshot_preview1 let wasi_ns = v8::Object::new(scope); let wasi_snapshot_preview1_str = v8::String::new(scope, "wasi_snapshot_preview1").unwrap(); let wasi_fd_close = v8::String::new(scope, "fd_close").unwrap(); let wasi_fd_close_callback = |_: &mut v8::HandleScope, _: v8::FunctionCallbackArguments, _: v8::ReturnValue| { // No-op. }; let wasi_fd_close_callback = v8::Function::new(scope, wasi_fd_close_callback).unwrap(); wasi_ns.set(scope, wasi_fd_close.into(), wasi_fd_close_callback.into()); let wasi_fd_seek = v8::String::new(scope, "fd_seek").unwrap(); let wasi_fd_seek_callback = |_: &mut v8::HandleScope, _: v8::FunctionCallbackArguments, _: v8::ReturnValue| { // No-op. }; let wasi_fd_seek_callback = v8::Function::new(scope, wasi_fd_seek_callback).unwrap(); wasi_ns.set(scope, wasi_fd_seek.into(), wasi_fd_seek_callback.into()); let wasi_fd_write = v8::String::new(scope, "fd_write").unwrap(); let wasi_fd_write_callback = |_: &mut v8::HandleScope, _: v8::FunctionCallbackArguments, _: v8::ReturnValue| { // No-op. }; let wasi_fd_write_callback = v8::Function::new(scope, wasi_fd_write_callback).unwrap(); wasi_ns.set(scope, wasi_fd_write.into(), wasi_fd_write_callback.into()); imports.set(scope, wasi_snapshot_preview1_str.into(), wasi_ns.into()); // << End wasi_snapshot_preview1 let instance = instance_constructor .new_instance(scope, &[module.into(), imports.into()]) .unwrap(); let exports_str = v8::String::new(scope, "exports").unwrap(); let exports = instance.get(scope, exports_str.into()).unwrap(); let exports = v8::Local::<v8::Object>::try_from(exports)?; global .set(scope, exports_str.into(), exports.into()) .unwrap(); let cost_str = v8::String::new(scope, "COST").unwrap(); let cost = v8::Number::new(scope, 0.0); global.set(scope, cost_str.into(), cost.into()).unwrap(); let alloc_str = v8::String::new(scope, "_alloc").unwrap(); let alloc_obj = exports.get(scope, alloc_str.into()).unwrap(); let allocator = v8::Local::<v8::Function>::try_from(alloc_obj)?; let allocator = v8::Global::new(scope, allocator); let handle_str = v8::String::new(scope, "handle").unwrap(); let handle_obj = exports.get(scope, handle_str.into()).unwrap(); let handle = v8::Local::<v8::Function>::try_from(handle_obj)?; let handle = v8::Global::new(scope, handle); let result_len_str = v8::String::new(scope, "get_len").unwrap(); let result_len_obj = exports.get(scope, result_len_str.into()).unwrap(); let result_len = v8::Local::<v8::Function>::try_from(result_len_obj)?; let result_len = v8::Global::new(scope, result_len); let exports = v8::Global::new(scope, exports); let undefined = v8::undefined(scope); let alloc_obj = allocator.open(scope).to_object(scope).unwrap(); let alloc = v8::Local::<v8::Function>::try_from(alloc_obj)?; (exports, handle, allocator, result_len) }; Ok(Self { rt, handle, allocator, result_len, exports, }) } pub fn get_cost(&mut self) -> usize { let scope = &mut self.rt.handle_scope(); let ctx = scope.get_current_context(); let global = ctx.global(scope); let cost_str = v8::String::new(scope, "COST").unwrap(); let cost = global.get(scope, cost_str.into()).unwrap(); let cost = v8::Local::<v8::Number>::try_from(cost).unwrap(); let cost = cost.int32_value(scope).unwrap(); cost as usize } pub fn call( &mut self, state: &mut [u8], action: &mut [u8], interaction_context: InteractionContext, ) -> Result<Vec<u8>, AnyError> { let mut interaction = deno_core::serde_json::to_vec(&interaction_context)?; let interaction_len_high_level = interaction.len(); let result = { let scope = &mut self.rt.handle_scope(); let undefined = v8::undefined(scope); let alloc_obj = self.allocator.open(scope).to_object(scope).unwrap(); let alloc = v8::Local::<v8::Function>::try_from(alloc_obj)?; let state_len = v8::Number::new(scope, state.len() as f64); let action_len = v8::Number::new(scope, action.len() as f64); let interaction_len = v8::Number::new(scope, interaction_len_high_level as f64); let interaction_ptr_high_level = wasm_alloc!(scope, alloc, undefined, interaction_len); let interaction_ptr_32: u32 = interaction_ptr_high_level.uint32_value(scope).unwrap(); let interaction_ptr = v8::Number::new(scope, interaction_ptr_32 as f64); let interaction_len = v8::Number::new(scope, interaction_len_high_level as f64); // Offset in memory for start of the block. let local_ptr = wasm_alloc!(scope, alloc, undefined, state_len); let local_ptr_u32 = local_ptr.uint32_value(scope).unwrap(); let action_ptr = wasm_alloc!(scope, alloc, undefined, action_len); let action_ptr_u32 = action_ptr.uint32_value(scope).unwrap(); let exports_obj = self.exports.open(scope).to_object(scope).unwrap(); let mem_str = v8::String::new(scope, "memory").unwrap(); let mem_obj = exports_obj.get(scope, mem_str.into()).unwrap(); let mem_obj = v8::Local::<v8::Object>::try_from(mem_obj)?; let buffer_str = v8::String::new(scope, "buffer").unwrap(); let buffer_obj = mem_obj.get(scope, buffer_str.into()).unwrap(); let mem_buf = v8::Local::<v8::ArrayBuffer>::try_from(buffer_obj)?; // O HOLY Backin' store. let store = mem_buf.get_backing_store(); let state_mem_region = unsafe { get_backing_store_slice_mut(&store, local_ptr_u32 as usize, state.len()) }; state_mem_region.swap_with_slice(state); let action_region = unsafe { get_backing_store_slice_mut( &store, action_ptr_u32 as usize, action.len(), ) }; action_region.swap_with_slice(action); let contract_mem_region = unsafe { get_backing_store_slice_mut( &store, interaction_ptr_32 as usize, interaction_len_high_level, ) }; contract_mem_region.swap_with_slice(&mut interaction); let handler_obj = self.handle.open(scope).to_object(scope).unwrap(); let handle = v8::Local::<v8::Function>::try_from(handler_obj)?; let result_ptr = handle .call( scope, undefined.into(), &[ local_ptr, state_len.into(), action_ptr, action_len.into(), interaction_ptr.into(), interaction_len.into(), ], ) .ok_or(Error::Terminated)?; let result_ptr_u32 = result_ptr.uint32_value(scope).unwrap(); let get_len_obj = self.result_len.open(scope).to_object(scope).unwrap(); let get_len = v8::Local::<v8::Function>::try_from(get_len_obj)?; let result_len = get_len.call(scope, undefined.into(), &[]).unwrap(); let result_len = result_len.uint32_value(scope).unwrap(); let result_mem = unsafe { get_backing_store_slice_mut( &store, result_ptr_u32 as usize, result_len as usize, ) }; result_mem.to_vec() }; Ok(result) } } #[allow(clippy::mut_from_ref)] unsafe fn get_backing_store_slice_mut( backing_store: &v8::SharedRef<v8::BackingStore>, byte_offset: usize, byte_length: usize, ) -> &mut [u8] { let cells: *const [Cell<u8>] = &backing_store[byte_offset..byte_offset + byte_length]; let bytes = cells as *const _ as *mut [u8]; &mut *bytes } #[cfg(test)] mod tests { use crate::WasmRuntime; use deno_core::serde_json::json; use deno_core::serde_json::Value; use three_em_smartweave::{ InteractionBlock, InteractionContext, InteractionTx, }; #[tokio::test] async fn test_wasm_runtime_contract() { let mut rt = WasmRuntime::new(include_bytes!("../../testdata/01_wasm/01_wasm.wasm")) .unwrap(); let action = json!({}); let mut action_bytes = deno_core::serde_json::to_vec(&action).unwrap(); let prev_state = json!({ "counter": 0, }); let mut prev_state_bytes = deno_core::serde_json::to_vec(&prev_state).unwrap(); let state = rt .call( &mut prev_state_bytes, &mut action_bytes, InteractionContext { transaction: InteractionTx::default(), block: InteractionBlock::default(), }, ) .unwrap(); let state: Value = deno_core::serde_json::from_slice(&state).unwrap(); assert_eq!(state.get("counter").unwrap(), 1); // No cost without metering. assert_eq!(rt.get_cost(), 0); } #[tokio::test] async fn test_wasm_panic() { let mut rt = WasmRuntime::new(include_bytes!("../../testdata/01_wasm/01_wasm.wasm")) .unwrap(); let action = json!({}); let mut action_bytes = deno_core::serde_json::to_vec(&action).unwrap(); let mut prev_state_bytes = vec![]; let state = rt .call( &mut prev_state_bytes, &mut action_bytes, InteractionContext { transaction: InteractionTx::default(), block: InteractionBlock::default(), }, ) .expect_err("should panic"); } #[tokio::test] async fn test_wasm_runtime_asc() { let mut rt = WasmRuntime::new(include_bytes!("../../testdata/02_wasm/02_wasm.wasm")) .unwrap(); let mut prev_state = json!({ "counter": 0, }); let action = json!({}); let mut action_bytes = deno_core::serde_json::to_vec(&action).unwrap(); for i in 1..100 { let mut prev_state_bytes = deno_core::serde_json::to_vec(&prev_state).unwrap(); let state = rt .call(&mut prev_state_bytes, &mut action_bytes, Default::default()) .unwrap(); let state: Value = deno_core::serde_json::from_slice(&state).unwrap(); assert_eq!(state.get("counter").unwrap(), i); prev_state = state; } // No cost without metering. assert_eq!(rt.get_cost(), 0); } #[tokio::test] async fn test_wasm_runtime_contract_interaction_context() { let mut rt = WasmRuntime::new(include_bytes!("../../testdata/03_wasm/03_wasm.wasm")) .unwrap(); let action = json!({}); let mut action_bytes = deno_core::serde_json::to_vec(&action).unwrap(); let prev_state = json!({ "txId": "", "owner": "", "height": 0 }); let mut prev_state_bytes = deno_core::serde_json::to_vec(&prev_state).unwrap(); let state = rt .call( &mut prev_state_bytes, &mut action_bytes, InteractionContext { transaction: InteractionTx { id: String::from("POCAHONTAS"), owner: String::from("ANDRES1234"), tags: vec![], target: String::new(), quantity: String::new(), reward: String::new(), }, block: InteractionBlock { height: 100, indep_hash: String::new(), timestamp: 0, }, }, ) .unwrap(); let state: Value = deno_core::serde_json::from_slice(&state).unwrap(); assert_eq!(state.get("txId").unwrap(), "POCAHONTAS"); assert_eq!(state.get("owner").unwrap(), "ANDRES1234"); assert_eq!(state.get("height").unwrap(), 100); // No cost without metering. assert_eq!(rt.get_cost(), 0); } }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/exm/lib.rs
crates/exm/lib.rs
use deno_core::error::AnyError; use deno_core::include_js_files; use deno_ops::op; use deno_core::serde::{Deserialize, Serialize}; use deno_core::serde_json::Value; use deno_core::Extension; use deno_core::OpState; use deno_core::ZeroCopyBuf; use std::cell::RefCell; use std::collections::HashMap; use std::future::Future; use std::rc::Rc; use std::{env, thread}; use three_em_arweave::gql_result::GQLTagInterface; pub struct ExecutorSettings { settings: HashMap<String, Value>, } #[derive(Deserialize)] pub struct DeterministicFetchOptions { url: String, } #[derive(Deserialize, Serialize, Default, Clone)] pub struct DeterministicFetchBody { #[serde(rename = "type")] pub req_type: String, pub url: String, pub statusText: String, pub status: i8, pub redirected: bool, pub ok: bool, pub headers: HashMap<String, String>, pub vector: Vec<u8>, } #[derive(Deserialize, Serialize, Default, Clone)] pub struct Data { pub instantiated: bool, } impl Data { pub fn new() -> Data { Data { instantiated: false, } } } #[derive(Deserialize, Serialize, Default, Clone)] pub struct ExmContext { pub requests: HashMap<String, DeterministicFetchBody>, pub kv: HashMap<String, deno_core::serde_json::Value>, //pub data: Data, } pub fn init(executor_settings: HashMap<String, Value>) -> Extension { Extension::builder() .js(include_js_files!( prefix "3em:baseops", "base.js", )) .ops(vec![ op_get_executor_settings::decl(), op_exm_write_to_console::decl(), ]) .state(move |state| { state.put(ExecutorSettings { settings: executor_settings.clone(), }); Ok(()) }) .build() } #[op] pub fn op_get_executor_settings( _state: &mut OpState, setting: String, _: (), ) -> Result<Value, AnyError> { let s = _state; let settings = s.borrow::<ExecutorSettings>(); if let Some(data) = settings.settings.get(&setting) { Ok(data.clone()) } else { Ok(Value::Null) } } #[op] pub fn op_exm_write_to_console(_: &mut OpState, content: String, _: ()) { println!("{}", content); }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/metering/lib.rs
crates/metering/lib.rs
#![allow(unused_assignments)] use std::borrow::Cow; use wasm_encoder::BlockType; use wasm_encoder::CodeSection; use wasm_encoder::ElementSection; use wasm_encoder::EntityType; use wasm_encoder::Function; use wasm_encoder::ImportSection; pub use wasm_encoder::Instruction; use wasm_encoder::MemArg; use wasm_encoder::Module; use wasm_encoder::RawSection; use wasm_encoder::SectionId; use wasm_encoder::StartSection; use wasm_encoder::TypeSection; use wasm_encoder::ValType; use wasmparser::Chunk; use wasmparser::CodeSectionReader; use wasmparser::ImportSectionEntryType; use wasmparser::MemoryImmediate; use wasmparser::Operator; use wasmparser::Parser; use wasmparser::Payload; use wasmparser::Result; use wasmparser::SectionReader; use wasmparser::Type; use wasmparser::TypeDef; use wasmparser::TypeOrFuncType; pub use wasm_encoder; pub use wasmparser; /// 3EM's WebAssembly metering module. pub struct Metering( // Cost function Box<dyn Fn(&Instruction) -> i32>, ); impl Metering { pub fn new<T>(cost_fn: T) -> Self where T: Fn(&Instruction) -> i32 + 'static, { Self(Box::new(cost_fn)) } pub fn inject(&self, input: &[u8]) -> Result<Module> { let mut source = input; let mut parser = Parser::new(0); let mut module = Module::new(); let mut consume_gas_index = -1; let mut func_idx: i32 = -1; // Temporary store for payloads. // We'd want to wait until the imports section // is processed i.e. func_idx >= 0 let mut pending_payloads = vec![]; loop { let (payload, consumed) = match parser.parse(source, true)? { Chunk::NeedMoreData(_) => unreachable!(), Chunk::Parsed { consumed, payload } => (payload, consumed), }; match payload { Payload::ImportSection(reader) => { let mut imports = ImportSection::new(); for import in reader { let import = import?; let ty = match import.ty { ImportSectionEntryType::Function(ty) => { if func_idx == -1 { func_idx = 0 }; func_idx += 1; EntityType::Function(ty) } ImportSectionEntryType::Table(wasmparser::TableType { element_type, initial: minimum, maximum, }) => EntityType::Table(wasm_encoder::TableType { element_type: map_type(element_type), minimum, maximum, }), ImportSectionEntryType::Memory(wasmparser::MemoryType { memory64, shared: _, initial: minimum, maximum, }) => EntityType::Memory(wasm_encoder::MemoryType { memory64, minimum, maximum, }), ImportSectionEntryType::Tag(wasmparser::TagType { type_index: func_type_idx, }) => EntityType::Tag(wasm_encoder::TagType { kind: wasm_encoder::TagKind::Exception, func_type_idx, }), ImportSectionEntryType::Global(wasmparser::GlobalType { mutable, content_type, }) => EntityType::Global(wasm_encoder::GlobalType { mutable, val_type: map_type(content_type), }), ImportSectionEntryType::Module(idx) => EntityType::Module(idx), ImportSectionEntryType::Instance(idx) => { EntityType::Instance(idx) } }; imports.import(import.module, import.field, ty); } imports.import( "3em", Some("consumeGas"), EntityType::Function(consume_gas_index as u32), ); module.section(&imports); } Payload::TypeSection(reader) => { let mut types = TypeSection::new(); for ty in reader { let ty = ty?; match ty { TypeDef::Func(func) => { let params: Vec<ValType> = func.params.iter().map(|ty| map_type(*ty)).collect(); let returns: Vec<ValType> = func.returns.iter().map(|ty| map_type(*ty)).collect(); types.function(params, returns); } TypeDef::Instance(instance) => { let exports: Vec<(&str, EntityType)> = instance .exports .iter() .map(|export| { let ty = match export.ty { ImportSectionEntryType::Function(ty) => { EntityType::Function(ty) } ImportSectionEntryType::Table( wasmparser::TableType { element_type, initial: minimum, maximum, }, ) => EntityType::Table(wasm_encoder::TableType { element_type: map_type(element_type), minimum, maximum, }), ImportSectionEntryType::Memory( wasmparser::MemoryType { memory64, shared: _, initial: minimum, maximum, }, ) => EntityType::Memory(wasm_encoder::MemoryType { memory64, minimum, maximum, }), ImportSectionEntryType::Tag(wasmparser::TagType { type_index: func_type_idx, }) => EntityType::Tag(wasm_encoder::TagType { kind: wasm_encoder::TagKind::Exception, func_type_idx, }), ImportSectionEntryType::Global( wasmparser::GlobalType { mutable, content_type, }, ) => EntityType::Global(wasm_encoder::GlobalType { mutable, val_type: map_type(content_type), }), ImportSectionEntryType::Module(idx) => { EntityType::Module(idx) } ImportSectionEntryType::Instance(idx) => { EntityType::Instance(idx) } }; let name = export.name; (name, ty) }) .collect(); types.instance(exports); } TypeDef::Module(module) => { let imports: Vec<(&str, Option<&str>, EntityType)> = module .imports .iter() .map(|import| { let ty = match import.ty { ImportSectionEntryType::Function(ty) => { EntityType::Function(ty) } ImportSectionEntryType::Table( wasmparser::TableType { element_type, initial: minimum, maximum, }, ) => EntityType::Table(wasm_encoder::TableType { element_type: map_type(element_type), minimum, maximum, }), ImportSectionEntryType::Memory( wasmparser::MemoryType { memory64, shared: _, initial: minimum, maximum, }, ) => EntityType::Memory(wasm_encoder::MemoryType { memory64, minimum, maximum, }), ImportSectionEntryType::Tag(wasmparser::TagType { type_index: func_type_idx, }) => EntityType::Tag(wasm_encoder::TagType { kind: wasm_encoder::TagKind::Exception, func_type_idx, }), ImportSectionEntryType::Global( wasmparser::GlobalType { mutable, content_type, }, ) => EntityType::Global(wasm_encoder::GlobalType { mutable, val_type: map_type(content_type), }), ImportSectionEntryType::Module(idx) => { EntityType::Module(idx) } ImportSectionEntryType::Instance(idx) => { EntityType::Instance(idx) } }; let module = import.module; let field = import.field; (module, field, ty) }) .collect(); let exports: Vec<(&str, EntityType)> = module .exports .iter() .map(|export| { let ty = match export.ty { ImportSectionEntryType::Function(ty) => { EntityType::Function(ty) } ImportSectionEntryType::Table( wasmparser::TableType { element_type, initial: minimum, maximum, }, ) => EntityType::Table(wasm_encoder::TableType { element_type: map_type(element_type), minimum, maximum, }), ImportSectionEntryType::Memory( wasmparser::MemoryType { memory64, shared: _, initial: minimum, maximum, }, ) => EntityType::Memory(wasm_encoder::MemoryType { memory64, minimum, maximum, }), ImportSectionEntryType::Tag(wasmparser::TagType { type_index: func_type_idx, }) => EntityType::Tag(wasm_encoder::TagType { kind: wasm_encoder::TagKind::Exception, func_type_idx, }), ImportSectionEntryType::Global( wasmparser::GlobalType { mutable, content_type, }, ) => EntityType::Global(wasm_encoder::GlobalType { mutable, val_type: map_type(content_type), }), ImportSectionEntryType::Module(idx) => { EntityType::Module(idx) } ImportSectionEntryType::Instance(idx) => { EntityType::Instance(idx) } }; let name = export.name; (name, ty) }) .collect(); types.module(imports, exports); } } } types.function([ValType::I32], []); consume_gas_index = types.len() as i32 - 1; module.section(&types); } Payload::Version { .. } => {} Payload::End => break, _ => pending_payloads.push(payload), }; source = &source[consumed..]; } // No types section? Make one :-) if consume_gas_index == -1 { let mut types = TypeSection::new(); types.function([ValType::I32], []); // This is the only type defined. consume_gas_index = 0; module.section(&types); } // There is no import section. Make one. if func_idx == -1 { let mut imports = ImportSection::new(); imports.import( "3em", Some("consumeGas"), EntityType::Function(consume_gas_index as u32), ); func_idx = 0; module.section(&imports); } for payload in pending_payloads { match payload { Payload::StartSection { func, range: _ } => { let function_index = if func >= func_idx as u32 { func + 1 } else { func }; let start = StartSection { function_index }; module.section(&start); } Payload::CodeSectionStart { count: _, range, size: _, } => { let section = &input[range.start..range.end]; let reader = CodeSectionReader::new(section, 0)?; let mut section = CodeSection::new(); for body in reader { let body = body?; // Preserve the locals. let locals = match body.get_locals_reader() { Ok(locals) => { locals.into_iter().collect::<Result<Vec<(u32, Type)>>>()? } Err(_) => vec![], }; let locals: Vec<(u32, ValType)> = locals.into_iter().map(|(i, t)| (i, map_type(t))).collect(); let mut func = Function::new(locals); let operators = body.get_operators_reader()?; let operators = operators.into_iter().collect::<Result<Vec<Operator>>>()?; for op in operators { let instruction = map_operator(op, func_idx as i32)?; let cost = self.0(&instruction); // There is no such thing as negative cost. // If the cost function returns a negative value // the gas is skipped. if cost >= 0 { func.instruction(&Instruction::I32Const(cost)); func.instruction(&Instruction::Call(func_idx as u32)); } func.instruction(&instruction); } section.function(&func); } module.section(&section); // FIXME: This is probably not correct. But I forgot why I put this here. source = &input[range.end..]; continue; } Payload::DataCountSection { count: _, range } => { module.section(&RawSection { id: SectionId::DataCount as u8, data: &input[range.start..range.end], }); } Payload::FunctionSection(reader) => { let range = reader.range(); module.section(&RawSection { id: SectionId::Function as u8, data: &input[range.start..range.end], }); } Payload::TableSection(reader) => { let range = reader.range(); module.section(&RawSection { id: SectionId::Table as u8, data: &input[range.start..range.end], }); } Payload::MemorySection(reader) => { let range = reader.range(); module.section(&RawSection { id: SectionId::Memory as u8, data: &input[range.start..range.end], }); } Payload::GlobalSection(reader) => { let range = reader.range(); module.section(&RawSection { id: SectionId::Global as u8, data: &input[range.start..range.end], }); } Payload::ExportSection(reader) => { let mut section = wasm_encoder::ExportSection::new(); for export in reader { let export = export?; let idx = export.index; let field = export.field; let export = match export.kind { wasmparser::ExternalKind::Function => { let idx = if idx >= func_idx as u32 { idx + 1 } else { idx }; wasm_encoder::Export::Function(idx) } wasmparser::ExternalKind::Table => { wasm_encoder::Export::Table(idx) } wasmparser::ExternalKind::Memory => { wasm_encoder::Export::Memory(idx) } wasmparser::ExternalKind::Tag => wasm_encoder::Export::Tag(idx), wasmparser::ExternalKind::Global => { wasm_encoder::Export::Global(idx) } wasmparser::ExternalKind::Type => { unreachable!("No encoder mappings") } wasmparser::ExternalKind::Module => { wasm_encoder::Export::Module(idx) } wasmparser::ExternalKind::Instance => { wasm_encoder::Export::Instance(idx) } }; section.export(field, export); } module.section(&section); } Payload::ElementSection(reader) => { let mut section = ElementSection::new(); for element in reader { let element = element?; let element_type = map_type(element.ty); let mut funcs = vec![]; for item in element.items.get_items_reader().unwrap() { match item.unwrap() { wasmparser::ElementItem::Func(idx) => { let idx = if idx >= func_idx as u32 { idx + 1 } else { idx }; funcs.push(idx); } wasmparser::ElementItem::Expr(_) => { todo!("Implement Expr Item.") } } } let elements = wasm_encoder::Elements::Functions(&funcs); match element.kind { wasmparser::ElementKind::Passive => { section.passive(element_type, elements); } wasmparser::ElementKind::Active { table_index, init_expr, } => { let mut reader = init_expr.get_operators_reader(); let op = reader.read()?; // A "constant-time" instruction // (*.const or global.get) let offset = map_operator(op, func_idx as i32)?; section.active( Some(table_index), &offset, element_type, elements, ); } wasmparser::ElementKind::Declared => { section.declared(element_type, elements); } }; } module.section(&section); } Payload::DataSection(reader) => { let range = reader.range(); module.section(&RawSection { id: SectionId::Data as u8, data: &input[range.start..range.end], }); } Payload::CustomSection { name: _, data_offset: _, data: _, range, } => { module.section(&RawSection { id: SectionId::Custom as u8, data: &input[range.start..range.end], }); } Payload::AliasSection(reader) => { let range = reader.range(); module.section(&RawSection { id: SectionId::Alias as u8, data: &input[range.start..range.end], }); } Payload::UnknownSection { id, contents: _, range, } => { module.section(&RawSection { id, data: &input[range.start..range.end], }); } Payload::InstanceSection(reader) => { let range = reader.range(); module.section(&RawSection { id: SectionId::Instance as u8, data: &input[range.start..range.end], }); } Payload::TagSection(reader) => { let range = reader.range(); module.section(&RawSection { id: SectionId::Tag as u8, data: &input[range.start..range.end], }); } Payload::CodeSectionEntry(_) => { // Already parsed in Payload::CodeSectionStart // unreachable!(); } Payload::ModuleSectionStart { count: _, size: _, range, } => { module.section(&RawSection { id: SectionId::Module as u8, data: &input[range.start..range.end], }); } Payload::ModuleSectionEntry { parser: _, range } => { module.section(&RawSection { id: SectionId::Module as u8, data: &input[range.start..range.end], }); } _ => unreachable!(), } } Ok(module) } } fn map_operator(operator: Operator, gas_idx: i32) -> Result<Instruction> { let inst = match operator { Operator::Unreachable => Instruction::Unreachable, Operator::Nop => Instruction::Nop, Operator::Block { ty, .. } => Instruction::Block(map_block_type(ty)), Operator::Loop { ty, .. } => Instruction::Loop(map_block_type(ty)), Operator::If { ty, .. } => Instruction::If(map_block_type(ty)), Operator::Else => Instruction::Else, Operator::Try { ty, .. } => Instruction::Try(map_block_type(ty)), Operator::Catch { index } => Instruction::Catch(index), Operator::Throw { index } => Instruction::Throw(index), Operator::Rethrow { relative_depth } => { Instruction::Rethrow(relative_depth) } Operator::End => Instruction::End, Operator::Br { relative_depth } => Instruction::Br(relative_depth), Operator::BrIf { relative_depth } => Instruction::BrIf(relative_depth), Operator::BrTable { table } => Instruction::BrTable( table.targets().collect::<Result<Cow<'_, [u32]>>>()?, table.default(), ), Operator::Return => Instruction::Return, Operator::Call { function_index } => { let function_index = if gas_idx >= 0 && function_index >= gas_idx as u32 { function_index + 1 } else { function_index }; Instruction::Call(function_index) } Operator::CallIndirect { index: ty, table_index: table, } => Instruction::CallIndirect { ty, table }, // Tail-call proposal // https://github.com/WebAssembly/tail-call/blob/master/proposals/tail-call/Overview.md // // Operator::ReturnCall => Instruction::ReturnCall, // Operator::ReturnCallIndirect => Instruction::ReturnCallIndirect, Operator::Delegate { relative_depth } => { Instruction::Delegate(relative_depth) } Operator::CatchAll => Instruction::CatchAll, Operator::Drop => Instruction::Drop, Operator::Select => Instruction::Select, Operator::TypedSelect { ty } => Instruction::TypedSelect(map_type(ty)), Operator::LocalGet { local_index } => Instruction::LocalGet(local_index), Operator::LocalSet { local_index } => Instruction::LocalSet(local_index), Operator::LocalTee { local_index } => Instruction::LocalTee(local_index), Operator::GlobalGet { global_index } => { Instruction::GlobalGet(global_index) } Operator::GlobalSet { global_index } => { Instruction::GlobalSet(global_index) } Operator::I32Load { memarg } => Instruction::I32Load(map_memarg(&memarg)), Operator::I64Load { memarg } => Instruction::I64Load(map_memarg(&memarg)), Operator::F32Load { memarg } => Instruction::F32Load(map_memarg(&memarg)), Operator::F64Load { memarg } => Instruction::F64Load(map_memarg(&memarg)), Operator::I32Load8S { memarg } => { Instruction::I32Load8_S(map_memarg(&memarg)) } Operator::I32Load8U { memarg } => { Instruction::I32Load8_U(map_memarg(&memarg)) } Operator::I32Load16S { memarg } => { Instruction::I32Load16_S(map_memarg(&memarg)) } Operator::I32Load16U { memarg } => { Instruction::I32Load16_U(map_memarg(&memarg)) } Operator::I64Load8S { memarg } => { Instruction::I64Load8_S(map_memarg(&memarg)) } Operator::I64Load8U { memarg } => { Instruction::I64Load8_U(map_memarg(&memarg)) } Operator::I64Load16S { memarg } => { Instruction::I64Load16_S(map_memarg(&memarg)) } Operator::I64Load16U { memarg } => { Instruction::I64Load16_U(map_memarg(&memarg)) } Operator::I64Load32S { memarg } => { Instruction::I64Load32_S(map_memarg(&memarg)) } Operator::I64Load32U { memarg } => { Instruction::I64Load32_U(map_memarg(&memarg)) } Operator::I32Store { memarg } => Instruction::I32Store(map_memarg(&memarg)), Operator::I64Store { memarg } => Instruction::I64Store(map_memarg(&memarg)), Operator::F32Store { memarg } => Instruction::F32Store(map_memarg(&memarg)), Operator::F64Store { memarg } => Instruction::F64Store(map_memarg(&memarg)), Operator::I32Store8 { memarg } => { Instruction::I32Store8(map_memarg(&memarg)) } Operator::I32Store16 { memarg } => { Instruction::I32Store16(map_memarg(&memarg)) } Operator::I64Store8 { memarg } => { Instruction::I64Store8(map_memarg(&memarg)) } Operator::I64Store16 { memarg } => { Instruction::I64Store16(map_memarg(&memarg)) } Operator::I64Store32 { memarg } => { Instruction::I64Store32(map_memarg(&memarg)) } Operator::MemorySize { mem, mem_byte: _ } => Instruction::MemorySize(mem), Operator::MemoryGrow { mem, mem_byte: _ } => Instruction::MemoryGrow(mem), Operator::I32Const { value } => Instruction::I32Const(value), Operator::I64Const { value } => Instruction::I64Const(value), // Floats and Ints have the same endianness on all supported platforms. Operator::F32Const { value } => { Instruction::F32Const(f32::from_bits(value.bits())) } Operator::F64Const { value } => { Instruction::F64Const(f64::from_bits(value.bits())) } Operator::RefNull { ty } => Instruction::RefNull(map_type(ty)), Operator::RefIsNull => Instruction::RefIsNull, Operator::RefFunc { function_index: index, } => Instruction::RefFunc(index), Operator::I32Eqz => Instruction::I32Eqz, Operator::I32Eq => Instruction::I32Eq, Operator::I32Ne => Instruction::I32Neq, Operator::I32LtS => Instruction::I32LtS, Operator::I32LtU => Instruction::I32LtU, Operator::I32GtS => Instruction::I32GtS, Operator::I32GtU => Instruction::I32GtU, Operator::I32LeS => Instruction::I32LeS, Operator::I32LeU => Instruction::I32LeU, Operator::I32GeS => Instruction::I32GeS, Operator::I32GeU => Instruction::I32GeU, Operator::I64Eqz => Instruction::I64Eqz, Operator::I64Eq => Instruction::I64Eq, Operator::I64Ne => Instruction::I64Neq, Operator::I64LtS => Instruction::I64LtS, Operator::I64LtU => Instruction::I64LtU, Operator::I64GtS => Instruction::I64GtS, Operator::I64GtU => Instruction::I64GtU, Operator::I64LeS => Instruction::I64LeS, Operator::I64LeU => Instruction::I64LeU, Operator::I64GeS => Instruction::I64GeS, Operator::I64GeU => Instruction::I64GeU, Operator::F32Eq => Instruction::F32Eq, Operator::F32Ne => Instruction::F32Neq, Operator::F32Lt => Instruction::F32Lt, Operator::F32Gt => Instruction::F32Gt, Operator::F32Le => Instruction::F32Le, Operator::F32Ge => Instruction::F32Ge, Operator::F64Eq => Instruction::F64Eq, Operator::F64Ne => Instruction::F64Neq, Operator::F64Lt => Instruction::F64Lt, Operator::F64Gt => Instruction::F64Gt, Operator::F64Le => Instruction::F64Le, Operator::F64Ge => Instruction::F64Ge, Operator::I32Clz => Instruction::I32Clz, Operator::I32Ctz => Instruction::I32Ctz, Operator::I32Popcnt => Instruction::I32Popcnt, Operator::I32Add => Instruction::I32Add, Operator::I32Sub => Instruction::I32Sub, Operator::I32Mul => Instruction::I32Mul, Operator::I32DivS => Instruction::I32DivS, Operator::I32DivU => Instruction::I32DivU, Operator::I32RemS => Instruction::I32RemS, Operator::I32RemU => Instruction::I32RemU, Operator::I32And => Instruction::I32And, Operator::I32Or => Instruction::I32Or, Operator::I32Xor => Instruction::I32Xor, Operator::I32Shl => Instruction::I32Shl, Operator::I32ShrS => Instruction::I32ShrS, Operator::I32ShrU => Instruction::I32ShrU, Operator::I32Rotl => Instruction::I32Rotl, Operator::I32Rotr => Instruction::I32Rotr, Operator::I64Clz => Instruction::I64Clz, Operator::I64Ctz => Instruction::I64Ctz, Operator::I64Popcnt => Instruction::I64Popcnt, Operator::I64Add => Instruction::I64Add, Operator::I64Sub => Instruction::I64Sub, Operator::I64Mul => Instruction::I64Mul, Operator::I64DivS => Instruction::I64DivS, Operator::I64DivU => Instruction::I64DivU, Operator::I64RemS => Instruction::I64RemS, Operator::I64RemU => Instruction::I64RemU, Operator::I64And => Instruction::I64And, Operator::I64Or => Instruction::I64Or, Operator::I64Xor => Instruction::I64Xor, Operator::I64Shl => Instruction::I64Shl, Operator::I64ShrS => Instruction::I64ShrS, Operator::I64ShrU => Instruction::I64ShrU, Operator::I64Rotl => Instruction::I64Rotl, Operator::I64Rotr => Instruction::I64Rotr, Operator::F32Abs => Instruction::F32Abs, Operator::F32Neg => Instruction::F32Neg, Operator::F32Ceil => Instruction::F32Ceil, Operator::F32Floor => Instruction::F32Floor, Operator::F32Trunc => Instruction::F32Trunc, Operator::F32Nearest => Instruction::F32Nearest, Operator::F32Sqrt => Instruction::F32Sqrt, Operator::F32Add => Instruction::F32Add, Operator::F32Sub => Instruction::F32Sub, Operator::F32Mul => Instruction::F32Mul, Operator::F32Div => Instruction::F32Div, Operator::F32Min => Instruction::F32Min, Operator::F32Max => Instruction::F32Max, Operator::F32Copysign => Instruction::F32Copysign, Operator::F64Abs => Instruction::F64Abs, Operator::F64Neg => Instruction::F64Neg, Operator::F64Ceil => Instruction::F64Ceil, Operator::F64Floor => Instruction::F64Floor, Operator::F64Trunc => Instruction::F64Trunc, Operator::F64Nearest => Instruction::F64Nearest, Operator::F64Sqrt => Instruction::F64Sqrt, Operator::F64Add => Instruction::F64Add, Operator::F64Sub => Instruction::F64Sub, Operator::F64Mul => Instruction::F64Mul, Operator::F64Div => Instruction::F64Div, Operator::F64Min => Instruction::F64Min, Operator::F64Max => Instruction::F64Max, Operator::F64Copysign => Instruction::F64Copysign, Operator::I32WrapI64 => Instruction::I32WrapI64, Operator::I32TruncF32S => Instruction::I32TruncF32S, Operator::I32TruncF32U => Instruction::I32TruncF32U, Operator::I32TruncF64S => Instruction::I32TruncF64S, Operator::I32TruncF64U => Instruction::I32TruncF64U, Operator::I64ExtendI32S => Instruction::I64ExtendI32S, Operator::I64ExtendI32U => Instruction::I64ExtendI32U, Operator::I64TruncF32S => Instruction::I64TruncF32S, Operator::I64TruncF32U => Instruction::I64TruncF32U, Operator::I64TruncF64S => Instruction::I64TruncF64S, Operator::I64TruncF64U => Instruction::I64TruncF64U, Operator::F32ConvertI32S => Instruction::F32ConvertI32S, Operator::F32ConvertI32U => Instruction::F32ConvertI32U, Operator::F32ConvertI64S => Instruction::F32ConvertI64S, Operator::F32ConvertI64U => Instruction::F32ConvertI64U, Operator::F32DemoteF64 => Instruction::F32DemoteF64, Operator::F64ConvertI32S => Instruction::F64ConvertI32S, Operator::F64ConvertI32U => Instruction::F64ConvertI32U, Operator::F64ConvertI64S => Instruction::F64ConvertI64S, Operator::F64ConvertI64U => Instruction::F64ConvertI64U, Operator::F64PromoteF32 => Instruction::F64PromoteF32, Operator::I32ReinterpretF32 => Instruction::I32ReinterpretF32, Operator::I64ReinterpretF64 => Instruction::I64ReinterpretF64, Operator::F32ReinterpretI32 => Instruction::F32ReinterpretI32, Operator::F64ReinterpretI64 => Instruction::F64ReinterpretI64, Operator::I32Extend8S => Instruction::I32Extend8S,
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
true
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/js/lib.rs
crates/js/lib.rs
pub mod default_permissions; mod loader; pub mod snapshot; use crate::default_permissions::Permissions; use crate::loader::EmbeddedModuleLoader; use deno_core::error::{generic_error, AnyError}; use deno_core::serde::de::DeserializeOwned; use deno_core::serde::Serialize; use deno_core::serde_json::Value; use deno_core::serde_v8; use deno_core::JsRuntime; use deno_core::OpDecl; use deno_core::OpState; use deno_core::RuntimeOptions; use deno_fetch::Options; use deno_web::BlobStore; use std::cell::RefCell; use std::collections::HashMap; use std::fmt::Debug; use std::future::Future; use std::rc::Rc; use three_em_smartweave::InteractionContext; use v8::HandleScope; #[derive(Debug, Clone)] pub enum HeapLimitState { /// Ok, the heap limit is not exceeded. Ok, /// The heap limit is exceeded. Exceeded(usize), } impl Default for HeapLimitState { fn default() -> Self { HeapLimitState::Ok } } #[derive(Debug, PartialEq, Eq)] pub enum Error { /// Isolate is terminated. Terminated, } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Error::Terminated => write!(f, "Isolate is terminated"), } } } impl std::error::Error for Error {} // TODO(@littledivy): Maybe add a Null variant? #[derive(Debug, PartialEq)] pub enum CallResult { // Contract wants to "evolve" Evolve(String), // Result, was state updated? Result(v8::Global<v8::Value>, bool), } unsafe impl Send for Runtime {} unsafe impl Sync for Runtime {} unsafe impl Send for EmbeddedModuleLoader {} unsafe impl Sync for EmbeddedModuleLoader {} pub struct Runtime { rt: JsRuntime, module: v8::Global<v8::Value>, pub state: Rc<RefCell<HeapLimitState>>, /// Optimization to avoid running the event loop in certain cases. /// /// None, if the handler is not yet called. /// Some(true), if the handler is called and it returns a pending promise. /// Some(false), if the handler is called and it does not return a pending promise. is_promise: Option<bool>, /// Current state value. contract_state: v8::Global<v8::Value>, /// Whether the current runtime belongs to EXM execution is_exm: bool, } impl Runtime { pub async fn new<T>( source: &str, init: T, arweave: (i32, String, String), op_smartweave_read_state: OpDecl, executor_settings: HashMap<String, deno_core::serde_json::Value>, maybe_exm_context: Option<deno_core::serde_json::Value>, ) -> Result<Self, AnyError> where T: Serialize + 'static, { let specifier = "file:///main.js".to_string(); let module_loader = Rc::new(EmbeddedModuleLoader(source.to_owned(), specifier.clone())); let flags = concat!("--predictable", " --hash-seed=42", " --random-seed=42",); v8::V8::set_flags_from_string(flags); // Make's Math.random() and V8 hash seeds, address space layout repr deterministic. v8::V8::set_entropy_source(|buf| { for c in buf { *c = 42; } true }); let heap_default = deno_core::serde_json::Value::String(String::from("200")); let heap_mbs = { let heap_limit_mb_value = executor_settings .get("HEAP_LIMIT") .unwrap_or_else(|| &heap_default); let heap_limit_mb = heap_limit_mb_value.as_str().unwrap(); let heap_limit_usize: usize = heap_limit_mb.parse().unwrap(); heap_limit_usize }; let params = v8::CreateParams::default().heap_limits(0, heap_mbs.clone() << 20); let mut rt = JsRuntime::new(RuntimeOptions { extensions: vec![ deno_webidl::init(), deno_url::init(), deno_web::init::<Permissions>(BlobStore::default(), None), deno_crypto::init(Some(0)), deno_fetch::init::<Permissions>(Options { user_agent: String::from("EXM"), ..Default::default() }), three_em_smartweave::init(arweave, op_smartweave_read_state), three_em_exm_base_ops::init(executor_settings.clone()), ], module_loader: Some(module_loader), startup_snapshot: Some(snapshot::snapshot()), create_params: Some(params), ..Default::default() }); { let op_state = rt.op_state(); op_state.borrow_mut().put(Permissions); } let isolate = rt.v8_isolate(); let handle = isolate.thread_safe_handle(); let state = Rc::new(RefCell::new(HeapLimitState::default())); let state_clone = state.clone(); rt.add_near_heap_limit_callback(move |curr, _| { println!("Heap limit reached {}", curr); let terminated = handle.terminate_execution(); assert!(terminated); *state_clone.borrow_mut() = HeapLimitState::Exceeded(curr); (curr + heap_mbs.clone()) << 20 }); /// TODO: rt.sync_ops_cache(); let global = rt.execute_script("<anon>", &format!("import(\"{}\")", specifier))?; let module = rt.resolve_value(global).await?; let contract_state = { let scope = &mut rt.handle_scope(); let local = serde_v8::to_v8(scope, init)?; v8::Global::new(scope, local) }; { let scope = &mut rt.handle_scope(); let context = scope.get_current_context(); if maybe_exm_context.is_some() { let exm_context = maybe_exm_context.unwrap(); let inner_scope = &mut v8::ContextScope::new(scope, context); let global = context.global(inner_scope); let v8_key = serde_v8::to_v8(inner_scope, "exmContext").unwrap(); let v8_val = serde_v8::to_v8(inner_scope, exm_context).unwrap(); global.set(inner_scope, v8_key, v8_val); } }; { rt.execute_script( "<anon>", "globalThis.exmContext = Object.freeze(globalThis.exmContext);", ); } let exm_setting_val = executor_settings .get("EXM") .unwrap_or_else(|| &Value::Bool(false)); let is_exm = exm_setting_val.as_bool().unwrap(); Ok(Self { rt, module, state, is_promise: None, contract_state, is_exm, }) } pub fn state(&self) -> HeapLimitState { self.state.borrow().clone() } pub fn scope(&mut self) -> v8::HandleScope { self.rt.handle_scope() } pub fn to_value<T>( &mut self, global_value: &v8::Global<v8::Value>, ) -> Result<T, AnyError> where T: DeserializeOwned + 'static, { let scope = &mut self.rt.handle_scope(); let value = v8::Local::new(scope, global_value.clone()); Ok(serde_v8::from_v8(scope, value)?) } pub fn get_contract_state<T>(&mut self) -> Result<T, AnyError> where T: DeserializeOwned + 'static, { let scope = &mut self.rt.handle_scope(); let value = v8::Local::new(scope, self.contract_state.clone()); Ok(serde_v8::from_v8(scope, value)?) } pub fn get_exm_context<T>(&mut self) -> Result<T, AnyError> where T: DeserializeOwned + 'static, { let scope = &mut self.rt.handle_scope(); let context = scope.get_current_context(); let inner_scope = &mut v8::ContextScope::new(scope, context); let global = context.global(inner_scope); let v8_key = serde_v8::to_v8(inner_scope, "EXM").unwrap(); let output = global.get(inner_scope, v8_key); if let Some(output_val) = output { Ok(serde_v8::from_v8(inner_scope, output_val)?) } else { Err(generic_error("Impossible to get fetch calls")) } } pub async fn call<R>( &mut self, action: R, interaction_data: Option<InteractionContext>, ) -> Result<Option<CallResult>, AnyError> where R: Serialize + 'static, { let global = { let scope = &mut self.rt.handle_scope(); let context = scope.get_current_context(); { if interaction_data.is_some() { let inner_scope = &mut v8::ContextScope::new(scope, context); let global = context.global(inner_scope); let v8_key = serde_v8::to_v8(inner_scope, "currentInteraction").unwrap(); let v8_val = serde_v8::to_v8(inner_scope, interaction_data.unwrap()).unwrap(); global.set(inner_scope, v8_key, v8_val); } }; let action: v8::Local<v8::Value> = serde_v8::to_v8(scope, action).unwrap(); let module_obj = self.module.open(scope).to_object(scope).unwrap(); let key = v8::String::new(scope, "handle").unwrap().into(); let func_obj = module_obj.get(scope, key).unwrap(); let func = v8::Local::<v8::Function>::try_from(func_obj).unwrap(); let state = v8::Local::<v8::Value>::new(scope, self.contract_state.clone()); let state_clone = { let state_json = serde_v8::from_v8::<Value>(scope, state).unwrap(); serde_v8::to_v8(scope, state_json).unwrap() }; let undefined = v8::undefined(scope); let mut local = func .call(scope, undefined.into(), &[state_clone, action]) .ok_or(Error::Terminated)?; if self.is_promise.is_none() { self.is_promise = Some(local.is_promise()); } if let Some(true) = self.is_promise { let promise = v8::Local::<v8::Promise>::try_from(local).unwrap(); match promise.state() { v8::PromiseState::Pending => {} v8::PromiseState::Fulfilled | v8::PromiseState::Rejected => { self.is_promise = Some(false); local = promise.result(scope); } } } v8::Global::new(scope, local) }; let mut was_state_updated = false; { let mut result_act: Option<v8::Global<v8::Value>> = None; // Run the event loop. let global = self.rt.resolve_value(global).await?; // let data = self.get_contract_state::<Value>().unwrap(); // println!("{}", data.to_string()); let scope = &mut self.rt.handle_scope(); let state_obj_local = v8::Local::new(scope, global).to_object(scope); if let Some(state) = state_obj_local { let state_key = v8::String::new(scope, "state").unwrap().into(); // Return value. let result_key = v8::String::new(scope, "result").unwrap().into(); let result = state.get(scope, result_key).unwrap(); if !result.is_null_or_undefined() { result_act = Some(v8::Global::new(scope, result)); } if let Some(state_obj) = state.get(scope, state_key) { if let Some(state) = state_obj.to_object(scope) { // Update the contract state. if !state_obj.is_null_or_undefined() { self.contract_state = v8::Global::new(scope, state_obj); was_state_updated = true; if !self.is_exm { // Contract evolution. let evolve_key = v8::String::new(scope, "canEvolve").unwrap().into(); let can_evolve = state.get(scope, evolve_key).unwrap(); if can_evolve.boolean_value(scope) { let evolve_key = v8::String::new(scope, "evolve").unwrap().into(); let evolve = state.get(scope, evolve_key).unwrap(); return Ok(Some(CallResult::Evolve( evolve.to_rust_string_lossy(scope), ))); } } } } } if let Some(result_v8_val) = result_act { return Ok(Some(CallResult::Result( result_v8_val, was_state_updated, ))); } } }; Ok(None) } } #[cfg(test)] mod test { use crate::CallResult; use crate::Error; use crate::HeapLimitState; use crate::Runtime; use deno_core::error::AnyError; use deno_core::serde::Deserialize; use deno_core::serde::Serialize; use deno_core::serde_json::{json, Value}; use deno_core::OpState; use deno_core::ZeroCopyBuf; use deno_ops::op; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use three_em_exm_base_ops::ExmContext; use three_em_smartweave::{InteractionBlock, InteractionContext}; use v8::Boolean; #[op] pub async fn never_op(_: (), _: (), _: ()) -> Result<Value, AnyError> { unreachable!() } #[tokio::test] async fn test_runtime() { let mut rt = Runtime::new( "export async function handle() { return { state: -69 } }", (), (80, String::from("arweave.net"), String::from("https")), never_op::decl(), HashMap::new(), None, ) .await .unwrap(); rt.call((), None).await.unwrap(); let value = rt.get_contract_state::<i32>().unwrap(); assert_eq!(value, -69); } // KV Tests // PUT #[tokio::test] async fn test_putKv() { let mut exec_settings: HashMap<String, deno_core::serde_json::Value> = HashMap::new(); exec_settings.insert( String::from("EXM"), deno_core::serde_json::Value::Bool(true), ); let mut rt = Runtime::new( r#" export async function handle() { try { EXM.print("Data"); SmartWeave.kv.put("hello", "world"); return { state: EXM.testPutKv() }; } catch(e) { return { state: e.toString() } } } "#, (), (12345, String::from("arweave.net"), String::from("http")), never_op::decl(), exec_settings, None, ) .await .unwrap(); rt.call((), None).await.unwrap(); let calls = rt.get_exm_context::<ExmContext>().unwrap(); let state = rt .get_contract_state::<deno_core::serde_json::Value>() .unwrap(); let variable_type = format!("{:?}", state.as_str().unwrap()); println!("**Testing PUT: {}", state.as_str().unwrap()); let res = calls.kv.get("hello").unwrap(); println!("**Test PUT 2: {}", res); assert_eq!(res, "world"); } // GET #[tokio::test] async fn test_getKv() { let mut exec_settings: HashMap<String, deno_core::serde_json::Value> = HashMap::new(); exec_settings.insert( String::from("EXM"), deno_core::serde_json::Value::Bool(true), ); let mut rt = Runtime::new( r#" export async function handle() { try { EXM.print("Data"); SmartWeave.kv.put("blue", "butterflies"); const val = SmartWeave.kv.get("blue"); return { state: val }; } catch(e) { return { state: e.toString() } } } "#, (), (12345, String::from("arweave.net"), String::from("http")), never_op::decl(), exec_settings, None, ) .await .unwrap(); rt.call((), None).await.unwrap(); let state = rt .get_contract_state::<deno_core::serde_json::Value>() .unwrap(); println!("**Testing GET: {}", state); //assert_eq!(state.as_str().unwrap(), "hello world"); } // DELETE #[tokio::test] async fn test_delKv() { let mut exec_settings: HashMap<String, deno_core::serde_json::Value> = HashMap::new(); exec_settings.insert( String::from("EXM"), deno_core::serde_json::Value::Bool(true), ); let mut rt = Runtime::new( r#" export async function handle() { try { EXM.print("Data"); SmartWeave.kv.put("hello", "apples"); SmartWeave.kv.put("blue", "butterflies"); SmartWeave.kv.del("blue"); return { state: EXM.testDelKv() }; } catch(e) { return { state: e.toString() } } } "#, (), (12345, String::from("arweave.net"), String::from("http")), never_op::decl(), exec_settings, None, ) .await .unwrap(); rt.call((), None).await.unwrap(); let state = rt .get_contract_state::<deno_core::serde_json::Value>() .unwrap(); println!("**Testing DEL: {}", state); //assert_eq!(state.as_str().unwrap(), "hello world"); } #[tokio::test] async fn test_state_empty() { let mut rt = Runtime::new( r#"export async function handle(state, action) { state.data++; state.data = Number(100 * 2 + state.data); if(state.data < 300) { return { state }; } }"#, json!({ "data": 0 }), (80, String::from("arweave.net"), String::from("https")), never_op::decl(), HashMap::new(), None, ) .await .unwrap(); rt.call((), None).await.unwrap(); rt.call((), None).await.unwrap(); let value = rt.get_contract_state::<Value>().unwrap(); let number = value.get("data").unwrap().as_i64().unwrap(); assert_eq!(number, 201); } #[tokio::test] async fn test_runtime_smartweave() { let mut rt = Runtime::new( r#" export async function handle(slice) { return { state: await SmartWeave .arweave .crypto.hash(new Uint8Array(slice), 'SHA-1') } } "#, json!([0]), (80, String::from("arweave.net"), String::from("https")), never_op::decl(), HashMap::new(), None, ) .await .unwrap(); rt.call((), None).await.unwrap(); let hash = rt.get_contract_state::<[u8; 20]>().unwrap(); assert_eq!( hash.to_vec(), [ 91, 169, 60, 157, 176, 207, 249, 63, 82, 181, 33, 215, 66, 14, 67, 246, 237, 162, 120, 79 ] ); } #[tokio::test] async fn test_runtime_smartweave_arweave_wallets_ownertoaddress() { let mut rt = Runtime::new( r#" export async function handle() { return { state: await SmartWeave.arweave.wallets.ownerToAddress("kTuBmCmd8dbEiq4zbEPx0laVMEbgXNQ1KBUYqg3TWpLDokkcrZfa04hxYWVLZMnXH2PRSCjvCi5YVu3TG27kl29eMs-CJ-D97WyfvEZwZ7V4EDLS1uqiOrfnkBxXDfJwMI7pdGWg0JYwhsqePB8A9WfIfjrWXiGkleAAtU-dLc8Q3QYIbUBa_rNrvC_AwhXhoKUNq5gaKAdB5xQBfHJg8vMFaTsbGOxIH8v7gJyz7gc9JQf0F42ByWPmhIsm4bIHs7eGPgtUKASNBmWIgs8blP7AmbzyJp4bx_AOQ4KOCei25Smw2-UAZehCGibl50i-blv5ldpGhcKDBC7ukjZpOY99V0mdDynbQBi606DdTWGJSXGNkvpwYnLh53VOE3uX0zuxNnRlwA9BN_VisWMrQwk_KnB0Fz0qGlJsXNQEWb_TEaf6eWLcSIUZUUC9o0L6J6mI9hiJjf_sisiR6AsWF4UoA-snWsFNzgPdkeOHW_biJMep6DOnWX8lmh8meDGMi1XOxJ4hJAawD7uS3A8jL7Kn7eYtiQ7bnZG69WtBueyOQh78yStMvoKz6awzBt1IaTBUG9_CHrEy_Tx6aQZu1c2D_nZonTd0pV2ljC7E642VtOWsRFL78-1xF6P0FD4eWh6HoDpD05_3oUBrAdusLMkn8Gm5tl0wIwMrLF58FYk") } } "#, json!([0]), (80, String::from("arweave.net"), String::from("https")), never_op::decl(), HashMap::new(), None, ) .await .unwrap(); rt.call((), None).await.unwrap(); let address = rt.get_contract_state::<String>().unwrap(); assert_eq!(address, "z5-Ql2zU5Voac97BHMDGrk3_2gEDqM72iHxCJhkcJ5A"); } #[tokio::test] async fn test_runtime_smartweave_crypto_sign() { let mut rt = Runtime::new( r#" export async function handle(slice) { try { const jwk = { kty: 'RSA', n: 'kTuBmCmd8dbEiq4zbEPx0laVMEbgXNQ1KBUYqg3TWpLDokkcrZfa04hxYWVLZMnXH2PRSCjvCi5YVu3TG27kl29eMs-CJ-D97WyfvEZwZ7V4EDLS1uqiOrfnkBxXDfJwMI7pdGWg0JYwhsqePB8A9WfIfjrWXiGkleAAtU-dLc8Q3QYIbUBa_rNrvC_AwhXhoKUNq5gaKAdB5xQBfHJg8vMFaTsbGOxIH8v7gJyz7gc9JQf0F42ByWPmhIsm4bIHs7eGPgtUKASNBmWIgs8blP7AmbzyJp4bx_AOQ4KOCei25Smw2-UAZehCGibl50i-blv5ldpGhcKDBC7ukjZpOY99V0mdDynbQBi606DdTWGJSXGNkvpwYnLh53VOE3uX0zuxNnRlwA9BN_VisWMrQwk_KnB0Fz0qGlJsXNQEWb_TEaf6eWLcSIUZUUC9o0L6J6mI9hiJjf_sisiR6AsWF4UoA-snWsFNzgPdkeOHW_biJMep6DOnWX8lmh8meDGMi1XOxJ4hJAawD7uS3A8jL7Kn7eYtiQ7bnZG69WtBueyOQh78yStMvoKz6awzBt1IaTBUG9_CHrEy_Tx6aQZu1c2D_nZonTd0pV2ljC7E642VtOWsRFL78-1xF6P0FD4eWh6HoDpD05_3oUBrAdusLMkn8Gm5tl0wIwMrLF58FYk', e: 'AQAB', d: 'XKMTT8bD-32dkkP5gwZ32k3mDYw4Ep49ZdrHB7mX5f8VkI-IHmZta15ty8074QcqE9isppWNm_Xh3VkHvkjmwH2GHWzlPaCy993AqexYSJ6k_dgdSn8RidjCeNbK5JeO3jpaSSeGA2a5f1EAy6KPDvnrFjFbiWF2RS9D5GLrBEw_Gmx9tYpGQI6bmsbu8h3Y9IozhQ-ZJ40xiT7mj8W5d15yRiQwbZ5Rhw6q1uedkafGZbeEB_34GkiBwmusGmxfo0_d7fd176yvc7QR9jY7BrfUjHvMDbvuRoMl5gQBq-pntxb3u9t_fIFAoMPNA9EPvv8l3WMEds-SmHmDLXpNdTbIXn6yguGSs9Lci0o7jjLCigOX0qu73UqSuCbXY0TE39s4bAoFWFVcaIgyHWMkbt6BV_OERhbsU5K47NYRg__BUEr39ruG3BnuvWJFwIeLGp5OUDlvsvWQn9VkOSXNJi7kvrVucwwT95vYvGtgoQnU5csIIo66ciyvCatjVUy7YLS8kdoKjRdu57wQJXUsrH5PXgUnomIGO8NCrf0WB5XBFaPL8m5_nDs4_Ym_gD7A5rR-S0OHGDF6L4xDcStvmpeqHEmF1o872vKeayXi23pfsFWfpLM1WnuFcIGuqxjT6TQQZFL1Z-LwEQp5RyvnF8SBapLMJiQYXOcm0M8K2-0', p: 'wNeunobSmEgjFw1uNyWMsXtCBFNQDs_XY1oYMq6S_Y9d6AQ0cVx7TFjikUb4ipzIenUc28PlAAGe1c7E6WjcSbIrcyiTT_vkSy6KJznlRYOMZkckRnkvm7f7w80OfSrb4kSUyyXhlL0XfH_WjG9CMGbwoA5MM-3NEyUCJ04cFBtCQC2Lx-lcT30HZKbjVCblVG9zNqu3FePcz90zKpxno6z9Ie9zkmO1xPjFNlUug3NFGj8GOVrii4PxXDIycinUv08zcxY5z9XqD3vUYk84N5JgGoHBsQ1BdbU2naGJ374RXueYb3Ogx-4wYfzp7l_CPqsQCcL9HEGKsM2QzVXniw', q: 'wMwY5tm_Jj4V9eYQ_UgfWZkqtLzzhqVU_VFZ1G_6s36OGpSVevQKcEQpvFnCphihDzthW4N5sSyO0eBgwHdbuQ4tkS-iSNsKnASQVT81yQUanslI11-259L1aUNIJynAqSXFcoNPhyUMrouOR4bYCCFqnyXlpxSWg2zYQUDJnG5Uv_wGR5zizVAgYeWJyvlwUxBJIJUCaLbNs0hKK09OZ0Z0C7WSCcAKwDW6LK3KWZfFGedaMMQQTWCBpK14Y1WYAN67t7I9dEHimZI5jSNRmi2FX4NXrhNuORk20hcPT4s4Fdvuwu7yrlhg_5VOr7IpZY8mXtUgwmVHBFFGNko5uw', dp: 'kEMJY5hShQ86CO3ILMMPbFpb-aZltp7vb2ifv5JvbfZJdt9maAOaTXQVEj84gWFmbI2d6B20-3s62pHTJxWF7i-2Z3DMO0Kh90g6m7uo84bEimLgFURlRCWv1ztYgnSEh9FsSkjtZ3rJzh5IX0iACHuJuQLZKOPVzWObJ9I8GSKHPkGUVxoRL3nGBRr_5x0t5Ct30kdFMMAEmQ_OTisxMPWhbDiYicPD4DWGOu4gXL_nywmo21FNNree4KzApjz65Z8XSxouZ3eMoMavDFhdIt2CvXGid5QGC0tkLyoAXXvvvMKee4nRlp9uXG96hRPn2T_ZQKQ4-2FgooE1uRZxnw', dq: 'uVe8HLl57G7FN9bLwGJEWSNJDeWUC34HnVtGi1Z3YXUpcV4j8caH_nNY2AxGdty4gOcp6gsTwwK97f_Ro1VbZSS_I5LyZS3GHkS46GrS7wQsGjgRAZOvR1_jsyUOSS_3WeTI0xRvMNGqRmY9CoAUUISndoW9KAk_xOqvXtPEvdDHQqUq-E9XLd94sgQzmmB_3iqK0nrNjRMn3tGBE--yxM_TIaqU0TDAZRWBfBA6tjSUNBnX94eU0H4VQ9XMJVqUvUlilu8P6yKnj9El6Ivql9hpHnAqq1tcnCGkNQYcHvEMot8Cwn1p6bdm0G2d7oPNDig2z_X9_0PTqM_lOq3Snw', qi: 'WA7rs38z_LZad6SFGJNUblyuJ-W7zFkFtHqh8_ToUVbS6wuNLbmsOr5_AsOWKWKils2eHWj5bA4Io5SajWl499JgGLS7nMwhn1gSzIfYskoHCl4_isEu7mB2uOWqPtSt6xYvCaxutyTQSbaUj9ioOsOU5Gjt-Vuigm3M5rmQS6Kli1rPgs1boYj8NPtou21SwrHXZnsfA2J7QqzDddhhLdd8U85_H4eFygiSwYbnnIkMSciWt6CAviPve-MeQMIKKtATjIUspUzBlbCuHR7WaMqyVvYfCRhsDg8WaRIsgebz4qSUwzuy-Lip8EFXcMbzocjP5JHE4eKFm5H9Iq0V5Q' }; const data = new TextEncoder().encode('Hello'); const sign = await SmartWeave.arweave.crypto.sign(jwk, data); const verify = await SmartWeave.arweave.crypto.verify(jwk.n, data, sign); return { state: verify } } catch(e) { return { state: e.stack } } } "#, json!([0]), (80, String::from("arweave.net"), String::from("https")), never_op::decl(), HashMap::new(), None, ) .await .unwrap(); rt.call((), None).await.unwrap(); let hash = rt.get_contract_state::<Value>().unwrap(); assert_eq!(hash, Value::Bool(true)); } #[tokio::test] async fn test_runtime_date() { let mut executor_settings: HashMap<String, Value> = HashMap::new(); executor_settings.insert( String::from("TX_DATE"), Value::String(String::from("1662327465259")), ); executor_settings.insert( String::from("EXM"), deno_core::serde_json::Value::Bool(true), ); let mut rt = Runtime::new( r#" export async function handle(slice) { try { return { state: EXM.getDate().getTime() } } catch(e) { return { state: e.stack } } } "#, json!([0]), (80, String::from("arweave.net"), String::from("https")), never_op::decl(), executor_settings, None, ) .await .unwrap(); rt.call((), None).await.unwrap(); let hash = rt.get_contract_state::<usize>().unwrap(); assert_eq!(hash, 1662327465259 as usize); } #[tokio::test] async fn test_runtime_vanilla_date() { let mut executor_settings: HashMap<String, Value> = HashMap::new(); let mut rt = Runtime::new( r#" export async function handle(slice) { try { return { state: new Date().getTime() } } catch(e) { return { state: e.stack } } } "#, json!([0]), (80, String::from("arweave.net"), String::from("https")), never_op::decl(), executor_settings, None, ) .await .unwrap(); rt.call( (), Some(InteractionContext { transaction: Default::default(), block: InteractionBlock { timestamp: 1662327465200 as usize, height: 0 as usize, indep_hash: String::new(), }, }), ) .await .unwrap(); let hash = rt.get_contract_state::<usize>().unwrap(); assert_eq!(hash, 1662327465200 as usize); } #[tokio::test] async fn test_base_fetch_op() { let mut exec_settings: HashMap<String, deno_core::serde_json::Value> = HashMap::new(); exec_settings.insert( String::from("EXM"), deno_core::serde_json::Value::Bool(true), ); let mut rt = Runtime::new( r#" export async function handle() { try { const someFetch = await EXM.deterministicFetch("https://arweave.net/tx/YuJvCJEMik0J4QQjZULCaEjifABKYh-hEZPH9zokOwI"); const someFetch2 = await EXM.deterministicFetch("https://arweave.net/tx/RjOdIx9Y42f0T19-Tm_xB2Nk_blBv56eJ14tfXMNZTg"); return { state: someFetch.asJSON().id }; } catch(e) { return { state: e.toString() } } } "#, (), (12345, String::from("arweave.net"), String::from("http")), never_op::decl(), exec_settings, None ) .await .unwrap(); rt.call((), None).await.unwrap(); let calls = rt.get_exm_context::<ExmContext>().unwrap(); println!("{}", deno_core::serde_json::to_string(&calls).unwrap()); let tx_id = rt.get_contract_state::<String>().unwrap(); assert_eq!( tx_id.to_string(), "YuJvCJEMik0J4QQjZULCaEjifABKYh-hEZPH9zokOwI" ); assert_eq!(calls.requests.keys().len(), 2); assert_eq!( calls .requests .get( "7c13bc2cb63b30754ee3047ca46337e626d61d01b8484ecea8d3e235a617091a" .into() ) .unwrap() .url, "https://arweave.net/tx/YuJvCJEMik0J4QQjZULCaEjifABKYh-hEZPH9zokOwI" ); } #[tokio::test] async fn test_base_fetch_op_with_context() { let mut exec_settings: HashMap<String, deno_core::serde_json::Value> = HashMap::new(); exec_settings.insert( String::from("EXM"), deno_core::serde_json::Value::Bool(true), ); exec_settings.insert( String::from("LAZY_EVALUATION"), deno_core::serde_json::Value::Bool(true), );
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
true
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/js/build.rs
crates/js/build.rs
pub mod default_permissions; use crate::default_permissions::Permissions; use deno_core::error::AnyError; use deno_core::serde_json::Value; use deno_core::JsRuntime; use deno_core::OpState; use deno_core::RuntimeOptions; use deno_fetch::Options; use deno_ops::op; use deno_web::BlobStore; use std::cell::RefCell; use std::collections::HashMap; use std::env; use std::path::Path; use std::path::PathBuf; use std::rc::Rc; #[op] pub async fn never_op(_: (), _: (), _: ()) -> Result<Value, AnyError> { unreachable!() } // Adapted from deno_runtime // https://github.com/denoland/deno/blob/fdf890a68d3d54d40c766fd78faeccb20bd2e2c6/runtime/build.rs#L37-L41 fn create_snapshot(snapshot_path: &Path) { let mut snapshot_runtime = JsRuntime::new(RuntimeOptions { extensions: vec![ deno_webidl::init(), deno_url::init(), deno_web::init::<Permissions>(BlobStore::default(), None), deno_crypto::init(None), deno_fetch::init::<Permissions>(Options { user_agent: String::from("EXM"), ..Default::default() }), three_em_smartweave::init( (443, String::from(""), String::from("")), never_op::decl(), ), three_em_exm_base_ops::init(HashMap::new()), ], will_snapshot: true, ..Default::default() }); let snapshot = snapshot_runtime.snapshot(); let snapshot_slice: &[u8] = &*snapshot; println!("Snapshot size: {}", snapshot_slice.len()); std::fs::write(&snapshot_path, snapshot_slice).unwrap(); println!("Snapshot written to: {} ", snapshot_path.display()); } fn main() { let o = PathBuf::from(env::var_os("OUT_DIR").unwrap()); let runtime_snapshot_path = o.join("CLI_SNAPSHOT.bin"); create_snapshot(&runtime_snapshot_path); }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/js/loader.rs
crates/js/loader.rs
use deno_core::error::type_error; use deno_core::error::AnyError; use deno_core::futures::FutureExt; use deno_core::ModuleLoader; use deno_core::ModuleSpecifier; use deno_core::ModuleType; use std::pin::Pin; pub struct EmbeddedModuleLoader(pub String, pub String); impl ModuleLoader for EmbeddedModuleLoader { fn resolve( &self, specifier: &str, _referrer: &str, _is_main: bool, ) -> Result<ModuleSpecifier, AnyError> { if let Ok(module_specifier) = deno_core::resolve_url(specifier) { if specifier == self.1 { return Ok(module_specifier); } } Err(type_error("Module loading prohibited.")) } fn load( &self, module_specifier: &ModuleSpecifier, _maybe_referrer: Option<ModuleSpecifier>, _is_dynamic: bool, ) -> Pin<Box<deno_core::ModuleSourceFuture>> { let module_specifier = module_specifier.clone(); let code = (self.0.clone()).into_bytes().into_boxed_slice(); async move { let specifier = module_specifier.to_string(); Ok(deno_core::ModuleSource { code, module_url_specified: specifier.clone(), module_url_found: specifier, module_type: ModuleType::JavaScript, }) } .boxed_local() } }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/js/default_permissions.rs
crates/js/default_permissions.rs
use deno_core::OpState; use std::path::Path; pub struct Permissions; impl deno_web::TimersPermission for Permissions { fn allow_hrtime(&mut self) -> bool { true } fn check_unstable(&self, state: &OpState, api_name: &'static str) {} } impl deno_fetch::FetchPermissions for Permissions { fn check_net_url( &mut self, _url: &deno_core::url::Url, ) -> Result<(), deno_core::error::AnyError> { Ok(()) } fn check_read( &mut self, _p: &Path, ) -> Result<(), deno_core::error::AnyError> { Ok(()) } }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/js/snapshot.rs
crates/js/snapshot.rs
use deno_core::Snapshot; pub static CLI_SNAPSHOT: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/CLI_SNAPSHOT.bin")); pub fn snapshot() -> Snapshot { let data = CLI_SNAPSHOT; Snapshot::Static(data) }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/smartweave/lib.rs
crates/smartweave/lib.rs
use deno_core::error::AnyError; use deno_core::include_js_files; use deno_core::OpDecl; use deno_ops::op; use deno_core::serde::Serialize; use deno_core::serde_json::Value; use deno_core::Extension; use deno_core::OpState; use deno_core::ZeroCopyBuf; use std::cell::RefCell; use std::collections::HashMap; use std::future::Future; use std::rc::Rc; use std::{env, thread}; use three_em_arweave::gql_result::GQLTagInterface; pub struct ArweaveInfo { pub port: i32, pub host: String, pub protocol: String, } pub struct ExecutorSettings { settings: HashMap<String, deno_core::serde_json::Value>, } #[derive(Serialize, Default, Clone)] pub struct InteractionTx { pub id: String, pub owner: String, pub tags: Vec<GQLTagInterface>, pub target: String, pub quantity: String, pub reward: String, } #[derive(Serialize, Default, Clone)] pub struct InteractionBlock { pub height: usize, pub indep_hash: String, pub timestamp: usize, } #[derive(Serialize, Default, Clone)] pub struct InteractionContext { pub transaction: InteractionTx, pub block: InteractionBlock, } pub fn init( arweave: (i32, String, String), op_smartweave_read_contract: OpDecl, ) -> Extension { Extension::builder() .js(include_js_files!( prefix "3em:smartweave", "arweave.js", "bignumber.js", "smartweave.js", "contract-assert.js", )) .ops(vec![ op_smartweave_unsafe_exit_process::decl(), op_smartweave_wallet_balance::decl(), op_smartweave_wallet_last_tx::decl(), op_smartweave_get_tx_data::decl(), op_smartweave_get_tx::decl(), op_smartweave_get_host::decl(), op_smartweave_read_contract, ]) .state(move |state| { let (port, host, protocol) = arweave.clone(); state.put(ArweaveInfo { port, host, protocol, }); Ok(()) }) .build() } #[op] pub fn op_smartweave_unsafe_exit_process( _state: &mut OpState, _: (), _: (), ) -> Result<(), AnyError> { println!("Unsafe calls have been invoked outside of a safe context"); std::process::exit(1) } #[op] pub async fn op_smartweave_wallet_balance( _state: Rc<RefCell<OpState>>, address: String, _: (), ) -> Result<String, AnyError> { let s = _state.borrow(); let arweave = s.borrow::<ArweaveInfo>(); // Winston string let balance = reqwest::get(format!("{}/wallet/{}/balance", get_host(arweave), address)) .await? .text() .await?; Ok(balance) } #[op] pub async fn op_smartweave_wallet_last_tx( _state: Rc<RefCell<OpState>>, address: String, _: (), ) -> Result<String, AnyError> { let s = _state.borrow(); let arweave = s.borrow::<ArweaveInfo>(); let tx = reqwest::get(format!("{}/wallet/{}/last_tx", get_host(arweave), address)) .await? .text() .await?; Ok(tx) } #[op] pub async fn op_smartweave_get_tx_data( _state: Rc<RefCell<OpState>>, tx_id: String, _: (), ) -> Result<ZeroCopyBuf, AnyError> { let s = _state.borrow(); let arweave = s.borrow::<ArweaveInfo>(); let req = reqwest::get(format!("{}/{}", get_host(arweave), tx_id)) .await? .bytes() .await?; Ok(req.to_vec().into()) } #[op] pub async fn op_smartweave_get_tx( _state: Rc<RefCell<OpState>>, tx_id: String, _: (), ) -> Result<String, AnyError> { let s = _state.borrow(); let arweave = s.borrow::<ArweaveInfo>(); let req = reqwest::get(format!("{}/tx/{}", get_host(arweave), tx_id)) .await? .text() .await?; Ok(req) } pub fn read_contract_state(id: String) -> Value { // We want this to be a synchronous operation // because of its use with v8::Function. // But, Tokio will panic if we make blocking calls, // so we need offload it to a thread. thread::spawn(move || { println!("Reading contract state for {}", id); let state: Value = reqwest::blocking::get(format!( "https://storage.googleapis.com/verto-exchange-contracts/{}/{}_state.json", id, id, )) .unwrap() .json() .unwrap(); state }) .join() .unwrap() } pub fn get_host(arweave_info: &ArweaveInfo) -> String { if arweave_info.port == 80 { format!("{}://{}", arweave_info.protocol, arweave_info.host) } else { format!( "{}://{}:{}", arweave_info.protocol, arweave_info.host, arweave_info.port ) } } #[op] pub async fn op_smartweave_get_host( _state: Rc<RefCell<OpState>>, _parameters: (), _: (), ) -> Result<String, AnyError> { let s = _state.borrow(); let arweave = s.borrow::<ArweaveInfo>(); Ok(get_host(arweave)) }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/executor/lib.rs
crates/executor/lib.rs
pub mod executor; pub mod test_util; pub mod utils; pub use crate::executor::ExecuteResult; pub use crate::executor::ValidityTable; use crate::executor::{raw_execute_contract, V8Result}; use deno_core::error::{generic_error, AnyError}; use deno_core::serde_json::Value; pub use indexmap::map::IndexMap; use lru::LruCache; use once_cell::sync::Lazy; use std::cmp::Ordering; use std::collections::HashMap; use std::ffi::CString; use std::sync::Mutex; use three_em_arweave::arweave::Arweave; use three_em_arweave::arweave::LoadedContract; use three_em_arweave::arweave::{get_cache, ManualLoadedContract}; use three_em_arweave::gql_result::GQLEdgeInterface; use three_em_arweave::gql_result::GQLNodeInterface; use three_em_arweave::miscellaneous::get_sort_key; use three_em_evm::Instruction; use three_em_evm::U256; /** * @Purpose - Enables execution of contracts * * Questions. * what is interactions and maybe exm context * * elaborate on the loaded contract with tokio::join * * what does raw_execute_contract call exactly? Is this the final step that will really simulate a contract * * how is execute contract different from simulate_contract and why does mem-core rely on simulate_contract instead. * * Which crates matter in 3em to cover anything and everythng arweave, not EVM * * Biggest take home here is to how to grab this data base and test out each piece of the code. * */ static LRU_CACHE: Lazy<Mutex<LruCache<String, ExecuteResult>>> = Lazy::new(|| Mutex::new(LruCache::unbounded())); pub type ExmContext = three_em_exm_base_ops::ExmContext; pub async fn simulate_contract( contract_id: String, contract_init_state: Option<String>, interactions: Vec<GQLEdgeInterface>, arweave: &Arweave, maybe_cache: Option<bool>, maybe_bundled_contract: Option<bool>, maybe_settings: Option<HashMap<String, deno_core::serde_json::Value>>, maybe_exm_context_str: Option<String>, maybe_contract_source: Option<ManualLoadedContract>, ) -> Result<ExecuteResult, AnyError> { let shared_id = contract_id.clone(); /** * Two Options * if contract source provided * Load contract type and source * else * load_contract based on contract id * return * loaded contract * */ // There is no reason to join - you join here to run async tasks concurrently. let loaded_contract = tokio::join!(async move { if let Some(contract_source) = maybe_contract_source { let contract = LoadedContract { contract_src: contract_source.contract_src, contract_type: contract_source.contract_type, init_state: contract_init_state.clone().unwrap(), ..Default::default() }; Ok(contract) } else { let contract: Result<LoadedContract, AnyError> = arweave .load_contract( shared_id, None, None, contract_init_state, maybe_cache.unwrap_or(false), true, maybe_bundled_contract.unwrap_or(false), ) .await; contract } }) .0; // Grab user defined settings, else create new hashmap let mut settings: HashMap<String, deno_core::serde_json::Value> = maybe_settings.unwrap_or_else(|| HashMap::new()); settings.insert( String::from("Simulated"), deno_core::serde_json::Value::Bool(true), ); settings.insert( String::from("EXM"), deno_core::serde_json::Value::Bool(true), ); /** * * maybe_exm_context_str != None, save it * * */ if loaded_contract.is_ok() { let maybe_exm_context = { if let Some(context_str) = maybe_exm_context_str { Some(deno_core::serde_json::from_str(&context_str[..]).unwrap()) //convert the context_str into JSON } else { None } }; let execute = raw_execute_contract( contract_id, loaded_contract.unwrap(), interactions, IndexMap::new(), None, true, false, |validity_table, cache_state, errors| { ExecuteResult::V8(V8Result { state: cache_state.unwrap(), validity: validity_table, context: Default::default(), result: None, updated: true, errors, }) }, arweave, settings, maybe_exm_context, ) .await; Ok(execute) } else { Err(generic_error("Contract could not be loaded")) } } #[async_recursion::async_recursion(?Send)] pub async fn execute_contract( contract_id: String, height: Option<usize>, cache: bool, show_errors: bool, contract_src_tx: Option<String>, contract_content_type: Option<String>, arweave: &Arweave, ) -> Result<ExecuteResult, AnyError> { // Need to see how getting contract_id from LRU_CACHE yields result variable if let Some(result) = LRU_CACHE.lock().unwrap().get(&contract_id) { return Ok(result.clone()); } // Two copies bc we have to pass ownership to the functions below let contract_id_copy = contract_id.to_owned(); let contract_id_copy2 = contract_id.to_owned(); let shared_id = contract_id.clone(); // tokio::join behaves like Promise.all // each async move will return a piece of the tuple (loaded_contract, interactions) let (loaded_contract, interactions) = tokio::join!( async move { let contract: Result<LoadedContract, AnyError> = arweave .load_contract( shared_id, contract_src_tx, contract_content_type, None, cache, false, false, ) .await; contract }, async move { let interactions: Result<(Vec<GQLEdgeInterface>, usize, bool), AnyError> = arweave .get_interactions(contract_id_copy2, height, cache) .await; let ( result_interactions, new_interaction_index, are_there_new_interactions, ) = interactions?; let mut interactions = result_interactions; sort_interactions(&mut interactions); Ok(( interactions, new_interaction_index, are_there_new_interactions, )) as Result<(Vec<GQLEdgeInterface>, usize, bool), AnyError> } ); let loaded_contract = loaded_contract?; let (result_interactions, new_interaction_index, are_there_new_interactions) = interactions?; let mut interactions = result_interactions; let mut validity: IndexMap<String, Value> = IndexMap::new(); let mut needs_processing = true; let mut cache_state: Option<Value> = None; if cache { let get_cached_state = get_cache() .lock() .unwrap() .find_state(contract_id_copy.to_owned()); if let Some(cached_state) = get_cached_state { cache_state = Some(cached_state.state); validity = cached_state.validity; needs_processing = are_there_new_interactions; } } let is_cache_state_present = cache_state.is_some(); if cache && is_cache_state_present && are_there_new_interactions { interactions = (&interactions[new_interaction_index..]).to_vec(); } let result = raw_execute_contract( contract_id_copy.to_owned(), loaded_contract, interactions, validity, cache_state, needs_processing, show_errors, |validity_table, cache_state, errors| { ExecuteResult::V8(V8Result { state: cache_state.unwrap(), validity: validity_table, context: Default::default(), result: None, updated: false, errors: errors, }) }, arweave, HashMap::new(), None, ) .await; LRU_CACHE.lock().unwrap().put(contract_id, result.clone()); Ok(result) } pub fn get_input_from_interaction(interaction_tx: &GQLNodeInterface) -> &str { let tag = &interaction_tx .tags .iter() .find(|data| &data.name == "Input"); match tag { Some(data) => &data.value, None => "", } } pub fn has_multiple_interactions(interaction_tx: &GQLNodeInterface) -> bool { let tags = (&interaction_tx.tags).to_owned(); let count = tags .iter() .filter(|data| data.name == *"Contract") .cloned() .count(); count > 1 } // String locale compare fn strcoll(s1: &str, s2: &str) -> Ordering { let c1 = CString::new(s1).unwrap_or_default(); let c2 = CString::new(s2).unwrap_or_default(); let cmp = unsafe { libc::strcoll(c1.as_ptr(), c2.as_ptr()) }; cmp.cmp(&0) } pub fn sort_interactions(interactions: &mut Vec<GQLEdgeInterface>) { interactions.sort_by(|a, b| { let a_sort_key = get_sort_key(&a.node.block.height, &a.node.block.id, &a.node.id); let b_sort_key = get_sort_key(&b.node.block.height, &b.node.block.id, &b.node.id); strcoll(&a_sort_key, &b_sort_key) }); } fn nop_cost_fn(_: &Instruction) -> U256 { U256::zero() } #[cfg(test)] mod test { use crate::test_util::generate_fake_interaction; use crate::ExecuteResult; use crate::{execute_contract, sort_interactions}; use deno_core::serde_json; use deno_core::serde_json::value::Value::Null; use deno_core::serde_json::Value; use indexmap::map::IndexMap; use serde::Deserialize; use serde::Serialize; use std::collections::HashMap; use three_em_arweave::arweave::Arweave; use three_em_arweave::cache::ArweaveCache; use three_em_arweave::cache::CacheExt; use three_em_arweave::gql_result::GQLEdgeInterface; #[derive(Deserialize, Serialize)] struct People { username: String, } #[tokio::test] async fn load_contract_test() { let ar = Arweave::new_no_cache( 443, String::from("arweave.net"), String::from("https"), ); let load_contract_maybe = ar .load_contract( String::from("RadpzdYtVrQiS25JR1hGxZppwCXVCel_nfXk-noyFmc"), None, None, None, false, true, true, ) .await; let loaded_contract = load_contract_maybe.unwrap(); assert_eq!( loaded_contract.id, "RadpzdYtVrQiS25JR1hGxZppwCXVCel_nfXk-noyFmc" ); assert_eq!(loaded_contract.contract_transaction.format, 2); } #[tokio::test] async fn test_sorting() { // expected: j7Q8fkIG1mWnZYt8A0eYP46pGXV8sQXBBO51vqOjeGI, mFSUswFVKO8vPU4igACglukRxRuEGH4_ZJ89VdJHnNo, YFlMzDiiGLJvRnS2VSDzqRA5Zv551o-oW29R-FCIj8U let mut interactions: Vec<GQLEdgeInterface> = vec![ generate_fake_interaction( Null, "YFlMzDiiGLJvRnS2VSDzqRA5Zv551o-oW29R-FCIj8U", Some(String::from( "J_SFAxga87oQIFctKTT9NkSypZUWRblFIJa03p7TulrkytQaHaTD_ue2MwQQKLj1", )), Some(743424 as usize), None, None, None, None, None, None, ), generate_fake_interaction( Null, "j7Q8fkIG1mWnZYt8A0eYP46pGXV8sQXBBO51vqOjeGI", Some(String::from( "Q9VhW9qp_zKspSG7VswGE6NFsSgxzmP4evuhGIJUqUrq4vBLYCXrPrYcE5DwSODP", )), Some(743316 as usize), None, None, None, None, None, None, ), generate_fake_interaction( Null, "mFSUswFVKO8vPU4igACglukRxRuEGH4_ZJ89VdJHnNo", Some(String::from( "Q9VhW9qp_zKspSG7VswGE6NFsSgxzmP4evuhGIJUqUrq4vBLYCXrPrYcE5DwSODP", )), Some(743316 as usize), None, None, None, None, None, None, ), ]; sort_interactions(&mut interactions); assert_eq!( interactions .iter() .map(|item| String::from(&item.node.id)) .collect::<Vec<String>>(), vec![ "j7Q8fkIG1mWnZYt8A0eYP46pGXV8sQXBBO51vqOjeGI", "mFSUswFVKO8vPU4igACglukRxRuEGH4_ZJ89VdJHnNo", "YFlMzDiiGLJvRnS2VSDzqRA5Zv551o-oW29R-FCIj8U" ] ); } #[tokio::test] async fn test_sorting_2() { // expected: hwwRzR-sB89uQ_hU9UDViQYBmUg-tyf_1C-YmesZbck, ObACsVmx58xdmsH0k0MCdKdqPXyaT5QJl-lZLkjGDjE let mut interactions: Vec<GQLEdgeInterface> = vec![ generate_fake_interaction( Null, "ObACsVmx58xdmsH0k0MCdKdqPXyaT5QJl-lZLkjGDjE", Some(String::from( "luiqFPm09idjhj9YiNOxN8MvTGcWLa2oCYPa9WdZsFuJi06oHgSqJ3wv3aXR8Nlq", )), Some(741972 as usize), None, None, None, None, None, None, ), generate_fake_interaction( Null, "hwwRzR-sB89uQ_hU9UDViQYBmUg-tyf_1C-YmesZbck", Some(String::from( "luiqFPm09idjhj9YiNOxN8MvTGcWLa2oCYPa9WdZsFuJi06oHgSqJ3wv3aXR8Nlq", )), Some(741972 as usize), None, None, None, None, None, None, ), ]; sort_interactions(&mut interactions); assert_eq!( interactions .iter() .map(|item| String::from(&item.node.id)) .collect::<Vec<String>>(), vec![ "hwwRzR-sB89uQ_hU9UDViQYBmUg-tyf_1C-YmesZbck", "ObACsVmx58xdmsH0k0MCdKdqPXyaT5QJl-lZLkjGDjE", ] ); } #[tokio::test] async fn test_sorting_3() { // expected: 0J9RP8MwtB6y-Z3oRNgdURHXC2p5u5pm3AGJH4JBPLM, RqBAEgQtmpIwV9SYqxh0eZpil85Hh1ILhVBg8B9FmxA let mut interactions: Vec<GQLEdgeInterface> = vec![ generate_fake_interaction( Null, "RqBAEgQtmpIwV9SYqxh0eZpil85Hh1ILhVBg8B9FmxA", Some(String::from( "20vRhS4EjGRgI66joMVWmYZS9hLflTpFV5iQvFKGFbMYJBPxM8kptBNI9Pi4wcEU", )), Some(832275 as usize), None, None, None, None, None, None, ), generate_fake_interaction( Null, "0J9RP8MwtB6y-Z3oRNgdURHXC2p5u5pm3AGJH4JBPLM", Some(String::from( "20vRhS4EjGRgI66joMVWmYZS9hLflTpFV5iQvFKGFbMYJBPxM8kptBNI9Pi4wcEU", )), Some(832275 as usize), None, None, None, None, None, None, ), ]; sort_interactions(&mut interactions); assert_eq!( interactions .iter() .map(|item| String::from(&item.node.id)) .collect::<Vec<String>>(), vec![ "0J9RP8MwtB6y-Z3oRNgdURHXC2p5u5pm3AGJH4JBPLM", "RqBAEgQtmpIwV9SYqxh0eZpil85Hh1ILhVBg8B9FmxA", ] ); } // #[tokio::test] // async fn test_sorting_all() {
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
true