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(anvil): anvil_metadata #6240

Merged
merged 4 commits into from
Nov 7, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
4 changes: 4 additions & 0 deletions crates/anvil/core/src/eth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,10 @@ pub enum EthRequest {
#[cfg_attr(feature = "serde", serde(rename = "anvil_nodeInfo", with = "empty_params"))]
NodeInfo(()),

/// Retrieves the Anvil node metadata.
#[cfg_attr(feature = "serde", serde(rename = "anvil_metadata", with = "empty_params"))]
AnvilMetadata(()),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's also add hardhat_metdata alias?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh ya, sounds good


// Ganache compatible calls
/// Snapshot the state of the blockchain at the current block.
#[cfg_attr(
Expand Down
28 changes: 27 additions & 1 deletion crates/anvil/core/src/types.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use ethers_core::types::{H256, U256, U64};
use ethers_core::types::{TxHash, H256, U256, U64};
use revm::primitives::SpecId;

#[cfg(feature = "serde")]
Expand Down Expand Up @@ -204,6 +204,32 @@ pub struct NodeForkConfig {
pub fork_retry_backoff: Option<u128>,
}

/// Anvil equivalent of `hardhat_metadata`.
/// Metadata about the current Anvil instance.
/// See <https://hardhat.org/hardhat-network/docs/reference#hardhat_metadata>
#[derive(Debug, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct AnvilMetadata {
pub client_version: &'static str,
pub chain_id: U256,
pub instance_id: H256,
pub latest_block_number: U64,
pub latest_block_hash: H256,
pub forked_network: Option<ForkedNetwork>,
}

/// Information about the forked network.
/// See <https://hardhat.org/hardhat-network/docs/reference#hardhat_metadata>
#[derive(Debug, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct ForkedNetwork {
pub chain_id: U256,
pub fork_block_number: U64,
pub fork_block_hash: TxHash,
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
42 changes: 41 additions & 1 deletion crates/anvil/src/eth/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@ use anvil_core::{
},
EthRequest,
},
types::{EvmMineOptions, Forking, Index, NodeEnvironment, NodeForkConfig, NodeInfo, Work},
types::{
AnvilMetadata, EvmMineOptions, ForkedNetwork, Forking, Index, NodeEnvironment,
NodeForkConfig, NodeInfo, Work,
},
};
use anvil_rpc::{error::RpcError, response::ResponseResult};
use ethers::{
Expand Down Expand Up @@ -108,6 +111,8 @@ pub struct EthApi {
transaction_order: Arc<RwLock<TransactionOrder>>,
/// Whether we're listening for RPC calls
net_listening: bool,
/// The instance ID. Changes on every reset.
instance_id: Arc<RwLock<H256>>,
}

// === impl Eth RPC API ===
Expand Down Expand Up @@ -138,6 +143,7 @@ impl EthApi {
filters,
net_listening: true,
transaction_order: Arc::new(RwLock::new(transactions_order)),
instance_id: Arc::new(RwLock::new(H256::random())),
}
}

