Compiling Contracts with the Huff Compiler

NOTE: Installing the Huff Compiler is a prerequisite for compiling contracts. See installing to install hnc.

Below we outline the few steps it takes to compile a Huff contract.

1. Create a file called addTwo.huff and enter the following:

#define function addTwo(uint256,uint256) view returns(uint256)

#define macro MAIN() = takes(0) returns(0) {

    // Get the function selector
    0x00
    calldataload
    0xE0
    shr

    // Jump to the implementation of the ADD_TWO function if the calldata matches the function selector
    __FUNC_SIG(addTwo) eq addTwo jumpi

    addTwo:
        ADD_TWO()
}

#define macro ADD_TWO() = takes(0) returns(0) {
    0x04 calldataload     // load first 32 bytes onto the stack - number 1
    0x24 calldataload     // load second 32 bytes onto the stack - number 2
    add                   // add number 1 and 2 and put the result onto the stack

    0x00 mstore           // place the result in memory
    0x20 0x00 return      // return the result
}

2. Use hnc to compile the contract and output bytecode:

hnc addTwo.huff --bytecode

This will output something similar to:

600c8060093d393df35f35602035015f5260205ff3

You can find an in-depth explanation of this contract in The Basics tutorial.