cast/cmd/
storage.rs

1use crate::{Cast, opts::parse_slot};
2use alloy_ens::NameOrAddress;
3use alloy_network::AnyNetwork;
4use alloy_primitives::{Address, B256, U256};
5use alloy_provider::Provider;
6use alloy_rpc_types::BlockId;
7use clap::Parser;
8use comfy_table::{Cell, Table, modifiers::UTF8_ROUND_CORNERS, presets::ASCII_MARKDOWN};
9use eyre::Result;
10use foundry_block_explorers::Client;
11use foundry_cli::{
12    opts::{BuildOpts, EtherscanOpts, RpcOpts},
13    utils,
14    utils::LoadConfig,
15};
16use foundry_common::{
17    abi::find_source,
18    compile::{ProjectCompiler, etherscan_project},
19    shell,
20};
21use foundry_compilers::{
22    Artifact, Project,
23    artifacts::{ConfigurableContractArtifact, Contract, StorageLayout},
24    compilers::{
25        Compiler,
26        solc::{Solc, SolcCompiler},
27    },
28};
29use foundry_config::{
30    Config,
31    figment::{self, Metadata, Profile, value::Dict},
32    impl_figment_convert_cast,
33};
34use semver::Version;
35use serde::{Deserialize, Serialize};
36use std::str::FromStr;
37
38/// The minimum Solc version for outputting storage layouts.
39///
40/// <https://github.com/ethereum/solidity/blob/develop/Changelog.md#065-2020-04-06>
41const MIN_SOLC: Version = Version::new(0, 6, 5);
42
43/// CLI arguments for `cast storage`.
44#[derive(Clone, Debug, Parser)]
45pub struct StorageArgs {
46    /// The contract address.
47    #[arg(value_parser = NameOrAddress::from_str)]
48    address: NameOrAddress,
49
50    /// The storage slot number. If not provided, it gets the full storage layout.
51    #[arg(value_parser = parse_slot)]
52    base_slot: Option<B256>,
53
54    /// The storage offset from the base slot. If not provided, it is assumed to be zero.
55    #[arg(value_parser = str::parse::<U256>, default_value_t = U256::ZERO)]
56    offset: U256,
57
58    /// The known proxy address. If provided, the storage layout is retrieved from this address.
59    #[arg(long,value_parser = NameOrAddress::from_str)]
60    proxy: Option<NameOrAddress>,
61
62    /// The block height to query at.
63    ///
64    /// Can also be the tags earliest, finalized, safe, latest, or pending.
65    #[arg(long, short)]
66    block: Option<BlockId>,
67
68    #[command(flatten)]
69    rpc: RpcOpts,
70
71    #[command(flatten)]
72    etherscan: EtherscanOpts,
73
74    #[command(flatten)]
75    build: BuildOpts,
76
77    /// Specify the solc version to compile with. Overrides detected version.
78    #[arg(long, value_parser = Version::parse)]
79    solc_version: Option<Version>,
80}
81
82impl_figment_convert_cast!(StorageArgs);
83
84impl figment::Provider for StorageArgs {
85    fn metadata(&self) -> Metadata {
86        Metadata::named("StorageArgs")
87    }
88
89    fn data(&self) -> Result<figment::value::Map<Profile, Dict>, figment::Error> {
90        let mut map = self.build.data()?;
91        let dict = map.get_mut(&Config::selected_profile()).unwrap();
92        dict.extend(self.rpc.dict());
93        dict.extend(self.etherscan.dict());
94        Ok(map)
95    }
96}
97
98impl StorageArgs {
99    pub async fn run(self) -> Result<()> {
100        let config = self.load_config()?;
101
102        let Self { address, base_slot, offset, block, build, .. } = self;
103        let provider = utils::get_provider(&config)?;
104        let address = address.resolve(&provider).await?;
105
106        // Slot was provided, perform a simple RPC call
107        if let Some(slot) = base_slot {
108            let cast = Cast::new(provider);
109            sh_println!(
110                "{}",
111                cast.storage(
112                    address,
113                    (Into::<U256>::into(slot).saturating_add(offset)).into(),
114                    block
115                )
116                .await?
117            )?;
118            return Ok(());
119        }
120
121        // No slot was provided
122        // Get deployed bytecode at given address
123        let address_code =
124            provider.get_code_at(address).block_id(block.unwrap_or_default()).await?;
125        if address_code.is_empty() {
126            eyre::bail!("Provided address has no deployed code and thus no storage");
127        }
128
129        // Check if we're in a forge project and if we can find the address' code
130        let mut project = build.project()?;
131        if project.paths.has_input_files() {
132            // Find in artifacts and pretty print
133            add_storage_layout_output(&mut project);
134            let out = ProjectCompiler::new().quiet(shell::is_json()).compile(&project)?;
135            let artifact = out.artifacts().find(|(_, artifact)| {
136                artifact.get_deployed_bytecode_bytes().is_some_and(|b| *b == address_code)
137            });
138            if let Some((_, artifact)) = artifact {
139                return fetch_and_print_storage(provider, address, block, artifact).await;
140            }
141        }
142
143        if !self.etherscan.has_key() {
144            eyre::bail!(
145                "You must provide an Etherscan API key if you're fetching a remote contract's storage."
146            );
147        }
148
149        let chain = utils::get_chain(config.chain, &provider).await?;
150        let api_key = config.get_etherscan_api_key(Some(chain)).unwrap_or_default();
151        let client = Client::new(chain, api_key)?;
152        let source = if let Some(proxy) = self.proxy {
153            find_source(client, proxy.resolve(&provider).await?).await?
154        } else {
155            find_source(client, address).await?
156        };
157        let metadata = source.items.first().unwrap();
158        if metadata.is_vyper() {
159            eyre::bail!("Contract at provided address is not a valid Solidity contract")
160        }
161
162        // Create a new temp project
163        // TODO: Cache instead of using a temp directory: metadata from Etherscan won't change
164        let root = tempfile::tempdir()?;
165        let root_path = root.path();
166        let mut project = etherscan_project(metadata, root_path)?;
167        add_storage_layout_output(&mut project);
168
169        // Decide on compiler to use (user override -> metadata -> autodetect)
170        let meta_version = metadata.compiler_version()?;
171        let mut auto_detect = false;
172        let desired = if let Some(user_version) = self.solc_version {
173            if user_version < MIN_SOLC {
174                sh_warn!(
175                    "The provided --solc-version is {user_version} while the minimum version for \
176                     storage layouts is {MIN_SOLC} and as a result the output may be empty."
177                )?;
178            }
179            SolcCompiler::Specific(Solc::find_or_install(&user_version)?)
180        } else if meta_version < MIN_SOLC {
181            auto_detect = true;
182            SolcCompiler::AutoDetect
183        } else {
184            SolcCompiler::Specific(Solc::find_or_install(&meta_version)?)
185        };
186        project.compiler.solc = Some(desired);
187
188        // Compile
189        let mut out = ProjectCompiler::new().quiet(true).compile(&project)?;
190        let artifact = {
191            let (_, mut artifact) = out
192                .artifacts()
193                .find(|(name, _)| name == &metadata.contract_name)
194                .ok_or_else(|| eyre::eyre!("Could not find artifact"))?;
195
196            if auto_detect && is_storage_layout_empty(&artifact.storage_layout) {
197                // try recompiling with the minimum version
198                sh_warn!(
199                    "The requested contract was compiled with {meta_version} while the minimum version \
200                     for storage layouts is {MIN_SOLC} and as a result the output may be empty.",
201                )?;
202                let solc = Solc::find_or_install(&MIN_SOLC)?;
203                project.compiler.solc = Some(SolcCompiler::Specific(solc));
204                if let Ok(output) = ProjectCompiler::new().quiet(true).compile(&project) {
205                    out = output;
206                    let (_, new_artifact) = out
207                        .artifacts()
208                        .find(|(name, _)| name == &metadata.contract_name)
209                        .ok_or_else(|| eyre::eyre!("Could not find artifact"))?;
210                    artifact = new_artifact;
211                }
212            }
213
214            artifact
215        };
216
217        // Clear temp directory
218        root.close()?;
219
220        fetch_and_print_storage(provider, address, block, artifact).await
221    }
222}
223
224/// Represents the value of a storage slot `eth_getStorageAt` call.
225#[derive(Clone, Debug, PartialEq, Eq)]
226struct StorageValue {
227    /// The slot number.
228    slot: B256,
229    /// The value as returned by `eth_getStorageAt`.
230    raw_slot_value: B256,
231}
232
233impl StorageValue {
234    /// Returns the value of the storage slot, applying the offset if necessary.
235    fn value(&self, offset: i64, number_of_bytes: Option<usize>) -> B256 {
236        let offset = offset as usize;
237        let mut end = 32;
238        if let Some(number_of_bytes) = number_of_bytes {
239            end = offset + number_of_bytes;
240            if end > 32 {
241                end = 32;
242            }
243        }
244
245        // reverse range, because the value is stored in big endian
246        let raw_sliced_value = &self.raw_slot_value.as_slice()[32 - end..32 - offset];
247
248        // copy the raw sliced value as tail
249        let mut value = [0u8; 32];
250        value[32 - raw_sliced_value.len()..32].copy_from_slice(raw_sliced_value);
251        B256::from(value)
252    }
253}
254
255/// Represents the storage layout of a contract and its values.
256#[derive(Clone, Debug, Serialize, Deserialize)]
257struct StorageReport {
258    #[serde(flatten)]
259    layout: StorageLayout,
260    values: Vec<B256>,
261}
262
263async fn fetch_and_print_storage<P: Provider<AnyNetwork>>(
264    provider: P,
265    address: Address,
266    block: Option<BlockId>,
267    artifact: &ConfigurableContractArtifact,
268) -> Result<()> {
269    if is_storage_layout_empty(&artifact.storage_layout) {
270        sh_warn!("Storage layout is empty.")?;
271        Ok(())
272    } else {
273        let layout = artifact.storage_layout.as_ref().unwrap().clone();
274        let values = fetch_storage_slots(provider, address, block, &layout).await?;
275        print_storage(layout, values)
276    }
277}
278
279async fn fetch_storage_slots<P: Provider<AnyNetwork>>(
280    provider: P,
281    address: Address,
282    block: Option<BlockId>,
283    layout: &StorageLayout,
284) -> Result<Vec<StorageValue>> {
285    let requests = layout.storage.iter().map(|storage_slot| async {
286        let slot = B256::from(U256::from_str(&storage_slot.slot)?);
287        let raw_slot_value = provider
288            .get_storage_at(address, slot.into())
289            .block_id(block.unwrap_or_default())
290            .await?;
291
292        let value = StorageValue { slot, raw_slot_value: raw_slot_value.into() };
293
294        Ok(value)
295    });
296
297    futures::future::try_join_all(requests).await
298}
299
300fn print_storage(layout: StorageLayout, values: Vec<StorageValue>) -> Result<()> {
301    if shell::is_json() {
302        let values: Vec<_> = layout
303            .storage
304            .iter()
305            .zip(&values)
306            .map(|(slot, storage_value)| {
307                let storage_type = layout.types.get(&slot.storage_type);
308                storage_value.value(
309                    slot.offset,
310                    storage_type.and_then(|t| t.number_of_bytes.parse::<usize>().ok()),
311                )
312            })
313            .collect();
314        sh_println!(
315            "{}",
316            serde_json::to_string_pretty(&serde_json::to_value(StorageReport { layout, values })?)?
317        )?;
318        return Ok(());
319    }
320
321    let mut table = Table::new();
322    if shell::is_markdown() {
323        table.load_preset(ASCII_MARKDOWN);
324    } else {
325        table.apply_modifier(UTF8_ROUND_CORNERS);
326    }
327
328    table.set_header(vec![
329        Cell::new("Name"),
330        Cell::new("Type"),
331        Cell::new("Slot"),
332        Cell::new("Offset"),
333        Cell::new("Bytes"),
334        Cell::new("Value"),
335        Cell::new("Hex Value"),
336        Cell::new("Contract"),
337    ]);
338
339    for (slot, storage_value) in layout.storage.into_iter().zip(values) {
340        let storage_type = layout.types.get(&slot.storage_type);
341        let value = storage_value
342            .value(slot.offset, storage_type.and_then(|t| t.number_of_bytes.parse::<usize>().ok()));
343        let converted_value = U256::from_be_bytes(value.0);
344
345        table.add_row([
346            slot.label.as_str(),
347            storage_type.map_or("?", |t| &t.label),
348            &slot.slot,
349            &slot.offset.to_string(),
350            storage_type.map_or("?", |t| &t.number_of_bytes),
351            &converted_value.to_string(),
352            &value.to_string(),
353            &slot.contract,
354        ]);
355    }
356
357    sh_println!("\n{table}\n")?;
358
359    Ok(())
360}
361
362fn add_storage_layout_output<C: Compiler<CompilerContract = Contract>>(project: &mut Project<C>) {
363    project.artifacts.additional_values.storage_layout = true;
364    project.update_output_selection(|selection| {
365        selection.0.values_mut().for_each(|contract_selection| {
366            contract_selection
367                .values_mut()
368                .for_each(|selection| selection.push("storageLayout".to_string()))
369        });
370    })
371}
372
373fn is_storage_layout_empty(storage_layout: &Option<StorageLayout>) -> bool {
374    if let Some(s) = storage_layout { s.storage.is_empty() } else { true }
375}
376
377#[cfg(test)]
378mod tests {
379    use super::*;
380
381    #[test]
382    fn parse_storage_etherscan_api_key() {
383        let args =
384            StorageArgs::parse_from(["foundry-cli", "addr.eth", "--etherscan-api-key", "dummykey"]);
385        assert_eq!(args.etherscan.key(), Some("dummykey".to_string()));
386
387        unsafe {
388            std::env::set_var("ETHERSCAN_API_KEY", "FXY");
389        }
390        let config = args.load_config().unwrap();
391        unsafe {
392            std::env::remove_var("ETHERSCAN_API_KEY");
393        }
394        assert_eq!(config.etherscan_api_key, Some("dummykey".to_string()));
395
396        let key = config.get_etherscan_api_key(None).unwrap();
397        assert_eq!(key, "dummykey".to_string());
398    }
399
400    #[test]
401    fn parse_solc_version_arg() {
402        let args = StorageArgs::parse_from(["foundry-cli", "addr.eth", "--solc-version", "0.8.10"]);
403        assert_eq!(args.solc_version, Some(Version::parse("0.8.10").unwrap()));
404    }
405}