Mental model
A smart contract security review should treat every external call as a control transfer and every privileged operation as an explicit trust boundary. Checks-effects-interactions orders validation and state updates before callbacks, while role design, replay-safe wallet validation, and invariant-driven tests protect the wider system. On Ethereum, correct behavior means observers can derive the same state transition from the transaction and versioned code.
Theory
An Ethereum transaction executes atomically: its state changes commit together, or a revert discards them. Atomicity does not mean a contract runs alone. An external call, token hook, plugin, or wallet module can execute arbitrary code before the caller resumes. That callback may call the original contract again, query another protocol in a temporarily inconsistent state, or exploit an assumption shared by two contracts.
For a withdrawal, checks-effects-interactions (CEI) makes the sequence explicit. First, check the caller's claim and the requested amount. Second, reduce the caller's credit and the contract's liability. Third, send Ether to the recipient. If the recipient reenters during the third step, it sees the reduced credit. If the send fails and the function reverts, Ethereum rolls the earlier writes back with the transaction. Solidity's security guidance recommends this order because an external function call gives control to its receiver; OpenZeppelin's ReentrancyGuard can add a separate nested-call barrier around sensitive entry points.
Neither CEI nor a guard proves the whole application safe. A callback can enter a different function that reads the same temporarily inconsistent state. A view call can expose a transient price or balance to another protocol. Token hooks, cross-contract accounting, and upgrade modules create additional paths. Protect related entry points, keep checks and effects local where possible, and test invariants across a malicious receiver rather than assuming one modifier closes every path.
Access control is another state machine. A role answers who may call an operation; it does not prove the operation is safe. Separate emergency pause authority from role administration and upgrade authority. Use a multisignature account or a timelock for high-impact changes, emit role-change events, and exercise grant, revoke, pause, and recovery paths in tests. A proxy adds a code boundary: DELEGATECALL runs implementation code against the proxy's storage. Upgrades must preserve storage layout, initialize each proxy exactly once, and restrict the upgrade hook to deliberate governance.
Wallets also have explicit validation stages. An externally owned account signs a transaction; an ERC-4337 smart account validates a UserOperation through an EntryPoint flow and then executes account logic. The account verifies its signature policy over a userOpHash that is bound to the EntryPoint and chain. The EntryPoint enforces the operation nonce, preventing replay of an already accepted operation. Bundlers and paymasters are separate trust boundaries: a paymaster can sponsor gas, but the account still decides which call and value its signer authorized. Safe smart accounts add configurable owners and thresholds, so review the installed modules and guards as part of the wallet's authority surface.
Worked invariant
For a pull-payment vault, let be the contract balance in wei and the withdrawal credit owed to account , also in wei. The solvency invariant is:
Here, is total outstanding liability in wei and is the set of credited accounts. A deposit of wei increases both and by . A successful withdrawal of wei reduces both by , so the margin stays constant. An external forced transfer can increase without increasing ; it creates surplus and does not justify paying any account more than its recorded credit.
Suppose the vault holds 10 ETH and records 8.75 ETH of credits. Alice owns 2.4 ETH of that liability and requests 0.7 ETH. After the effects step, the expected values are ETH and ETH; the 1.25 ETH surplus is unchanged. Since 1 ETH is wei, an invariant test can compare exact integer balances rather than rounded display values. Fuzz deposits and withdrawals across several accounts, and assert that every completed sequence preserves address(vault).balance >= totalLiabilities.
Failure modes and misconceptions
A reentrancy guard makes ordering irrelevant. The guard blocks nested calls only on the guarded entry points. Another function may remain callable, and a view callback can still observe a transient value. Keep CEI and assert shared invariants before adding the modifier.
An admin role is just deployment plumbing. A compromised role can pause withdrawals, grant itself access, or change an implementation. Put administration behind a reviewed multisig or timelock, monitor role changes, and test the recovery path before funds depend on it.
A valid wallet signature authorizes any call. The signed operation must bind the sender, target call, value, nonce, chain, and EntryPoint context under the account's policy. Replaying a signature against a different chain or account, or accepting a module that bypasses the threshold, invalidates that assumption.
A passing unit test covers the callback surface. A benign receiver will not exercise reentrancy. Include a receiver that calls back, an ERC-777-style hook where relevant, a failing recipient, and cross-function paths. For proxies, run upgrade tests against populated storage and verify the deployed implementation and initializer state.
Trade-offs
CEI often costs little runtime overhead and makes the state transition easier to audit, but it can be difficult when a protocol needs an external result before its final accounting decision. In that case, stage the operation, bind it to a nonce or pending record, and define what happens if settlement is delayed. ReentrancyGuard adds storage reads and writes and may constrain which guarded functions can call one another. A pause mechanism limits some damage but can also delay legitimate withdrawals; scope it narrowly and document who can resume service.
Proxy upgrades let a protocol correct bugs without migrating every user, while adding governance, storage-layout, and implementation-authenticity risks. Immutable deployments reduce that upgrade surface but make recovery harder. Smart accounts improve signing flexibility and can support recovery or sponsorship; each module, validator, and paymaster adds code that must be reviewed. Choose the smallest authority surface that meets the product's recovery requirements, then measure gas and test the complete transaction path on the target network.
Decision scenario
A vault's auditor finds that withdraw sends Ether before reducing the user's credit. The team also plans to install a new smart-account module and upgrade a proxy tomorrow. Pause new deposits, keep the withdrawal path disabled until CEI and malicious-receiver tests pass, and review the module's signer and call scope. Exercise the upgrade against a fork with populated storage, verify the implementation and initializer state, and schedule the change through the documented multisig or timelock process. A green audit report cannot replace those state-transition and authority checks.
Implementation example
This non-upgradeable pull vault demonstrates CEI, a non-reentrancy guard, and separate pauser and administrator roles using OpenZeppelin Contracts 5.x. A production deployment should assign administration to reviewed governance and test the pause, failed-send, and malicious-recipient cases.
solidity// SPDX-License-Identifier: MITpragma solidity ^0.8.24;import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";contract PullVault is AccessControl, Pausable, ReentrancyGuard {bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");mapping(address => uint256) public credit;uint256 public totalLiabilities;event Deposited(address indexed account, uint256 amount);event Withdrawn(address indexed account, uint256 amount);constructor(address admin, address pauser) {require(admin != address(0) && pauser != address(0), "zero role address");_grantRole(DEFAULT_ADMIN_ROLE, admin);_grantRole(PAUSER_ROLE, pauser);}function deposit() external payable whenNotPaused {require(msg.value > 0, "zero deposit");credit[msg.sender] += msg.value;totalLiabilities += msg.value;emit Deposited(msg.sender, msg.value);}function withdraw(uint256 amount) external whenNotPaused nonReentrant {require(amount > 0 && amount <= credit[msg.sender], "invalid amount");credit[msg.sender] -= amount;totalLiabilities -= amount;(bool sent, ) = payable(msg.sender).call{value: amount}("");require(sent, "transfer failed");emit Withdrawn(msg.sender, amount);}function pause() external onlyRole(PAUSER_ROLE) {_pause();}function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) {_unpause();}}
Learning outcomes
- Trace an external callback through checks-effects-interactions and explain how a revert restores the transaction's prior state.
- Calculate the vault solvency margin and write a property test that checks liabilities across deposits and withdrawals.
- Distinguish contract roles, proxy upgrade authority, and ERC-4337 account validation responsibilities.
- Design reentrancy, signature replay, role-change, and upgrade tests for the trust boundaries in a wallet-backed application.