Smart Contract Testing Beyond Happy Paths: Fuzzing and Invariants
Examples prove that one scenario worked. Property-based tests probe accounting, access and state transitions across many scenarios before an audit has to explain why your assumptions failed.

A contract test suite with deposit, withdraw and owner-update examples can look complete while never exploring the state combinations that break accounting. Example tests are necessary. They are not the same as testing the rules that should hold after many different operations.
Fuzzing varies inputs. Invariant testing varies sequences of actions and checks properties across the resulting state. Both become useful when you can state the contract's intended rules precisely enough to turn them into assertions.
Write the accounting story first
Name the assets, liabilities and privileged actions. For a simple escrow, whose deposits count toward liabilities? Can surplus assets arrive directly? Are withdrawals immediate or queued? What happens when a recipient rejects payment?
A property such as "assets always equal liabilities" can be wrong if the system permits unsolicited transfers. A weaker inequality may be appropriate, or the accounting may need a separately recorded surplus. For a yield-bearing vault, exchange rates and rounding introduce different rules again.
Do not borrow invariants from another protocol without understanding its model. An assertion that always passes because it expresses nothing meaningful wastes runtime and creates false confidence.
Keep deterministic examples
Use ordinary tests for named behaviours: unauthorised withdrawals revert, paused deposits fail, and a zero amount follows the specified rule. Those make failures easy to understand and preserve a clear specification.
Then use fuzz tests for ranges and relationships. In this illustrative Foundry test, the contract is assumed to implement a simple escrow API with deposits and immediate withdrawals:
function testFuzz_DepositWithdraw(uint256 rawAmount) public {
uint256 amount = bound(rawAmount, 1, 100 ether);
address depositor = address(0xA11CE);
vm.deal(depositor, amount);
vm.startPrank(depositor);
escrow.deposit{value: amount}();
assertEq(escrow.credit(depositor), amount);
escrow.withdraw(amount);
vm.stopPrank();
assertEq(escrow.credit(depositor), 0);
assertEq(depositor.balance, amount);
}The escrow interface and setup are intentionally not included. Adapt the test to the actual implementation. This unit-test balance assertion does not model a user's real transaction fees.
Bound inputs deliberately and preserve separate boundary tests for zero, maximum permitted amounts and rounding edges. Excessive assume statements can discard so many cases that the fuzzer explores little useful territory.
Introduce a handler for sequences
For invariant testing, expose realistic actions through a handler: deposit, withdraw, transfer ownership if relevant, and pause or resume where permitted. Keep actor identities and preconditions explicit.
Track a ghost model of intended accounting independently from the contract's own internal variables. If the test merely compares two values derived from the same broken storage value, it may agree with the bug perfectly.
Restrict the targeted calls to the actions you intend to explore. Randomly invoking every method on every helper contract produces noise instead of useful coverage. Decide whether invalid calls should be expected to revert or treated as a failure of the handler's assumptions.
Test more than balances
| Property | Example question | |---|---| | Authorization | Can a non-owner alter privileged configuration? | | Conservation | Can withdrawals exceed recorded entitlement? | | State transitions | Can a completed operation happen again? | | Rounding | Does repeated small activity accumulate an advantage? | | Availability | Can one hostile recipient block unrelated users? |
Include adversarial actors. A receiver can re-enter, reject native payments or consume unusual amounts of gas. Tokens may return false, charge transfer fees or use nonstandard return behaviour. Define which assets your system supports rather than claiming compatibility with every token.
A passing test against a standard mock token does not establish correct behaviour against a fee-on-transfer token. Either implement and test support or explicitly reject unsupported behaviour.
Preserve failing cases
When the tool finds a failure, save the input or sequence as a deterministic regression test. A random seed can help reproduce a run, but tool versions and configuration changes can still affect exploration.
Read the minimal failure carefully. Was the contract wrong, the property wrong, or the handler performing an impossible operation? Fixing a test by weakening the assertion until it passes is not a diagnosis.
Record toolchain version, fuzz runs, sequence depth and any exclusions. A tiny local run and a long CI campaign do not offer the same exploration. Longer execution is useful only if the actions and properties describe the real system.
Combine with other evidence
Run static analysis, review external call ordering and examine storage layout for upgradeable contracts. Use fork tests when behaviour depends on deployed integrations, pinning the block and chain so the result is reproducible.
Fork tests inherit the state at the chosen block. They do not guarantee future integration behaviour or price conditions. Keep mocks for controlled failures and use forks for real interface assumptions.
An independent audit is still valuable. Give reviewers the invariant definitions and failure history; they explain what you believe the system should do and where that belief has already been challenged.
Make testing part of release approval
Run the core suite on each change and reserve deeper campaigns for scheduled or release checks. Do not bypass a flaky invariant by disabling it without documenting the unresolved question.
Review new privileged functions as new state transitions. Changing a fee calculation or withdrawal queue should trigger a review of the model, not just an update to one expected number.
The best invariant is a sentence a reviewer understands and an assertion the tool can falsify. If the system moves value, testing the accounting story across hostile sequences is far more useful than proving that your favourite demonstration still works.
Paj Digital Labs
The engineering journal of Paj Digital Solutions — hosting, server infrastructure and web engineering, written by the people who run the servers.
Related reading

Solana Transaction Operations: Blockhash Expiry, Commitments and Retries
A timed-out submission may still have landed. Track signatures, validity windows and commitment levels before rebuilding a transaction and risking a duplicate business action.

Blockchain Dependency Incidents: Circuit Breakers for RPC and Indexer Failures
A stale indexer and an unavailable RPC need different responses. Monitor data freshness, stop unsafe writes and preserve transaction tracking when chain infrastructure degrades.

ERC-4337 Account Abstraction: Bundlers, Paymasters and the Product Boundary
Smart accounts can improve recovery and transaction UX, but their dependencies need explicit limits. Understand user operations, sponsorship and deployed versions before treating gasless as free.