1use 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
22pub const ENCODING_INPLACE: &str = "inplace";
24pub const ENCODING_MAPPING: &str = "mapping";
26pub const ENCODING_BYTES: &str = "bytes";
29pub const ENCODING_DYN_ARRAY: &str = "dynamic_array";
31
32#[derive(Clone, Serialize, Debug)]
34pub struct SlotInfo {
35 pub label: String,
43 #[serde(rename = "type", serialize_with = "serialize_slot_type")]
45 pub slot_type: StorageTypeInfo,
46 pub offset: i64,
48 pub slot: String,
50 #[serde(skip_serializing_if = "Option::is_none")]
54 pub members: Option<Vec<Self>>,
55 #[serde(skip_serializing_if = "Option::is_none")]
57 pub decoded: Option<DecodedSlotValues>,
58 #[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#[derive(Clone, Debug)]
73pub struct StorageTypeInfo {
74 pub label: String,
77 pub dyn_sol_type: DynSolType,
79}
80
81impl fmt::Display for StorageTypeInfo {
85 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86 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 pub fn decode(&self, value: B256) -> Option<DynSolValue> {
106 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 let mut actual_type = &self.slot_type.dyn_sol_type;
116 while let DynSolType::FixedArray(elem_type, _) = actual_type {
118 actual_type = elem_type.as_ref();
119 }
120
121 match actual_type {
123 DynSolType::Bytes | DynSolType::String => {
124 let length_byte = value.0[31];
128
129 if length_byte & 1 == 0 {
130 let length = ((length_byte >> 1) as usize).min(31);
132 let data = if length == 0 { Vec::new() } else { value.0[0..length].to_vec() };
134
135 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 None
151 }
152 }
153 DynSolType::Array(_) => DynSolType::Uint(256).abi_decode(&value.0).ok(),
155 _ => {
156 actual_type.abi_decode(&value.0).ok()
158 }
159 }
160 }
161
162 pub const fn is_bytes_or_string(&self) -> bool {
164 matches!(self.slot_type.dyn_sol_type, DynSolType::Bytes | DynSolType::String)
165 }
166
167 pub fn decode_bytes_or_string(
170 &mut self,
171 base_slot: &B256,
172 storage_values: &B256Map<B256>,
173 ) -> Option<DynSolValue> {
174 if !self.is_bytes_or_string() {
176 return None;
177 }
178
179 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 pub fn decode_bytes_or_string_values(
196 &mut self,
197 base_slot: &B256,
198 storage_accesses: &BTreeMap<B256, (B256, B256)>,
199 ) {
200 if !self.is_bytes_or_string() {
202 return;
203 }
204
205 if let Some((prev_base_value, new_base_value)) = storage_accesses.get(base_slot) {
207 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 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 self.decode(base_value)
220 }
221 };
222
223 let prev_decoded = decode_value(*prev_base_value, false);
225
226 let new_decoded = decode_value(*new_base_value, true);
228
229 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 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 if let Some(base_value) = storage_values.get(base_slot) {
251 let length_byte = base_value.0[31];
252
253 if length_byte & 1 == 1 {
255 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 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 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 if !members.is_empty() {
294 self.members = Some(members);
295 }
296
297 return Some(full_data);
298 }
299 }
300
301 None
302 }
303
304 pub fn decode_values(&mut self, previous_value: B256, new_value: B256) {
307 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 } else {
322 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
332fn 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
340fn 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#[derive(Clone, Debug)]
361pub struct DecodedSlotValues {
362 pub previous_value: DynSolValue,
364 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
380pub 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#[derive(Clone)]
407pub struct SlotIdentifier {
408 storage_layout: Arc<StorageLayout>,
409 parsed_types: BTreeMap<String, Option<DynSolType>>,
410}
411
412impl SlotIdentifier {
413 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 pub fn identify(&self, slot: &B256, mapping_slots: Option<&MappingSlots>) -> Option<SlotInfo> {
431 self.identify_at_depth(slot, mapping_slots, 0)
432 }
433
434 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 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 if storage_type.encoding == ENCODING_INPLACE {
464 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 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 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 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 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 if element_bytes <= 16 {
622 let element = element?;
624 let per_slot = 32 / element_bytes;
625 let first = index_slot * per_slot;
626 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 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 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 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 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 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 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 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 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 let label = match parsed_type {
763 DynSolType::FixedArray(inner, _) => {
764 if let DynSolType::FixedArray(_, inner_size) = inner.as_ref() {
765 let row = index / (*inner_size as u64);
767 let col = index % (*inner_size as u64);
768 format!("{label}[{row}][{col}]")
769 } else {
770 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 #[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 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 struct_start_slot == target_slot
830 && 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 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 if storage_type.number_of_bytes == "32" {
851 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 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 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 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 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 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 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 let mut levels = Vec::new();
1003 let mut current = *slot;
1004 loop {
1005 let (entry, offset) = mapping_entry(¤t, 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 let mut mapping_type = storage_type;
1021 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 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 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 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 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(¤t, 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 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 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 if storage_type.encoding != ENCODING_BYTES {
1196 return None;
1197 }
1198
1199 let base_slot = U256::from_str(&storage.slot).ok()?;
1201 if slot == base_slot {
1202 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 let data_start = Into::<U256>::into(keccak256(B256::from(base_slot)));
1228
1229 let length_byte = base_slot_value.0[31];
1232 if length_byte & 1 == 1 {
1233 let length = Into::<U256>::into(*base_slot_value) >> 1;
1235 let num_slots = (length + U256::from(31)) / U256::from(32);
1237
1238 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 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 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 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 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
1321const MAX_DEPTH: usize = 10;
1323
1324const MAX_ARRAY_SLOTS: U256 = U256::from_limbs([0, 1, 0, 0]);
1327
1328const MAX_VALUE_SLOTS: u64 = 256;
1331
1332fn 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
1345fn 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 format!("[0]{}", get_array_base_indices(inner))
1352 } else {
1353 "[0]".to_string()
1355 }
1356 }
1357 _ => String::new(),
1358 }
1359}
1360
1361const UDVT_TYPE_PREFIX: &str = "t_userDefinedValueType(";
1364
1365fn resolve_sol_type(id: &str, storage_type: &StorageType) -> Option<DynSolType> {
1375 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 (storage_type.encoding == ENCODING_DYN_ARRAY)
1384 .then(|| DynSolType::Array(Box::new(DynSolType::FixedBytes(32))))
1385 })
1386}
1387
1388fn 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
1405pub fn is_struct(s: &str) -> bool {
1407 s.starts_with("struct ")
1408}
1409
1410const 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
1421fn 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
1429fn decode_packed(ty: &DynSolType, offset: usize, word: B256) -> Option<DynSolValue> {
1431 let size = packed_size(ty).unwrap_or(32);
1433
1434 let mut bytes = [0u8; 32];
1435 if offset + size <= 32 {
1436 let byte_start = 32 - offset - size;
1443 if matches!(ty, DynSolType::Int(_)) && word.0[byte_start] & 0x80 != 0 {
1445 bytes.fill(0xff);
1446 }
1447 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 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 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 #[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 #[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 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 #[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 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 #[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 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 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 #[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 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 #[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 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 const SCOPES: [&str; 2] = ["", "erc7201(example.udvt)::"];
2078
2079 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 for slot in [2, 3] {
2133 assert!(identifier.identify(&B256::from(U256::from(slot)), None).is_none());
2134 }
2135 }
2136
2137 #[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 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 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 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 let info = identifier.identify(&element(U256::from(3), 3), None).unwrap();
2257 assert_eq!(info.label, "wide[1][1]");
2258
2259 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 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}