How would one append data to a storage array in huff?

Let's say for example we start off with an array that looks like:


And want to end with an array that looks like:


1 Answer 1


To store a dynamic array, you first have to get a starting storage slot.

Let's say our starting storage slot is n.

Then to get the storage slot for the first value, you just have to hash n like this:


This will give you the storage slot where to save the first variable.

Then if you want to push something to the array, you compute the hash again and add 1:

keccak256(n) + 1;

And so on.

So in huff it will look something like this:

#define macro STORE_BYTES32() = takes(0) returns(0) {
    0x04 calldataload    // [Argument to store]
    [STARTING_SLOT]      // [StartingSLot, Argument]
    0x00 mstore          // [Argument]
    0x20 0x00            // [offset, size, Argument]
    sha3                 // [HashedStorageSlot, Argument]
    sstore               // []

This stores the first value. To store the second value after the sha3, just add 1 to it.

Also, in solidity, the first storage slot n holds the size of the array.

That's how the EVM knows where to push the next variable.

I created a contract that shows how to do dynamic arrays: https://github.com/Kuly14/Huff-Arrays/blob/main/src/DynamicArray.huff

It is a bit more complex than the example above because we need to calculate how many items are in the array to not override any vars.

I didn't yet have time to create any tests for it so just keep that in mind.

It gets a lot more complicated if you want to pack the variables together into the same slot to save gas. You have to do a lot of bytes masking.

Here is a great article by noxx on the topic: https://noxx.substack.com/p/evm-deep-dives-the-path-to-shadowy-3ea

Here is also link to the docs where it's explained more in depth: https://docs.soliditylang.org/en/v0.8.13/internals/layout_in_storage.html#bytes-and-string

  • This is great! I'd love to see some examples of a solidity style dynamic array, a vyper style bounded dynamic array, and a full fixed array... But that'll probably take some time and some tests. This solves the answer for now, thanks! Commented Aug 4, 2022 at 20:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.