Skip to content

Commit

Permalink
Add query by blockNumber RPC changes to metachain-cli (#1977)
Browse files Browse the repository at this point in the history
* Remove EVMState tests

* Add latest RPC changes to CLI
  • Loading branch information
Jouzo authored May 8, 2023
1 parent a5cad26 commit ec9cf0b
Show file tree
Hide file tree
Showing 8 changed files with 65 additions and 162 deletions.
119 changes: 0 additions & 119 deletions lib/ain-evm/src/storage/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,122 +118,3 @@ impl From<bincode::Error> for PersistentStateError {
PersistentStateError::BincodeError(error)
}
}

#[cfg(test_off)]
mod tests {
use crate::evm::EVMState;
use crate::traits::PersistentState;
use evm::backend::MemoryAccount;
use primitive_types::{H160, H256, U256};
use std::collections::BTreeMap;
use std::fs::File;
use std::io::Write;

fn create_account(
nonce: U256,
balance: U256,
code: Vec<u8>,
storage: BTreeMap<H256, H256>,
) -> MemoryAccount {
MemoryAccount {
nonce,
balance,
code,
storage,
}
}

#[test]
fn test_load_non_existent_file() {
let state = EVMState::load_from_disk("non_existent_file.bin").unwrap();
assert_eq!(state, EVMState::default());
}

#[test]
fn test_empty_file() {
let state = BTreeMap::new();
let path = "empty_test.bin";

state.save_to_disk(path).unwrap();

let new_state = EVMState::load_from_disk(path).unwrap();

assert_eq!(state, new_state);
}

#[test]
fn test_invalid_file_format() {
let invalid_data = b"invalid_data";
let path = "invalid_file_format.bin";

let mut file = File::create(path).unwrap();
file.write_all(invalid_data).unwrap();

let state = EVMState::load_from_disk(path);

assert!(state.is_err());
}

#[test]
fn test_save_and_load_empty_backend() {
let path = "test_empty_backend.bin";
let state = BTreeMap::new();

state.save_to_disk(path).unwrap();

let loaded_backend = EVMState::load_from_disk(path).unwrap();

assert_eq!(state, loaded_backend);
}

#[test]
fn test_save_and_load_single_account() {
let path = "test_single_account.bin";
let mut state = BTreeMap::new();

let account = create_account(
U256::from(1),
U256::from(1000),
vec![1, 2, 3],
BTreeMap::new(),
);
let address = H160::from_low_u64_be(1);
state.insert(address, account);

state.save_to_disk(path).unwrap();

let loaded_backend = EVMState::load_from_disk(path).unwrap();

assert_eq!(state, loaded_backend);
}

#[test]
fn test_save_and_load_multiple_accounts() {
let path = "test_multiple_accounts.bin";
let mut state = BTreeMap::new();

let account1 = create_account(
U256::from(1),
U256::from(1000),
vec![1, 2, 3],
BTreeMap::new(),
);
let address1 = H160::from_low_u64_be(1);
state.insert(address1, account1);

let account2 = create_account(
U256::from(2),
U256::from(2000),
vec![4, 5, 6],
BTreeMap::new(),
);
let address2 = H160::from_low_u64_be(2);
state.insert(address2, account2);

state.save_to_disk(path).unwrap();

let loaded_backend = EVMState::load_from_disk(path).unwrap();

assert_eq!(state, loaded_backend);
}
}
5 changes: 2 additions & 3 deletions lib/ain-grpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@ extern crate serde;
extern crate serde_json;

pub mod block;
mod call_request;
mod codegen;
pub mod call_request;
pub mod codegen;
mod impls;
mod receipt;
pub mod rpc;
// pub use ain_evm::evm::EVMState;

