GithubHelp home page GithubHelp logo

forge-std's Introduction

Forge Standard Library • tests

Forge Standard Library is a collection of helpful contracts for use with forge and foundry. It leverages forge's cheatcodes to make writing tests easier and faster, while improving the UX of cheatcodes. For more in-depth usage examples checkout the tests.

Install

forge install brockelmore/forge-std

Contracts

stdError

This is a helper contract for errors and reverts in solidity. In forge, this contract is particularly helpful for the expectRevert cheatcode, as it provides all compiler builtin errors.

See the contract itself for all error codes.

Example usage

import "ds-test/test.sol";
import "forge-std/stdlib.sol";
import "forge-std/Vm.sol";

contract TestContract is DSTest, stdError {
    Vm public constant vm = Vm(HEVM_ADDRESS);

    ErrorsTest test;
    function setUp() public {
        test = new ErrorsTest();
    }

    function testExpectArithmetic() public {
        vm.expectRevert(stdError.arithmeticError);
        test.arithmeticError(10);
    }
}

contract ErrorsTest {
    function arithmeticError(uint256 a) public {
        uint256 a = a - 100;
    }
}

stdStorage

This is a rather large contract due to all of the overloading to make the UX decent. Primarly, it is a wrapper around the record and accesses cheatcodes. It can always find and write the storage slot(s) associated with a particular variable without knowing the storage layout. The one major caveat to this is while a slot can be found for packed storage variables, we can't write to that variable safely. If a user tries to write to a packed slot, the execution throws an error, unless it is uninitialized (bytes32(0)).

This works by recording all SLOADs and SSTOREs during a function call. If there is a single slot read or written to, it immediately returns the slot. Otherwise, behind the scenes, we iterate through and check each one (assuming the user passed in a depth parameter). If the variable is a struct, you can pass in a depth parameter which is basically the field depth.

I.e.:

struct T {
    // depth 0
    uint256 a;
    // depth 1
    uint256 b;
}

Example usage

import "ds-test/test.sol";
import "forge-std/stdlib.sol";
import "forge-std/Vm.sol";

contract TestContract is DSTest {
    using stdStorage for StdStorage;

    Vm public constant vm = Vm(HEVM_ADDRESS);

    Storage test;
    StdStorage stdstore;

    function setUp() public {
        test = new Storage();
    }

    function testFindExists() public {
        // Lets say we want to find the slot for the public
        // variable `exists`. We just pass in the function selector
        // to the `find` command
        uint256 slot = stdstore.target(address(test)).sig("exists()").find();
        assertEq(slot, 0);
    }

    function testWriteExists() public {
        // Lets say we want to write to the slot for the public
        // variable `exists`. We just pass in the function selector
        // to the `checked_write` command
        stdstore.target(address(test)).sig("exists()").checked_write(100);
        assertEq(test.exists(), 100);
    }

    // It supports arbitrary storage layouts, like assembly based storage locations
    function testFindHidden() public {
        // hidden is a random hash of a bytes, iteration through slots would
        // not find it. Our mechanism does
        // Also, you can use the selector instead of string
        uint256 slot = stdstore.target(address(test)).sig(test.hidden.selector).find();
        assertEq(slot, keccak256("my.random.var"));
    }

    // if targeting a mapping, you have to pass in the keys necessary to perform the find
    // i.e.:
    function testFindMapping() public {
        uint256 slot = stdstore
            .target(address(test))
            .sig(test.map_addr.selector)
            .with_key(address(this))
            .find();
        // in the `Storage` constructor, we wrote that this address' value was 1 in the map
        // so when we load the slot, we expect it to be 1
        assertEq(vm.load(slot), 1);
    }

    // If the target is a struct, you can specify the field depth:
    function testFindStruct() public {
        // NOTE: see the depth parameter - 0 means 0th field, 1 means 1st field, etc.
        uint256 slot_for_a_field = stdstore
            .target(address(test))
            .sig(test.basicStruct.selector)
            .depth(0)
            .find();

        uint256 slot_for_b_field = stdstore
            .target(address(test))
            .sig(test.basicStruct.selector)
            .depth(1)
            .find();

        assertEq(vm.load(slot_for_a_field), 1);
        assertEq(vm.load(slot_for_b_field), 2);
    }
}

// A complex storage contract
contract Storage {
    struct UnpackedStruct {
        uint256 a;
        uint256 b;
    }

    constructor() {
        map_addr[msg.sender] = 1;
    }

    uint256 public exists = 1;
    mapping(address => uint256) public map_addr;
    mapping(address => Packed) public map_packed;
    mapping(address => UnpackedStruct) public map_struct;
    mapping(address => mapping(address => uint256)) public deep_map;
    mapping(address => mapping(address => UnpackedStruct)) public deep_map_struct;
    UnpackedStruct public basicStruct = UnpackedStruct({
        a: 1,
        b: 2,
    });

    function hidden() public returns (bytes32 t) {
        // an extremely hidden storage slot
        bytes32 slot = keccak256("my.random.var");
        assembly {
            t := sload(slot)
        }
    }
}

The concepts above can be combined in intuitive ways. Here is a full list of functions provided for find - all checked_write concepts are the same and should exist as well:

  1. find: Finds flat data structures or shallow mappings
  2. find_struct: Same as above, but adds a depth input to specify the field depth
  3. find_multi_key: Finds deeply nested mappings, i.e. mapping(uint => mapping(uint => uint))
  4. find_multi_key_struct: Same as above, but adds a depth input to specify the field depth

With these 4 functions, you can find any slot (or write to it with their counterpart checked_write_*).

stdCheats

This is a wrapper over miscellaneous cheatcodes that need wrappers to be more dev friendly. Currently there are only function related to prank. In general, users may expect ETH to be put into an address on prank, but this is not the case for safety reasons. Explicitly this hoax function should only be used for address that have expected balances as it will get overwritten. If an address already has Eth, you should just use prank. If you want to change that balance explicitly, just use deal. If you want to do both, hoax is also right for you.

Example usage:

// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;

import "ds-test/test.sol";
import {stdCheats} from "../stdlib.sol";
import "../Vm.sol";

// Inherit the stdCheats
contract StdCheatsTest is DSTest, stdCheats {
    Vm public constant vm = Vm(HEVM_ADDRESS);

    Bar test;
    function setUp() public {
        test = new Bar();
    }

    function testHoax() public {
        // we call the hoax, which gives the target address
        // eth and then calls `prank`
        hoax(address(1337));
        test.bar{value: 100}(address(1337));

        // overloaded to allow you to specify how much eth to
        // initialize the addres with
        hoax(address(1337), 1);
        test.bar{value: 1}(address(1337));
    }

    function testStartHoax() public {
        // we call the startHoax, which gives the target address
        // eth and then calls `startPrank`
        //
        // it is also overloaded so that you can specify eth amount
        startHoax(address(1337));
        test.bar{value: 100}(address(1337));
        test.bar{value: 100}(address(1337));
        vm.stopPrank();
        test.bar(address(this));
    }
}

contract Bar {
    function bar(address expectedSender) public payable {
        require(msg.sender == expectedSender, "!prank");
    }
}

forge-std's People

Contributors

brockelmore avatar refcell avatar mds1 avatar rootulp avatar ncitron avatar zeroekkusu avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.