Huff Challenge #1

I recently got to know about a new programming language called Huff. Huff is a low-level programming language to write EVM smartcontracts directly in opcodes. With Huff one can write more optimised smartcontracts as It doesn’t abstract anything from the devs and gives complete control over the stack.

I’m learning huff to get to know more about the EVM.

Huff’s official Twitter has recently started posting challenges. I’ll try to solve them and document it here :).

Challenge #1

Huff Challenge #1
Huff Challenge #1

As the challenge description says, the target is to write as little huff code as possible to return the current block number.

Solution

#define macro MAIN() = takes(0) returns(0) {
  number              //[blockNumber]
  0x00                //[0x00, blockNumber]
  mstore              //saves blockNumber to mem offset 0x00
                      //[]

  0x20                //[0x20]
  0x00                //[0x00]
  return              //returns 
}

Huff code always starts from the MAIN() macro.

takes(0) returns(0) means that this macro doesn’t take any data from the stack and doesn’t push any data to the stack upon completion.

The following snippet gets the blockNumber and saves it to memory at offset 0.

number
0x00
mstore

First, the NUMBER opcode is executed, which pushes the current block number to the stack.

Our target is to return the block number. To return any data, we need to use the RETURN opcode. The RETURN opcodes takes input from the memory, so the block number should be stored in the memory.

Followed by NUMBER is, 0x00 which pushes 0 to the stack. So the stack looks like [0x00, blockNumber].

MSTORE opcode stores the input(block number) to the memory. It takes 2 args,

  1. The memory offset,
  2. The data to store.

Here, 0x00 is the memory offset and blockNumber is the data. The BlockNumber is saved to the memory at offset 0.

As mentioned before, The RETURN opcode is used to return the data.

0x20 
0x00 
return

RETURN takes 2 inputs,

  1. The memory offset to start reading from,
  2. The size in bytes.

First, the byte size 0x20(32 bytes) is pushed into the stack. Followed by the memory offset 0x00.

The stack now looks like, [0x00, 0x20]

The RETURN opcode is then pushed to the stack, which reads 32 bytes**(0x20)** starting from the memory offset 0 and returns it.

Subscribe to Seshanth
Receive the latest updates directly to your inbox.
Mint this entry as an NFT to add it to your collection.
Verification
This entry has been permanently stored onchain and signed by its creator.