Format large values in Foundry for easier to read logs | Solidity Tip of the Week
If you’ve ever struggled with interpreting large values in your solidity tests, you’re not alone! With Foundry's latest update, you can now format logged values with the correct number of decimals using the %ne format specifier.
For example, when logging balances of addresses holding USDC (6 decimals) or WETH (18 decimals), setting to match the token’s decimals gives you a clear and easier way to read the logged balances:Foundry's latest update, you can now format logged values with the correct number of decimals using the %ne format specifier.
For example, when logging balances of addresses holding USDC (6 decimals) or WETH (18 decimals), setting to match the token’s decimals gives you a clear and easier way to read the logged balances:
1// SPDX-License-Identifier: MIT
2pragma solidity ^0.8.13;
3
4import {Test, console} from "./../lib/forge-std/src/Test.sol";
5import {IERC20} from "./../lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
6
7contract LogTest is Test {
8 address internal immutable USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
9 address internal immutable WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
10
11 address internal immutable USDC_WHALE = 0x37305B1cD40574E4C5Ce33f8e8306Be057fD7341;
12 address internal immutable WETH_WHALE = 0xF04a5cC80B1E94C69B48f5ee68a08CD2F09A7c3E;
13
14 function setUp() public {
15 vm.createSelectFork("https://eth.llamarpc.com");
16 }
17
18 function test_log_balances() public view {
19 uint256 usdcBalance = IERC20(USDC).balanceOf(USDC_WHALE);
20 uint256 wethBalance = IERC20(WETH).balanceOf(WETH_WHALE);
21
22 console.log("USDC balance :", usdcBalance);
23 console.log("WETH balance :", wethBalance);
24
25 console.log("USDC balance adjusted : %6e", usdcBalance);
26 console.log("WETH balance adjusted : %18e", wethBalance);
27 }
28}
With %ne format specifier you get the exact token amounts adjusted based on the decimals of the token, making your solidity tests easier to read and debug. Here's the output of the above Foundry test:
1forge test --mt test_log_balances -vvv
2[⠊] Compiling...
3[⠔] Compiling 1 files with Solc 0.8.28
4[⠒] Solc 0.8.28 finished in 430.95ms
5Compiler run successful!
6
7Ran 1 test for test/Test.t.sol:LogTest
8[PASS] test_log_balances() (gas: 25255)
9Logs:
10 USDC balance : 4824736539983005
11 WETH balance : 554216517563127004346971
12 USDC balance adjusted : 4824736539.983005
13 WETH balance adjusted : 554216.517563127004346971
14
15Suite result: ok. 1 passed; 0 failed; 0 skipped; finished in 2.32s (1.11s CPU time)
16
17Ran 1 test suite in 2.33s (2.32s CPU time): 1 tests passed, 0 failed, 0 skipped (1 total tests)