safeconsole
safeconsole copied to clipboard
Foundry Memory-Preserving Logging Library
The safeconsole library provides a foundry/hardhat-like console logging interface whereby
the individual log functions do not modify the state of memory. This is important for
debugging low-level assembly that may touch on and rely on the free memory pointer and the
consistent state of memory beyond the free memory pointer. To ensure that the Solidity compiler does
not allocate any memory unexpectedly the safeconsole.log functions accept bytes32 arguments instead
of strings as they are kept on the stack. This means that the string part of log messages will
have to be resricted to 32-character chunks.
logMemory
Besides the standard logging functions that can take various combinations of up to 4 bytes32,
bool, address and uint256 arguments safeconsole also has a logMemory(uint256 offset, uint256 length)
function that allows you to log a chunk of memory without modifying the state of memory:
assembly {
mstore(0x00, 1)
mstore(0x20, 2)
}
safeconsole.logMemory(0x00, 0x40);
// > 0x00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002
Installation
Foundry
- Install the library
forge install philogy/safeconsole --no-commit
- Just import the lib and use:
Example:
import {safeconsole} from "safeconsole/safeconsole.sol";
// Some example uses
safeconsole.log("My number: %d", 34);
safeconsole.log("Caller: %s", msg.sender);
safeconsole.log("Where in loop %d-%d", i, j);
Hardhat
- Install Foundry (I mean come on it's 2023)
- Check Foundry installation instructions
Truffle
Lmao ngmi. (Jk just install Hardhat and then check Hardhat installation instructions)
Caveats
- certain
safeconsole.logfunctions will increasemsize, no function will modifymsizeif it's already larger than0x1a0 safeconsole.logwill treat allbytes32arguments as strings and truncate them at their first0x00-byte (.e.ghex"6162630064"will result in the string"abc"of length 3)safeconsole.logMemorywill increasemsizeif theoffsetargument is below0x60