Published on

Retroactively Updating Dependent Solidity Code

Authors

Yesterday I spoke about how important it is to add error messages to requires in Solidity. One thing that is frustrating is if a library you are using does not do this. For example pretend I have the following code in a truffle project:

import "openzeppelin-solidity/contracts/math/SafeMath.sol";
...
uint256 foo = blah.sub(2);
...

In SafeMath.sol sub looks as follows:

    /**
     * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b <= a);
        uint256 c = a - b;

        return c;
    }

OpenZeppelin is an excellent library but for some reason they never have messages in their requires. One workaround for this while deving is in your truffle project find the node_modules folder and find the contracts under there. In those contracts add error messages to help you in your debugging. For example with the SafeMath.sol case I found it under: truffleProjectRoot/node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol

I simply went in there and updated sub as follows:

    /**
     * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b <= a, "sub - b<=a which will result in a negative number for uint");
        uint256 c = a - b;

        return c;
    }

I then removed my build directory and redeployed my contracts to Ganache. I could now see the require message I added being hit in the one piece of code I was having trouble with :). This helped significantly guide my debugging efforts. This approach is very hacky as updating your node_modules will wipe this change out but it is still another approach that can be used to assist in debugging Solidity code on Ganache. Openzeppelin is aware of this issue and it looks like they will add require messages to the library in a future release.