Expand Down Expand Up @@ -315,6 +321,7 @@ impl EthApi {
EthRequest::DumpState(_) => self.anvil_dump_state().await.to_rpc_result(),
EthRequest::LoadState(buf) => self.anvil_load_state(buf).await.to_rpc_result(),
EthRequest::NodeInfo(_) => self.anvil_node_info().await.to_rpc_result(),
EthRequest::AnvilMetadata(_) => self.anvil_metadata().await.to_rpc_result(),
EthRequest::EvmSnapshot(_) => self.evm_snapshot().await.to_rpc_result(),
EthRequest::EvmRevert(id) => self.evm_revert(id).await.to_rpc_result(),
EthRequest::EvmIncreaseTime(time) => self.evm_increase_time(time).await.to_rpc_result(),
Expand Down Expand Up @@ -1532,6 +1539,8 @@ impl EthApi {
pub async fn anvil_reset(&self, forking: Option<Forking>) -> Result<()> {
node_info!("anvil_reset");
if let Some(forking) = forking {
// if we're resetting the fork we need to reset the instance id
self.reset_instance_id();
self.backend.reset_fork(forking).await
} else {
Err(BlockchainError::RpcUnimplemented)
Expand Down Expand Up @@ -1695,6 +1704,27 @@ impl EthApi {
})
}

/// Retrieves metadata about the Anvil instance.
///
/// Handler for RPC call: `anvil_metadata`
pub async fn anvil_metadata(&self) -> Result<AnvilMetadata> {
node_info!("anvil_metadata");
let fork_config = self.backend.get_fork();

Ok(AnvilMetadata {
client_version: CLIENT_VERSION,
chain_id: self.backend.chain_id(),
latest_block_hash: self.backend.best_hash(),
latest_block_number: self.backend.best_number(),
instance_id: *self.instance_id.read(),
forked_network: fork_config.map(|cfg| ForkedNetwork {
chain_id: cfg.chain_id().into(),
fork_block_number: cfg.block_number().into(),
fork_block_hash: cfg.block_hash(),
}),
})
}

/// Snapshot the state of the blockchain at the current block.
///
/// Handler for RPC call: `evm_snapshot`
Expand Down Expand Up @@ -2280,6 +2310,16 @@ impl EthApi {
self.backend.get_fork()
}

/// Returns the current instance's ID.
pub fn instance_id(&self) -> H256 {
*self.instance_id.read()
}

/// Resets the instance ID.
pub fn reset_instance_id(&self) {
*self.instance_id.write() = H256::random();
}

/// Returns the first signer that can sign for the given address
#[allow(clippy::borrowed_box)]
pub fn get_signer(&self, address: Address) -> Option<&Box<dyn Signer>> {
Expand Down
72 changes: 70 additions & 2 deletions crates/anvil/tests/it/anvil_api.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
//! tests for custom anvil endpoints
use crate::{abi::*, fork::fork_config};
use anvil::{spawn, Hardfork, NodeConfig};
use anvil::{eth::api::CLIENT_VERSION, spawn, Hardfork, NodeConfig};
use anvil_core::{
eth::EthRequest,
types::{NodeEnvironment, NodeForkConfig, NodeInfo},
types::{AnvilMetadata, ForkedNetwork, Forking, NodeEnvironment, NodeForkConfig, NodeInfo},
};
use ethers::{
abi::{ethereum_types::BigEndianHash, AbiDecode},
Expand Down Expand Up @@ -454,6 +454,74 @@ async fn can_get_node_info() {
assert_eq!(node_info, expected_node_info);
}

#[tokio::test(flavor = "multi_thread")]
async fn can_get_metadata() {
let (api, handle) = spawn(NodeConfig::test()).await;

let metadata = api.anvil_metadata().await.unwrap();

let provider = handle.http_provider();

let block_number = provider.get_block_number().await.unwrap();
let chain_id = provider.get_chainid().await.unwrap();
let block = provider.get_block(block_number).await.unwrap().unwrap();

let expected_metadata = AnvilMetadata {
latest_block_hash: block.hash.unwrap(),
latest_block_number: block_number,
chain_id,
client_version: CLIENT_VERSION,
instance_id: api.instance_id(),
forked_network: None,
};

assert_eq!(metadata, expected_metadata);
}

#[tokio::test(flavor = "multi_thread")]
async fn can_get_metadata_on_fork() {
let (api, handle) =
spawn(NodeConfig::test().with_eth_rpc_url(Some("https://bsc-dataseed.binance.org/"))).await;
let provider = Arc::new(handle.http_provider());

let metadata = api.anvil_metadata().await.unwrap();

let block_number = provider.get_block_number().await.unwrap();
let chain_id = provider.get_chainid().await.unwrap();
let block = provider.get_block(block_number).await.unwrap().unwrap();

let expected_metadata = AnvilMetadata {
latest_block_hash: block.hash.unwrap(),
latest_block_number: block_number,
chain_id,
client_version: CLIENT_VERSION,
instance_id: api.instance_id(),
forked_network: Some(ForkedNetwork {
chain_id,
fork_block_number: block_number,
fork_block_hash: block.hash.unwrap(),
}),
};

assert_eq!(metadata, expected_metadata);
}

#[tokio::test(flavor = "multi_thread")]
async fn metadata_changes_on_reset() {
let (api, _) =
spawn(NodeConfig::test().with_eth_rpc_url(Some("https://bsc-dataseed.binance.org/"))).await;

let metadata = api.anvil_metadata().await.unwrap();
let instance_id = metadata.instance_id;

api.anvil_reset(Some(Forking { json_rpc_url: None, block_number: None })).await.unwrap();

let new_metadata = api.anvil_metadata().await.unwrap();
let new_instance_id = new_metadata.instance_id;

assert_ne!(instance_id, new_instance_id);
}

#[tokio::test(flavor = "multi_thread")]
async fn test_get_transaction_receipt() {
let (api, handle) = spawn(NodeConfig::test()).await;
Expand Down