Skip to main content

foundry_common/
slot_identifier.rs

1//! Storage slot identification and decoding utilities for Solidity storage layouts.
2//!
3//! This module provides functionality to identify and decode storage slots based on
4//! Solidity storage layout information from the compiler.
5
6use crate::{
7    constants::{EIP1967_ADMIN_SLOT, EIP1967_BEACON_SLOT, EIP1967_IMPLEMENTATION_SLOT},
8    mapping_slots::MappingSlots,
9    namespaced_storage::unscoped_type_id,
10};
11use alloy_dyn_abi::{DynSolType, DynSolValue};
12use alloy_primitives::{B256, U256, hex, keccak256, map::B256Map};
13use foundry_common_fmt::format_token_raw;
14use foundry_compilers::artifacts::{Storage, StorageLayout, StorageType};
15use serde::{
16    Serialize,
17    ser::{SerializeMap, SerializeStruct},
18};
19use std::{collections::BTreeMap, fmt, str::FromStr, sync::Arc};
20use tracing::trace;
21
22/// "inplace" encoding type for variables that fit in one storage slot i.e 32 bytes
23pub const ENCODING_INPLACE: &str = "inplace";
24/// "mapping" encoding type for Solidity mappings, which use keccak256 hash-based storage
25pub const ENCODING_MAPPING: &str = "mapping";
26/// "bytes" encoding type for bytes and string types, which use either inplace or keccak256
27/// hash-based storage depending on length
28pub const ENCODING_BYTES: &str = "bytes";
29/// "dynamic_array" encoding type for dynamic arrays, which uses keccak256 hash-based storage
30pub const ENCODING_DYN_ARRAY: &str = "dynamic_array";
31
32/// Information about a storage slot including its label, type, and decoded values.
33#[derive(Clone, Serialize, Debug)]
34pub struct SlotInfo {
35    /// The variable name from the storage layout.
36    ///
37    /// For top-level variables: just the variable name (e.g., "myVariable")
38    /// For struct members: dotted path (e.g., "myStruct.memberName")
39    /// For array elements: name with indices (e.g., "myArray\[0\]", "matrix\[1\]\[2\]")
40    /// For nested structures: full path (e.g., "outer.inner.field")
41    /// For mappings: base name with keys (e.g., "balances\[0x1234...\]")/ex
42    pub label: String,
43    /// The Solidity type information
44    #[serde(rename = "type", serialize_with = "serialize_slot_type")]
45    pub slot_type: StorageTypeInfo,
46    /// Offset within the storage slot (for packed storage)
47    pub offset: i64,
48    /// The storage slot number as a string
49    pub slot: String,
50    /// For struct members, contains nested SlotInfo for each member
51    ///
52    /// This is populated when a struct's members / fields are packed in a single slot.
53    #[serde(skip_serializing_if = "Option::is_none")]
54    pub members: Option<Vec<Self>>,
55    /// Decoded values (if available) - used for struct members
56    #[serde(skip_serializing_if = "Option::is_none")]
57    pub decoded: Option<DecodedSlotValues>,
58    /// Decoded mapping keys (serialized as "key" for single, "keys" for multiple)
59    #[serde(
60        skip_serializing_if = "Option::is_none",
61        flatten,
62        serialize_with = "serialize_mapping_keys"
63    )]
64    pub keys: Option<Vec<String>>,
65}
66
67/// Wrapper type that holds both the original type label and the parsed DynSolType.
68///
69/// We need both because:
70/// - `label`: Used for serialization to ensure output matches user expectations
71/// - `dyn_sol_type`: The parsed type used for actual value decoding
72#[derive(Clone, Debug)]
73pub struct StorageTypeInfo {
74    /// The original type label from storage layout (e.g., "uint256", "address", "mapping(address
75    /// => uint256)")
76    pub label: String,
77    /// The parsed dynamic Solidity type used for decoding
78    pub dyn_sol_type: DynSolType,
79}
80
81/// Shows the parsed type, except for a dynamic array whose elements have no ABI type, such as
82/// structs: it is parsed as `bytes32[]` only to decode its length, so it shows its declared type
83/// from the layout, without the `struct` keyword.
84impl fmt::Display for StorageTypeInfo {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        // A mapping entry is labeled with the mapping's type; its value type is what it holds.
87        let mut value = self.label.as_str();
88        while let Some(inner) = value.strip_prefix("mapping(")
89            && let Some((_, value_type)) = inner.split_once(" => ")
90        {
91            value = value_type.strip_suffix(')').unwrap_or(value_type);
92        }
93        if matches!(self.dyn_sol_type, DynSolType::Array(_)) && parse_sol_type(value).is_none() {
94            return f.write_str(value.strip_prefix("struct ").unwrap_or(value));
95        }
96        self.dyn_sol_type.fmt(f)
97    }
98}
99
100impl SlotInfo {
101    /// Decodes a single storage value based on the slot's type information.
102    ///
103    /// Note: For decoding [`DynSolType::Bytes`] or [`DynSolType::String`] that span multiple slots,
104    /// use [`SlotInfo::decode_bytes_or_string`].
105    pub fn decode(&self, value: B256) -> Option<DynSolValue> {
106        // Array elements packed into the slot decode as one array of them.
107        if let Some((element, len, size)) = packed_array(&self.slot_type.dyn_sol_type) {
108            return (0..len)
109                .map(|i| decode_packed(element, i * size, value))
110                .collect::<Option<Vec<_>>>()
111                .map(DynSolValue::FixedArray);
112        }
113
114        // Storage values are always 32 bytes, stored as a single word
115        let mut actual_type = &self.slot_type.dyn_sol_type;
116        // Unwrap nested arrays to get to the base element type.
117        while let DynSolType::FixedArray(elem_type, _) = actual_type {
118            actual_type = elem_type.as_ref();
119        }
120
121        // Special handling for bytes and string types
122        match actual_type {
123            DynSolType::Bytes | DynSolType::String => {
124                // Decode bytes/string from storage
125                // The last byte contains the length * 2 for short strings/bytes
126                // or length * 2 + 1 for long strings/bytes
127                let length_byte = value.0[31];
128
129                if length_byte & 1 == 0 {
130                    // Short string/bytes (less than 32 bytes)
131                    let length = ((length_byte >> 1) as usize).min(31);
132                    // Extract data
133                    let data = if length == 0 { Vec::new() } else { value.0[0..length].to_vec() };
134
135                    // Create the appropriate value based on type
136                    if matches!(actual_type, DynSolType::String) {
137                        let str_val = if data.is_empty() {
138                            String::new()
139                        } else {
140                            String::from_utf8(data).unwrap_or_default()
141                        };
142                        Some(DynSolValue::String(str_val))
143                    } else {
144                        Some(DynSolValue::Bytes(data))
145                    }
146                } else {
147                    // Long string/bytes (32 bytes or more)
148                    // The actual data is stored at keccak256(slot)
149                    // Return None for long values - they need decode_bytes_or_string()
150                    None
151                }
152            }
153            // A dynamic array's own slot holds its length; the elements live at keccak256(slot).
154            DynSolType::Array(_) => DynSolType::Uint(256).abi_decode(&value.0).ok(),
155            _ => {
156                // Decode based on the actual type
157                actual_type.abi_decode(&value.0).ok()
158            }
159        }
160    }
161
162    /// Slot is of type [`DynSolType::Bytes`] or [`DynSolType::String`]
163    pub const fn is_bytes_or_string(&self) -> bool {
164        matches!(self.slot_type.dyn_sol_type, DynSolType::Bytes | DynSolType::String)
165    }
166
167    /// Decodes a [`DynSolType::Bytes`] or [`DynSolType::String`] value
168    /// that spans across multiple slots.
169    pub fn decode_bytes_or_string(
170        &mut self,
171        base_slot: &B256,
172        storage_values: &B256Map<B256>,
173    ) -> Option<DynSolValue> {
174        // Only process bytes/string types
175        if !self.is_bytes_or_string() {
176            return None;
177        }
178
179        // Try to handle as long bytes/string
180        self.aggregate_bytes_or_strings(base_slot, storage_values).map(|data| {
181            match self.slot_type.dyn_sol_type {
182                DynSolType::String => {
183                    DynSolValue::String(String::from_utf8(data).unwrap_or_default())
184                }
185                DynSolType::Bytes => DynSolValue::Bytes(data),
186                _ => unreachable!(),
187            }
188        })
189    }
190
191    /// Decodes both previous and new [`DynSolType::Bytes`] or [`DynSolType::String`] values
192    /// that span across multiple slots using state diff data.
193    ///
194    /// Accepts a mapping of storage_slot to (previous_value, new_value).
195    pub fn decode_bytes_or_string_values(
196        &mut self,
197        base_slot: &B256,
198        storage_accesses: &BTreeMap<B256, (B256, B256)>,
199    ) {
200        // Only process bytes/string types
201        if !self.is_bytes_or_string() {
202            return;
203        }
204
205        // Get both previous and new values from the storage accesses
206        if let Some((prev_base_value, new_base_value)) = storage_accesses.get(base_slot) {
207            // Reusable closure to decode bytes/string based on length encoding
208            let mut decode_value = |base_value: B256, is_new: bool| {
209                let length_byte = base_value.0[31];
210                if length_byte & 1 == 1 {
211                    // Long bytes/string - aggregate from multiple slots
212                    let value_map = storage_accesses
213                        .iter()
214                        .map(|(slot, (prev, new))| (*slot, if is_new { *new } else { *prev }))
215                        .collect::<B256Map<_>>();
216                    self.decode_bytes_or_string(base_slot, &value_map)
217                } else {
218                    // Short bytes/string - decode directly from base slot
219                    self.decode(base_value)
220                }
221            };
222
223            // Decode previous value
224            let prev_decoded = decode_value(*prev_base_value, false);
225
226            // Decode new value
227            let new_decoded = decode_value(*new_base_value, true);
228
229            // Set decoded values if both were successfully decoded
230            if let (Some(prev), Some(new)) = (prev_decoded, new_decoded) {
231                self.decoded = Some(DecodedSlotValues { previous_value: prev, new_value: new });
232            }
233        }
234    }
235
236    /// Aggregates a [`DynSolType::Bytes`] or [`DynSolType::String`] value that spans across
237    /// multiple slots by looking up the length in the base_slot.
238    ///
239    /// Returns the aggregated raw bytes.
240    fn aggregate_bytes_or_strings(
241        &mut self,
242        base_slot: &B256,
243        storage_values: &B256Map<B256>,
244    ) -> Option<Vec<u8>> {
245        if !self.is_bytes_or_string() {
246            return None;
247        }
248
249        // Check if it's a long bytes/string by looking at the base value
250        if let Some(base_value) = storage_values.get(base_slot) {
251            let length_byte = base_value.0[31];
252
253            // Check if value is long
254            if length_byte & 1 == 1 {
255                // Long bytes/string - populate members
256                let length: U256 = Into::<U256>::into(*base_value) >> 1;
257                let byte_len = length.saturating_to::<usize>();
258                let num_slots = byte_len.div_ceil(32).min(256);
259                let data_start = Into::<U256>::into(keccak256(base_slot.0));
260
261                let mut members = Vec::new();
262                let mut full_data = Vec::with_capacity(num_slots * 32);
263
264                for i in 0..num_slots {
265                    let data_slot = B256::from(data_start + U256::from(i));
266                    let data_slot_u256 = data_start + U256::from(i);
267
268                    // Create member info for this data slot with indexed label
269                    let member_info = Self {
270                        label: format!("{}[{}]", self.label, i),
271                        slot_type: StorageTypeInfo {
272                            label: self.slot_type.label.clone(),
273                            dyn_sol_type: DynSolType::FixedBytes(32),
274                        },
275                        offset: 0,
276                        slot: data_slot_u256.to_string(),
277                        members: None,
278                        decoded: None,
279                        keys: None,
280                    };
281
282                    if let Some(value) = storage_values.get(&data_slot) {
283                        // Collect data
284                        let bytes_to_take =
285                            std::cmp::min(32, byte_len.saturating_sub(full_data.len()));
286                        full_data.extend_from_slice(&value.0[..bytes_to_take]);
287                    }
288
289                    members.push(member_info);
290                }
291
292                // Set the members field
293                if !members.is_empty() {
294                    self.members = Some(members);
295                }
296
297                return Some(full_data);
298            }
299        }
300
301        None
302    }
303
304    /// Decodes storage values (previous and new) and populates the decoded field.
305    /// For structs with members, it decodes each member individually.
306    pub fn decode_values(&mut self, previous_value: B256, new_value: B256) {
307        // If this is a struct with members, decode each member individually
308        if let Some(members) = &mut self.members {
309            for member in members.iter_mut() {
310                let ty = &member.slot_type.dyn_sol_type;
311                let offset = member.offset as usize;
312                if let (Some(prev_val), Some(new_val)) = (
313                    decode_packed(ty, offset, previous_value),
314                    decode_packed(ty, offset, new_value),
315                ) {
316                    member.decoded =
317                        Some(DecodedSlotValues { previous_value: prev_val, new_value: new_val });
318                }
319            }
320            // For structs with members, we don't need a top-level decoded value
321        } else {
322            // For non-struct types, decode directly
323            // Note: decode() returns None for long bytes/strings, which will be handled by
324            // decode_bytes_or_string()
325            if let (Some(prev), Some(new)) = (self.decode(previous_value), self.decode(new_value)) {
326                self.decoded = Some(DecodedSlotValues { previous_value: prev, new_value: new });
327            }
328        }
329    }
330}
331
332/// Custom serializer for StorageTypeInfo that only outputs the label
333fn serialize_slot_type<S>(info: &StorageTypeInfo, serializer: S) -> Result<S::Ok, S::Error>
334where
335    S: serde::Serializer,
336{
337    serializer.serialize_str(&info.label)
338}
339
340/// Custom serializer for mapping keys
341fn serialize_mapping_keys<S>(keys: &Option<Vec<String>>, serializer: S) -> Result<S::Ok, S::Error>
342where
343    S: serde::Serializer,
344{
345    if let Some(keys) = keys {
346        let len = if keys.is_empty() { 0 } else { 1 };
347        let mut map = serializer.serialize_map(Some(len))?;
348        if keys.len() == 1 {
349            map.serialize_entry("key", &keys[0])?;
350        } else if keys.len() > 1 {
351            map.serialize_entry("keys", keys)?;
352        }
353        map.end()
354    } else {
355        serializer.serialize_none()
356    }
357}
358
359/// Decoded storage slot values
360#[derive(Clone, Debug)]
361pub struct DecodedSlotValues {
362    /// Initial decoded storage value
363    pub previous_value: DynSolValue,
364    /// Current decoded storage value
365    pub new_value: DynSolValue,
366}
367
368impl Serialize for DecodedSlotValues {
369    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
370    where
371        S: serde::Serializer,
372    {
373        let mut state = serializer.serialize_struct("DecodedSlotValues", 2)?;
374        state.serialize_field("previousValue", &format_token_raw(&self.previous_value))?;
375        state.serialize_field("newValue", &format_token_raw(&self.new_value))?;
376        state.end()
377    }
378}
379
380/// Identifies the standard [EIP-1967](https://eips.ethereum.org/EIPS/eip-1967) proxy slots, which
381/// proxies write from assembly constants that no storage layout covers.
382///
383/// Callers should prefer a layout's identification of the same slot.
384pub fn identify_eip1967_slot(slot: &B256) -> Option<SlotInfo> {
385    let label = match *slot {
386        EIP1967_IMPLEMENTATION_SLOT => "eip1967.proxy.implementation",
387        EIP1967_ADMIN_SLOT => "eip1967.proxy.admin",
388        EIP1967_BEACON_SLOT => "eip1967.proxy.beacon",
389        _ => return None,
390    };
391    Some(SlotInfo {
392        label: label.to_string(),
393        slot_type: StorageTypeInfo {
394            label: "address".to_string(),
395            dyn_sol_type: DynSolType::Address,
396        },
397        offset: 0,
398        slot: Into::<U256>::into(*slot).to_string(),
399        members: None,
400        decoded: None,
401        keys: None,
402    })
403}
404
405/// Storage slot identifier that uses Solidity [`StorageLayout`] to identify storage slots.
406#[derive(Clone)]
407pub struct SlotIdentifier {
408    storage_layout: Arc<StorageLayout>,
409    parsed_types: BTreeMap<String, Option<DynSolType>>,
410}
411
412impl SlotIdentifier {
413    /// Creates a new SlotIdentifier with the given storage layout.
414    pub fn new(storage_layout: Arc<StorageLayout>) -> Self {
415        let parsed_types = storage_layout
416            .types
417            .iter()
418            .map(|(id, storage_type)| (id.clone(), resolve_sol_type(id, storage_type)))
419            .collect();
420        Self { storage_layout, parsed_types }
421    }
422
423    fn parsed_type(&self, storage_type: &str) -> Option<&DynSolType> {
424        self.parsed_types.get(storage_type).and_then(Option::as_ref)
425    }
426
427    /// Identifies a storage slots type using the [`StorageLayout`].
428    ///
429    /// It can also identify whether a slot belongs to a mapping if provided with [`MappingSlots`].
430    pub fn identify(&self, slot: &B256, mapping_slots: Option<&MappingSlots>) -> Option<SlotInfo> {
431        self.identify_at_depth(slot, mapping_slots, 0)
432    }
433
434    /// [`Self::identify`], `depth` dynamic arrays below the slot it was first called for.
435    fn identify_at_depth(
436        &self,
437        slot: &B256,
438        mapping_slots: Option<&MappingSlots>,
439        depth: usize,
440    ) -> Option<SlotInfo> {
441        trace!(?slot, "identifying slot");
442        let slot_u256 = Into::<U256>::into(*slot);
443        let slot_str = slot_u256.to_string();
444
445        // Match on a base slot from the layout. This is always the case for primitive types, which
446        // may share the slot with other variables.
447        if let Some(slot_info) = self.slot_variables(
448            self.storage_layout
449                .storage
450                .iter()
451                .filter(|storage| storage.slot == slot_str)
452                .map(|storage| (storage.label.clone(), storage)),
453            &slot_str,
454        ) {
455            return Some(slot_info);
456        }
457
458        for storage in &self.storage_layout.storage {
459            let storage_type = self.storage_layout.types.get(&storage.storage_type)?;
460            let dyn_type = self.parsed_type(&storage.storage_type);
461
462            // Encoding types: <https://docs.soliditylang.org/en/latest/internals/layout_in_storage.html#json-output>
463            if storage_type.encoding == ENCODING_INPLACE {
464                // Can be of type FixedArrays or Structs
465                // Handles the case where the accessed `slot` is maybe different from the base slot.
466                let array_start_slot = U256::from_str(&storage.slot).ok()?;
467
468                if let Some(parsed_type) = dyn_type
469                    && let DynSolType::FixedArray(_, _) = parsed_type
470                    && let Some(slot_info) = self.handle_array_slot(
471                        &storage.label,
472                        storage_type,
473                        parsed_type,
474                        slot_u256,
475                        array_start_slot,
476                        &slot_str,
477                    )
478                {
479                    return Some(slot_info);
480                }
481
482                // If type parsing fails and the label is a struct
483                if is_struct(&storage_type.label) {
484                    let struct_start_slot = U256::from_str(&storage.slot).ok()?;
485                    if let Some(slot_info) = self.handle_struct(
486                        &storage.label,
487                        storage_type,
488                        slot_u256,
489                        struct_start_slot,
490                        storage.offset,
491                        &slot_str,
492                        0,
493                    ) {
494                        return Some(slot_info);
495                    }
496                    if let Some(mapping_slots) = mapping_slots
497                        && let Some(slot_info) = self.handle_struct_mapping(
498                            &storage.label,
499                            storage_type,
500                            struct_start_slot,
501                            slot,
502                            &slot_str,
503                            mapping_slots,
504                        )
505                    {
506                        return Some(slot_info);
507                    }
508                }
509            } else if storage_type.encoding == ENCODING_DYN_ARRAY
510                && let Ok(base_slot) = U256::from_str(&storage.slot)
511                && let Some(info) = self.handle_dynamic_array(
512                    &storage.label,
513                    storage_type,
514                    base_slot,
515                    slot_u256,
516                    &slot_str,
517                    0,
518                )
519            {
520                return Some(info);
521            } else if storage_type.encoding == ENCODING_MAPPING
522                && let Some(mapping_slots) = mapping_slots
523                && let Ok(base_slot) = U256::from_str(&storage.slot)
524                && let Some(info) = self.handle_mapping(
525                    &storage.label,
526                    storage_type,
527                    base_slot.into(),
528                    slot,
529                    &slot_str,
530                    mapping_slots,
531                )
532            {
533                return Some(info);
534            }
535        }
536
537        mapping_slots.and_then(|mapping_slots| {
538            self.handle_hashed_array(slot_u256, &slot_str, mapping_slots, depth)
539        })
540    }
541
542    /// Identifies an element of a dynamic array whose own slot is computed, e.g. a mapping value
543    /// or an element of another array, from the recorded hash of that slot.
544    ///
545    /// The slot is attributed to the nearest recorded hash below it whose input identifies as a
546    /// dynamic array, so a hash of anything else (a string's slot, an ERC-7201 namespace id) is
547    /// never taken for an array's data.
548    fn handle_hashed_array(
549        &self,
550        slot: U256,
551        slot_str: &str,
552        mapping_slots: &MappingSlots,
553        depth: usize,
554    ) -> Option<SlotInfo> {
555        if depth >= MAX_DEPTH {
556            return None;
557        }
558        let data_starts = slot.saturating_sub(MAX_ARRAY_SLOTS - U256::ONE)..=slot;
559        mapping_slots.seen_word_sha3.range(data_starts).rev().find_map(|(_, &array_slot)| {
560            let array = self.identify_at_depth(&array_slot, Some(mapping_slots), depth + 1)?;
561            let array_type = self.dynamic_array_type(&array.slot_type.label)?;
562            let mut info = self.handle_dynamic_array(
563                &array.label,
564                array_type,
565                array_slot.into(),
566                slot,
567                slot_str,
568                depth + 1,
569            )?;
570            info.keys = array.keys;
571            Some(info)
572        })
573    }
574
575    /// The dynamic array type labeled `label`, or held by the mapping labeled `label`: a value
576    /// reached through a mapping is labeled with the mapping's type.
577    fn dynamic_array_type(&self, label: &str) -> Option<&StorageType> {
578        self.storage_layout.types.values().filter(|t| t.label == label).find_map(|mut t| {
579            while t.encoding == ENCODING_MAPPING {
580                t = self.storage_layout.types.get(t.value.as_ref()?)?;
581            }
582            (t.encoding == ENCODING_DYN_ARRAY).then_some(t)
583        })
584    }
585
586    /// Handles identification of dynamic array elements.
587    ///
588    /// The elements of the array at `base_slot` start at `keccak256(base_slot)`, several to a slot
589    /// when they are value types that fit, otherwise each taking whole slots. The length is not
590    /// checked, so an element just cleared by `pop` is still identified.
591    ///
592    /// # Arguments
593    /// * `label` - The label of the array
594    /// * `array_type` - Type information for the array
595    /// * `base_slot` - The slot holding the array's length
596    /// * `slot` - The target slot being identified
597    /// * `slot_str` - String representation of the slot for output
598    /// * `depth` - Current recursion depth
599    fn handle_dynamic_array(
600        &self,
601        label: &str,
602        array_type: &StorageType,
603        base_slot: U256,
604        slot: U256,
605        slot_str: &str,
606        depth: usize,
607    ) -> Option<SlotInfo> {
608        if depth > MAX_DEPTH || array_type.encoding != ENCODING_DYN_ARRAY {
609            return None;
610        }
611        let data_start = Into::<U256>::into(keccak256(B256::from(base_slot)));
612        let index_slot = slot.checked_sub(data_start).filter(|i| *i < MAX_ARRAY_SLOTS)?;
613        let index_slot = index_slot.to::<u128>();
614
615        let element_id = array_type.other.get("base")?.as_str()?;
616        let element_type = self.storage_layout.types.get(element_id)?;
617        let element_bytes = element_type.number_of_bytes.parse::<u128>().ok()?;
618        let element = self.parsed_type(element_id);
619
620        // Value types up to 16 bytes share slots; structs and static arrays fill whole slots.
621        if element_bytes <= 16 {
622            // Without a type, the elements sharing the slot cannot be told apart.
623            let element = element?;
624            let per_slot = 32 / element_bytes;
625            let first = index_slot * per_slot;
626            // The array length is unknown here, so the slot is labeled with the whole range of
627            // elements it can hold, and decodes as an array of them, see `SlotInfo::decode`.
628            return Some(SlotInfo {
629                label: format!("{label}[{first}..{}]", first + per_slot - 1),
630                slot_type: StorageTypeInfo {
631                    label: format!("{}[{per_slot}]", element_type.label),
632                    dyn_sol_type: DynSolType::FixedArray(
633                        Box::new(element.clone()),
634                        per_slot as usize,
635                    ),
636                },
637                offset: 0,
638                slot: slot_str.to_string(),
639                members: None,
640                decoded: None,
641                keys: None,
642            });
643        }
644
645        let element_slots = element_bytes.div_ceil(32).max(1);
646        let index = index_slot / element_slots;
647        let element_start = data_start + U256::from(index * element_slots);
648        let element_label = format!("{label}[{index}]");
649
650        // An array of structs is labeled `struct S[]` too, but has no members.
651        if element_type.other.contains_key("members") {
652            return self.handle_struct(
653                &element_label,
654                element_type,
655                slot,
656                element_start,
657                0,
658                slot_str,
659                depth + 1,
660            );
661        }
662        if let Some(element @ DynSolType::FixedArray(..)) = element {
663            // `handle_array_slot` takes each slot for one element, so skip elements that share one.
664            let mut leaves = 1;
665            let mut leaf = element;
666            while let DynSolType::FixedArray(inner, len) = leaf {
667                leaves *= *len as u128;
668                leaf = inner;
669            }
670            if leaves != element_slots {
671                return None;
672            }
673            return self.handle_array_slot(
674                &element_label,
675                element_type,
676                element,
677                slot,
678                element_start,
679                slot_str,
680            );
681        }
682        // An element without an ABI equivalent is shown raw if it fills one slot; a slot of a
683        // larger one holds only a part of it.
684        let element = element
685            .cloned()
686            .or_else(|| (element_slots == 1).then_some(DynSolType::FixedBytes(32)))?;
687        (slot == element_start).then(|| SlotInfo {
688            label: element_label,
689            slot_type: StorageTypeInfo { label: element_type.label.clone(), dyn_sol_type: element },
690            offset: 0,
691            slot: slot_str.to_string(),
692            members: None,
693            decoded: None,
694            keys: None,
695        })
696    }
697
698    /// Identifies a bytes or string storage slot by checking all bytes/string variables
699    /// in the storage layout and using their base slot values from the provided storage changes.
700    ///
701    /// # Arguments
702    /// * `slot` - The slot being identified
703    /// * `storage_values` - Map of storage slots to their current values
704    pub fn identify_bytes_or_string(
705        &self,
706        slot: &B256,
707        storage_values: &B256Map<B256>,
708    ) -> Option<SlotInfo> {
709        let slot_u256 = Into::<U256>::into(*slot);
710        let slot_str = slot_u256.to_string();
711
712        // Search through all bytes/string variables in the storage layout
713        for storage in &self.storage_layout.storage {
714            if let Some(storage_type) = self.storage_layout.types.get(&storage.storage_type)
715                && storage_type.encoding == ENCODING_BYTES
716            {
717                let Some(base_slot) = U256::from_str(&storage.slot).map(B256::from).ok() else {
718                    continue;
719                };
720                // Get the base slot value from storage_values
721                if let Some(base_value) = storage_values.get(&base_slot)
722                    && let Some(info) = self.handle_bytes_string(
723                        storage,
724                        storage_type,
725                        slot_u256,
726                        &slot_str,
727                        base_value,
728                    )
729                {
730                    return Some(info);
731                }
732            }
733        }
734
735        None
736    }
737
738    /// Handles identification of array slots.
739    ///
740    /// # Arguments
741    /// * `label` - The label of the array
742    /// * `storage_type` - Type information for the storage slot
743    /// * `slot` - The target slot being identified
744    /// * `array_start_slot` - The starting slot of the array in storage i.e base_slot
745    /// * `slot_str` - String representation of the slot for output
746    fn handle_array_slot(
747        &self,
748        label: &str,
749        storage_type: &StorageType,
750        parsed_type: &DynSolType,
751        slot: U256,
752        array_start_slot: U256,
753        slot_str: &str,
754    ) -> Option<SlotInfo> {
755        // Check if slot is within array bounds
756        let total_bytes = storage_type.number_of_bytes.parse::<u64>().ok()?;
757        let total_slots = total_bytes.div_ceil(32);
758
759        if slot >= array_start_slot && slot < array_start_slot + U256::from(total_slots) {
760            let index = (slot - array_start_slot).to::<u64>();
761            // Format the array element label based on array dimensions
762            let label = match parsed_type {
763                DynSolType::FixedArray(inner, _) => {
764                    if let DynSolType::FixedArray(_, inner_size) = inner.as_ref() {
765                        // 2D array: calculate row and column
766                        let row = index / (*inner_size as u64);
767                        let col = index % (*inner_size as u64);
768                        format!("{label}[{row}][{col}]")
769                    } else {
770                        // 1D array
771                        format!("{label}[{index}]")
772                    }
773                }
774                _ => label.to_string(),
775            };
776
777            return Some(SlotInfo {
778                label,
779                slot_type: StorageTypeInfo {
780                    label: storage_type.label.clone(),
781                    dyn_sol_type: parsed_type.clone(),
782                },
783                offset: 0,
784                slot: slot_str.to_string(),
785                members: None,
786                decoded: None,
787                keys: None,
788            });
789        }
790
791        None
792    }
793
794    /// Handles identification of struct slots.
795    ///
796    /// Recursively resolves struct members to find the exact member corresponding
797    /// to the target slot. Handles both single-slot (packed) and multi-slot structs.
798    ///
799    /// # Arguments
800    /// * `base_label` - The label/name for this struct or member
801    /// * `storage_type` - Type information for the storage
802    /// * `target_slot` - The target slot being identified
803    /// * `struct_start_slot` - The starting slot of this struct
804    /// * `offset` - Offset within the slot (for packed storage)
805    /// * `slot_str` - String representation of the slot for output
806    /// * `depth` - Current recursion depth
807    #[allow(clippy::too_many_arguments)]
808    fn handle_struct(
809        &self,
810        base_label: &str,
811        storage_type: &StorageType,
812        target_slot: U256,
813        struct_start_slot: U256,
814        offset: i64,
815        slot_str: &str,
816        depth: usize,
817    ) -> Option<SlotInfo> {
818        // Limit recursion depth to prevent stack overflow
819        if depth > MAX_DEPTH {
820            return None;
821        }
822
823        let members = storage_type
824            .other
825            .get("members")
826            .and_then(|v| serde_json::from_value::<Vec<Storage>>(v.clone()).ok())?;
827
828        // If this is the exact slot we're looking for (struct's base slot)
829        if struct_start_slot == target_slot
830        // Find the member at slot offset 0 (the member that starts at this slot)
831            && let Some(first_member) = members.iter().find(|m| m.slot == "0")
832        {
833            let member_type_info = self.storage_layout.types.get(&first_member.storage_type)?;
834            let member_label = format!("{}.{}", base_label, first_member.label);
835
836            // A nested struct starts its own slot, so it is the only member at slot "0".
837            if is_struct(&member_type_info.label) {
838                return self.handle_struct(
839                    &member_label,
840                    member_type_info,
841                    target_slot,
842                    struct_start_slot,
843                    first_member.offset,
844                    slot_str,
845                    depth + 1,
846                );
847            }
848
849            // Structs fill whole slots; a sole member at slot "0" can still span several.
850            if storage_type.number_of_bytes == "32" {
851                // Build member info for single-slot struct
852                let mut member_infos = Vec::new();
853                for member in &members {
854                    if let Some(member_type_info) =
855                        self.storage_layout.types.get(&member.storage_type)
856                        && let Some(member_type) = self.parsed_type(&member.storage_type).cloned()
857                    {
858                        member_infos.push(SlotInfo {
859                            label: member.label.clone(),
860                            slot_type: StorageTypeInfo {
861                                label: member_type_info.label.clone(),
862                                dyn_sol_type: member_type,
863                            },
864                            offset: member.offset,
865                            slot: slot_str.to_string(),
866                            members: None,
867                            decoded: None,
868                            keys: None,
869                        });
870                    }
871                }
872
873                // Build the CustomStruct type
874                let struct_name =
875                    storage_type.label.strip_prefix("struct ").unwrap_or(&storage_type.label);
876                let prop_names: Vec<String> = members.iter().map(|m| m.label.clone()).collect();
877                let member_types: Vec<DynSolType> =
878                    member_infos.iter().map(|info| info.slot_type.dyn_sol_type.clone()).collect();
879
880                let parsed_type = DynSolType::CustomStruct {
881                    name: struct_name.to_string(),
882                    prop_names,
883                    tuple: member_types,
884                };
885
886                return Some(SlotInfo {
887                    label: base_label.to_string(),
888                    slot_type: StorageTypeInfo {
889                        label: storage_type.label.clone(),
890                        dyn_sol_type: parsed_type,
891                    },
892                    offset,
893                    slot: slot_str.to_string(),
894                    decoded: None,
895                    members: if member_infos.is_empty() { None } else { Some(member_infos) },
896                    keys: None,
897                });
898            }
899
900            // Multi-slot struct - return the primitive members packed into the first slot.
901            return self.slot_variables(
902                members
903                    .iter()
904                    .filter(|m| m.slot == "0")
905                    .map(|m| (format!("{base_label}.{}", m.label), m)),
906                slot_str,
907            );
908        }
909
910        // Not the base slot - search through members
911        for member in &members {
912            let member_slot_offset = U256::from_str(&member.slot).ok()?;
913            let member_slot = struct_start_slot + member_slot_offset;
914            let member_type_info = self.storage_layout.types.get(&member.storage_type)?;
915            let member_label = format!("{}.{}", base_label, member.label);
916
917            // If this member is a struct, recurse into it
918            if is_struct(&member_type_info.label) {
919                let slot_info = self.handle_struct(
920                    &member_label,
921                    member_type_info,
922                    target_slot,
923                    member_slot,
924                    member.offset,
925                    slot_str,
926                    depth + 1,
927                );
928
929                if member_slot == target_slot || slot_info.is_some() {
930                    return slot_info;
931                }
932            }
933
934            if member_type_info.encoding == ENCODING_DYN_ARRAY
935                && let Some(slot_info) = self.handle_dynamic_array(
936                    &member_label,
937                    member_type_info,
938                    member_slot,
939                    target_slot,
940                    slot_str,
941                    depth + 1,
942                )
943            {
944                return Some(slot_info);
945            }
946
947            if member_slot == target_slot {
948                // Found the exact member slot, which may be shared by packed members.
949                return self.slot_variables(
950                    members
951                        .iter()
952                        .filter(|m| m.slot == member.slot)
953                        .map(|m| (format!("{base_label}.{}", m.label), m)),
954                    slot_str,
955                );
956            }
957        }
958
959        None
960    }
961
962    /// Handles identification of mapping slots.
963    ///
964    /// A mapping value lives at `keccak256(key . parent)`. When the value is a struct, its fields
965    /// sit at slot offsets from that entry, and a mapping among them is the parent of the next
966    /// level. So the accessed slot is walked up to the variable's base slot one recorded entry
967    /// at a time, each possibly displaced by a field's offset, and then resolved down through the
968    /// types: every key is decoded with its mapping's key type, a struct member holding the next
969    /// mapping is added to the label, and the final value is identified within the entry, by
970    /// [`Self::handle_struct`] when it is a struct, or as a whole when its fields can't be.
971    ///
972    /// # Arguments
973    /// * `base_label` - The label of the mapping variable or struct member
974    /// * `storage_type` - Type information for the mapping
975    /// * `base_slot` - The slot of the mapping
976    /// * `slot` - The accessed slot being identified
977    /// * `slot_str` - String representation of the slot for output
978    /// * `mapping_slots` - Tracked mapping slot accesses for key resolution
979    fn handle_mapping(
980        &self,
981        base_label: &str,
982        storage_type: &StorageType,
983        base_slot: B256,
984        slot: &B256,
985        slot_str: &str,
986        mapping_slots: &MappingSlots,
987    ) -> Option<SlotInfo> {
988        trace!(
989            "handle_mapping: base_slot={}, slot={:?}, has_keys={}, has_parents={}",
990            base_slot,
991            slot,
992            mapping_slots.keys.contains_key(slot),
993            mapping_slots.parent_slots.contains_key(slot)
994        );
995
996        if storage_type.encoding != ENCODING_MAPPING {
997            return None;
998        }
999
1000        // Walk up to the base slot, collecting each level's entry, key and the offset of the
1001        // child (the next level's mapping, or the accessed slot) within that entry's value.
1002        let mut levels = Vec::new();
1003        let mut current = *slot;
1004        loop {
1005            let (entry, offset) = mapping_entry(&current, mapping_slots)?;
1006            let &(key, parent) = mapping_slots.seen_sha3.get(&entry)?;
1007            levels.push((entry, key, offset));
1008            if parent == base_slot {
1009                break;
1010            }
1011            if levels.len() > mapping_slots.seen_sha3.len() {
1012                trace!("Mapping slot {base_slot} does not match any parent in chain");
1013                return None;
1014            }
1015            current = parent;
1016        }
1017        levels.reverse();
1018
1019        // Resolve down from the variable's mapping type.
1020        let mut mapping_type = storage_type;
1021        // The type reported for a plain value: the mapping it was reached through, outermost of
1022        // its directly nested levels, as it is declared.
1023        let mut type_label = storage_type.label.clone();
1024        let mut label = base_label.to_string();
1025        let mut decoded_keys = Vec::new();
1026
1027        for (i, (entry, key, offset)) in levels.iter().enumerate() {
1028            if mapping_type.encoding != ENCODING_MAPPING {
1029                return None;
1030            }
1031            let decoded_key = self
1032                .parsed_type(mapping_type.key.as_ref()?)
1033                .and_then(|sol_type| sol_type.abi_decode(&key.0).ok())
1034                .map(|decoded| format_token_raw(&decoded))
1035                .unwrap_or_else(|| hex::encode_prefixed(key.0));
1036            label = format!("{label}[{decoded_key}]");
1037            decoded_keys.push(decoded_key);
1038
1039            let value_type = self.storage_layout.types.get(mapping_type.value.as_ref()?)?;
1040
1041            if i + 1 < levels.len() {
1042                // The next level is a mapping `offset` slots into this value: the value itself, or
1043                // a member of a struct value.
1044                if value_type.encoding == ENCODING_MAPPING && *offset == U256::ZERO {
1045                    mapping_type = value_type;
1046                } else {
1047                    let (member_label, member_type) =
1048                        self.mapping_member(value_type, *offset, 0)?;
1049                    label = format!("{label}.{member_label}");
1050                    type_label = member_type.label.clone();
1051                    mapping_type = member_type;
1052                }
1053                continue;
1054            }
1055
1056            // The last level: the accessed slot is `offset` slots into this entry's value. A struct
1057            // is identified by its fields; if they can't be (e.g. a user-defined value type or an
1058            // array of structs), the entry slot is still identified as the whole value.
1059            let entry_slot = U256::from_be_bytes(entry.0);
1060            let mut info = if is_struct(&value_type.label)
1061                && let Some(info) = self.handle_struct(
1062                    &label,
1063                    value_type,
1064                    entry_slot + *offset,
1065                    entry_slot,
1066                    0,
1067                    slot_str,
1068                    0,
1069                ) {
1070                info
1071            } else if *offset == U256::ZERO {
1072                // Contract types (e.g., "contract IPool") are addresses under the hood.
1073                SlotInfo {
1074                    label,
1075                    slot_type: StorageTypeInfo {
1076                        label: type_label,
1077                        dyn_sol_type: self
1078                            .parsed_type(mapping_type.value.as_ref()?)
1079                            .cloned()
1080                            .unwrap_or(DynSolType::Bytes),
1081                    },
1082                    offset: 0,
1083                    slot: slot_str.to_string(),
1084                    members: None,
1085                    decoded: None,
1086                    keys: None,
1087                }
1088            } else {
1089                return None;
1090            };
1091            info.keys = Some(decoded_keys);
1092            return Some(info);
1093        }
1094
1095        None
1096    }
1097
1098    /// Handles identification of slots of mappings held by a struct variable, directly or in a
1099    /// nested struct.
1100    ///
1101    /// The accessed slot is walked up the recorded entries until one's parent falls within the
1102    /// struct; the mapping member at that parent's offset is then resolved by
1103    /// [`Self::handle_mapping`].
1104    fn handle_struct_mapping(
1105        &self,
1106        base_label: &str,
1107        struct_type: &StorageType,
1108        struct_start_slot: U256,
1109        slot: &B256,
1110        slot_str: &str,
1111        mapping_slots: &MappingSlots,
1112    ) -> Option<SlotInfo> {
1113        let struct_slots =
1114            U256::from(struct_type.number_of_bytes.parse::<u64>().ok()?.div_ceil(32));
1115        let mut current = *slot;
1116        for _ in 0..=mapping_slots.seen_sha3.len() {
1117            let (entry, _) = mapping_entry(&current, mapping_slots)?;
1118            let &(_, parent) = mapping_slots.seen_sha3.get(&entry)?;
1119            let parent_slot = U256::from_be_bytes(parent.0);
1120            if let Some(offset) = parent_slot.checked_sub(struct_start_slot)
1121                && offset < struct_slots
1122            {
1123                let (member_label, member_type) = self.mapping_member(struct_type, offset, 0)?;
1124                return self.handle_mapping(
1125                    &format!("{base_label}.{member_label}"),
1126                    member_type,
1127                    parent,
1128                    slot,
1129                    slot_str,
1130                    mapping_slots,
1131                );
1132            }
1133            current = parent;
1134        }
1135        None
1136    }
1137
1138    /// Finds the mapping-typed member `offset` slots into a struct, descending into nested
1139    /// structs, and returns its dotted label and type.
1140    fn mapping_member(
1141        &self,
1142        struct_type: &StorageType,
1143        offset: U256,
1144        depth: usize,
1145    ) -> Option<(String, &StorageType)> {
1146        if depth > MAX_DEPTH || !is_struct(&struct_type.label) {
1147            return None;
1148        }
1149        let members = struct_type
1150            .other
1151            .get("members")
1152            .and_then(|v| serde_json::from_value::<Vec<Storage>>(v.clone()).ok())?;
1153        for member in &members {
1154            let member_slot = U256::from_str(&member.slot).ok()?;
1155            let member_type = self.storage_layout.types.get(&member.storage_type)?;
1156            let member_slots =
1157                U256::from(member_type.number_of_bytes.parse::<u64>().ok()?.div_ceil(32));
1158            if offset < member_slot || offset >= member_slot + member_slots {
1159                continue;
1160            }
1161            if member_type.encoding == ENCODING_MAPPING && offset == member_slot {
1162                return Some((member.label.clone(), member_type));
1163            }
1164            let (nested_label, nested_type) =
1165                self.mapping_member(member_type, offset - member_slot, depth + 1)?;
1166            return Some((format!("{}.{nested_label}", member.label), nested_type));
1167        }
1168        None
1169    }
1170
1171    /// Handles identification of bytes/string storage slots.
1172    ///
1173    /// Bytes and strings in Solidity use a special storage layout:
1174    /// - Short values (<32 bytes): stored in the same slot with length * 2
1175    /// - Long values (>=32 bytes): length * 2 + 1 in main slot, data at keccak256(slot)
1176    ///
1177    /// This function checks if the given slot is:
1178    /// 1. A main slot for a bytes/string variable
1179    /// 2. A data slot for any long bytes/string variable in the storage layout
1180    ///
1181    /// # Arguments
1182    /// * `slot` - The accessed slot being identified
1183    /// * `slot_str` - String representation of the slot for output
1184    /// * `base_slot_value` - The value at the base slot (used to determine length for long
1185    ///   bytes/strings)
1186    fn handle_bytes_string(
1187        &self,
1188        storage: &Storage,
1189        storage_type: &StorageType,
1190        slot: U256,
1191        slot_str: &str,
1192        base_slot_value: &B256,
1193    ) -> Option<SlotInfo> {
1194        // Only handle bytes/string encoded variables for this specific storage entry
1195        if storage_type.encoding != ENCODING_BYTES {
1196            return None;
1197        }
1198
1199        // Check if this is the main slot for this variable
1200        let base_slot = U256::from_str(&storage.slot).ok()?;
1201        if slot == base_slot {
1202            // Parse the type to get the correct DynSolType
1203            let dyn_type = if storage_type.label == "string" {
1204                DynSolType::String
1205            } else if storage_type.label == "bytes" {
1206                DynSolType::Bytes
1207            } else {
1208                return None;
1209            };
1210
1211            return Some(SlotInfo {
1212                label: storage.label.clone(),
1213                slot_type: StorageTypeInfo {
1214                    label: storage_type.label.clone(),
1215                    dyn_sol_type: dyn_type,
1216                },
1217                offset: storage.offset,
1218                slot: slot_str.to_string(),
1219                members: None,
1220                decoded: None,
1221                keys: None,
1222            });
1223        }
1224
1225        // Check if it could be a data slot for this long bytes/string
1226        // Calculate where data slots would start for this variable
1227        let data_start = Into::<U256>::into(keccak256(B256::from(base_slot)));
1228
1229        // Get the length from the base slot value to calculate exact number of slots
1230        // For long bytes/strings, the length is stored as (length * 2 + 1) in the base slot
1231        let length_byte = base_slot_value.0[31];
1232        if length_byte & 1 == 1 {
1233            // It's a long bytes/string
1234            let length = Into::<U256>::into(*base_slot_value) >> 1;
1235            // Calculate number of slots needed (round up)
1236            let num_slots = (length + U256::from(31)) / U256::from(32);
1237
1238            // Check if our slot is within the data region
1239            if slot >= data_start && slot < data_start + num_slots {
1240                let slot_index = (slot - data_start).saturating_to::<usize>();
1241
1242                return Some(SlotInfo {
1243                    label: format!("{}[{}]", storage.label, slot_index),
1244                    slot_type: StorageTypeInfo {
1245                        label: storage_type.label.clone(),
1246                        // Type is assigned as FixedBytes(32) for data slots
1247                        dyn_sol_type: DynSolType::FixedBytes(32),
1248                    },
1249                    offset: 0,
1250                    slot: slot_str.to_string(),
1251                    members: None,
1252                    decoded: None,
1253                    keys: None,
1254                });
1255            }
1256        }
1257
1258        None
1259    }
1260
1261    /// Identifies a slot holding the ABI-decodable variables in `entries`, all stored in it.
1262    ///
1263    /// A slot shared by several packed variables gets one member per variable, so each is decoded
1264    /// from its own bytes and labeled with its own name. Returns `None` if there are no such
1265    /// variables.
1266    fn slot_variables<'a>(
1267        &self,
1268        entries: impl IntoIterator<Item = (String, &'a Storage)>,
1269        slot_str: &str,
1270    ) -> Option<SlotInfo> {
1271        let entries = entries.into_iter().collect::<Vec<_>>();
1272        let entry_count = entries.len();
1273        let mut variables = entries
1274            .into_iter()
1275            .filter_map(|(label, storage)| {
1276                let storage_type = self.storage_layout.types.get(&storage.storage_type)?;
1277                let parsed_type = self.parsed_type(&storage.storage_type)?.clone();
1278                // An array packed into the slot is labeled with the range of its elements.
1279                let label = if let Some((_, len, _)) = packed_array(&parsed_type) {
1280                    format!("{label}[0..{}]", len - 1)
1281                } else if let DynSolType::FixedArray(_, _) = &parsed_type {
1282                    format!("{label}{}", get_array_base_indices(&parsed_type))
1283                } else {
1284                    label
1285                };
1286                Some(SlotInfo {
1287                    label,
1288                    slot_type: StorageTypeInfo {
1289                        label: storage_type.label.clone(),
1290                        dyn_sol_type: parsed_type,
1291                    },
1292                    offset: storage.offset,
1293                    slot: slot_str.to_string(),
1294                    members: None,
1295                    decoded: None,
1296                    keys: None,
1297                })
1298            })
1299            .collect::<Vec<_>>();
1300        // A lone variable is decoded from the whole word, so it stands alone only if it doesn't
1301        // share the slot with variables that can't be decoded.
1302        if variables.is_empty() || entry_count == 1 {
1303            return variables.pop();
1304        }
1305
1306        let label = variables.iter().map(|v| v.label.as_str()).collect::<Vec<_>>().join(", ");
1307        let types = variables.iter().map(|v| v.slot_type.dyn_sol_type.clone()).collect::<Vec<_>>();
1308        let tuple = DynSolType::Tuple(types);
1309        Some(SlotInfo {
1310            label,
1311            slot_type: StorageTypeInfo { label: tuple.to_string(), dyn_sol_type: tuple },
1312            offset: 0,
1313            slot: slot_str.to_string(),
1314            members: Some(variables),
1315            decoded: None,
1316            keys: None,
1317        })
1318    }
1319}
1320
1321/// How deep nested structs, mappings and dynamic arrays are followed when identifying a slot.
1322const MAX_DEPTH: usize = 10;
1323
1324/// How many slots past its data start an element of a dynamic array is searched for. Data starts
1325/// are hashes, so any other slot this close to one would be a hash collision.
1326const MAX_ARRAY_SLOTS: U256 = U256::from_limbs([0, 1, 0, 0]);
1327
1328/// How far into a mapping value a recorded entry is searched for: the slot offset of a struct
1329/// field from the entry holding the struct.
1330const MAX_VALUE_SLOTS: u64 = 256;
1331
1332/// The recorded mapping entry `slot` belongs to and its slot offset from it: the entry itself,
1333/// or a field of a struct stored there.
1334///
1335/// An offset-only store need not promote the entry into `keys`, so use all observed preimages.
1336fn mapping_entry(slot: &B256, mapping_slots: &MappingSlots) -> Option<(B256, U256)> {
1337    let slot = U256::from_be_bytes(slot.0);
1338    (0..MAX_VALUE_SLOTS).find_map(|offset| {
1339        let offset = U256::from(offset);
1340        let entry = B256::from(slot.checked_sub(offset)?);
1341        mapping_slots.seen_sha3.contains_key(&entry).then_some((entry, offset))
1342    })
1343}
1344
1345/// Returns the base indices for array types, e.g. "\[0\]\[0\]" for 2D arrays.
1346fn get_array_base_indices(dyn_type: &DynSolType) -> String {
1347    match dyn_type {
1348        DynSolType::FixedArray(inner, _) => {
1349            if let DynSolType::FixedArray(_, _) = inner.as_ref() {
1350                // Nested array (2D or higher)
1351                format!("[0]{}", get_array_base_indices(inner))
1352            } else {
1353                // Simple 1D array
1354                "[0]".to_string()
1355            }
1356        }
1357        _ => String::new(),
1358    }
1359}
1360
1361/// Prefix of the layout's type ids for user-defined value types, e.g.
1362/// `t_userDefinedValueType(Delay)1234`.
1363const UDVT_TYPE_PREFIX: &str = "t_userDefinedValueType(";
1364
1365/// Resolves the layout type `id` to a [`DynSolType`], returning `None` for types that have no
1366/// direct ABI equivalent (mappings, structs).
1367///
1368/// A user-defined value type's label is its name (`Delay`, or `Time.Delay` when declared in a
1369/// library), which says nothing of the underlying type, and the layout records only its size. It is
1370/// resolved to an unsigned integer of that size, which keeps packed neighbours apart and decodes
1371/// the common unsigned underlying types exactly. Other underlying types are displayed as raw
1372/// unsigned bits, not their original signed, address, bool or fixed-bytes values. Mapping keys
1373/// retain the full encoded key word, whose padding can differ from compact storage.
1374fn resolve_sol_type(id: &str, storage_type: &StorageType) -> Option<DynSolType> {
1375    // ERC-7201 namespaces scope their type IDs.
1376    if unscoped_type_id(id).starts_with(UDVT_TYPE_PREFIX) {
1377        let bytes = storage_type.number_of_bytes.parse::<usize>().ok()?;
1378        return (1..=32).contains(&bytes).then(|| DynSolType::Uint(bytes * 8));
1379    }
1380    parse_sol_type(&storage_type.label).or_else(|| {
1381        // An array of elements without an ABI type, such as structs, is still an array whose own
1382        // slot holds its length.
1383        (storage_type.encoding == ENCODING_DYN_ARRAY)
1384            .then(|| DynSolType::Array(Box::new(DynSolType::FixedBytes(32))))
1385    })
1386}
1387
1388/// Parses a storage type label into a [`DynSolType`], returning `None` for labels that have no
1389/// direct ABI equivalent (mappings, structs).
1390///
1391/// Handles `contract X` types (which are addresses under the hood) and `enum X` types
1392/// (which are uint8) that `DynSolType::parse` doesn't recognize.
1393fn parse_sol_type(label: &str) -> Option<DynSolType> {
1394    let scalar = if label.starts_with("contract ") {
1395        "address"
1396    } else if label.starts_with("enum ") {
1397        "uint8"
1398    } else {
1399        return DynSolType::parse(label).ok();
1400    };
1401    let suffix = label.find('[').map_or("", |index| &label[index..]);
1402    DynSolType::parse(&format!("{scalar}{suffix}")).ok()
1403}
1404
1405/// Checks if a given type label represents a struct type.
1406pub fn is_struct(s: &str) -> bool {
1407    s.starts_with("struct ")
1408}
1409
1410/// The size in bytes of a value type that can share a slot with others.
1411const fn packed_size(ty: &DynSolType) -> Option<usize> {
1412    match ty {
1413        DynSolType::Uint(bits) | DynSolType::Int(bits) => Some(*bits / 8),
1414        DynSolType::Address => Some(20),
1415        DynSolType::Bool => Some(1),
1416        DynSolType::FixedBytes(size) => Some(*size),
1417        _ => None,
1418    }
1419}
1420
1421/// The element type, length and element size of an array of several elements packed into one
1422/// slot.
1423fn packed_array(ty: &DynSolType) -> Option<(&DynSolType, usize, usize)> {
1424    let DynSolType::FixedArray(element, len) = ty else { return None };
1425    let size = packed_size(element)?;
1426    (*len > 1 && size * len <= 32).then_some((element.as_ref(), *len, size))
1427}
1428
1429/// Decodes the value of type `ty` packed into `word` at byte `offset`.
1430fn decode_packed(ty: &DynSolType, offset: usize, word: B256) -> Option<DynSolValue> {
1431    // Default to the full word.
1432    let size = packed_size(ty).unwrap_or(32);
1433
1434    let mut bytes = [0u8; 32];
1435    if offset + size <= 32 {
1436        // In Solidity storage, values are right-aligned
1437        // For offset 0, we want the rightmost bytes
1438        // For offset 16 (for a uint128), we want bytes 0-16
1439        // For packed storage: offset 0 is at the rightmost position
1440        // offset 0, size 16 -> read bytes 16-32 (rightmost)
1441        // offset 16, size 16 -> read bytes 0-16 (leftmost)
1442        let byte_start = 32 - offset - size;
1443        // ABI signed integers must be sign-extended to a full word.
1444        if matches!(ty, DynSolType::Int(_)) && word.0[byte_start] & 0x80 != 0 {
1445            bytes.fill(0xff);
1446        }
1447        // ABI fixed bytes are left-aligned, unlike integers and addresses.
1448        let abi_start = if matches!(ty, DynSolType::FixedBytes(_)) { 0 } else { 32 - size };
1449        bytes[abi_start..abi_start + size].copy_from_slice(&word.0[byte_start..byte_start + size]);
1450    }
1451
1452    ty.abi_decode(&bytes).ok()
1453}
1454
1455#[cfg(test)]
1456mod tests {
1457    use super::*;
1458    use alloy_primitives::Address;
1459
1460    #[test]
1461    fn preserves_contract_and_enum_array_dimensions() {
1462        for (label, expected) in [
1463            ("contract IERC20", "address"),
1464            ("contract IERC20[]", "address[]"),
1465            ("contract IERC20[4][]", "address[4][]"),
1466            ("enum Example.Status", "uint8"),
1467            ("enum Example.Status[4]", "uint8[4]"),
1468            ("enum Example.Status[][4]", "uint8[][4]"),
1469        ] {
1470            assert_eq!(parse_sol_type(label), DynSolType::parse(expected).ok(), "{label}");
1471        }
1472    }
1473
1474    fn decoded(info: &SlotInfo) -> Vec<(&str, String, String)> {
1475        info.members
1476            .iter()
1477            .flatten()
1478            .map(|member| {
1479                let decoded = member.decoded.as_ref().unwrap();
1480                (
1481                    member.label.as_str(),
1482                    format_token_raw(&decoded.previous_value),
1483                    format_token_raw(&decoded.new_value),
1484                )
1485            })
1486            .collect()
1487    }
1488
1489    #[test]
1490    fn decodes_each_packed_variable() {
1491        let layout = serde_json::from_value::<StorageLayout>(serde_json::json!({
1492            "storage": [
1493                { "astId": 1, "contract": "C", "label": "initialized", "offset": 0, "slot": "5", "type": "t_uint64" },
1494                { "astId": 2, "contract": "C", "label": "initializing", "offset": 8, "slot": "5", "type": "t_bool" },
1495                { "astId": 3, "contract": "C", "label": "next", "offset": 0, "slot": "6", "type": "t_uint64" }
1496            ],
1497            "types": {
1498                "t_uint64": { "encoding": "inplace", "label": "uint64", "numberOfBytes": "8" },
1499                "t_bool": { "encoding": "inplace", "label": "bool", "numberOfBytes": "1" }
1500            }
1501        }))
1502        .unwrap();
1503        let identifier = SlotIdentifier::new(Arc::new(layout));
1504
1505        let mut info = identifier.identify(&B256::from(U256::from(5)), None).unwrap();
1506        assert_eq!(info.label, "initialized, initializing");
1507        assert_eq!(info.slot_type.label, "(uint64,bool)");
1508        let new_value = B256::from(U256::from(1) << 64 | U256::from(7));
1509        info.decode_values(B256::ZERO, new_value);
1510        assert_eq!(
1511            decoded(&info),
1512            [
1513                ("initialized", "0".to_string(), "7".to_string()),
1514                ("initializing", "false".to_string(), "true".to_string())
1515            ]
1516        );
1517
1518        let info = identifier.identify(&B256::from(U256::from(6)), None).unwrap();
1519        assert_eq!(info.label, "next");
1520        assert!(info.members.is_none());
1521    }
1522
1523    #[test]
1524    fn decodes_packed_struct_members_past_the_first_slot() {
1525        let layout = serde_json::from_value::<StorageLayout>(serde_json::json!({
1526            "storage": [
1527                { "astId": 1, "contract": "C", "label": "data", "offset": 0, "slot": "0", "type": "t_struct(Data)" }
1528            ],
1529            "types": {
1530                "t_struct(Data)": {
1531                    "encoding": "inplace", "label": "struct C.Data", "numberOfBytes": "64",
1532                    "members": [
1533                        { "astId": 2, "contract": "C", "label": "total", "offset": 0, "slot": "0", "type": "t_uint256" },
1534                        { "astId": 3, "contract": "C", "label": "owner", "offset": 0, "slot": "1", "type": "t_address" },
1535                        { "astId": 4, "contract": "C", "label": "paused", "offset": 20, "slot": "1", "type": "t_bool" }
1536                    ]
1537                },
1538                "t_uint256": { "encoding": "inplace", "label": "uint256", "numberOfBytes": "32" },
1539                "t_address": { "encoding": "inplace", "label": "address", "numberOfBytes": "20" },
1540                "t_bool": { "encoding": "inplace", "label": "bool", "numberOfBytes": "1" }
1541            }
1542        }))
1543        .unwrap();
1544        let identifier = SlotIdentifier::new(Arc::new(layout));
1545
1546        let info = identifier.identify(&B256::ZERO, None).unwrap();
1547        assert_eq!(info.label, "data.total");
1548
1549        let mut info = identifier.identify(&B256::from(U256::from(1)), None).unwrap();
1550        assert_eq!(info.label, "data.owner, data.paused");
1551        let new_value = B256::from(U256::from(1) << 160 | U256::from(0x1234));
1552        info.decode_values(B256::ZERO, new_value);
1553        assert_eq!(
1554            decoded(&info),
1555            [
1556                (
1557                    "data.owner",
1558                    "0x0000000000000000000000000000000000000000".to_string(),
1559                    "0x0000000000000000000000000000000000001234".to_string()
1560                ),
1561                ("data.paused", "false".to_string(), "true".to_string())
1562            ]
1563        );
1564    }
1565
1566    #[test]
1567    fn decodes_packed_signed_variables() {
1568        let layout = serde_json::from_value::<StorageLayout>(serde_json::json!({
1569            "storage": [
1570                { "astId": 1, "contract": "C", "label": "a", "offset": 0, "slot": "0", "type": "t_int8" },
1571                { "astId": 2, "contract": "C", "label": "b", "offset": 1, "slot": "0", "type": "t_int8" }
1572            ],
1573            "types": {
1574                "t_int8": { "encoding": "inplace", "label": "int8", "numberOfBytes": "1" }
1575            }
1576        }))
1577        .unwrap();
1578        let identifier = SlotIdentifier::new(Arc::new(layout));
1579        let mut info = identifier.identify(&B256::ZERO, None).unwrap();
1580
1581        info.decode_values(B256::from(U256::from(0x7fff)), B256::from(U256::from(0x80fe)));
1582        assert_eq!(
1583            decoded(&info),
1584            [
1585                ("a", "-1".to_string(), "-2".to_string()),
1586                ("b", "127".to_string(), "-128".to_string())
1587            ]
1588        );
1589
1590        info.decode_values(B256::from(U256::from(0x80fe)), B256::from(U256::from(0xff7f)));
1591        assert_eq!(
1592            decoded(&info),
1593            [
1594                ("a", "-2".to_string(), "127".to_string()),
1595                ("b", "-128".to_string(), "-1".to_string())
1596            ]
1597        );
1598    }
1599
1600    #[test]
1601    fn decodes_packed_fixed_bytes() {
1602        let layout = serde_json::from_value::<StorageLayout>(serde_json::json!({
1603            "storage": [
1604                { "astId": 1, "contract": "C", "label": "counter", "offset": 0, "slot": "0", "type": "t_uint8" },
1605                { "astId": 2, "contract": "C", "label": "tag", "offset": 1, "slot": "0", "type": "t_bytes1" },
1606                { "astId": 3, "contract": "C", "label": "hash", "offset": 2, "slot": "0", "type": "t_bytes16" }
1607            ],
1608            "types": {
1609                "t_uint8": { "encoding": "inplace", "label": "uint8", "numberOfBytes": "1" },
1610                "t_bytes1": { "encoding": "inplace", "label": "bytes1", "numberOfBytes": "1" },
1611                "t_bytes16": { "encoding": "inplace", "label": "bytes16", "numberOfBytes": "16" }
1612            }
1613        }))
1614        .unwrap();
1615        let identifier = SlotIdentifier::new(Arc::new(layout));
1616        let mut info = identifier.identify(&B256::ZERO, None).unwrap();
1617        let previous =
1618            U256::from(0x0123456789abcdef0123456789abcdef_u128) << 16 | U256::from(0xab07);
1619        let new = U256::from(0xfedcba9876543210fedcba9876543210_u128) << 16 | U256::from(0xcd0b);
1620        info.decode_values(B256::from(previous), B256::from(new));
1621        assert_eq!(
1622            decoded(&info),
1623            [
1624                ("counter", "7".to_string(), "11".to_string()),
1625                ("tag", "0xab".to_string(), "0xcd".to_string()),
1626                (
1627                    "hash",
1628                    "0x0123456789abcdef0123456789abcdef".to_string(),
1629                    "0xfedcba9876543210fedcba9876543210".to_string()
1630                )
1631            ]
1632        );
1633    }
1634
1635    /// A layout with mappings to structs holding mappings, as OpenZeppelin's `AccessManager` has,
1636    /// and mappings to values whose fields can't be identified.
1637    fn mapping_struct_layout() -> SlotIdentifier {
1638        let layout = serde_json::from_value::<StorageLayout>(serde_json::json!({
1639            "storage": [
1640                { "astId": 1, "contract": "C", "label": "roles", "offset": 0, "slot": "0", "type": "t_mapping(t_uint64,t_struct(Role))" },
1641                { "astId": 2, "contract": "C", "label": "pools", "offset": 0, "slot": "1", "type": "t_mapping(t_uint256,t_struct(Pool))" },
1642                { "astId": 3, "contract": "C", "label": "allowances", "offset": 0, "slot": "2", "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))" },
1643                { "astId": 11, "contract": "C", "label": "orders", "offset": 0, "slot": "3", "type": "t_mapping(t_uint256,t_struct(Order))" },
1644                { "astId": 12, "contract": "C", "label": "queues", "offset": 0, "slot": "4", "type": "t_mapping(t_uint256,t_array(t_struct(Access))dyn_storage)" },
1645                { "astId": 15, "contract": "C", "label": "pays", "offset": 0, "slot": "5", "type": "t_mapping(t_uint256,t_struct(Pay))" }
1646            ],
1647            "types": {
1648                "t_mapping(t_uint64,t_struct(Role))": {
1649                    "encoding": "mapping", "label": "mapping(uint64 => struct C.Role)", "numberOfBytes": "32",
1650                    "key": "t_uint64", "value": "t_struct(Role)"
1651                },
1652                "t_struct(Role)": {
1653                    "encoding": "inplace", "label": "struct C.Role", "numberOfBytes": "64",
1654                    "members": [
1655                        { "astId": 4, "contract": "C", "label": "members", "offset": 0, "slot": "0", "type": "t_mapping(t_address,t_struct(Access))" },
1656                        { "astId": 5, "contract": "C", "label": "admin", "offset": 0, "slot": "1", "type": "t_uint64" },
1657                        { "astId": 6, "contract": "C", "label": "guardian", "offset": 8, "slot": "1", "type": "t_uint64" }
1658                    ]
1659                },
1660                "t_mapping(t_address,t_struct(Access))": {
1661                    "encoding": "mapping", "label": "mapping(address => struct C.Access)", "numberOfBytes": "32",
1662                    "key": "t_address", "value": "t_struct(Access)"
1663                },
1664                "t_struct(Access)": {
1665                    "encoding": "inplace", "label": "struct C.Access", "numberOfBytes": "32",
1666                    "members": [
1667                        { "astId": 7, "contract": "C", "label": "since", "offset": 0, "slot": "0", "type": "t_uint48" },
1668                        { "astId": 8, "contract": "C", "label": "delay", "offset": 6, "slot": "0", "type": "t_uint112" }
1669                    ]
1670                },
1671                "t_mapping(t_uint256,t_struct(Pool))": {
1672                    "encoding": "mapping", "label": "mapping(uint256 => struct C.Pool)", "numberOfBytes": "32",
1673                    "key": "t_uint256", "value": "t_struct(Pool)"
1674                },
1675                "t_struct(Pool)": {
1676                    "encoding": "inplace", "label": "struct C.Pool", "numberOfBytes": "64",
1677                    "members": [
1678                        { "astId": 9, "contract": "C", "label": "total", "offset": 0, "slot": "0", "type": "t_uint256" },
1679                        { "astId": 10, "contract": "C", "label": "shares", "offset": 0, "slot": "1", "type": "t_mapping(t_address,t_uint256)" }
1680                    ]
1681                },
1682                "t_mapping(t_address,t_mapping(t_address,t_uint256))": {
1683                    "encoding": "mapping", "label": "mapping(address => mapping(address => uint256))", "numberOfBytes": "32",
1684                    "key": "t_address", "value": "t_mapping(t_address,t_uint256)"
1685                },
1686                "t_mapping(t_address,t_uint256)": {
1687                    "encoding": "mapping", "label": "mapping(address => uint256)", "numberOfBytes": "32",
1688                    "key": "t_address", "value": "t_uint256"
1689                },
1690                "t_mapping(t_uint256,t_struct(Order))": {
1691                    "encoding": "mapping", "label": "mapping(uint256 => struct C.Order)", "numberOfBytes": "32",
1692                    "key": "t_uint256", "value": "t_struct(Order)"
1693                },
1694                "t_struct(Order)": {
1695                    "encoding": "inplace", "label": "struct C.Order", "numberOfBytes": "64",
1696                    "members": [
1697                        { "astId": 13, "contract": "C", "label": "callback", "offset": 0, "slot": "0", "type": "t_function_external_nonpayable(t_uint256)returns()" },
1698                        { "astId": 14, "contract": "C", "label": "qty", "offset": 0, "slot": "1", "type": "t_uint256" }
1699                    ]
1700                },
1701                "t_function_external_nonpayable(t_uint256)returns()": { "encoding": "inplace", "label": "function (uint256) external", "numberOfBytes": "24" },
1702                "t_mapping(t_uint256,t_array(t_struct(Access))dyn_storage)": {
1703                    "encoding": "mapping", "label": "mapping(uint256 => struct C.Access[])", "numberOfBytes": "32",
1704                    "key": "t_uint256", "value": "t_array(t_struct(Access))dyn_storage"
1705                },
1706                "t_array(t_struct(Access))dyn_storage": {
1707                    "encoding": "dynamic_array", "label": "struct C.Access[]", "numberOfBytes": "32",
1708                    "base": "t_struct(Access)"
1709                },
1710                "t_mapping(t_uint256,t_struct(Pay))": {
1711                    "encoding": "mapping", "label": "mapping(uint256 => struct C.Pay)", "numberOfBytes": "32",
1712                    "key": "t_uint256", "value": "t_struct(Pay)"
1713                },
1714                "t_struct(Pay)": {
1715                    "encoding": "inplace", "label": "struct C.Pay", "numberOfBytes": "96",
1716                    "members": [
1717                        { "astId": 16, "contract": "C", "label": "hook", "offset": 0, "slot": "0", "type": "t_function_external_nonpayable(t_uint256)returns()" },
1718                        { "astId": 17, "contract": "C", "label": "amount", "offset": 24, "slot": "0", "type": "t_uint64" },
1719                        { "astId": 18, "contract": "C", "label": "deadline", "offset": 0, "slot": "1", "type": "t_uint256" },
1720                        { "astId": 19, "contract": "C", "label": "fee", "offset": 0, "slot": "2", "type": "t_uint64" },
1721                        { "astId": 20, "contract": "C", "label": "payee", "offset": 8, "slot": "2", "type": "t_function_external_nonpayable(t_uint256)returns()" }
1722                    ]
1723                },
1724                "t_uint48": { "encoding": "inplace", "label": "uint48", "numberOfBytes": "6" },
1725                "t_uint64": { "encoding": "inplace", "label": "uint64", "numberOfBytes": "8" },
1726                "t_uint112": { "encoding": "inplace", "label": "uint112", "numberOfBytes": "14" },
1727                "t_uint256": { "encoding": "inplace", "label": "uint256", "numberOfBytes": "32" },
1728                "t_address": { "encoding": "inplace", "label": "address", "numberOfBytes": "20" }
1729            }
1730        }))
1731        .unwrap();
1732        SlotIdentifier::new(Arc::new(layout))
1733    }
1734
1735    /// Records the mapping entry `keccak256(key . parent)` as the EVM would, and returns it.
1736    fn entry(mapping_slots: &mut MappingSlots, key: B256, parent: U256) -> U256 {
1737        let parent = B256::from(parent);
1738        let result = keccak256([key.0, parent.0].concat());
1739        mapping_slots.record_hash(result, key, parent);
1740        U256::from_be_bytes(result.0)
1741    }
1742
1743    const USER: Address = Address::repeat_byte(0x11);
1744
1745    #[test]
1746    fn identifies_nested_mappings_as_declared() {
1747        let identifier = mapping_struct_layout();
1748        let mut slots = MappingSlots::default();
1749        let outer = entry(&mut slots, USER.into_word(), U256::from(2));
1750        let inner = entry(&mut slots, Address::repeat_byte(0x22).into_word(), outer);
1751        slots.insert(inner.into());
1752
1753        let info = identifier.identify(&B256::from(inner), Some(&slots)).unwrap();
1754        assert_eq!(
1755            info.label,
1756            "allowances[0x1111111111111111111111111111111111111111][0x2222222222222222222222222222222222222222]"
1757        );
1758        assert_eq!(info.slot_type.label, "mapping(address => mapping(address => uint256))");
1759        assert_eq!(info.slot_type.dyn_sol_type, DynSolType::Uint(256));
1760    }
1761
1762    #[test]
1763    fn identifies_struct_fields_past_a_mapping_entry() {
1764        let identifier = mapping_struct_layout();
1765        let mut slots = MappingSlots::default();
1766        let role = entry(&mut slots, U256::from(2).into(), U256::ZERO);
1767        slots.insert((role + U256::from(1)).into());
1768
1769        let mut info =
1770            identifier.identify(&B256::from(role + U256::from(1)), Some(&slots)).unwrap();
1771        assert_eq!(info.label, "roles[2].admin, roles[2].guardian");
1772        assert_eq!(info.keys, Some(vec!["2".to_string()]));
1773        info.decode_values(B256::ZERO, B256::from(U256::from(5) << 64 | U256::from(4)));
1774        assert_eq!(
1775            decoded(&info),
1776            [
1777                ("roles[2].admin", "0".to_string(), "4".to_string()),
1778                ("roles[2].guardian", "0".to_string(), "5".to_string())
1779            ]
1780        );
1781    }
1782
1783    /// `roles[2].members[user]`: the inner mapping is the struct's first member, so its entry's
1784    /// parent is the outer entry itself, which used to read as one more key of `roles`.
1785    #[test]
1786    fn identifies_a_mapping_inside_a_mapped_struct() {
1787        let identifier = mapping_struct_layout();
1788        let mut slots = MappingSlots::default();
1789        let role = entry(&mut slots, U256::from(2).into(), U256::ZERO);
1790        let access = entry(&mut slots, USER.into_word(), role);
1791        slots.insert(access.into());
1792
1793        let mut info = identifier.identify(&B256::from(access), Some(&slots)).unwrap();
1794        assert_eq!(info.label, "roles[2].members[0x1111111111111111111111111111111111111111]");
1795        assert_eq!(info.slot_type.label, "struct C.Access");
1796        assert_eq!(
1797            info.keys,
1798            Some(vec!["2".to_string(), "0x1111111111111111111111111111111111111111".to_string()])
1799        );
1800        info.decode_values(B256::ZERO, B256::from(U256::from(9) << 48 | U256::from(1_700_000_000)));
1801        assert_eq!(
1802            decoded(&info),
1803            [
1804                ("since", "0".to_string(), "1700000000".to_string()),
1805                ("delay", "0".to_string(), "9".to_string())
1806            ]
1807        );
1808    }
1809
1810    /// `pools[1].shares[user]`: the inner mapping is the struct's second slot, so its parent is
1811    /// displaced from the outer entry and the chain used to break there.
1812    #[test]
1813    fn identifies_a_mapping_member_past_the_first_slot() {
1814        let identifier = mapping_struct_layout();
1815        let mut slots = MappingSlots::default();
1816        let pool = entry(&mut slots, U256::from(1).into(), U256::from(1));
1817        let share = entry(&mut slots, USER.into_word(), pool + U256::from(1));
1818        slots.insert(share.into());
1819
1820        let info = identifier.identify(&B256::from(share), Some(&slots)).unwrap();
1821        assert_eq!(info.label, "pools[1].shares[0x1111111111111111111111111111111111111111]");
1822        assert_eq!(info.slot_type.label, "mapping(address => uint256)");
1823        assert_eq!(info.slot_type.dyn_sol_type, DynSolType::Uint(256));
1824
1825        let info = identifier.identify(&B256::from(pool), Some(&slots)).unwrap();
1826        assert_eq!(info.label, "pools[1].total");
1827    }
1828
1829    /// A struct variable holding mappings directly (`s.balances`, `s.vaults`) and one holding an
1830    /// OpenZeppelin `EnumerableSet.AddressSet`, whose `_positions` mapping is a member of the
1831    /// nested `Set` struct.
1832    fn struct_mapping_layout() -> SlotIdentifier {
1833        let layout = serde_json::from_value::<StorageLayout>(serde_json::json!({
1834            "storage": [
1835                { "astId": 1, "contract": "C", "label": "s", "offset": 0, "slot": "0", "type": "t_struct(S)" },
1836                { "astId": 2, "contract": "C", "label": "set", "offset": 0, "slot": "3", "type": "t_struct(AddressSet)" }
1837            ],
1838            "types": {
1839                "t_struct(S)": {
1840                    "encoding": "inplace", "label": "struct C.S", "numberOfBytes": "96",
1841                    "members": [
1842                        { "astId": 3, "contract": "C", "label": "total", "offset": 0, "slot": "0", "type": "t_uint256" },
1843                        { "astId": 4, "contract": "C", "label": "balances", "offset": 0, "slot": "1", "type": "t_mapping(t_address,t_uint256)" },
1844                        { "astId": 8, "contract": "C", "label": "vaults", "offset": 0, "slot": "2", "type": "t_mapping(t_uint256,t_struct(V))" }
1845                    ]
1846                },
1847                "t_struct(V)": {
1848                    "encoding": "inplace", "label": "struct C.V", "numberOfBytes": "96",
1849                    "members": [
1850                        { "astId": 9, "contract": "C", "label": "owner", "offset": 0, "slot": "0", "type": "t_address" },
1851                        { "astId": 10, "contract": "C", "label": "shares", "offset": 0, "slot": "1", "type": "t_uint256" },
1852                        { "astId": 11, "contract": "C", "label": "allowed", "offset": 0, "slot": "2", "type": "t_mapping(t_address,t_uint256)" }
1853                    ]
1854                },
1855                "t_mapping(t_uint256,t_struct(V))": {
1856                    "encoding": "mapping", "label": "mapping(uint256 => struct C.V)", "numberOfBytes": "32",
1857                    "key": "t_uint256", "value": "t_struct(V)"
1858                },
1859                "t_struct(AddressSet)": {
1860                    "encoding": "inplace", "label": "struct EnumerableSet.AddressSet", "numberOfBytes": "64",
1861                    "members": [
1862                        { "astId": 5, "contract": "C", "label": "_inner", "offset": 0, "slot": "0", "type": "t_struct(Set)" }
1863                    ]
1864                },
1865                "t_struct(Set)": {
1866                    "encoding": "inplace", "label": "struct EnumerableSet.Set", "numberOfBytes": "64",
1867                    "members": [
1868                        { "astId": 6, "contract": "C", "label": "_values", "offset": 0, "slot": "0", "type": "t_array(t_bytes32)dyn_storage" },
1869                        { "astId": 7, "contract": "C", "label": "_positions", "offset": 0, "slot": "1", "type": "t_mapping(t_bytes32,t_uint256)" }
1870                    ]
1871                },
1872                "t_array(t_bytes32)dyn_storage": {
1873                    "encoding": "dynamic_array", "label": "bytes32[]", "numberOfBytes": "32", "base": "t_bytes32"
1874                },
1875                "t_mapping(t_address,t_uint256)": {
1876                    "encoding": "mapping", "label": "mapping(address => uint256)", "numberOfBytes": "32",
1877                    "key": "t_address", "value": "t_uint256"
1878                },
1879                "t_mapping(t_bytes32,t_uint256)": {
1880                    "encoding": "mapping", "label": "mapping(bytes32 => uint256)", "numberOfBytes": "32",
1881                    "key": "t_bytes32", "value": "t_uint256"
1882                },
1883                "t_bytes32": { "encoding": "inplace", "label": "bytes32", "numberOfBytes": "32" },
1884                "t_uint256": { "encoding": "inplace", "label": "uint256", "numberOfBytes": "32" },
1885                "t_address": { "encoding": "inplace", "label": "address", "numberOfBytes": "20" }
1886            }
1887        }))
1888        .unwrap();
1889        SlotIdentifier::new(Arc::new(layout))
1890    }
1891
1892    /// `s.balances[user]`: a mapping that is a member of a struct variable.
1893    #[test]
1894    fn identifies_a_mapping_member_of_a_struct_variable() {
1895        let identifier = struct_mapping_layout();
1896        let mut slots = MappingSlots::default();
1897        let balance = entry(&mut slots, USER.into_word(), U256::from(1));
1898        slots.insert(balance.into());
1899
1900        let info = identifier.identify(&B256::from(balance), Some(&slots)).unwrap();
1901        assert_eq!(info.label, "s.balances[0x1111111111111111111111111111111111111111]");
1902        assert_eq!(info.slot_type.label, "mapping(address => uint256)");
1903        assert_eq!(info.slot_type.dyn_sol_type, DynSolType::Uint(256));
1904        assert_eq!(info.keys, Some(vec!["0x1111111111111111111111111111111111111111".to_string()]));
1905
1906        // `s.vaults[3].shares` and `s.vaults[3].allowed[user]`: a mapping member of a struct held
1907        // by a mapping member.
1908        let vault = entry(&mut slots, U256::from(3).into(), U256::from(2));
1909        let shares = vault + U256::from(1);
1910        slots.insert(shares.into());
1911        let info = identifier.identify(&B256::from(shares), Some(&slots)).unwrap();
1912        assert_eq!(info.label, "s.vaults[3].shares");
1913        assert_eq!(info.slot_type.dyn_sol_type, DynSolType::Uint(256));
1914
1915        let allowed = entry(&mut slots, USER.into_word(), vault + U256::from(2));
1916        slots.insert(allowed.into());
1917        let info = identifier.identify(&B256::from(allowed), Some(&slots)).unwrap();
1918        assert_eq!(info.label, "s.vaults[3].allowed[0x1111111111111111111111111111111111111111]");
1919        assert_eq!(info.slot_type.label, "mapping(address => uint256)");
1920        assert_eq!(info.keys, Some(vec!["3".to_string(), USER.to_string()]));
1921    }
1922
1923    /// `set._inner._positions[value]`: a mapping that is a member of a struct nested in a struct
1924    /// variable, as in OpenZeppelin's `EnumerableSet`.
1925    #[test]
1926    fn identifies_a_mapping_member_of_a_nested_struct() {
1927        let identifier = struct_mapping_layout();
1928        let mut slots = MappingSlots::default();
1929        let position = entry(&mut slots, USER.into_word(), U256::from(4));
1930        slots.insert(position.into());
1931
1932        let info = identifier.identify(&B256::from(position), Some(&slots)).unwrap();
1933        assert_eq!(
1934            info.label,
1935            "set._inner._positions[0x0000000000000000000000001111111111111111111111111111111111111111]"
1936        );
1937        assert_eq!(info.slot_type.label, "mapping(bytes32 => uint256)");
1938        assert_eq!(info.slot_type.dyn_sol_type, DynSolType::Uint(256));
1939
1940        // A slot past the struct's mappings is left unidentified.
1941        let other = entry(&mut slots, USER.into_word(), U256::from(5));
1942        assert!(identifier.identify(&B256::from(other), Some(&slots)).is_none());
1943    }
1944
1945    #[test]
1946    fn identifies_deep_mappings_and_rejects_cycles() {
1947        let mut types = serde_json::json!({
1948            "uint": { "encoding": "inplace", "label": "uint256", "numberOfBytes": "32" }
1949        });
1950        let mut value_id = "uint".to_string();
1951        let mut type_label = "uint256".to_string();
1952        for depth in 0..34 {
1953            let id = format!("mapping{depth}");
1954            type_label = format!("mapping(uint256 => {type_label})");
1955            types[&id] = serde_json::json!({
1956                "encoding": "mapping", "label": type_label, "numberOfBytes": "32",
1957                "key": "uint", "value": value_id
1958            });
1959            value_id = id;
1960        }
1961        let layout = serde_json::from_value(serde_json::json!({
1962            "storage": [
1963                { "astId": 1, "contract": "C", "label": "deep", "offset": 0, "slot": "0", "type": value_id }
1964            ],
1965            "types": types
1966        }))
1967        .unwrap();
1968        let identifier = SlotIdentifier::new(Arc::new(layout));
1969        let mut slots = MappingSlots::default();
1970        let mut slot = U256::ZERO;
1971        for key in 1..=34 {
1972            slot = entry(&mut slots, U256::from(key).into(), slot);
1973        }
1974        slots.insert(slot.into());
1975
1976        let mut info = identifier.identify(&slot.into(), Some(&slots)).unwrap();
1977        let keys = (1..=34).map(|key| key.to_string()).collect::<Vec<_>>();
1978        let suffix = keys.iter().map(|key| format!("[{key}]")).collect::<String>();
1979        assert_eq!(info.label, format!("deep{suffix}"));
1980        assert_eq!(info.keys, Some(keys));
1981        assert_eq!(info.slot_type.label, type_label);
1982        info.decode_values(B256::ZERO, U256::from(123).into());
1983        assert_eq!(format_token_raw(&info.decoded.unwrap().new_value), "123");
1984
1985        // An observed hash that points to itself must not loop indefinitely.
1986        let mut slots = MappingSlots::default();
1987        slots.record_hash(slot.into(), U256::ONE.into(), slot.into());
1988        slots.insert(slot.into());
1989        assert!(identifier.identify(&slot.into(), Some(&slots)).is_none());
1990    }
1991
1992    /// `orders[2]` starts with an external function and `queues[1]` is an array of structs,
1993    /// so neither entry can be identified field by field, but each is still identified whole.
1994    #[test]
1995    fn identifies_mapping_entries_with_unidentifiable_fields() {
1996        let identifier = mapping_struct_layout();
1997        let mut slots = MappingSlots::default();
1998        let order = entry(&mut slots, U256::from(2).into(), U256::from(3));
1999        let queue = entry(&mut slots, U256::from(1).into(), U256::from(4));
2000        slots.insert(order.into());
2001        slots.insert(queue.into());
2002
2003        // The array of structs is still an array, whose entry holds its length.
2004        let struct_array = DynSolType::Array(Box::new(DynSolType::FixedBytes(32)));
2005        for (slot, label, key, type_label, ty) in [
2006            (order, "orders[2]", "2", "mapping(uint256 => struct C.Order)", DynSolType::Bytes),
2007            (queue, "queues[1]", "1", "mapping(uint256 => struct C.Access[])", struct_array),
2008        ] {
2009            let info = identifier.identify(&B256::from(slot), Some(&slots)).unwrap();
2010            assert_eq!(info.label, label);
2011            assert_eq!(info.keys, Some(vec![key.to_string()]));
2012            assert_eq!(info.slot_type.label, type_label);
2013            assert_eq!(info.slot_type.dyn_sol_type, ty);
2014        }
2015    }
2016
2017    /// `pays[1].amount` and `pays[1].fee` share their slots with an external function, which can't
2018    /// be decoded, so each is decoded from its own bytes rather than the whole word.
2019    #[test]
2020    fn decodes_mapped_struct_fields_beside_undecodable_ones() {
2021        let identifier = mapping_struct_layout();
2022        let mut slots = MappingSlots::default();
2023        let pay = entry(&mut slots, U256::from(1).into(), U256::from(5));
2024
2025        for (offset, word, label, value) in [
2026            (0, U256::from(3) << 192 | U256::from(0xdead), "pays[1].amount", "3"),
2027            (2, U256::from(0xbeef) << 64 | U256::from(4), "pays[1].fee", "4"),
2028        ] {
2029            let slot = B256::from(pay + U256::from(offset));
2030            let mut info = identifier.identify(&slot, Some(&slots)).unwrap();
2031            assert_eq!(info.label, label);
2032            assert_eq!(info.keys, Some(vec!["1".to_string()]));
2033            info.decode_values(B256::ZERO, B256::from(word));
2034            assert_eq!(decoded(&info), [(label, "0".to_string(), value.to_string())]);
2035        }
2036    }
2037
2038    /// User-defined value types as solc lays them out: a file-level one labeled by its name, a
2039    /// library one by `Library.Name`, both 12 bytes (`uint96`).
2040    ///
2041    /// Every type ID is prefixed by `scope`, as ERC-7201 namespaces scope theirs.
2042    fn udvt_layout(scope: &str) -> SlotIdentifier {
2043        let t = |id: &str| format!("{scope}{id}");
2044        let layout = serde_json::from_value::<StorageLayout>(serde_json::json!({
2045            "storage": [
2046                { "astId": 1, "contract": "C", "label": "config", "offset": 0, "slot": "0", "type": t("t_struct(Config)") },
2047                { "astId": 2, "contract": "C", "label": "ids", "offset": 0, "slot": "2", "type": t("t_array(t_userDefinedValueType(FileId)10)3_storage") },
2048                { "astId": 3, "contract": "C", "label": "byId", "offset": 0, "slot": "4", "type": t("t_mapping(t_userDefinedValueType(FileId)10,t_userDefinedValueType(LibId)11)") }
2049            ],
2050            "types": {
2051                t("t_struct(Config)"): {
2052                    "encoding": "inplace", "label": "struct C.Config", "numberOfBytes": "64",
2053                    "members": [
2054                        { "astId": 4, "contract": "C", "label": "owner", "offset": 0, "slot": "0", "type": t("t_address") },
2055                        { "astId": 5, "contract": "C", "label": "fileId", "offset": 20, "slot": "0", "type": t("t_userDefinedValueType(FileId)10") },
2056                        { "astId": 6, "contract": "C", "label": "libId", "offset": 0, "slot": "1", "type": t("t_userDefinedValueType(LibId)11") }
2057                    ]
2058                },
2059                t("t_array(t_userDefinedValueType(FileId)10)3_storage"): {
2060                    "encoding": "inplace", "label": "FileId[3]", "numberOfBytes": "64",
2061                    "base": t("t_userDefinedValueType(FileId)10")
2062                },
2063                t("t_mapping(t_userDefinedValueType(FileId)10,t_userDefinedValueType(LibId)11)"): {
2064                    "encoding": "mapping", "label": "mapping(FileId => L.LibId)", "numberOfBytes": "32",
2065                    "key": t("t_userDefinedValueType(FileId)10"), "value": t("t_userDefinedValueType(LibId)11")
2066                },
2067                t("t_userDefinedValueType(FileId)10"): { "encoding": "inplace", "label": "FileId", "numberOfBytes": "12" },
2068                t("t_userDefinedValueType(LibId)11"): { "encoding": "inplace", "label": "L.LibId", "numberOfBytes": "12" },
2069                t("t_address"): { "encoding": "inplace", "label": "address", "numberOfBytes": "20" }
2070            }
2071        }))
2072        .unwrap();
2073        SlotIdentifier::new(Arc::new(layout))
2074    }
2075
2076    /// Unscoped type IDs, and IDs scoped the way [`crate::namespaced_storage`] scopes a namespace.
2077    const SCOPES: [&str; 2] = ["", "erc7201(example.udvt)::"];
2078
2079    /// Wider than a byte, which a `Library.Name` label used to be parsed as.
2080    const ID: u64 = 0x0102_0304_0506;
2081
2082    #[test]
2083    fn decodes_user_defined_value_type_members() {
2084        for scope in SCOPES {
2085            let identifier = udvt_layout(scope);
2086            let mut info = identifier.identify(&B256::ZERO, None).unwrap();
2087            assert_eq!(info.label, "config.owner, config.fileId");
2088            info.decode_values(B256::ZERO, B256::from(U256::from(ID) << 160 | U256::from(0x1234)));
2089            assert_eq!(
2090                decoded(&info),
2091                [
2092                    (
2093                        "config.owner",
2094                        "0x0000000000000000000000000000000000000000".to_string(),
2095                        "0x0000000000000000000000000000000000001234".to_string()
2096                    ),
2097                    ("config.fileId", "0".to_string(), ID.to_string())
2098                ]
2099            );
2100
2101            let mut info = identifier.identify(&B256::from(U256::from(1)), None).unwrap();
2102            assert_eq!(info.label, "config.libId");
2103            assert_eq!(info.slot_type.label, "L.LibId");
2104            info.decode_values(B256::ZERO, B256::from(U256::from(ID)));
2105            assert_eq!(format_token_raw(&info.decoded.unwrap().new_value), ID.to_string());
2106        }
2107    }
2108
2109    #[test]
2110    fn resolves_mappings_of_user_defined_value_types() {
2111        for scope in SCOPES {
2112            let identifier = udvt_layout(scope);
2113            let mut slots = MappingSlots::default();
2114            let key = B256::from(U256::from(ID));
2115            let parent = B256::from(U256::from(4));
2116            let entry = keccak256([key.0, parent.0].concat());
2117            slots.record_hash(entry, key, parent);
2118            slots.insert(entry);
2119
2120            let mut info = identifier.identify(&entry, Some(&slots)).unwrap();
2121            assert_eq!(info.label, format!("byId[{ID}]"));
2122            info.decode_values(B256::ZERO, B256::from(U256::from(ID)));
2123            assert_eq!(format_token_raw(&info.decoded.unwrap().new_value), ID.to_string());
2124        }
2125    }
2126
2127    #[test]
2128    fn leaves_unresolved_packed_udvt_arrays_unidentified() {
2129        let identifier = udvt_layout("");
2130        // Resolving FileId[3] to uint96[3] would feed packed words into a decoder that treats
2131        // slots as elements, giving both incorrect values and incorrect indices.
2132        for slot in [2, 3] {
2133            assert!(identifier.identify(&B256::from(U256::from(slot)), None).is_none());
2134        }
2135    }
2136
2137    /// A struct whose sole member is a struct: OpenZeppelin's `EnumerableSet.AddressSet`, which
2138    /// wraps a two-slot struct holding a dynamic array and a mapping, and `wrapped`, which wraps a
2139    /// packed single-slot struct.
2140    #[test]
2141    fn descends_into_a_struct_whose_sole_member_is_a_struct() {
2142        let layout = serde_json::from_value::<StorageLayout>(serde_json::json!({
2143            "storage": [
2144                { "astId": 1, "contract": "C", "label": "set", "offset": 0, "slot": "0", "type": "t_struct(AddressSet)" },
2145                { "astId": 5, "contract": "C", "label": "wrapped", "offset": 0, "slot": "2", "type": "t_struct(A)" }
2146            ],
2147            "types": {
2148                "t_struct(A)": {
2149                    "encoding": "inplace", "label": "struct C.A", "numberOfBytes": "32",
2150                    "members": [
2151                        { "astId": 6, "contract": "C", "label": "b", "offset": 0, "slot": "0", "type": "t_struct(B)" }
2152                    ]
2153                },
2154                "t_struct(B)": {
2155                    "encoding": "inplace", "label": "struct C.B", "numberOfBytes": "32",
2156                    "members": [
2157                        { "astId": 7, "contract": "C", "label": "x", "offset": 0, "slot": "0", "type": "t_uint128" },
2158                        { "astId": 8, "contract": "C", "label": "y", "offset": 16, "slot": "0", "type": "t_uint64" }
2159                    ]
2160                },
2161                "t_uint128": { "encoding": "inplace", "label": "uint128", "numberOfBytes": "16" },
2162                "t_uint64": { "encoding": "inplace", "label": "uint64", "numberOfBytes": "8" },
2163                "t_struct(AddressSet)": {
2164                    "encoding": "inplace", "label": "struct EnumerableSet.AddressSet", "numberOfBytes": "64",
2165                    "members": [
2166                        { "astId": 2, "contract": "C", "label": "_inner", "offset": 0, "slot": "0", "type": "t_struct(Set)" }
2167                    ]
2168                },
2169                "t_struct(Set)": {
2170                    "encoding": "inplace", "label": "struct EnumerableSet.Set", "numberOfBytes": "64",
2171                    "members": [
2172                        { "astId": 3, "contract": "C", "label": "_values", "offset": 0, "slot": "0", "type": "t_array(t_bytes32)dyn_storage" },
2173                        { "astId": 4, "contract": "C", "label": "_positions", "offset": 0, "slot": "1", "type": "t_mapping(t_bytes32,t_uint256)" }
2174                    ]
2175                },
2176                "t_array(t_bytes32)dyn_storage": {
2177                    "encoding": "dynamic_array", "label": "bytes32[]", "numberOfBytes": "32", "base": "t_bytes32"
2178                },
2179                "t_mapping(t_bytes32,t_uint256)": {
2180                    "encoding": "mapping", "label": "mapping(bytes32 => uint256)", "numberOfBytes": "32",
2181                    "key": "t_bytes32", "value": "t_uint256"
2182                },
2183                "t_bytes32": { "encoding": "inplace", "label": "bytes32", "numberOfBytes": "32" },
2184                "t_uint256": { "encoding": "inplace", "label": "uint256", "numberOfBytes": "32" }
2185            }
2186        }))
2187        .unwrap();
2188        let identifier = SlotIdentifier::new(Arc::new(layout));
2189
2190        let mut info = identifier.identify(&B256::ZERO, None).unwrap();
2191        assert_eq!(info.label, "set._inner._values");
2192        assert_eq!(info.slot_type.label, "bytes32[]");
2193        // The array's own slot holds its length.
2194        info.decode_values(B256::ZERO, B256::from(U256::from(1)));
2195        let length = info.decoded.unwrap();
2196        assert_eq!(format_token_raw(&length.previous_value), "0");
2197        assert_eq!(format_token_raw(&length.new_value), "1");
2198
2199        let mut info = identifier.identify(&B256::from(U256::from(2)), None).unwrap();
2200        assert_eq!(info.label, "wrapped.b");
2201        assert_eq!(info.slot_type.label, "struct C.B");
2202        // `y = 7` sits above `x = 5`.
2203        info.decode_values(B256::ZERO, B256::from((U256::from(7) << 128) | U256::from(5)));
2204        assert_eq!(
2205            decoded(&info),
2206            [("x", "0".to_string(), "5".to_string()), ("y", "0".to_string(), "7".to_string())]
2207        );
2208    }
2209
2210    fn dynamic_array_layout() -> SlotIdentifier {
2211        let layout = serde_json::from_value::<StorageLayout>(serde_json::json!({
2212            "storage": [
2213                { "astId": 1, "contract": "C", "label": "name", "offset": 0, "slot": "0", "type": "t_string_storage" },
2214                { "astId": 2, "contract": "C", "label": "pairs", "offset": 0, "slot": "1", "type": "t_array(t_array(t_uint128)2_storage)dyn_storage" },
2215                { "astId": 3, "contract": "C", "label": "fns", "offset": 0, "slot": "2", "type": "t_array(t_function_internal_nonpayable()returns())dyn_storage" },
2216                { "astId": 4, "contract": "C", "label": "wide", "offset": 0, "slot": "3", "type": "t_array(t_array(t_uint256)2_storage)dyn_storage" }
2217            ],
2218            "types": {
2219                "t_array(t_array(t_uint128)2_storage)dyn_storage": {
2220                    "encoding": "dynamic_array", "label": "uint128[2][]", "numberOfBytes": "32", "base": "t_array(t_uint128)2_storage"
2221                },
2222                "t_array(t_uint128)2_storage": {
2223                    "encoding": "inplace", "label": "uint128[2]", "numberOfBytes": "32", "base": "t_uint128"
2224                },
2225                "t_array(t_array(t_uint256)2_storage)dyn_storage": {
2226                    "encoding": "dynamic_array", "label": "uint256[2][]", "numberOfBytes": "32", "base": "t_array(t_uint256)2_storage"
2227                },
2228                "t_array(t_uint256)2_storage": {
2229                    "encoding": "inplace", "label": "uint256[2]", "numberOfBytes": "64", "base": "t_uint256"
2230                },
2231                "t_array(t_function_internal_nonpayable()returns())dyn_storage": {
2232                    "encoding": "dynamic_array", "label": "function ()[]", "numberOfBytes": "32", "base": "t_function_internal_nonpayable()returns()"
2233                },
2234                "t_function_internal_nonpayable()returns()": {
2235                    "encoding": "inplace", "label": "function ()", "numberOfBytes": "8"
2236                },
2237                "t_string_storage": { "encoding": "bytes", "label": "string", "numberOfBytes": "32" },
2238                "t_uint128": { "encoding": "inplace", "label": "uint128", "numberOfBytes": "16" },
2239                "t_uint256": { "encoding": "inplace", "label": "uint256", "numberOfBytes": "32" }
2240            }
2241        }))
2242        .unwrap();
2243        SlotIdentifier::new(Arc::new(layout))
2244    }
2245
2246    /// The slot `index` slots into the data of the dynamic array at `base`.
2247    fn element(base: U256, index: u64) -> B256 {
2248        B256::from(Into::<U256>::into(keccak256(B256::from(base))) + U256::from(index))
2249    }
2250
2251    #[test]
2252    fn identifies_elements_of_dynamic_arrays_of_static_arrays() {
2253        let identifier = dynamic_array_layout();
2254
2255        // Static array elements fill whole slots.
2256        let info = identifier.identify(&element(U256::from(3), 3), None).unwrap();
2257        assert_eq!(info.label, "wide[1][1]");
2258
2259        // Elements packed several to a slot without a decodable type would be labeled one per
2260        // slot, giving incorrect indices and values.
2261        for base in [1, 2] {
2262            assert!(identifier.identify(&element(U256::from(base), 1), None).is_none());
2263        }
2264    }
2265
2266    #[test]
2267    fn ignores_hashes_of_slots_that_are_not_dynamic_arrays() {
2268        let identifier = dynamic_array_layout();
2269        let mut slots = MappingSlots::default();
2270        // A long string's data and an unrelated hashed word start at recorded hashes too.
2271        for word in [U256::ZERO, U256::from(1234)] {
2272            slots.record_word_hash(keccak256(B256::from(word)), B256::from(word));
2273            assert!(identifier.identify(&element(word, 0), Some(&slots)).is_none());
2274        }
2275    }
2276
2277    #[test]
2278    fn shows_declared_types_of_arrays_without_abi_elements() {
2279        let struct_array = DynSolType::Array(Box::new(DynSolType::FixedBytes(32)));
2280        for (label, ty, shown) in [
2281            ("struct C.Item[]", struct_array.clone(), "C.Item[]"),
2282            ("struct C.Item[][]", struct_array.clone(), "C.Item[][]"),
2283            ("mapping(uint256 => mapping(address => struct C.Item[]))", struct_array, "C.Item[]"),
2284            ("uint256[]", DynSolType::Array(Box::new(DynSolType::Uint(256))), "uint256[]"),
2285            ("mapping(address => uint256)", DynSolType::Uint(256), "uint256"),
2286            (
2287                "struct C.Pair",
2288                DynSolType::Tuple(vec![DynSolType::Uint(128); 2]),
2289                "(uint128,uint128)",
2290            ),
2291        ] {
2292            let info = StorageTypeInfo { label: label.to_string(), dyn_sol_type: ty };
2293            assert_eq!(info.to_string(), shown, "{label}");
2294        }
2295    }
2296}