|
| 1 | +use alloy::{ |
| 2 | + eips::BlockId, |
| 3 | + primitives::{StorageValue, U256}, |
| 4 | + providers::{ |
| 5 | + network::{primitives::HeaderResponse, BlockResponse}, |
| 6 | + Network, Provider, |
| 7 | + }, |
| 8 | + transports::TransportError, |
| 9 | +}; |
| 10 | +use core::error::Error; |
| 11 | +use revm::{ |
| 12 | + database_interface::{async_db::DatabaseAsyncRef, DBErrorMarker}, |
| 13 | + primitives::{Address, B256}, |
| 14 | + state::{AccountInfo, Bytecode}, |
| 15 | +}; |
| 16 | +use std::fmt::Display; |
| 17 | + |
| 18 | +/// A type alias for the storage key used in the database. |
| 19 | +/// We use this instead of alloy's [`alloy::primitives::StorageKey`] as Revm requires |
| 20 | +/// the actual type to be an [`U256`] instead of a [`B256`]. |
| 21 | +pub type StorageKey = U256; |
| 22 | + |
| 23 | +/// An error that can occur when using [`AlloyDb`]. |
| 24 | +#[derive(Debug)] |
| 25 | +pub struct DBTransportError(pub TransportError); |
| 26 | + |
| 27 | +impl DBErrorMarker for DBTransportError {} |
| 28 | + |
| 29 | +impl Display for DBTransportError { |
| 30 | + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { |
| 31 | + write!(f, "Transport error: {}", self.0) |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +impl Error for DBTransportError {} |
| 36 | + |
| 37 | +impl From<TransportError> for DBTransportError { |
| 38 | + fn from(e: TransportError) -> Self { |
| 39 | + Self(e) |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +/// An alloy-powered REVM [`Database`][revm::database_interface::Database]. |
| 44 | +/// |
| 45 | +/// When accessing the database, it'll use the given provider to fetch the corresponding account's data. |
| 46 | +#[derive(Debug)] |
| 47 | +pub struct AlloyDb<N: Network, P: Provider<N>> { |
| 48 | + /// The provider to fetch the data from. |
| 49 | + provider: P, |
| 50 | + /// The block number on which the queries will be based on. |
| 51 | + block_number: BlockId, |
| 52 | + _marker: core::marker::PhantomData<fn() -> N>, |
| 53 | +} |
| 54 | + |
| 55 | +impl<N: Network, P: Provider<N>> AlloyDb<N, P> { |
| 56 | + /// Creates a new AlloyDB instance, with a [`Provider`] and a block. |
| 57 | + pub fn new(provider: P, block_number: BlockId) -> Self { |
| 58 | + Self { provider, block_number, _marker: core::marker::PhantomData } |
| 59 | + } |
| 60 | + |
| 61 | + /// Sets the block number on which the queries will be based on. |
| 62 | + pub const fn set_block_number(&mut self, block_number: BlockId) { |
| 63 | + self.block_number = block_number; |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +impl<N: Network, P: Provider<N>> DatabaseAsyncRef for AlloyDb<N, P> { |
| 68 | + type Error = DBTransportError; |
| 69 | + |
| 70 | + async fn basic_async_ref(&self, address: Address) -> Result<Option<AccountInfo>, Self::Error> { |
| 71 | + let nonce = self.provider.get_transaction_count(address).block_id(self.block_number); |
| 72 | + let balance = self.provider.get_balance(address).block_id(self.block_number); |
| 73 | + let code = self.provider.get_code_at(address).block_id(self.block_number); |
| 74 | + |
| 75 | + let (nonce, balance, code) = tokio::join!(nonce, balance, code,); |
| 76 | + |
| 77 | + let balance = balance?; |
| 78 | + let code = Bytecode::new_raw(code?.0.into()); |
| 79 | + let code_hash = code.hash_slow(); |
| 80 | + let nonce = nonce?; |
| 81 | + |
| 82 | + Ok(Some(AccountInfo::new(balance, nonce, code_hash, code))) |
| 83 | + } |
| 84 | + |
| 85 | + async fn block_hash_async_ref(&self, number: u64) -> Result<B256, Self::Error> { |
| 86 | + let block = self |
| 87 | + .provider |
| 88 | + // We know number <= u64::MAX, so we can safely convert it to u64 |
| 89 | + .get_block_by_number(number.into()) |
| 90 | + .await?; |
| 91 | + // If the number is given, the block is supposed to be finalized, so unwrapping is safe. |
| 92 | + Ok(B256::new(*block.unwrap().header().hash())) |
| 93 | + } |
| 94 | + |
| 95 | + async fn code_by_hash_async_ref(&self, _code_hash: B256) -> Result<Bytecode, Self::Error> { |
| 96 | + panic!("This should not be called, as the code is already loaded"); |
| 97 | + // This is not needed, as the code is already loaded with basic_ref |
| 98 | + } |
| 99 | + |
| 100 | + async fn storage_async_ref( |
| 101 | + &self, |
| 102 | + address: Address, |
| 103 | + index: StorageKey, |
| 104 | + ) -> Result<StorageValue, Self::Error> { |
| 105 | + Ok(self.provider.get_storage_at(address, index).block_id(self.block_number).await?) |
| 106 | + } |
| 107 | +} |
| 108 | + |
| 109 | +#[cfg(test)] |
| 110 | +mod tests { |
| 111 | + use super::*; |
| 112 | + use alloy::providers::ProviderBuilder; |
| 113 | + use revm::database_interface::{DatabaseRef, WrapDatabaseAsync}; |
| 114 | + |
| 115 | + #[test] |
| 116 | + #[ignore = "flaky RPC"] |
| 117 | + fn can_get_basic() { |
| 118 | + let client = ProviderBuilder::new().connect_http( |
| 119 | + "https://mainnet.infura.io/v3/c60b0bb42f8a4c6481ecd229eddaca27".parse().unwrap(), |
| 120 | + ); |
| 121 | + let alloydb = AlloyDb::new(client, BlockId::from(16148323)); |
| 122 | + let wrapped_alloydb = WrapDatabaseAsync::new(alloydb).unwrap(); |
| 123 | + |
| 124 | + // ETH/USDT pair on Uniswap V2 |
| 125 | + let address: Address = "0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852".parse().unwrap(); |
| 126 | + |
| 127 | + let acc_info = wrapped_alloydb.basic_ref(address).unwrap().unwrap(); |
| 128 | + assert!(acc_info.exists()); |
| 129 | + } |
| 130 | +} |
| 131 | + |
| 132 | +// This code has been reproduced from the original AlloyDB implementation |
| 133 | +// contained in revm. |
| 134 | +// <https://github.com/bluealloy/revm> |
| 135 | +// The original license is included below: |
| 136 | +// |
| 137 | +// MIT License |
| 138 | +// Copyright (c) 2021-2025 draganrakita |
| 139 | +// Permission is hereby granted, free of charge, to any person obtaining a copy |
| 140 | +// of this software and associated documentation files (the "Software"), to deal |
| 141 | +// in the Software without restriction, including without limitation the rights |
| 142 | +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 143 | +// copies of the Software, and to permit persons to whom the Software is |
| 144 | +// furnished to do so, subject to the following conditions: |
| 145 | +// The above copyright notice and this permission notice shall be included in all |
| 146 | +// copies or substantial portions of the Software. |
| 147 | +// |
| 148 | +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 149 | +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 150 | +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 151 | +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 152 | +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 153 | +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 154 | +// SOFTWARE. |
0 commit comments