Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: use full tx request in call #352

Merged
merged 3 commits into from
Aug 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,16 @@ alloy = { version = "0.2.1", features = [
"rlp",
"k256",
"provider-http",
"sol-types"
"sol-types",
"network",
]}
revm = { version = "12.1.0", default-features = false, features = [
"std",
"serde",
"optional_block_gas_limit",
"optional_eip3607",
"optional_no_base_fee",
]}
revm = { version = "12.1.0", default-features = false, features = ["std", "serde"] }
triehash-ethereum = { git = "https://github.com/openethereum/parity-ethereum", rev = "55c90d4016505317034e3e98f699af07f5404b63" }

# async/futures
Expand Down
13 changes: 7 additions & 6 deletions client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ use std::sync::Arc;
use std::time::Duration;

use alloy::primitives::{Address, B256, U256};
use alloy::rpc::types::{Filter, Log, SyncStatus, Transaction, TransactionReceipt};
use alloy::rpc::types::{
Filter, Log, SyncStatus, Transaction, TransactionReceipt, TransactionRequest,
};
use eyre::{eyre, Result};
use tracing::{info, warn};
use zduny_wasm_timer::Delay;
Expand All @@ -13,7 +15,6 @@ use common::types::{Block, BlockTag};
use config::networks::Network;
use config::Config;
use consensus::database::Database;
use execution::types::CallOpts;

use crate::node::Node;

Expand Down Expand Up @@ -267,12 +268,12 @@ impl<DB: Database> Client<DB> {
}
}

