
Summary: Smart contract errors rarely occur in isolation. When
forge buildfails or a transaction reverts with an empty bytes payload, tracing the underlying failure requires a methodical diagnostic sequence. This guide indexes 25 high-frequency error states documented across the open-source imminer668/Solidity-Guide curriculum and production EVM deployments. Organized across a 5-stage diagnostic funnel—Environment, Compiler, Native Test Tracing, Low-Level ABI Calls, and Advanced Proxy/Governance systems—each entry details the observed symptom, root cause, and concrete resolution.
1. The 5-Stage Diagnostic Funnel
Systematic debugging: the five-stage diagnostic sequence for isolating smart contract faults.
When a contract fails to compile, test, or execute, troubleshooting should follow a structured sequence rather than trial-and-error edits:
1. ENVIRONMENT: Verify toolchain binaries, PATH bindings, and git submodules.
2. COMPILER: Resolve pragma bounds, SPDX licenses, visibility, and types.
3. TEST TRACE: Run forge test -vvvv to trace setUp reverts and cheatcodes.
4. CALL & ABI: Inspect low-level call return flags, whitespace, and decoders.
5. STORAGE & STATE: Use forge inspect storage-layout to debug proxy slots and nonces.
2. Environment & Toolchain Errors (Issues 1–4)
1. bash: forge: command not found
-
Symptom: Terminal returns command not found after running
foundryup. -
Root Cause: The
$HOME/.foundry/bindirectory is missing from the active shell environment’s$PATH. -
Fix: Add the following line to
~/.zshrcor~/.bashrc, then executesource ~/.zshrc:export PATH="$HOME/.foundry/bin:$PATH"
2. Error: Target directory is not empty
-
Symptom:
forge initreverts on existing workspaces. -
Root Cause: Forge defaults to initializing only inside empty directories.
-
Fix: Pass the
--no-commitflag or initialize into a specific subdirectory:forge init my_project --no-commit
3. Error: Could not find "forge-std/Test.sol"
-
Symptom: Contracts fail compilation with missing import errors for standard testing libraries.
-
Root Cause: The repository was cloned without pulling nested git submodules.
-
Fix: Initialize submodules recursively from the root directory:
git submodule update --init --recursive
4. Error: network does not exist (127.0.0.1:8545)
- Symptom:
forge scriptorcast callfails to reach the local testnet. - Root Cause: Anvil is either inactive or the RPC address omitted the
http://prefix. - Fix: Verify Anvil is running in a dedicated terminal and pass
--rpc-url http://127.0.0.1:8545.
3. Compilation & Syntax Errors (Issues 5–8)
5. Warning: SPDX license identifier not provided in source file
-
Symptom: Compiler emits warnings on every build.
-
Root Cause: Missing open-source license header on the first line.
-
Fix: Place an explicit identifier at the very top of each
.solfile:// SPDX-License-Identifier: MIT
6. Error: Visibility must be declared for function
- Symptom: Functions fail to compile with visibility errors.
- Root Cause: Modern Solidity requires explicit visibility modifiers (
external,public,internal,private) on every function to prevent accidental administrative exposure. - Fix: Declare
externalfor external interfaces orinternalfor helper routines.
7. Error: Function declared as pure, but reads state
- Symptom: Compilation fails on helper calculations.
- Root Cause: A function marked
pureaccessed state variables,block.timestamp, ormsg.sender. - Fix: Downgrade the modifier to
viewif reading state, or remove both if modifying storage.
8. Error: Type uint256 is not implicitly convertible to expected type uint128
-
Symptom: Variable assignments fail with implicit conversion errors.
-
Root Cause: Downcasting to smaller integer types requires explicit conversion to acknowledge truncation risks.
-
Fix: Explicitly cast the value after asserting bounds:
require(val <= type(uint128).max, "Overflow"); uint128 downcasted = uint128(val);
4. Foundry Test & Cheatcode Failures (Issues 9–12)
9. Error: setUp failed
- Symptom: The entire test contract fails before running any
test*functions. - Root Cause: An unhandled revert happened inside
setUp()—frequently due to constructor arguments, insufficient mock ETH, or missing deployer pranks. - Fix: Run
forge test -vvvv(quadruple verbosity) to view the full opcode trace and locate the reverting line.
10. vm.expectRevert() Did Not Catch the Revert
-
Symptom: The test fails with
FAIL: Expected a revert, but transaction succeeded. -
Root Cause:
vm.expectRevert()was placed after the function call or an internal helper consumed the revert. -
Fix: Place
vm.expectRevert()immediately before the transaction that triggers the failure:vm.expectRevert(InsufficientBalance.selector); bank.withdraw(100);
11. Custom Error Selector Mismatch
-
Symptom: Test fails with
FAIL: Custom error mismatch. -
Root Cause: The contract reverted with
CustomError(arg1)but the test expected parameterlessCustomError(). -
Fix: When asserting parameterized custom errors, encode the expected arguments:
vm.expectRevert(abi.encodeWithSelector(CustomError.selector, expectedArg));
12. Synthetic Balances vs. Production Reverts
- Symptom: A test passing with
vm.deal()fails when deployed to Anvil or testnet. - Root Cause:
vm.dealsynthetically injects ETH into an account without triggeringreceive()callbacks or checking contract liquidity. - Fix: Test real transfer paths using actual funding transactions in your deployment scripts.
5. Low-Level Calls & ABI Failures (Issues 13–16)
13. Transfer failed on .call{value:}
-
Symptom: Low-level ETH transfer reverts unexpectedly.
-
Root Cause: The recipient is a contract that lacks a
receive() external payableorfallback() external payablefunction. -
Fix: Verify the recipient contract implements a payable fallback handler:
receive() external payable {}
14. .call(abi.encodeWithSignature(...)) Silently Returns false
-
Symptom: Target function does not execute and returns
success = false. -
Root Cause: Whitespace inside the signature string alters the selector hash (e.g.
"setValue(uint256 )"does not match"setValue(uint256)"). -
Fix: Replace string signatures with type-safe
abi.encodeCall:bytes memory data = abi.encodeCall(Target.setValue, (100));
15. abi.decode Reverts Without Error Message
-
Symptom: Execution halts abruptly during ABI decoding.
-
Root Cause: The returned payload byte length or type ordering does not match the tuple signature.
-
Fix: Verify the return data size before decoding:
require(data.length >= 64, "Malformed return payload"); (uint256 a, address b) = abi.decode(data, (uint256, address));
16. Naive .transfer() Gas Limit Revert (2,300 Gas Trap)
- Symptom: Transfers to smart accounts or multi-sigs fail consistently.
- Root Cause:
.transfer()limits forwarded gas to 2,300. Istanbul raisedSLOADcosts, causing smart accounts to exceed this budget. - Fix: Replace
.transfer()with.call{value: amount}("")and verify the boolean return flag.
6. Upgradeable Proxies & Storage Collisions (Issues 17–20)
17. UUPS Proxy Permanent Upgrade Deadlock
-
Symptom: Upgrading to a new logic version permanently breaks future upgradeability.
-
Root Cause: The new implementation contract forgot to inherit
UUPSUpgradeableor omitted theupgradeToAndCall()function. -
Fix: Verify methods on the new implementation before broadcasting:
forge inspect <NewLogic> methods | grep upgrade
18. Transparent Proxy Admin Revert on Business Functions
- Symptom: The admin address calling business functions always reverts.
- Root Cause: By design, Transparent Proxies intercept all admin calls to prevent function selector clashing. Admins can only call administrative functions (
upgradeTo,changeAdmin). - Fix: Call business functions using non-admin accounts via
vm.prank(user).
19. Storage Slot Collision Across Logic Versions
-
Symptom: Upgrading to Logic V2 causes existing balances or owner addresses to scramble or read zero.
-
Root Cause: New state variables were inserted in the middle of V2 instead of appended to the end, shifting storage slot positions.
-
Fix: Use Forge’s storage inspection diff tool before deploying upgrades:
forge inspect LogicV1 storage-layout > v1.json forge inspect LogicV2 storage-layout > v2.json diff v1.json v2.json
20. Implementation Contract Initialization Hijacking
-
Symptom: A third party calls
initialize()directly on the implementation contract. -
Root Cause: The implementation contract constructor was left uninitialized.
-
Fix: Call
_disableInitializers()inside the implementation constructor:constructor() { _disableInitializers(); }
7. Signatures, DeFi & Cross-Chain Faults (Issues 21–25)
21. ecrecover Silent Zero-Address Bypass
- Symptom: Unauthorized signatures are accepted as valid.
- Root Cause: Malformed
(v, r, s)signatures causeecrecoverto returnaddress(0)instead of reverting. - Fix: Assert
require(signer != address(0))or use OpenZeppelin’sECDSA.recover().
22. Multisig ERR10007 Signature Validation Failure
-
Symptom: A multisig transaction with valid signatures reverts on submission.
-
Root Cause: Signatures were not sorted in strictly ascending order of owner address (
currentOwner > lastOwner). -
Fix: Sort signatures by recovered owner address before concatenating:
Sort: address(ownerA) < address(ownerB) < address(ownerC)
23. DEX Swap Returns Truncated Output (6 vs 18 Decimals)
- Symptom: Swapping USDC for WETH yields an output near zero.
- Root Cause: Assuming all tokens use 18 decimals causes mathematical misalignments when interacting with 6-decimal tokens like USDC.
- Fix: Query
IERC20Metadata.decimals()dynamically and normalize integer scales.
24. Chainlink VRF fulfillRandomWords Revert (Out of Gas)
- Symptom: Oracle fulfillment transaction fails, leaving random requests unresolved.
- Root Cause: Business logic inside the VRF callback exceeded the
callbackGasLimit. - Fix: Store the random word into state during the callback and process game logic in a separate user transaction.
25. Cross-Chain Bridge Collateral Imbalance
- Symptom: Total wrapped tokens on destination networks exceed collateral in the source vault.
- Root Cause: Relayers processed unfinalized source transactions that were subsequently reorged.
- Fix: Enforce source chain block finality windows and track transaction hashes to prevent message replays.
8. Connecting Diagnostics to Production Architectures
Solving isolated bugs in Foundry is the foundation of smart contract engineering. In commercial software, these failure modes are mitigated by layered architectural patterns.
In production software built at Fone (0xF1): – Agent Wallet Guard (中文版): Uses EIP-712 structured envelopes and custom error selectors to isolate AI agents from malformed calldata and prevent budget race conditions. – StableIn Payments (中文版): Employs SafeERC20 wrappers and raw integer arithmetic across multi-chain USDC checkouts to prevent non-standard token failures. – Passage Bridge (中文版): Implements independent message review and finality confirmation windows to eliminate cross-chain replay vulnerabilities.
Review full systems on the Fone Products Center (中文版) or review technical notes on Fone Insights.
High-Frequency Solidity & Foundry Error Quick-Diagnosis Matrix
| Error Category | Observed Terminal / Revert Symptom | Root Technical Cause | Immediate Resolution Command / Code Fix |
|---|---|---|---|
| Foundry Build | Error: Could not find "forge-std/Test.sol" |
Missing nested git submodules in lib/ |
git submodule update --init --recursive |
| Foundry Test | FAIL: call did not revert as expected |
vm.expectRevert() placed before a helper call instead of target call |
Place vm.expectRevert(Err.selector) immediately above the reverting line |
| Low-Level Call | call(abi.encodeWithSignature(...)) returns false |
Whitespace or uint alias inside signature string alters 4-byte hash |
Replace with compile-time checked abi.encodeCall(ITarget.fn, (arg)) |
| ERC20 Mainnet | Transaction reverts with empty data on USDT transfer |
Mainnet USDT omits returns (bool), failing Solidity 0.8+ 32-byte check |
Use OpenZeppelin SafeERC20.safeTransfer(token, to, amount) |
| Proxy Upgrade | Variables read 0 or garbage after V2 upgrade |
New state variable inserted above existing variables in V2 | Run forge inspect V1 storage-layout diff; strictly append new variables |
| Multisig Auth | ECDSA: invalid signature or duplicate owner revert |
Concatenated (r, s, v) signatures not sorted by signer address |
Sort signatures off-chain in ascending order: uint160(signerA) < uint160(signerB) |
Verify It Locally with Foundry
Every contract and test pattern covered in this guide is runnable directly from the open-source imminer668/Solidity-Guide repository (foundry_projects/10_upgrade_governance/47_UUPS):
# 1. Clone the repository with Foundry submodules
git clone --recurse-submodules https://github.com/imminer668/Solidity-Guide.git
cd Solidity-Guide
# 2. Run the verified Foundry test suite for this module
cd foundry_projects/10_upgrade_governance/47_UUPS && forge test -vvvv
Expected local verification output:
[PASS] test_UpgradeToV2() (gas: 164210)
Suite result: ok. 1 passed; 0 failed; 0 skipped
Frequently Asked Questions (Technical FAQ)
How do I decode a raw 4-byte custom error hex string like 0xe450d38c returned by an RPC node?
Run cast 4byte 0xe450d38c in your terminal (which resolves to ERC20InsufficientBalance(address,uint256,uint256)), or run forge inspect <ContractName> errors to list every custom error selector compiled into your contract.
Why does vm.prank(alice) fail to change msg.sender when I call an internal helper function first?
vm.prank only overrides msg.sender for the next external call (CALL or DELEGATECALL opcode). Internal Solidity function calls (JUMP) do not create a new EVM call frame. If your test calls multiple external methods, wrap them in vm.startPrank(alice) and vm.stopPrank().
How can I reproduce a mainnet transaction revert locally in Foundry?
Pass the mainnet RPC URL and block number to forge test --fork-url <RPC_URL> --fork-block-number <BLOCK> -vvvv, or replay the exact transaction hash using cast run <TX_HASH> --rpc-url <RPC_URL> --trace-printer.
Series & Related Engineering Guides
- Foundational Curriculum (S01): Foundry Fast-Track: Compiling, Testing, and Scripting Your First Solidity Smart Contract
- Foundational Curriculum (S05): Low-Level EVM Calls in Solidity: ETH Transfers, Call vs. Delegatecall, and ABI Selectors
- Foundational Curriculum (S15): Production Governance & Cross-Chain in Solidity: Proxy Upgrades (Transparent vs. UUPS), Multisig, VRF, and Bridges
- Companion Deep-Dive (T08): The Practical Foundry Testing Cheat Sheet: Mastering vm.prank, expectRevert, vm.sign, and Time Manipulation
- Production Engineering Case Study: Free Release Review Checklist
- Open-Source Codebase: imminer668/Solidity-Guide (
foundry_projects/10_upgrade_governance/47_UUPS) - Commercial Platforms & Advisory: Fone Products Center (中文版) | Fone Services | Contact Engineering