Created
December 2, 2023 00:18
-
-
Save jesperkristensen58/50d1b67089ad80e6d6ae8fb6b2212a55 to your computer and use it in GitHub Desktop.
Solidity Example: Viewing Storage Layout of Array of Structs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
/** | |
* @title ArrayOfStructs | |
* @dev A contract to manage an array of structs, with functions to add members, | |
* hash numbers, and directly access storage. | |
*/ | |
contract ArrayOfStructs { | |
struct Member { | |
string name; | |
uint number; | |
} | |
Member[] private persons; | |
/** | |
* @dev Adds a new member to the array. | |
* @param _name Name of the member. | |
* @param _number Number associated with the member. | |
*/ | |
function pushToArray(string memory _name, uint _number) public { | |
persons.push(Member(_name, _number)); | |
} | |
/** | |
* @dev Retrieves the content of a storage slot at a given index. | |
* @param index The index of the storage slot. | |
* @return The content of the storage slot. | |
*/ | |
function getStorageAt(uint256 index) public view returns (bytes32) { | |
bytes32 storageContent; | |
assembly { | |
storageContent := sload(index) | |
} | |
return storageContent; | |
} | |
/** | |
* @dev Hashes a number using keccak256. | |
* @param number The number to hash. | |
* @return The keccak256 hash of the number. | |
*/ | |
function hashNumber(uint256 number) public pure returns (bytes32) { | |
return keccak256(abi.encodePacked(number)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Title: Solidity Example: Viewing Storage Layout of Array of Structs
Description:
This Solidity contract is a practical demonstration of managing and interacting with an array of structs. It illustrates not only how to add elements to a dynamic array of structs but also delves into advanced concepts like directly accessing Ethereum's storage slots and hashing numbers.
Key Features:
Dynamic Array Management: Functions to add new elements to an array of structs, showcasing how Solidity handles dynamic arrays.
Direct Storage Access: A function that uses low-level assembly to read the raw content of a specific storage slot, providing insight into how Solidity organizes and stores data.
Hashing Utility: Implementation of a hashing function using keccak256, demonstrating how to generate hashes from numerical inputs.
Use Case:
Ideal for developers looking to understand the underlying storage mechanism of Solidity, especially how arrays and structs are organized at the storage level.
Useful as a reference for implementing custom functions for debugging or inspecting contract storage.