Incorrect Comparison
Detects comparison operators that are likely wrong — using = instead of ==, > instead of >=, or comparing incompatible types.
Incorrect Comparison
Overview
The incorrect comparison detector identifies comparison operations that appear to use the wrong operator. Common patterns include off-by-one errors in boundary checks (> where >= was intended), boolean assignment instead of comparison (in languages that compile to EVM), and comparisons between values of incompatible types or scales (e.g., comparing a wei amount against an ether-scale constant).
Why This Is an Issue
A single wrong comparison operator can bypass access control (> instead of >= allows the boundary value through), break accounting (off-by-one in balance checks), or create exploitable edge cases. These bugs are subtle because they produce correct results for most inputs and only fail at boundary values — making them difficult to catch in testing but easy to exploit.
How to Resolve
// Before: Off-by-one — allows withdrawal of exact balance
function withdraw(uint256 amount) external {
require(amount < balances[msg.sender], "Insufficient"); // Bug: should be <=
balances[msg.sender] -= amount;
payable(msg.sender).transfer(amount);
}
// After: Fixed — correct boundary
function withdraw(uint256 amount) external {
require(amount <= balances[msg.sender], "Insufficient");
balances[msg.sender] -= amount;
payable(msg.sender).transfer(amount);
}
Detection Methodology
- Comparison extraction: Identifies LT, GT, SLT, SGT, EQ operations and their operands.
- Boundary pattern matching: Checks for common off-by-one patterns (e.g.,
length - 1compared with<instead of<=). - Scale mismatch detection: Identifies comparisons where operands differ by orders of magnitude (e.g., wei vs. ether scale).
- Context analysis: Examines whether the comparison guards a subtraction, array access, or other operation where off-by-one matters.
Limitations
False positives: Strict inequalities that are intentionally exclusive (e.g., < to exclude the boundary value) may be flagged as potential off-by-one errors. False negatives: Custom comparison logic (e.g., comparing via subtraction and sign check) may not be detected.
Related Detectors
- Tautological Compare — detects always-true/false comparisons
- Off-by-One — detects array/loop boundary errors