Complete Technical Paper Content — Integer Overflow Vulnerability Detector In Solidity Contracts
Overview & System Context
Integer Overflow Vulnerability Detector In Solidity Contracts: Comprehensive Web-Sourced Technical Investigation Exhaustive Research Dossier · Pure Web-Scraped Content: ~7656 Words · Real Software Screenshots: 3 1. Executive Overview & Technical Background Integer overflow and underflow describe situations where arithmetic operations produce values outside the representable range of the operand type. In Solidity 0.8+, arithmetic is checked by default and reverts on overflow/underflow. However, explicit unchecked blocks, assembly, or custom libraries can disable these checks. On non-EVM platforms (e.g., Move, Sui, Solana, Rust-based chains), default overflow semantics differ—some wrap silently, some abort—and incorrect assumptions or flawed custom checks can lead to wrapped values, miscomputed balances, and broken invariants.
This affects all contract types that perform arithmetic: DeFi (pool invariants, balances, interest, shares), NFTs (supply, token IDs), bridges (amounts, sequence numbers), and any logic involving large or user-controlled numeric inputs. The impact is especially severe when overflow/underflow breaks economic invariants (e.g., k = x * y in AMMs) or enables balance manipulation.
In Solidity versions before 0.8.0 , arithmetic overflow and underflow occurred silently —no revert, no error. Values wrapped around (e.g., uint8 255 + 1 = 0). Solidity 0.8.0+ fixes this by default; overflow/underflow reverts unless explicitly wrapped in unchecked . Key takeaway: Solidity 0.8.0+ provides built-in overflow/underflow checks. Use unchecked only when you have strong guarantees; otherwise prefer checked arithmetic.
Figure 1: Integer Overflow en Solidity | Operating systems, scripting, PowerShell ... On May 22, 2025 , Cetus Protocol (largest DEX on Sui) lost ~$223M due to a flawed overflow check in the integer-mate library. In Move , addition and multiplication abort on overflow, but left shift ( << ) does NOT abort —it truncates silently. The protocol used a custom checked_shlw to guard a << 64 shift; the guard was wrong.
Root cause: checked_shlw in math_u256.move used an incorrect threshold. It should reject values with any non-zero bits in the top 64 bits (i.e., n >= 1 << 192 ). The implementation used n > (0xFFFFFFFFFFFFFFFF << 192) instead, which is wrong and allowed values ≥ 2^192 to pass, then overflow on n << 64 . Where it was used: The CLMM function get_delta_a in clmm_math.move computed token A required for a liquidity position. It called: With liquidity ≈ 2^113 and sqrt_price_diff ≈ 2^79 , the product was ≈ 2^192 + ε . The flawed checked_shlw allowed it through; n << 64 overflowed and truncated to a tiny value. The protocol then computed that only 1 unit of token A was needed to mint massive liquidity (~10^37 units), enabling the drain.
Figure 2: Ethereum Smart Contracts Vulnerabilities: Integer Overflow and ... Attack flow (simplified): Flash swap → open narrow tick position → call add_liquidity with crafted liquidity parameter → undercharged (1 token) while credited huge liquidity → remove liquidity → drain pools → repay flash swap. Even on Solidity 0.8+, unchecked disables checks. Use only when overflow/underflow is provably impossible: Avoid unchecked for user-controlled or unbounded inputs unless you have formal reasoning or tests proving safety.
Cetus Protocol on Sui was exploited via a flawed checked_shlw in the shared integer-mate library. The function was meant to prevent u256 overflow when shifting left by 64 bits during CLMM liquidity calculations. The overflow check used the wrong threshold ( 0xFFFFFFFFFFFFFFFF << 192 instead of 1 << 192 ), allowing values ≥ 2^192 to pass. In Move, left shift does not abort on overflow—it truncates. The truncated numerator caused get_delta_a to return that only 1 token was required to mint enormous liquidity. Attackers repeated this across pools using flash swaps, draining ~$223M. Key lessons: (1) Move shift operations do not abort on overflow; (2) custom overflow guards must be rigorously verified; (3) shared math libraries are high-risk and need formal analysis.
- https://dedaub.com/blog/the-cetus-amm-200m-hack-how-a-flawed-overflow-check-led-to-catastrophic-loss/ - https://www.cyfrin.io/blog/inside-the-223m-cetus-exploit-root-cause-and-impact-analysis - https://www.halborn.com/blog/post/explained-the-cetus-hack-may-2025 - https://blog.verichains.io/p/cetus-protocol-hacked-analysis Figure 3: Ethereum Smart Contracts Vulnerabilities: Integer Overflow and ...
This content is in the version-(v1.0) and still under active development, so it is subject to change any time (e.g. structure, IDs, content, URLs, etc.). Integer overflows and underflows occur when arithmetic operations exceed the bounds of the integer data type, causing the value to "wrap around" to an unexpected number.
Integer overflow and underflow attacks have drained over $1 billion from Decentralized Finance (DeFi) protocols and web3 projects. In April 2018, a single line of vulnerable code allowed hackers to mint infinite tokens out of thin air - crashing exchanges and wiping out entire projects overnight. Solidity developers and auditors need to understand how bounded integers behave, especially in legacy code and modern unchecked blocks.
This guide explains integer wrapping, the BatchOverflow bug, vulnerable Solidity patterns, and current prevention and testing techniques. An integer overflow or underflow attack occurs when an arithmetic operation produces a value that exceeds the storage capacity of the data type (like a uint256 ), causing an unexpected "wrapping" behavior that attackers can aggressively exploit.
Overflow: When a calculation exceeds the maximum allowed value, the number "wraps around" back to zero. Underflow: When it drops below zero (for unsigned integers), it wraps back around to the maximum possible value. In smart contracts, unexpected wrapping can let users bypass balance checks, manipulate time locks, or interfere with access control logic.
When it reaches 999,999 miles and you drive one more mile, it doesn't show 1,000,000 - it wraps around to 000,000. Now it looks like a brand-new car with zero miles. That is exactly what integer overflow does. A uint8 variable holding 255 plus 1 doesn't become 256, it wraps to 0. Underflow is the reverse: subtracting 1 from 0 wraps to the maximum value, 255 for a uint8 . Picture the same odometer rolling backward from 000,000 to 999,999.
Before Solidity 0.8.0, every arithmetic operation was a potential exploit vector. Developers had to protect each calculation by hand, and missing one was enough. Overflow attacks were dangerous because they were silent, not because they were complicated. In pre-0.8.0 Solidity versions, arithmetic overflows didn't throw errors or revert transactions. The math simply wrapped around, and the code kept chugging along as if everything was perfectly normal.
Before Solidity 0.8.0, these operations produced no warning or revert unless the contract added its own checks. The BatchOverflow bug demonstrated how unchecked multiplication could invalidate a balance check. A single line of unprotected multiplication allowed attackers to mint unlimited tokens from thin air. The attacker broke no rule the contract enforced. They used the code exactly as written, which is the whole problem with "code is law" when the code is wrong.
BatchOverflow helped demonstrate the need for checked arithmetic by default, which Solidity introduced in version 0.8.0. Two years later, Solidity 0.8.0 finally shipped with built-in overflow protection - making this entire class of vulnerabilities significantly harder to execute. Legacy contracts still use older compiler behavior, and modern code can reintroduce wrapping through unchecked blocks or low-level arithmetic.
The Smart Contract Hacking course includes a hands-on module on arithmetic overflows and underflows, with exercises that reproduce the vulnerable behavior locally. Every overflow bug starts with a type whose range is smaller than the values a caller can reach, so the type table below is where an audit begins.
The attacker deposits 1 ETH into the time-locked contract. Their funds are locked for 1 week: lockTime = now + 1 week . The attacker computes: MAX_UINT - lockTime + 1 . This is the exact value needed to make lockTime wrap around to zero when added. Call increaseLockTime(overflowValue) . The addition overflows, wrapping lockTime to 0 . The 1-week lock is instantly bypassed.
Call withdraw() . The check now > 0 passes easily. Funds are withdrawn without waiting a single second. The pragma line therefore decides the verdict. The same source that is safe under 0.8.0 is exploitable when compiled with 0.7.6, so read the version before you read the arithmetic. Time lock bypass. Overflow time calculations to reset lock periods to zero or past dates.
Access control bypass. Underflow counters to bypass rate limits or authentication checks. Reward calculation exploits. Overflow multiplication in staking rewards to drain protocol treasuries. 2. System Architecture & Core Working Principles This contract demonstrates a classic time lock vulnerability exploitable through integer overflow.
The math: if lockTime = 1,700,000,000 and the attacker adds type(uint256).max - 1,700,000,000 + 1 , the result wraps to 0. Here's how an attacker exploits the vulnerable contract to instantly withdraw locked funds. Note that all six steps run inside one transaction. The attacker never waits out any part of the lock. Three layers matter here, in this order: the compiler version, the arithmetic you opt out of, and the bounds your business logic enforces regardless.
What it does: Built-in overflow/underflow protection that automatically reverts on wrap-around. No library imports needed. When to use: New Solidity contracts should use checked arithmetic unless a bounded invariant justifies an unchecked operation. Limitation: Can be bypassed with unchecked blocks. Legacy contracts still use pre-0.8.0.
What it does: OpenZeppelin library that wraps arithmetic operations with overflow checks using .add() , .sub() , .mul() . When to use: Any pre-0.8.0 contract that cannot be upgraded. Essential for legacy code. Limitation: Higher gas costs. Developers must remember to use SafeMath for every operation - miss one and you're vulnerable.
What it does: Adds meaningful constraints like MAX_LOCK_EXTENSION = 365 days to prevent unreasonable values. When to use: Always, as an additional layer even with 0.8.0+ protection. Defense in depth. Limitation: Doesn't protect against overflow directly - complements compiler protection by constraining inputs. Solidity 0.8+ allows disabling overflow protection for gas optimization. Use it with extreme caution: The following example combines checked arithmetic with business-level bounds. Adapt the limits and test protocol invariants before production use.
Applied to batchTransfer , the same two controls (checked multiplication plus a bound on the per-call amount) would have stopped the BatchOverflow mint at the first arithmetic step. Understanding both approaches is essential for auditing contracts across different compiler versions. For new contracts, use Solidity 0.8+. SafeMath is worth knowing anyway, because you will meet it in legacy code under audit.
Arithmetic wraps silently. No warnings, no reverts. Every calculation is an exploit vector. This is how the BatchOverflow bug created $1B in fake tokens. SafeMath library catches overflows but requires explicit use for every operation. Higher gas costs and verbose syntax. Miss one call and you're exposed.
Built-in overflow protection by default. Lower gas costs than SafeMath. Clean native syntax. Only disabled explicitly via unchecked blocks. While Solidity 0.8+ checks arithmetic by default, oracle manipulation attacks can still supply unexpectedly large values. Validate oracle data before using it in arithmetic operations.
Overflow vulnerabilities also relate to flash loan attacks , where large temporary balances can reach arithmetic edge cases in reward calculations, fee computations, or share-price formulas. Developers can disable protection using unchecked blocks for gas optimization. Any arithmetic inside unchecked with user-supplied values reintroduces the vulnerability.
Solidity 0.8+ has built-in overflow protection that's more gas-efficient than SafeMath. However, understanding SafeMath remains important for auditing legacy contracts. Billions of dollars remain locked in legacy contracts compiled with pre-0.8.0 Solidity. Plus, unchecked blocks in modern contracts can reintroduce vulnerabilities.
Multiplication overflow is actually the most dangerous - it grows exponentially faster. The BatchOverflow bug used 2 * 2^255 (multiplication) to create $1B in fake tokens. An integer overflow attack exploits the fact that numbers have maximum values. When you exceed that maximum, the number "wraps around" to zero - like an odometer rolling over. Attackers use this to bypass security checks, mint unlimited tokens, or withdraw locked funds.
No. Solidity 0.8+ has built-in overflow protection that's more gas-efficient than SafeMath. However, understanding SafeMath is still important for auditing older contracts and understanding why unchecked blocks are dangerous. Yes - if developers use unchecked blocks incorrectly. The built-in protection can be disabled for gas optimization, reintroducing vulnerabilities. Also, billions of dollars remain locked in legacy pre-0.8.0 contracts.
Overflow: Adding past the maximum wraps to zero (255 + 1 = 0). Underflow: Subtracting past zero wraps to maximum (0 - 1 = 255). Both exploit the same wrapping behavior, just in opposite directions. Check the Solidity version (pre-0.8.0 is suspicious), search for unchecked blocks, review arithmetic with user inputs (especially multiplication), use static analysis tools like Slither and Mythril, and fuzz test boundary values.
Checked arithmetic by default removed the accidental version of this bug, so what remains is deliberate: unchecked blocks, narrowing casts such as uint256 to uint128 , raw assembly, and contracts still pinned below 0.8.0. Those four places are where an audit should spend its time. The test that catches the rest is a boundary test. Assert that each arithmetic path behaves at 0, at type(uint256).max , and at whatever protocol-specific ceiling the accounting assumes.
The Smart Contract Hacking course includes hands-on exercises for finding and fixing arithmetic vulnerabilities. Build your auditing skills with guided exploit exercises in the Smart Contract Hacking course. Thanks for signing up. We'll email your trial onboarding details within 2-3 business days. Integer Overflow in Solidity: What It Is, Real Examples, and How to Prevent It (2026) An integer overflow vulnerability occurs when arithmetic operations exceed the maximum value a data type can hold...
An integer overflow vulnerability occurs when arithmetic operations exceed the maximum value a data type can hold — causi ng the value to wrap around to zero or a small number. Before Solidity 0.8.0, this was a critical security flaw that allowed attac kers to manipulate balances and bypass checks. The BEC Token hack in 2018 exploited integer overflow to generate $900 m illion worth of tokens from nothing.
Use the free Blockhertz AI Smart Contract Auditor to check your contracts for overflow vulnerabilities in under 60 seconds.
Every integer type in Solidity has a fixed range. A uint256 can hold values from 0 to 2²II-1. When an arithmetic operation ex ceeds this maximum, the value wraps around — like an odometer rolling over from 99999 to 00000. Before Solidity 0.8.0, this wrapping happened silently with no error. Attackers exploited this behavior to manipulate token balances, bypass transfer ch ecks, and drain contracts.
In April 2018, an attacker exploited an integer overflow vulnerability in the BeautyChain (BEC) token contract. The vulnerable batch transfer function allowed users to send tokens to multiple addresses. The attacker passed a carefully crafted value that caused an integer overflow in the amount calculation — generating an astronomically large token balance from nothing. The attacker then dumped these tokens on exchanges, causing the BEC token price to crash to near zero and wiping out an estim ated $900 million in market value.
Prevent integer overflow by upgrading to Solidity 0.8.0 or higher which has built-in protection, using OpenZeppelin SafeMath f or legacy contracts, and being careful with unchecked blocks and type casting. Yes — Solidity 0.8.0 introduced automatic overflow and underflow protection. Every arithmetic operation now reverts automati cally if it would overflow or underflow — no additional code required. Simply upgrading to Solidity 0.8.0+ eliminates integer ov erflow vulnerabilities entirely for standard arithmetic.
3. Software Implementation, Frameworks & Protocols SafeMath is an OpenZeppelin library for Solidity versions below 0.8.0 that prevents integer overflow and underflow by revertin g on unsafe arithmetic operations. It is no longer needed in Solidity 0.8.0 and above. Only use SafeMath when maintaining le gacy contracts that cannot be upgraded to Solidity 0.8+.
Use unchecked blocks only when overflow is mathematically impossible — such as loop counters already bounded by array l ength checks. Never use unchecked for token balances, amounts, or any value that could be influenced by user input. Yes — casting from a larger integer type to a smaller one can cause overflow even in Solidity 0.8.0+. Use OpenZeppelin's Sa feCast library to safely downcast between integer types with automatic revert on overflow.
Always multiply before dividing to avoid precision loss. Dividing first truncates the result to an integer before multiplication am plifies it — this can create exploitable rounding behavior in financial calculations. The Blockhertz AI Smart Contract Auditor automatically detects integer overflow vulnerabilities in your Solidity, Rust, Move, or Vyper contracts in under 60 seconds.
Automatically detect integer overflow and 10+ other vulnerabilities in your smart contracts at blockhertz.com/tools/ai-auditor — free, no signup required. MythX combines symbolic execution, fuzzing, and static analysis from ConsenSys. Blockhertz uses LLM-based AI to catch business logic vulnerabilities MythX can’t find. Here’s which tool to use — and when to use both.
Instant AI security audits for any deployed smart contract — straight from Telegram. Send /audit 0xYourAddress and get a risk score plus top findings in under 30 seconds. Free, no signup, no install. Supports Ethereum, Base, Arbitrum, Optimism, Polygon, and BNB Chain. $3.4 billion stolen from blockchain projects in 2025. Access control failures cost $953 million. Audited contracts have 98% fewer hacks. Complete blockchain security statistics for 2026 — updated monthly by the Blockhertz team.
Blockchain developer and security engineer with 8+ years of experience. Founded Blockhertz in 2018 to build AI-powered tools for Web3 teams — smart contract auditing, architecture generation, gas optimization, and RWA tokenization platforms. Serving clients worldwide. The Truebit exploit of January 8, 2026, which drained 8,535 ETH worth approximately $26.4 million from the protocol, was caused by a vulnerability class that should have been eliminated years ago: integer overflow in a Solidity smart contract. The Purchase contract, deployed in 2021 using Solidity 0.5.3, lacked overflow protection on a critical arithmetic operation. This tutorial walks through the technical process of identifying, exploiting, and patching integer overflow vulnerabilities in production smart contracts.
This tutorial aims to equip experienced solidity developers and security auditors with practical skills for detecting integer overflow vulnerabilities in deployed smart contracts. By the end, you will understand how overflow conditions arise, how to systematically identify vulnerable patterns in codebases, and how to implement robust mitigations that prevent these exploits from occurring.
The Truebit exploit specifically targeted the getPurchasePrice(uint256 amount) function in the Purchase contract. The function performed an unprotected integer addition that, when supplied with an extremely large input value, wrapped around to return a purchase price of zero ETH. This allowed the attacker to mint TRU tokens at no cost and then burn them through the bonding curve for ETH, repeating the cycle until the contract was drained.
To follow this tutorial, you should have experience with Solidity development, a working understanding of EVM arithmetic operations, familiarity with tools like Foundry, Hardhat, or Truffle, and access to a local Ethereum development environment. You will also need Slither (a static analysis tool for Solidity) and Echidna or Medusa for property-based fuzzing. Understanding the context is essential. Solidity 0.8.0 and later include built-in overflow checks for all arithmetic operations, but thousands of contracts deployed on earlier versions — 0.5.x, 0.6.x, and 0.7.x — remain active and potentially vulnerable. The Truebit contract used Solidity 0.5.3, which required explicit overflow protection through the SafeMath library or manual checks.
Step 1: Identify high-risk contracts. Begin by compiling a list of all deployed contracts interacting with financial logic — token minting, burning, pricing, swaps, lending, and staking. Focus on contracts deployed before Solidity 0.8.0 (released in December 2020) as they lack automatic overflow checks. Use Etherscan to verify contract source code and check the compiler version pragma.
Step 2: Map all arithmetic operations. For each high-risk contract, systematically catalog every arithmetic operation — addition, subtraction, multiplication, and division. Pay special attention to operations involving user-controlled inputs, as these are the values an attacker can manipulate. In the Truebit case, the amount parameter passed to getPurchasePrice was externally controllable and unbounded.
Step 3: Trace overflow conditions. For each arithmetic operation, determine whether inputs can cause an overflow. For uint256 addition, this occurs when a + b > 2^256 – 1, causing the result to wrap around to a small value. For multiplication, the risk is even higher as large operands more easily exceed the type limit. In the Truebit exploit, the extremely large amount parameter caused the price calculation to overflow, returning zero.
Step 4: Verify SafeMath usage. Check whether each arithmetic operation uses SafeMath or equivalent protection. Look for patterns like .add() , .sub() , .mul() , and .div() instead of raw operators + , - , * , / . Critically, verify that SafeMath is used consistently throughout the contract — not just in some functions. The Truebit contract used SafeMath in other parts of the codebase but left the vulnerable function unprotected.
Step 5: Analyze input validation. Even with overflow protection, contracts should validate input ranges. Check for supply caps, maximum transaction amounts, and boundary condition checks. The absence of such limits in the Truebit Purchase contract allowed the attacker to pass astronomically large values without triggering any validation errors. Step 6: Run automated analysis. Use Slither to perform static analysis: slither . --detect integer-overflow-bug . This detector specifically flags unprotected arithmetic operations in pre-0.8.0 contracts. Supplement with property-based fuzzing using Echidna to automatically discover overflow conditions through random input generation.
Step 7: Implement patches. For vulnerable contracts, the remediation depends on the situation. If the contract is upgradeable, deploy a new implementation that adds overflow checks and input validation. If immutable, consider deploying a wrapper contract or proxy that validates inputs before forwarding them. In both cases, add supply caps and maximum value constraints to prevent exploitation of edge cases that automated tools might miss.
If Slither reports no overflow vulnerabilities in a pre-0.8.0 contract, do not assume the contract is safe. Slither may miss vulnerabilities in complex control flow paths or when arithmetic operations are split across multiple internal function calls. Always perform manual review of all financial logic as a complement to automated analysis. When analyzing unverified contracts on Etherscan, you may not have access to the source code. In this case, use reverse engineering tools to decompile the bytecode. While decompiled code is harder to analyze, arithmetic patterns are generally identifiable. The Truebit Purchase contract was unverified on Etherscan, which complicated early detection.
If you discover a vulnerability in a deployed contract, follow responsible disclosure practices. Contact the project team privately through their security contact or bug bounty program. Do not exploit the vulnerability, even for demonstration purposes. The ethical and legal consequences of unauthorized exploitation are severe. Integer overflow detection is a foundational smart contract security skill, but it represents just one class of vulnerability. To build comprehensive audit capabilities, study the full spectrum of common weakness patterns including reentrancy, access control flaws, front-running vulnerabilities, and oracle manipulation. The $4.13 million Makina Finance exploit in January 2026, for instance, involved flash loan oracle manipulation — a completely different attack vector requiring different detection techniques.
Practice auditing real contracts on platforms like Code4rena, Sherlock, and Cantina, where you can test your skills against live codebases and earn bounties for legitimate findings. Review past exploit analyses — QuillAudits, Halborn, and Trail of Bits regularly publish detailed post-mortems that serve as excellent learning resources. Finally, stay current with the evolving Solidity language and security tooling landscape. New vulnerability classes emerge as the ecosystem evolves, and the tools for detecting them improve continuously. The crypto industry lost over $2 billion to exploits in 2025 — much of it preventable with thorough security auditing practices.
Disclaimer: This article is for educational purposes only and does not constitute financial or investment advice. Always conduct your own security audits before interacting with any smart contract. 25 thoughts on “Detecting Integer Overflow Vulnerabilities in Solidity Smart Contracts: An Advanced Security Audit Tutorial” Solidity 0.5.3 in 2026 is insane. SafeMath has been built into the compiler since 0.8.0 and they still had unchecked arithmetic on a price function handling 8 figure values getPurchasePrice with no overflow check on user input is basically a free mint button. one transact call with max uint256 and you own the treasury 8535 eth gone because of an overflow in a contract written in solidity 0.5.3 with no safemath. in 2026. i genuinely dont know what to say solidity 0.5.3 with no safemath in 2021 is negligent. by then openzeppelin contracts had been the standard for two years.
whoever deployed this skipped basic due diligence SafeMath was not the universal standard in early 2021 that people think it was. a lot of teams just copy pasted from tutorials audit_owl SafeMath not being universal in early 2021 is crazy talk. OpenZeppelin had 20k+ stars on github by then. teams just didnt import it Wei Z. solidity 0.5.3 in 2021 is wild. OpenZeppelin SafeMath was literally copy paste at that point. no excuse slither_pilled_ Solidity 0.5.3 was already 2 major versions behind when this deployed. 0.8 with built-in overflow checks existed. zero excuse nonce_overflow_ two major compiler versions behind and nobody thought to upgrade. 0.8 was literally a one line change in foundry config and this entire exploit wouldnt exist slither_pilled_ modern Solidity 0.8+ has built-in overflow checks but that creates a false sense of security. Unchecked blocks for gas optimization still create the same vulnerability in production code.
audit_newt_ the real question is how many contracts from 2019-2021 with active TVL still have no overflow protection. Truebit was just the one that got exploited first audit_newt_ deployed in 2021 using 0.5.3 when 0.8 was already live with built in overflow checks. this wasnt a subtle bug it was negligence the fact that this contract was deployed in 2021 and sat there for 5 years with no audit catching the overflow is damning.
legacy contracts are a ticking time bomb ^ this is why i always say check the compiler version before interacting with any contract. anything pre-0.8 without safemath is an automatic no from me 4. Practical Deployment, Analysis & Case Studies 3of5_panic_ checking compiler version is step one but most users interacting with contracts never check. the burden should be on protocol auditors not end users 5 years sitting there with an overflow and nobody noticed because nobody was looking at legacy contracts. how many more of these are lurking in old deployments the scary part is how many contracts from 2019-2021 are still live with active TVL and zero overflow protection Yuki T. the BEC token overflow was the case study that made SafeMath non-optional. Before that attack most auditors treated arithmetic checks as best practice. After, it was baseline survival.
26.4m on a bug that safe math would have prevented. the tutorial format here is solid though, good to see someone walking through the actual exploit mechanics step by step 8535 ETH gone because nobody ran slither on a 2021 deployment. static analysis tools have been free for years this one hurts 8535 ETH gone because nobody ran slither on a contract sitting live for 5 years. how many more legacy deployments are ticking like this right now legacy_rekt_ the answer is dozens. theres contracts from 2019-2021 with 9 figure TVL still running on pre-0.8 compilers.
ticking time bombs legacy_rekt_ the scary answer is probably hundreds. defillama shows dozens of protocols with TVL over 50M running on contracts that havent been touched since 2020-2021 Solidity 0.5.3 on a deployment from 2021 is actually insane. 0.8.x had been out for over a year with built in overflow checks.
no excuse at all rekt_compiler_ and the Truebit team had TVL over 20M on that contract. at what point does running slither once become standard procedure for anything holding user funds Smart contract security is one of the biggest impediments toward the mass adoption of the blockchain. For this reason, we are proud to present this series of articles regarding Solidity smart contract security to educate and improve the knowledge in this domain to the public. Integer overflow might be one of the most commonly known issues in the smart contract security field.
This article will explore how the integer overflow happens and how to prevent it when developing your smart contracts. Enjoy reading. I You can find all related source code at I https://github.com/serial-coder/solidity-security-by-example/tree/main/06_integer_overflow .
Disclaimer: The smart contracts in this article are used to demonstrate vulnerability issues only. Some contracts are vulnerable, some are simplified for minimal, some contain malicious code. Hence, do not use the source code in this article in your production. Nonetheless, feel free to contact Valix Consulting for your smart contract consulting and auditing services. I The following presents the InsecureMoonToken contract that allows a user to buy or sell MOON tokens. The MOON is a non-divisible token (token decimals = 0) pegged with 1 Ether. In other words, 1 MOON token will always have a fixed value of 1 Ether. Therefore, you can buy or sell 1, 2, 3, or 46 tokens but not 33.5. Exactly, the InsecureMoonToken contract is vulnerable to integer overflow . Can you catch up on the issue? I The integer overflow occurs in line 16 in the buy function. Consider the case that an attacker inputs some tremendous amount of _tokenToBuy into the buy function. What would happen? Figure 1 draws on how the overflow occurs. In the case of 2 * 2²II, the computed value would circle back to 0, as you can see. Consider the require(msg.value == _tokenToBuy * TOKEN_PRICE, “Ether received and Token amount to buy mismatch”); statement. With the overflow, an attacker can buy a large amount of MOON tokens ( _tokenToBuy ) by spending only a few Ethers ( msg.value ). Moreover, the attacker can even steal all Ethers locked in the InsecureMoonToken contract with a single sell transaction. OMG! I The following is the Attack contract in which an attacker can steal Ethers locked in the InsecureMoonToken contract.
Call: ethersRequired = attack.getEthersRequired() To calculate the number of Ethers required to complete a “buy” attack. Call: attack.attackBuy() and supplies the ethersRequired To exploit the overflow — spending a few Ethers but taking vast MOON tokens in return. The result of the attack is shown in Figure 2. As you can see, the attacker could steal 30 Ethers (10 and 20 Ethers were deposited by User1 and User2, respectively) by spending only 0.415 Ethers in exchange. I Another result of the attack, furthermore, the Attack contract’s balance recorded by the InsecureMoonToken was manipulated enormously. I Note that you may notice that the 0.415 Ethers deposited by the attacker were locked and could not withdraw any longer since the MOON is a non-divisible token with 0 decimals. In other words, you cannot sell 0.415 MOONs for 0.415 Ethers. In fact, the attacker can do some other trick by submitting another 0.585 Ethers to lock into the contract. This way, the attacker could withdraw 1 Ether being locked by exchanging it with 1 MOON I. Surely, we will explain that trick in the future article of this series. Stay tuned! I Applying the standard OpenZeppelin’s SafeMath library for arithmetic operations (for the Solidity below v0.8) Using the Solidity v0.8+ (Solidity v0.8+ came up with the built-in underflow and overflow detection mechanism on arithmetic operations) The FixedMoonToken contract above is the fixed version of the InsecureMoonToken . The contract applies the SafeMath library to prevent any underflow or overflow issues in lines 46, 50, 56, and 58. The library used in the code is just a simplified version for brevity’s sake. Please refer to this link for the latest OpenZeppelin’s SafeMath library.
In this article, you have discovered the integer overflow vulnerability in the smart contract, how an attacker exploits it, and the solutions to fix the issue. We hope you have learned something interesting. And, see you in the following articles. Again, you can find all related source code at I https://github.com/serial-coder/solidity-security-by-example/tree/main/06_integer_overflow .
Phuwanai Thummavet ( serial-coder ), Lead Blockchain Security Auditor and Consultant | Blockchain Architect and Developer. See the author’s profile . Valix Consulting is a blockchain and smart contract security firm offering a wide range of cybersecurity consulting services. Our specialists, combined with technical expertise with industry knowledge and support staff, strive to deliver consistently superior quality services. For any business inquiries, please get in touch with us via Twitter , Facebook , or info@valix.io .
Arithmetic bugs occupy a foundational position in smart contract security. An attacker who can force a uint256 balance to wrap from zero to its maximum value, or drive a token supply counter below zero, can mint unbounded tokens, bypass access checks, or drain funds the contract does not actually hold. These are not theoretical risks: they have caused nine-figure losses across multiple protocol generations, and they have not disappeared with the adoption of newer compiler versions.
The risk landscape has changed substantially since the early days of Solidity. Understanding what the pre-0.8.0 defaults were, what Solidity 0.8.0 changed, and where the residual risk now lives is a prerequisite for reading any audit report or evaluating a DeFi protocol's security posture. Before Solidity 0.8.0 (released November 2020), integer arithmetic in EVM smart contracts operated on the EVM's native wrapping semantics: unsigned integers silently wrap at their type boundary. A uint8 holding the value 255, incremented by 1, becomes 0.
A uint256 balance of 0, decremented by 1, becomes 115,792,089,237,316,195,423,570,985,008,687,907,853,269,984,665,640,564,039,457,584,007,913,129,639,935, the maximum representable uint256.
Both overflow (exceeding the upper bound) and underflow (going below zero on an unsigned integer) produce exploitable primitives. Overflow can bring a large counter back to a small value, passing a cap check that should have reverted. Underflow can transform a zero or near-zero balance into an astronomically large number, enabling phantom borrowing, excess reward claims, or unlimited minting. The attack surface was not academic. A naive mint cap check of the form require(totalSupply + amount >= totalSupply) is bypassed when totalSupply + amount overflows to a small number. The require passes because the wrapped result is numerically less than totalSupply , which is then incremented by a valid amount.
The Ethereum community responded with the OpenZeppelin SafeMath library, wrapper functions (add, sub, mul, div) that explicitly check for overflow and revert if one would occur. SafeMath became the community standard by 2017, and audit reports from that period routinely flag raw arithmetic operations as high-severity findings. Code written with SafeMath traded gas efficiency for overflow safety and required a verbose function-call style that many developers found difficult to read.
The SafeMath era proved the community could standardise defensive practice at the library layer. It also created pressure for a language-level solution that provided the same guarantee without the gas overhead and syntactic friction. Solidity 0.8.0 introduced checked arithmetic as the compiler default. Every addition, subtraction, multiplication, and exponentiation now includes an implicit overflow and underflow check: if the result would fall outside the type's representable range, the transaction reverts with a Panic(0x11) error. SafeMath became redundant for standard operations, and code could return to natural operator syntax (a + b, not a.add(b)).
Type casting is not checked. Downcasting a uint256 to uint128 truncates the upper 128 bits silently without reverting. If the value exceeds 2¹²I − 1, the cast produces a wrong result with no revert and no warning. OpenZeppelin's SafeCast library provides checked downcast functions for this reason. Assembly blocks bypass all Solidity safety guarantees. Arithmetic inside assembly (Yul) operates at the raw EVM level, where addition, subtraction, and multiplication wrap on overflow exactly as pre-0.8.0 Solidity did. Any assembly block that performs arithmetic on user-controlled values must be independently reasoned about.
The unchecked block explicitly disables overflow checking for performance, and it is now the primary source of arithmetic vulnerability in modern Solidity codebases. The unchecked {} block is an intentional performance optimisation. Removing the overflow check saves roughly 30–40 gas per arithmetic operation. For tight loops (iterator increments, reward sweeps, token distribution over many accounts), the savings compound over many iterations and can be material.
The canonical safe pattern is a loop counter whose upper bound makes overflow impossible: The security risk appears when developers apply the same pattern to arithmetic that operates on user-supplied values or protocol state variables without an equivalent range guarantee. An unchecked subtraction on a user-provided withdrawal amount, an unchecked multiplication in a reward-per-share calculation, or an unchecked addition to a fee accumulator can wrap silently if the inputs are not bounded before the block is entered. The correctness of every unchecked block depends entirely on an informal or formal proof that no reachable input can push the arithmetic to its type boundary.
Auditors review unchecked blocks in three passes: confirm there is a documented performance justification; identify the constraints that make overflow impossible and trace them to their enforcement points earlier in the call path; and assess whether those constraints are enforced by the actual code or merely assumed. An unchecked block without a code-enforced bound on its operands is typically a high or medium finding, depending on the degree to which an attacker can control the wrapped value.
Precision loss is the arithmetic counterpart of overflow: rather than producing a value larger than intended, it silently discards fractional remainders through integer division, accumulating small misallocations that compound across many transactions. Solidity performs integer division that truncates toward zero: there is no native fractional or floating-point type on the EVM. The result is predictable in isolation but dangerous in DeFi accounting: Fee calculations : fee = amount * feeBps / 10_000 . If amount * feeBps is smaller than 10,000, the computed fee is zero and users bypass fees entirely by routing transactions in small batches. An attacker who calls a fee-bearing function repeatedly with amounts sized to trigger this rounding can drain value without paying protocol fees.
Interest accrual : Per-block interest rates expressed as small fractions involve multiplication and division repeated every block. A rounding-down bias in every calculation slightly undercharges borrowers; over thousands of blocks the protocol accumulates bad debt that has no corresponding on-chain liability. 5. Performance Evaluation & Extended Technical Observations Share accounting : ERC-4626 vault share conversions divide assets by shares (or vice versa). Consistent rounding in one direction across both deposit and withdrawal paths allows an attacker to extract more assets than they deposited by exploiting the accumulated bias, a variant of the first-depositor inflation attack. How precision loss shapes interest-rate model security in lending protocols is a recurring audit focus, particularly in compound-interest formulas applied block-by-block.
The standard mitigation is to ensure multiplication is performed before division (preserving the largest numerator before truncation), and to explicitly document and enforce the rounding direction, typically rounding against the user in operations that favour the protocol's solvency. Arithmetic vulnerabilities are among the most historically significant in smart contract security. A selection of notable cases from arithmetic-triggered exploits in our historical incident database : Beauty Chain (BEC), April 2018 : The batchTransfer function multiplied a user-supplied amount by the number of recipients without overflow protection. The multiplication wrapped to a near-zero total-deduction value while crediting each recipient the full amount. Approximately $900M in BEC market capitalisation was effectively destroyed by a single transaction.
PoWH Coin, February 2018 : An overflow in the token purchase logic allowed an attacker to acquire tokens for far less than their stated price by exploiting the pre-SafeMath unsigned integer wrap. SpankChain, October 2018 : An integer underflow in a payment channel contract allowed an attacker to drain 165 ETH by setting a withdrawal value that underflowed to a very large number.
Akropolis, November 2020 : A rounding vulnerability in a yield aggregator vault, combined with flash loan-funded deposits, allowed extraction of more assets than were deposited by exploiting the accumulated per-transaction rounding bias. Post-0.8.0, direct overflow exploits are significantly rarer. Unchecked-block misuse and precision-loss vulnerabilities remain active finding categories in essentially every DeFi protocol review.
Manual review traces every arithmetic operation through the range of inputs an external caller can supply. Auditors ask: Automated tools complement manual review. Fuzzers (Echidna, Medusa) generate inputs that approach type boundaries and verify that no input causes an unintended state transition. Symbolic execution tools (Halmos, Manticore) can verify that named arithmetic invariants hold across all possible inputs without enumerating specific values. How fuzzers and symbolic execution tools surface arithmetic edge cases is covered in our automated testing analysis, which also explains how these tools are combined with manual review in a full audit engagement.
For protocols with complex accumulation logic (interest models, reward distributions, share price calculations), formal verification tools such as Certora's Prover can prove that a named invariant (for example, "total shares issued multiplied by share price never exceeds total protocol assets") holds for all possible execution traces, providing a guarantee that neither manual review nor fuzzing alone can achieve.
The practical conclusion for protocol developers: multiplication before division, explicit rounding-direction documentation, SafeCast for downcasts, and documented range proofs for every unchecked block. For auditors: treat every arithmetic operation as potentially user-influenced until the data-flow analysis proves otherwise. See our integer overflow and underflow vulnerability patterns entry for detailed technical definitions and the full taxonomy of arithmetic vulnerability sub-classes auditors use in report classification.
Published on 15 June 2026 · Updated 2 August 2026 by Ana Crudu & MoldStud Research Team Discover expert tips and techniques for building scalable blockchain solutions using Go. Enhance your development skills and optimize performance with practical insights. Utilizing the SafeMath library is essential for preventing integer overflow in Solidity. This library provides safe mathematical operations that revert on overflow, ensuring the integrity of your smart contracts.
This library provides safe mathematical operations that revert on overflow, ensuring the integrity of your smart contracts. Use SafeMath for Addition Prevents overflow in addition operations. The section frames how to use safemath library for arithmetic. as a point to evaluate in the article's specific context, not as a universal rule.
Use the cited section as a checklist when reviewing decisions related to how to use safemath library for arithmetic.. Implementing overflow checks in your smart contracts is vital. Follow these steps to ensure that your arithmetic operations are safe and reliable, minimizing the risk of vulnerabilities. Avoids overflow in multiplication. Cuts error rates by ~30% in arithmetic operations. Essential for preventing integer overflow.
Prevents overflow in addition operations. 73% of developers report fewer bugs using SafeMath. Selecting appropriate data types is crucial in preventing overflow issues. Use data types that suit your needs while considering their limits to avoid unexpected behavior in your contracts. If your contracts are already deployed, it's important to fix any potential overflow issues. Identify vulnerable areas and apply the necessary changes to enhance security.
Many developers fall into common pitfalls when performing arithmetic operations. Recognizing these can help you avoid vulnerabilities and ensure safer contract development. 80% of contracts use uint256 for safety. Increases risk of overflow. 67% of developers recommend larger types. 75% of developers overlook this step. Useful for precise calculations. Adopted by 50% of financial contracts. Understand limits to prevent overflows.
Planning for security audits and thorough testing is essential for any smart contract. Ensure that your contracts are reviewed and tested to prevent overflow issues effectively. This decision matrix compares two approaches to preventing integer overflow in Solidity smart contracts: using the SafeMath library and implementing custom overflow checks.
How can I effectively prevent integer overflow in my smart contract arithmetic operations? You should utilize established arithmetic libraries that automatically revert transactions when an overflow or underflow is detected. Replace standard arithmetic operators with library-provided functions and verify that all state-changing operations are wrapped in these checks. Relying solely on libraries does not replace the need for input validation, as extreme values can still cause logic errors even if the math remains safe.
Is it better to use manual checks or a library to handle potential arithmetic overflows? Using a standardized library is generally preferred because it reduces implementation errors and simplifies the auditing process for your code. Implement library functions for standard operations and reserve manual require statements only for complex, custom logic that falls outside standard arithmetic patterns. Custom manual checks increase the surface area for human error and may be harder to maintain or verify during security reviews.
What are the risks of using smaller data types in Solidity arithmetic? Default to using uint256 for all arithmetic operations unless specific memory or storage constraints strictly necessitate the use of smaller types. Choosing larger types does not eliminate overflow risk entirely; it only raises the threshold at which an overflow occurs. How should I verify that my arithmetic operations are secure before deploying to production? You must combine automated static analysis tools with comprehensive unit testing that specifically targets edge cases and boundary values. Execute test suites that include maximum and minimum possible values for every variable involved in arithmetic to ensure the contract reverts as expected. Automated tools may miss complex logic vulnerabilities, making manual code review an essential final step before deployment.
Explore key advanced features in modern blockchain development frameworks that enhance security, scalability, and user experience. Optimize your projects with the latest tools and techniques. Explore how blockchain-powered applications are transforming healthcare research, enhancing data integrity, security, and collaboration among stakeholders in the industry.
In today's fast-paced tech industry, companies are constantly under pressure to deliver cutting-edge solutions quickly and efficiently. One of the key challenges that many businesses face is finding and hiring skilled software developers to meet their development needs. Discover key questions to ask blockchain app developers during job interviews to assess their skills, experience, and understanding of emerging technologies.
Discover key questions to ask blockchain app developers during job interviews to assess their skills, experience, and understanding of emerging technologies. Discover key questions to ask blockchain app developers during job interviews to assess their skills, experience, and understanding of emerging technologies.
Explore key advanced features in modern blockchain development frameworks that enhance security, scalability, and user experience. Optimize your projects with the latest tools and techniques. Explore key advanced features in modern blockchain development frameworks that enhance security, scalability, and user experience. Optimize your projects with the latest tools and techniques.
The Impact of Tokenization on the Blockchain Ecosystem - Essential Insights for Developers Discover key questions to ask blockchain app developers during job interviews to assess their skills, experience, and understanding of emerging technologies. When it comes to building a successful software project, having the right team of developers is crucial. Laravel is a popular PHP framework known for its elegant syntax and powerful features. If you're looking to hire remote Laravel developers for your project, there are a few key steps you should follow to ensure you find the best talent for the job.
Harvested Online Documentation & Reference Sources • https://scs.owasp.org/sctop10/SC09-IntegerOverflowUnderflow/ • https://scs.owasp.org/SCWE/SCSVS-CODE/SCWE-047/ • https://smartcontractshacking.com/attacks/arithmetic-overflows-underflows • https://blockhertz.com/blog/integer-overflow-solidity-2026 • https://bitcoinsnews.com/detecting-integer-overflow-vulnerabilities-in-solidity-smart-contracts-an-advanced-security-audit-tut orial-77146 • https://www.serial-coder.com/post/solidity-smart-contract-security-by-example-06-integer-overflow/ • https://www.smartcontractaudit.com/guides/solidity-arithmetic-vulnerabilities • https://moldstud.com/articles/p-top-solidity-patterns-to-prevent-integer-overflow-issues
Extracted Research Figures & Simulation Topologies
Total 3 diagrams and telemetry visual outputs extracted directly from the complete technical documentation.
Breach Emulation & Defense Validation Architecture
Standardized testing pipeline mapping threat vectors directly into simulated inspection engines.
(AttackIQ / SafeBreach)
(Burp Suite Pro)
(Cisco Packet Tracer)
(Metasploit Engine)
(KnowBe4 Training)
Sample Simulation Code & Telemetry Log
Automated tool orchestration script and command window outputs for Integer Overflow Vulnerability Detector In Solidity Contracts.
[*] Initializing Burp Suite Spider & Vulnerability Engine for Integer Overflow Vulnerability Detector In Solidity Contracts... [✓] Burp Extender / Macro Automation Hook Synced ──────────────────────────────────────────────────────────────────────── [11:42:01.104] AUDIT Crawled dynamic endpoints | Injecting input vectors [11:42:01.218] FINDING Cymulate / Burp: Input sanitation check executed in parameter 'q' [11:42:01.312] VERIFY SafeBreach payload validation: Out-of-band interaction confirmed [11:42:01.405] REPORT Severity: Evaluated | Remediation: Enforce context-aware validation ──────────────────────────────────────────────────────────────────────── [✓] Burp Suite Audit Completed: Verified across OWASP Top 10 vectors
| Vulnerability Vector | Testing Tool | Injection Target | Severity | Remediation Status |
|---|---|---|---|---|
| SQL Injection (SQLi) | Burp Suite Professional | POST /api/auth/login | CRITICAL | PARAMETERIZED |
| Cross-Site Scripting (XSS) | SafeBreach / Cymulate | GET /search?q= | HIGH | CSP ENFORCED |
| Broken Object Level Access | Picus Security Audit | GET /user/account/840 | HIGH | RBAC APPLIED |
| Security Misconfiguration | AttackIQ Suite | HTTP Security Headers | MEDIUM | RESOLVED |