pub async fn call(&self, opts: &CallOpts, block: BlockTag) -> Result<Vec<u8>> {
self.node.call(opts, block).await.map_err(|err| err.into())
pub async fn call(&self, tx: &TransactionRequest, block: BlockTag) -> Result<Vec<u8>> {
self.node.call(tx, block).await.map_err(|err| err.into())
}

pub async fn estimate_gas(&self, opts: &CallOpts) -> Result<u64> {
self.node.estimate_gas(opts).await.map_err(|err| err.into())
pub async fn estimate_gas(&self, tx: &TransactionRequest) -> Result<u64> {
self.node.estimate_gas(tx).await.map_err(|err| err.into())
}

pub async fn get_balance(&self, address: &Address, block: BlockTag) -> Result<U256> {
Expand Down
18 changes: 11 additions & 7 deletions client/src/node.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use std::sync::Arc;

use alloy::primitives::{Address, B256, U256};
use alloy::rpc::types::{Filter, Log, SyncInfo, SyncStatus, Transaction, TransactionReceipt};
use alloy::rpc::types::{
Filter, Log, SyncInfo, SyncStatus, Transaction, TransactionReceipt, TransactionRequest,
};
use eyre::{eyre, Result};
use zduny_wasm_timer::{SystemTime, UNIX_EPOCH};

Expand All @@ -13,7 +15,6 @@ use consensus::ConsensusClient;
use execution::evm::Evm;
use execution::rpc::http_rpc::HttpRpc;
use execution::state::State;
use execution::types::CallOpts;
use execution::ExecutionClient;

use crate::errors::NodeError;
Expand Down Expand Up @@ -50,20 +51,23 @@ impl<DB: Database> Node<DB> {
})
}

pub async fn call(&self, opts: &CallOpts, block: BlockTag) -> Result<Vec<u8>, NodeError> {
pub async fn call(
&self,
tx: &TransactionRequest,
block: BlockTag,
) -> Result<Vec<u8>, NodeError> {
self.check_blocktag_age(&block).await?;

let mut evm = Evm::new(self.execution.clone(), self.chain_id(), block);

evm.call(opts).await.map_err(NodeError::ExecutionEvmError)
evm.call(tx).await.map_err(NodeError::ExecutionEvmError)
}

pub async fn estimate_gas(&self, opts: &CallOpts) -> Result<u64, NodeError> {
pub async fn estimate_gas(&self, tx: &TransactionRequest) -> Result<u64, NodeError> {
self.check_head_age().await?;

let mut evm = Evm::new(self.execution.clone(), self.chain_id(), BlockTag::Latest);

evm.estimate_gas(opts)
evm.estimate_gas(tx)
.await
.map_err(NodeError::ExecutionEvmError)
}
Expand Down
17 changes: 9 additions & 8 deletions client/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ use std::net::{IpAddr, Ipv4Addr};
use std::{fmt::Display, net::SocketAddr, str::FromStr, sync::Arc};

use alloy::primitives::{Address, B256, U256};
use alloy::rpc::types::{Filter, Log, SyncStatus, Transaction, TransactionReceipt};
use alloy::rpc::types::{
Filter, Log, SyncStatus, Transaction, TransactionReceipt, TransactionRequest,
};
use eyre::Result;
use jsonrpsee::{
core::{async_trait, server::Methods, Error},
Expand All @@ -16,7 +18,6 @@ use common::{
utils::{hex_str_to_bytes, u64_to_hex_string},
};
use consensus::database::Database;
use execution::types::CallOpts;

use crate::{errors::NodeError, node::Node};

Expand Down Expand Up @@ -68,9 +69,9 @@ trait EthRpc {
#[method(name = "getCode")]
async fn get_code(&self, address: &str, block: BlockTag) -> Result<String, Error>;
#[method(name = "call")]
async fn call(&self, opts: CallOpts, block: BlockTag) -> Result<String, Error>;
async fn call(&self, tx: TransactionRequest, block: BlockTag) -> Result<String, Error>;
#[method(name = "estimateGas")]
async fn estimate_gas(&self, opts: CallOpts) -> Result<String, Error>;
async fn estimate_gas(&self, tx: TransactionRequest) -> Result<String, Error>;
#[method(name = "chainId")]
async fn chain_id(&self) -> Result<String, Error>;
#[method(name = "gasPrice")]
Expand Down Expand Up @@ -177,20 +178,20 @@ impl<DB: Database> EthRpcServer for RpcInner<DB> {
Ok(format!("0x{:}", hex::encode(code)))
}

async fn call(&self, opts: CallOpts, block: BlockTag) -> Result<String, Error> {
async fn call(&self, tx: TransactionRequest, block: BlockTag) -> Result<String, Error> {
let res = self
.node
.call(&opts, block)
.call(&tx, block)
.await
.map_err(NodeError::to_json_rpsee_error)?;

Ok(format!("0x{}", hex::encode(res)))
}

async fn estimate_gas(&self, opts: CallOpts) -> Result<String, Error> {
async fn estimate_gas(&self, tx: TransactionRequest) -> Result<String, Error> {
let gas = self
.node
.estimate_gas(&opts)
.estimate_gas(&tx)
.await
.map_err(NodeError::to_json_rpsee_error)?;

Expand Down
2 changes: 2 additions & 0 deletions common/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ pub struct Block {
pub transactions: Transactions,
pub transactions_root: B256,
pub uncles: Vec<B256>,
pub blob_gas_used: Option<U64>,
pub excess_blob_gas: Option<U64>,
}

#[derive(Deserialize, Debug, Clone)]
Expand Down
2 changes: 2 additions & 0 deletions consensus-core/src/types/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,8 @@ impl From<ExecutionPayload> for Block {
size: U64::ZERO,
transactions_root: B256::default(),
uncles: vec![],
blob_gas_used: value.blob_gas_used().map(|v| U64::from(v.as_u64())).ok(),
excess_blob_gas: value.excess_blob_gas().map(|v| U64::from(v.as_u64())).ok(),
}
}
}
Expand Down
16 changes: 11 additions & 5 deletions examples/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use std::path::PathBuf;

use alloy::primitives::{Address, Bytes};
use alloy::rpc::types::TransactionRequest;
use dotenv::dotenv;
use tracing::info;
use tracing_subscriber::filter::{EnvFilter, LevelFilter};
Expand All @@ -11,7 +12,7 @@ use tracing_subscriber::FmtSubscriber;
use helios::{
client::{Client, ClientBuilder, FileDB},
config::networks::Network,
types::{BlockTag, CallOpts},
types::BlockTag,
};

#[tokio::main]
Expand Down Expand Up @@ -53,16 +54,21 @@ async fn main() -> eyre::Result<()> {
client.wait_synced().await;

// Call on helios client
let call_opts = CallOpts {
let tx = TransactionRequest {
from: None,
to: Some("0x6B175474E89094C44Da98b954EedeAC495271d0F".parse::<Address>()?),
to: Some(
"0x6B175474E89094C44Da98b954EedeAC495271d0F"
.parse::<Address>()?
.into(),
),
gas: None,
gas_price: None,
value: None,
data: Some("0x18160ddd".parse::<Bytes>()?),
input: "0x18160ddd".parse::<Bytes>()?.into(),
..Default::default()
};

let result = client.call(&call_opts, BlockTag::Latest).await?;
let result = client.call(&tx, BlockTag::Latest).await?;
info!("[HELIOS] DAI total supply: {:?}", result);

Ok(())
Expand Down
72 changes: 46 additions & 26 deletions execution/src/evm.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
use std::{borrow::BorrowMut, collections::HashMap, sync::Arc};

use alloy::{network::TransactionBuilder, rpc::types::TransactionRequest};
use eyre::{Report, Result};
use futures::future::join_all;
use revm::{
primitives::{
address, AccessListItem, AccountInfo, Address, Bytecode, Env, ExecutionResult,
ResultAndState, TransactTo, B256, U256,
address, AccessListItem, AccountInfo, Address, BlobExcessGasAndPrice, Bytecode, Env,
ExecutionResult, ResultAndState, B256, U256,
},
Database, Evm as Revm,
};
use tracing::trace;

use crate::{
constants::PARALLEL_QUERY_BATCH_SIZE, errors::EvmError, rpc::ExecutionRpc, types::CallOpts,
ExecutionClient,
constants::PARALLEL_QUERY_BATCH_SIZE, errors::EvmError, rpc::ExecutionRpc, ExecutionClient,
};
use common::types::BlockTag;

Expand All @@ -32,8 +32,8 @@ impl<R: ExecutionRpc> Evm<R> {
}
}

pub async fn call(&mut self, opts: &CallOpts) -> Result<Vec<u8>, EvmError> {
let tx = self.call_inner(opts).await?;
pub async fn call(&mut self, tx: &TransactionRequest) -> Result<Vec<u8>, EvmError> {
let tx = self.call_inner(tx).await?;

match tx.result {
ExecutionResult::Success { output, .. } => Ok(output.into_data().to_vec()),
Expand All @@ -44,8 +44,8 @@ impl<R: ExecutionRpc> Evm<R> {
}
}

pub async fn estimate_gas(&mut self, opts: &CallOpts) -> Result<u64, EvmError> {
let tx = self.call_inner(opts).await?;
pub async fn estimate_gas(&mut self, tx: &TransactionRequest) -> Result<u64, EvmError> {
let tx = self.call_inner(tx).await?;

match tx.result {
ExecutionResult::Success { gas_used, .. } => Ok(gas_used),
Expand All @@ -54,11 +54,11 @@ impl<R: ExecutionRpc> Evm<R> {
}
}

async fn call_inner(&mut self, opts: &CallOpts) -> Result<ResultAndState, EvmError> {
async fn call_inner(&mut self, tx: &TransactionRequest) -> Result<ResultAndState, EvmError> {
let mut db = ProofDB::new(self.tag, self.execution.clone());
_ = db.state.prefetch_state(opts).await;
_ = db.state.prefetch_state(tx).await;

let env = Box::new(self.get_env(opts, self.tag).await);
let env = Box::new(self.get_env(tx, self.tag).await);
let evm = Revm::builder().with_db(db).with_env(env).build();
let mut ctx = evm.into_context_with_handler_cfg();

Expand All @@ -70,36 +70,56 @@ impl<R: ExecutionRpc> Evm<R> {

let mut evm = Revm::builder().with_context_with_handler_cfg(ctx).build();
let res = evm.transact();

ctx = evm.into_context_with_handler_cfg();

if res.is_ok() {
let db = ctx.context.evm.db.borrow_mut();
let needs_update = db.state.needs_update();

if res.is_ok() || !needs_update {
break res;
}
};

tx_res.map_err(|_| EvmError::Generic("evm error".to_string()))
}

async fn get_env(&self, opts: &CallOpts, tag: BlockTag) -> Env {
async fn get_env(&self, tx: &TransactionRequest, tag: BlockTag) -> Env {
let mut env = Env::default();
let to = &opts.to.unwrap_or_default();
let from = &opts.from.unwrap_or_default();

env.tx.transact_to = TransactTo::Call(*to);
env.tx.caller = *from;
env.tx.value = opts.value.unwrap_or_default();
env.tx.data = opts.data.clone().unwrap_or_default();
env.tx.gas_limit = opts.gas.map(|v| v.to()).unwrap_or(u64::MAX);
env.tx.gas_price = opts.gas_price.unwrap_or_default();
env.tx.caller = tx.from.unwrap_or_default();
env.tx.gas_limit = tx.gas_limit().map(|v| v as u64).unwrap_or(u64::MAX);
env.tx.gas_price = tx.gas_price().map(U256::from).unwrap_or_default();
env.tx.transact_to = tx.to.unwrap_or_default();
env.tx.value = tx.value.unwrap_or_default();
env.tx.data = tx.input().unwrap_or_default().clone();
env.tx.nonce = tx.nonce();
env.tx.chain_id = tx.chain_id();
env.tx.access_list = tx.access_list().map(|v| v.to_vec()).unwrap_or_default();
env.tx.gas_priority_fee = tx.max_priority_fee_per_gas().map(U256::from);
env.tx.max_fee_per_blob_gas = tx.max_fee_per_gas().map(U256::from);
env.tx.blob_hashes = tx
.blob_versioned_hashes
.as_ref()
.map(|v| v.to_vec())
.unwrap_or_default();

let block = self.execution.get_block(tag, false).await.unwrap();

env.block.number = block.number.to();
env.block.coinbase = block.miner;
env.block.timestamp = block.timestamp.to();
env.block.gas_limit = block.gas_limit.to();
env.block.basefee = block.base_fee_per_gas;
env.block.difficulty = block.difficulty;
env.block.prevrandao = Some(block.mix_hash);
env.block.blob_excess_gas_and_price = block
.excess_blob_gas
.map(|v| BlobExcessGasAndPrice::new(v.to()));

env.cfg.chain_id = self.chain_id;
env.cfg.disable_block_gas_limit = true;
env.cfg.disable_eip3607 = true;
env.cfg.disable_base_fee = true;

env
}
Expand Down Expand Up @@ -219,22 +239,22 @@ impl<R: ExecutionRpc> EvmState<R> {
}
}

pub async fn prefetch_state(&mut self, opts: &CallOpts) -> Result<()> {
pub async fn prefetch_state(&mut self, tx: &TransactionRequest) -> Result<()> {
let mut list = self
.execution
.rpc
.create_access_list(opts, self.block)
.create_access_list(tx, self.block)
.await
.map_err(EvmError::RpcError)?
.0;

let from_access_entry = AccessListItem {
address: opts.from.unwrap_or_default(),
address: tx.from.unwrap_or_default(),
storage_keys: Vec::default(),
};

let to_access_entry = AccessListItem {
address: opts.to.unwrap_or_default(),
address: tx.to().unwrap_or_default(),
storage_keys: Vec::default(),
};

Expand Down
Loading
Loading