use env_logger::{Builder as LogBuilder, Env, Target};
use jsonrpsee::core::server::rpc_module::Methods;
Expand Down
34 changes: 24 additions & 10 deletions lib/cli/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ pub async fn execute_cli_command(
MetachainCLI::NetVersion => client.net_version().await?.into(),
MetachainCLI::Mining => client.mining().await?.into(),
MetachainCLI::Call { input } => client.call((*input).into()).await?.into(),
MetachainCLI::GetBalance { address } => client.get_balance(address).await?.into(),
MetachainCLI::GetBalance {
address,
block_number,
} => client.get_balance(address, block_number).await?.into(),
MetachainCLI::GetBlockByHash { hash } => client.get_block_by_hash(hash).await?.into(),
MetachainCLI::HashRate => client.hash_rate().await?.into(),
MetachainCLI::BlockNumber => client.block_number().await?.into(),
Expand Down Expand Up @@ -46,18 +49,29 @@ pub async fn execute_cli_command(
.get_block_transaction_count_by_number(number)
.await?
.into(),
MetachainCLI::GetCode { address } => client.get_code(address).await?.into(),
MetachainCLI::GetStorageAt { address, position } => {
client.get_storage_at(address, position).await?.into()
}
MetachainCLI::GetCode {
address,
block_number,
} => client.get_code(address, block_number).await?.into(),
MetachainCLI::GetStorageAt {
address,
position,
block_number,
} => client
.get_storage_at(address, position, block_number)
.await?
.into(),
MetachainCLI::SendRawTransaction { input } => {
client.send_raw_transaction(&input).await?.into()
}
MetachainCLI::GetTransactionCount { input } => {
client.get_transaction_count(input).await?.into()
}
MetachainCLI::EstimateGas => client.estimate_gas().await?.into(),
MetachainCLI::GetState => client.get_state().await?.into(),
MetachainCLI::GetTransactionCount {
input,
block_number,
} => client
.get_transaction_count(input, block_number)
.await?
.into(),
MetachainCLI::EstimateGas { input } => client.estimate_gas((*input).into()).await?.into(),
MetachainCLI::GasPrice => client.gas_price().await?.into(),
};
Ok(result)
Expand Down
2 changes: 1 addition & 1 deletion lib/cli/src/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ impl FromStr for Format {
"json" => Ok(Format::Json),
"rust" => Ok(Format::Rust),
"pp" => Ok(Format::PrettyJson),
_ => Err(format!("Unsupported format: {}", s)),
_ => Err(format!("Unsupported format: {s}")),
}
}
}
19 changes: 14 additions & 5 deletions lib/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ pub enum MetachainCLI {
GetBalance {
#[structopt(parse(try_from_str))]
address: H160,
#[structopt(parse(try_from_str))]
block_number: Option<BlockNumber>,
},
/// Returns information about a block by its hash.
GetBlockByHash {
Expand Down Expand Up @@ -95,25 +97,32 @@ pub enum MetachainCLI {
GetCode {
#[structopt(parse(try_from_str))]
address: H160,
#[structopt(parse(try_from_str))]
block_number: Option<BlockNumber>,
},
/// Returns the value from a storage position at a given address.
GetStorageAt {
#[structopt(parse(try_from_str))]
address: H160,
#[structopt(parse(try_from_str))]
position: H256,
position: U256,
#[structopt(parse(try_from_str))]
block_number: Option<BlockNumber>,
},
/// Sends a signed transaction and returns the transaction hash.
SendRawTransaction { input: String },
/// Returns the number of transactions sent from an address.
GetTransactionCount {
#[structopt(parse(try_from_str))]
input: H160,
#[structopt(parse(try_from_str))]
block_number: Option<BlockNumber>,
},
/// Generates and returns an estimate of how much gas is necessary to allow the transaction to complete.
EstimateGas,
/// Returns an object representing the current state of the Metachain network.
GetState,
EstimateGas {
#[structopt(flatten)]
input: Box<CallRequest>,
},
/// Returns the current price per gas in wei.
GasPrice,
}
Expand All @@ -131,7 +140,7 @@ async fn main() -> Result<(), jsonrpsee::core::Error> {

let result = execute_cli_command(opt.cmd, &client).await?;
match opt.format {
Format::Rust => println!("{}", result),
Format::Rust => println!("{result}"),
Format::Json => println!("{}", serde_json::to_string(&result)?),
Format::PrettyJson => println!("{}", serde_json::to_string_pretty(&result)?),
};
Expand Down
4 changes: 2 additions & 2 deletions lib/cli/src/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ impl FromStr for Chain {
"testnet" => Ok(Chain::Testnet),
"devnet" => Ok(Chain::Devnet),
"regtest" => Ok(Chain::Regtest),
_ => Err(format!("Unknown chain: {}", s)),
_ => Err(format!("Unknown chain: {s}")),
}
}
}
Expand All @@ -35,7 +35,7 @@ impl BaseChainParams {
pub fn create(chain: &Chain) -> Self {
match chain {
Chain::Main => Self {
data_dir: "".to_string(),
data_dir: String::new(),
rpc_port: 8554,
grpc_port: 8550,
eth_rpc_port: 8551,
Expand Down
36 changes: 18 additions & 18 deletions lib/cli/src/result.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use ain_grpc::block::RpcBlock;
use ain_grpc::codegen::types::EthTransactionInfo;
use ain_grpc::{block::RpcBlock, EVMState};
use primitive_types::U256;
use primitive_types::{H256, U256};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
Expand All @@ -9,9 +9,9 @@ pub enum RpcResult {
String(String),
VecString(Vec<String>),
U256(U256),
H256(H256),
Bool(bool),
EthTransactionInfo(EthTransactionInfo),
EVMState(EVMState),
Usize(usize),
Block(Box<RpcBlock>),
Option(Option<Box<RpcResult>>),
Expand All @@ -35,6 +35,12 @@ impl From<U256> for RpcResult {
}
}

impl From<H256> for RpcResult {
fn from(value: H256) -> Self {
RpcResult::H256(value)
}
}

impl From<bool> for RpcResult {
fn from(value: bool) -> Self {
RpcResult::Bool(value)
Expand All @@ -47,12 +53,6 @@ impl From<EthTransactionInfo> for RpcResult {
}
}

impl From<EVMState> for RpcResult {
fn from(value: EVMState) -> Self {
RpcResult::EVMState(value)
}
}

impl From<usize> for RpcResult {
fn from(value: usize) -> Self {
RpcResult::Usize(value)
Expand All @@ -76,16 +76,16 @@ use std::fmt::{self, Display, Formatter};
impl Display for RpcResult {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
RpcResult::String(value) => write!(f, "{}", value),
RpcResult::VecString(value) => write!(f, "{:?}", value),
RpcResult::U256(value) => write!(f, "{}", value),
RpcResult::Bool(value) => write!(f, "{}", value),
RpcResult::EthTransactionInfo(value) => write!(f, "{:?}", value),
RpcResult::EVMState(value) => write!(f, "{:?}", value),
RpcResult::Usize(value) => write!(f, "{}", value),
RpcResult::Block(value) => write!(f, "{:?}", value),
RpcResult::String(value) => write!(f, "{value}"),
RpcResult::VecString(value) => write!(f, "{value:?}"),
RpcResult::U256(value) => write!(f, "{value:#x}"),
RpcResult::H256(value) => write!(f, "{value:#x}"),
RpcResult::Bool(value) => write!(f, "{value}"),
RpcResult::EthTransactionInfo(value) => write!(f, "{value:?}"),
RpcResult::Usize(value) => write!(f, "{value}"),
RpcResult::Block(value) => write!(f, "{value:?}"),
RpcResult::Option(value) => match value {
Some(inner_value) => write!(f, "Some({})", inner_value),
Some(inner_value) => write!(f, "Some({inner_value})"),
None => write!(f, "None"),
},
}
Expand Down
8 changes: 4 additions & 4 deletions lib/cli/src/structs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,25 +57,25 @@ pub struct CallRequest {

fn parse_h160(s: &str) -> Result<H160, String> {
s.parse::<H160>()
.map_err(|e| format!("Failed to parse H160: {}", e))
.map_err(|e| format!("Failed to parse H160: {e}"))
}

fn parse_u256(s: &str) -> Result<U256, String> {
s.parse::<U256>()
.map_err(|e| format!("Failed to parse U256: {}", e))
.map_err(|e| format!("Failed to parse U256: {e}"))
}

fn parse_hex_data(s: &str) -> Result<HexData, String> {
if let Some(stripped) = s.strip_prefix("0x") {
let hex = hex::decode(stripped).map_err(|e| format!("Failed to parse hex data: {}", e))?;
let hex = hex::decode(stripped).map_err(|e| format!("Failed to parse hex data: {e}"))?;
Ok(HexData(hex))
} else {
Err("Data must start with 0x".to_string())
}
}

fn parse_access_list(s: &str) -> Result<Vec<AccessListItem>, String> {
serde_json::from_str(s).map_err(|e| format!("Failed to parse access list: {}", e))
serde_json::from_str(s).map_err(|e| format!("Failed to parse access list: {e}"))
}

impl From<CallRequest> for ain_grpc::call_request::CallRequest {
Expand Down

0 comments on commit ec9cf0b

Please sign in to comment.