12 Solidity smart contract security best practices – Alchemy
Smart contracts are the wizards behind blockchain's magic. They are the code blocks that automate onchain logic, specifying everything from the liquidation thresholds of decentralized lending protocols to the tokenization of real world assets, and much more.
But with great power comes great responsibility, especially when it comes to security. One bug can lead to massive exploits, and nobody wants their project to be the next headline for a multimillion dollar hack.
In the first half of 2025 alone, over $2.3 billion in crypto was lost to exploits and breaches, with access control issues alone accounting for over $1.6 billion of that pain. If you're building with Solidity on Ethereum or similar chains, nailing security isn't optional: it's what keeps your users' funds safe and your reputation intact.
In this post, we'll break down what smart contract security really means, dive into some of the biggest contract vulnerabilities, and share practical best practices with code examples to help you bulletproof your code and deploy safe contracts on mainnet.
And remember, always test on testnets first before mainnet deployments. Its far better to find vulnerabilities before your users start sending funds to your contract.
Smart contracts are self executing pieces of code that run when certain conditions are met. Think automated agreements that handle transfers, votes, or even complex DeFi maneuvers without middlemen. They're deployed as bytecode on the blockchain, and once live, they're immutable, so any flaw in a contract is there for the public to see.
Security here boils down to making sure that code is rock solid because often contracts themselves custody onchain assets. Can hackers drain funds from a particular contract? Does the contract logic hold up under weird edge cases? Are assets locked away from unauthorized access?
A vulnerability in those answers means a malicious actor could drain the contract of user funds and take that money for themself. To protect those vulnerabilities, you need to be thinking about implementing input checks, design patterns, and code audits that can harden your code before mainnet deployment.
For a deeper intro, check out the Ethereum docs on smart contract security.
Building insecure contracts isn't just risky for users, it can tank your project overnight. When a project gets drained, users lose faith, and they often dont come back. Blockchain's irreversibility means that once funds are gone, they're gone. There are no chargebacks here. And just as funds can get wiped out in a moment, so can your reputation.
With billions of dollars flowing onchain, hackers are always probing for weak spots; recent stats show the stakes: that $2.3B lost in H1 2025. Most of those losses came from preventable bugs like bad access controls and reentrancy. By prioritizing security, you can protect your users, build trust, and avoid the nightmare of your project going to $0 in a single transaction.
With the tools and best practices on the market, there are plenty of things that you can do that will allow you to write better code that is not only functional, but resilient.
One helpful resource to understanding smart contract vulnerabilities is OWASP (short for Open Web Application Security Project), which is a nonprofit that creates free resources to improve software security worldwide. Their Smart Contract Top 10 is like a hit list of the most dangerous vulnerabilities in blockchain apps, based on real world exploits and data from incidents causing billions in losses.
This list gives devs a prioritized shortlist of vulnerabilities to focus on in audits and contract design, drawing from patterns in hacks across ecosystems. The 2025 edition highlights risks like access flaws that led to $953M in losses last year alone. When reviewing your code, being conscious about these common vulnerabilities is a great grounding framework to start building up your codes resiliency.
For the full OWASP details, head to their Smart Contract Top 10 page. And for Ethereum specific tips, see their security guidelines.
Now that you understand the threat landscape, let's dive into practical defenses. Each vulnerability on the OWASP list has corresponding best practices that have been battletested across thousands of contracts.
The following sections break down these common flaws one by one with concrete code examples showing both vulnerable patterns and secure implementations. Think of this as your defensive playbook: straightforward techniques that when applied consistently can reduce your attack surface.
Delegatecall lets one contract run code from another while using its own storage super useful for libraries or upgrades, but risky because it can lead to unexpected state changes if the called code messes with your variables. It's behind major exploits where hackers inject malicious logic that overwrites critical state like owner addresses or drains funds.
The danger is that delegatecall preserves the calling contract's context (msg.sender, msg.value, storage), so the external code runs with full privileges. Only use it when absolutely needed, and ensure storage layouts match perfectly between contracts - misaligned slots can corrupt your data.
Here's a vulnerable example:
Heres a safer approach:
Best practices: Use established proxy patterns like OpenZeppelin's upgradeable contracts, maintain identical storage layouts between versions (never reorder or change variable types), restrict delegatecall to trusted, audited contracts only, and consider using libraries with library keyword which uses delegatecall safely under the hood and never allow user controlled addresses in delegatecall: that's an instant takeover vector.
Reentrancy occurs when an external call hands over control before your function completes its state updates, etting the caller jump back in and repeat actions like withdrawals before balances update. It's ranked #5 on OWASP's top Web3 risks and powered some of the most massive hacks in crypto like The Infamous DAO Hack ($60M loss).
Attackers can exploit this reentrancy window between sending funds and updating state to drain contracts by recursively calling withdrawal functions. You should always assume external contracts are hostile.
Vulnerable example:
Secure implementation:
solidity
`import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
contract SecureBank is ReentrancyGuard { mapping(address => uint256) public balances;
Best practices: Use OpenZeppelin's ReentrancyGuard modifier, follow Checks-Effects-Interactions pattern (validate update state external calls), and consider pull-over-push patterns where users withdraw funds themselves.
The call tx.origin traces back to the original transaction initiator, while msg.sender refers to the immediate caller; this distinction matters heavily in security. In multi-contract call chains, tx.origin remains constant, but it can be exploited by malicious intermediary contracts that trick your code into thinking the original user is authorized.
An attacker can create a phishing contract that calls your function, and if you check tx.origin, it points to the victim who initiated the transaction, completely bypassing your authentication. msg.sender is always the direct caller, making it reliable for access control. Only use tx.origin in rare cases where you specifically need the transaction originator, and never for authentication. This vulnerability ties directly into access control flaws, OWASP's #1 risk.
Vulnerable example:
Secure implementation:
Why this matters: If an owner accidentally interacts with a malicious contract (clicking a phishing link, using a compromised app), that contract can drain the vulnerable wallet because tx.origin still points to the owner. With msg.sender, only the owner address itself can authorize transfers. Make sure you always use msg.sender for authentication and access control checks.
Visibility modifiers define access boundaries: public (callable by anyone, internally or externally), external (only from outside the contract), internal (this contract plus inheriting contracts), and private (strictly this contract). In older Solidity versions, omitting a modifier defaulted to public, accidentally exposing sensitive functions to external attackers.
Wrong visibility has led to exploits where hackers called admin functions or manipulated critical state variables that should've been restricted. Always explicitly declare visibility: it's both a security practice and readability win.
solidity
`contract VulnerableBank { mapping(address => uint) balances;
Use static analysis tools like Slither to catch missing or incorrect visibility modifiers before deployment.
Validators can manipulate block.timestamp within a small window (roughly 15 seconds on Ethereum), making it unreliable for precise timing or as a source of randomness. Miners or validators can adjust timestamps to their advantage, triggering payouts, winning lotteries, or bypassing time based checks.
To that end, never use block.timestamp for critical logic where seconds matter, and absolutely never use it for generating random numbers. It's fine for rough time estimates (like "has 24 hours passed?") but dangerous for exact conditions.
Vulnerable example:
Better approach for timing:
For randomness, never roll your own. Instead use Chainlink VRF or similar verifiable random function oracles that provide cryptographically secure, tamper proof randomness.
In Solidity versions before 0.8, integers wrap around silently when they exceed their maximum or minimum values. Meaning a uint8 at 255 increments to 0, or 0 decrements to 255.
This has caused catastrophic exploits where attackers minted infinite tokens, created negative balances that wrapped to huge amounts, or bypassed critical checks.
Vulnerable example (pre-0.8):
Upgrade to Solidity >=0.8 for automatic overflow protection:
If stuck on older Solidity, use OpenZeppelin's SafeMath library. For 0.8+, checks are built-in and revert automatically, but you can use unchecked {} blocks when you intentionally want wrapping behavior for gas optimization.
Broken access control lets unauthorized users execute privileged functions, it's the #1 vulnerability on OWASP's Web3 top 10 and caused over $1.6 billion in losses during the first half of 2025 alone. Without proper guards, attackers can drain funds, mint tokens, pause contracts, or change ownership.
Common mistakes include missing modifiers, relying on tx.origin for auth, or using simple require(msg.sender == owner) checks that get overlooked during upgrades. The fix is role-based access control with principle of least privilege: give each address only the permissions it absolutely needs.
Secure implementation with OpenZeppelin:
Regularly audit role assignments, implement time delayed admin actions for high-stakes changes, and use multi-sig wallets for critical roles. Never use tx.origin for authentication. Leverage battle-tested libraries like OpenZeppelin AccessControl rather than rolling your own.
Oracles merge blockchain and real world data, but if they're centralized or easily manipulated, attackers can feed false information to exploit your contracts. This type of exploit is ranked #2 on OWASP's Web3 risks and has drained hundreds of millions from DeFi protocols.
Flash loan attacks often manipulate onchain price oracles (like using a single DEX as a price source), letting hackers artificially inflate or crash prices to liquidate positions, drain liquidity pools, or mint undercollateralized loans. Never rely on a single price source or spot prices that can be manipulated within one transaction.
Secure oracle usage with Chainlink:
Best practices: use decentralized oracle networks like Chainlink with multiple data sources, implement Time-Weighted Average Prices (TWAPs) for critical operations, validate freshness and sanity-check price bounds, and aggregate multiple oracles when possible. Check Chainlink docs for network-specific feeds and security considerations.
Failing to validate user inputs lets attackers inject malicious data, trigger unexpected behavior, or exploit edge cases in code. It's #4 on OWASP's Web3 vulnerabilities and a common vector for draining funds or breaking contract logic.
Without proper checks, users can pass zero values to bypass fees, negative amounts to exploit arithmetic, addresses pointing to zero or malicious contracts, or array indices that cause out-of-bounds access. Every external input is untrusted until proven safe. Defense in depth means validating at every boundary: check ranges, nulls, array lengths, and business logic constraints before processing any user-supplied data.
Proper input validation:
}`
Always validate that amounts are non-zero and within bounds, addresses aren't null or invalid, array indices are in range, and business logic constraints are met.
Use custom errors in Solidity 0.8.4+ for gas efficient reverts with detailed messages.
External calls to other contracts can fail silently if you don't check their return values. This issue is #6 on OWASP's Web3 risks and has led to funds getting stuck or contracts assuming success when operations actually failed.
Low-level calls like call(), delegatecall(), and send() return boolean success indicators instead of reverting automatically. If you ignore these return values, your contract might continue executing with false assumptions, thinking funds transferred when they didn't, or that a critical operation completed when it failed. ERC-20's transfer() also has this issue in some implementations that return false instead of reverting.
Vulnerable pattern:
Secure implementation:
}`
Always capture and check return values from external calls. For Ether transfers, prefer call{value: x}("") over deprecated send() or transfer(). For token transfers, use OpenZeppelin's SafeERC20 wrapper which handles non standard ERC-20 implementations that don't revert on failure.
Flash loans allow borrowing massive amounts with no collateral as long as you repay within the same transaction. Attackers can exploit this logic to manipulate prices, drain pools, or exploit protocol logic, making it #7 on OWASP's Web3 risks with billions lost across DeFi.
Hackers use flash loaned capital to artificially skew oracle prices, exploit rounding errors at scale, or create temporary market conditions that trigger vulnerable contract logic. A classic pattern that has played out in hacks time and time again: borrow millions, manipulate a price oracle or liquidity pool, exploit the mispricing in your protocol, repay the loan, and pocket the difference all atomically in one transaction.
Vulnerable pattern:
Better approach:
Defense strategies: use Time Weighted Average Prices (TWAPs) or Chainlink instead of spot prices. Add multi-block cooldowns for critical operations, require over-collateralization, and verify your protocol's health after state changes. If you don't need flash loans, consider blocking them entirely.
Logic errors in critical functions break your contract's core security assumptions and can be catastrophic. This category of error is #3 on OWASP's Web3 risks because these flaws undermine the entire system despite being technically "correct" code.
Unlike syntax bugs caught by compilers, logic errors pass all checks but produce wrong outcomes: off-by-one errors in loops, incorrect order of operations, missing edge case handling, or flawed conditions. Classic examples include forgetting to update balances after transfers, using >= instead of >, or calculating fees in the wrong order causing precision loss.
Common logic errors:
Corrected version:
Defense strategies: Follow checks-effects-interactions pattern (validate update state external calls), write unit tests for edge cases (zero, max values, empty arrays), use fuzzing with Foundry to test random inputs, and define invariants like "total distributed should never exceed pool balance." Always have peer reviews for critical functions.
The above best practices can help you increase the resiliency, but you also need tools that can catch errors the eye might miss. Here's a mix of classic and modern tools for auditing your code:
Along with these 6 tools, you can also partner with platforms like Code4rena for bountied audits.
As a dev, your goal is simple: build contracts that don't get hacked, keeping user funds safe and your app running smooth. In that process, you should adopt the best practices above and embrace the mentality of being secure by design.
Use upgradable proxies (via OpenZeppelin Upgrades), modular code, and account abstraction (like ERC-4337 for better UX/security see our ERC-4337 guide for more details). Run unit tests, formal verifs, pro audits, runtime monitoring (e.g., via Fortress), and bug bounties on Immunefi. Your users (and your projects success) depend on it.
For more resources around contract security, check out the following:
The most critical patterns include using checks-effects-interactions, implementing reentrancy guards, validating all inputs, setting explicit visibility modifiers, and following proper access control with role-based permissions.
Use OpenZeppelin's ReentrancyGuard modifier, follow the checks-effects-interactions pattern by updating contract state before making external calls, and consider pull-over-push patterns where users withdraw funds themselves.
tx.origin can be exploited by malicious intermediary contracts that trick your code into thinking the original user is authorized, while msg.sender always refers to the direct caller, making it reliable for access control.
Upgrade to Solidity 0.8.x or later, which has built-in overflow/underflow checks that automatically revert on errors. For older versions, use well-tested libraries like OpenZeppelin's SafeMath.
Comprehensive unit tests, fuzzing with tools like Foundry, and static analysis with Slither help uncover edge cases and vulnerabilities, while independent security audits identify logic flaws before mainnet deployment.
Only use delegatecall with trusted, audited implementations, never with user-controlled addresses, maintain identical storage layouts between contracts, and prefer established proxy patterns like OpenZeppelin's upgradeable contracts.
Use Time-Weighted Average Prices (TWAPs) or Chainlink oracles instead of spot prices, implement multi-block cooldowns for critical operations, require over-collateralization, and verify protocol health after state changes.
Popular tools include Slither for static analysis, Foundry for testing and fuzzing, Mythril for bytecode analysis, and Securify for comprehensive vulnerability scanning before deployment.
See the article here:
12 Solidity smart contract security best practices - Alchemy
- Snap Specs Review: Standalone AR Glasses Are Neat, All The Bugs Are Not - Engadget - December 5th, 2026
- The 9 States in America With the Highest Risk of Bed Bugs, Ranked - Mental Floss - December 3rd, 2026
- Bed bugs found at 2 North Royalton schools, prompting partial closure - FOX 8 News - December 3rd, 2026
- Bed bugs discovered in office at FEMA headquarters in DC - ABC7 New York - November 27th, 2026
- Police shut cell at Sheffield station after reports of bed bugs - The Star - November 27th, 2026
- Over 1,000 emergency employees told to work from home after FEMA's Washington DC office was found infeste - The Times of India - November 27th, 2026
- Meet the Bugs That Live in Your Home - Nautilus | Science Connected - November 25th, 2026
- I have bed bugs and my landlord refuses to act - The Times - November 25th, 2026
- Trumps Disaster Agency Hit With Skin-Crawling Revelations - The Daily Beast - November 25th, 2026
- Bed bugs found in FEMA Headquarters office prompts building closure - WJLA - November 23rd, 2026
- FEMA is dealing with its own emergency: bed bugs - WTOP News - November 23rd, 2026
- FEMA facing bed bug infestation - KPLC 7 News - November 23rd, 2026
- Trumps FEMA headquarters dealing with bed bug outbreak with staffers ordered to stay home - The Independent - November 23rd, 2026
- Cypermethrin and Imidacloprid Combination Clears Bed Bugs in Tehran Field Trial - Bioengineer.org - November 23rd, 2026
- Exclusive | Bedbug infestation plaguing NYC 911 call center - New York Post - November 23rd, 2026
- FEMA is dealing with its own emergency: bed bugs - CNN - November 23rd, 2026
- How To Clean Your Suitcase After TravelingAnd Why You Should Never Skip This Step - Southern Living - November 23rd, 2026
- FEMA Barely Exists at This Point, but at Least Its Also Completely Infested with Bed Bugs - Jezebel - November 23rd, 2026
- In 2025, a 24-year-old Montreal woman died mysteriously at an Istanbul hotel; food poisoning was suspecte - The Times of India - November 23rd, 2026
- Bed bug infestation gets out of control inside Brooklyn 911 call center - The Weekly Times - November 23rd, 2026
- FEMA faces bed bug infestation - KXLY.com - November 23rd, 2026
- Baby dies after home filled with poisonous pesticides used to kill bed bugs as pest control boss is jailed - The Irish Sun - November 23rd, 2026
- Bed bugs discovered in office at FEMA headquarters in DC - ABC News - Breaking News, Latest News and Videos - November 21st, 2026
- FEMA facing bed bug infestation - KCRG - November 21st, 2026
- Stop bed bugs before your guests find them - Asian Hospitality - November 21st, 2026
- FEMA hit with bed bugs - KXLY.com - November 21st, 2026
- A bed bug infestation at FEMA's Washington, D.C., headquarters sent nearly 1,000 staffers home Thursday for a "building-wide" pest control... - November 21st, 2026
- FEMA facing bed bug infestation - KMVT - November 21st, 2026
- Safe extermination of bedbugs - CBC - November 21st, 2026
- Reliable Revenue in the Year Ahead - Pest Control Technology - November 21st, 2026
- FEMAs Washington base infested with bedbugs what it means for staff - The Independent - November 21st, 2026
- FEMA Staff Ordered to Stay Home Due to Bed Bug Infestation - The Daily Beast - November 21st, 2026
- Baby dies after home filled with poisonous pesticides used to kill bed bugs as pest control boss is jailed - The Sun - November 21st, 2026
- Bedbugs conquered Britain this man is fighting back by letting them bite him - The Telegraph - November 19th, 2026
- Bed bugs found at Fort Simpson high school prompt health inspection - Cabin Radio - November 19th, 2026
- Rats, bed bugs and mould: New rules planned for Reading council homes - Reading Today Online - November 17th, 2026
- Its the End Of The World As We Know It - The Trek - November 17th, 2026
- The pest Ill never forget: the bedbugs that bit me and worried Jake Gyllenhaal - The Guardian - November 17th, 2026
- Cumberland Council deals with 3,499 complaints about pests in three years - Whitehaven News - November 15th, 2026
- Bed bugs arent just a poverty problem, new study reveals - Earth.com - November 13th, 2026
- 32 Deeply Unsettling Facts About The World That Make Me Wish I Could Unlearn How To Read - BuzzFeed - November 11th, 2026
- Bedbug-killing drying room - a practical initiative of the Navy. - Vietnam.vn - November 11th, 2026
- Dont let the bed bugs bite! Chinas viral hotel map draws 200,000 users and angry hoteliers - Malay Mail - November 11th, 2026
- What is a reentrancy attack in Solidity? - Alchemy - November 11th, 2026
- Qantas to Cut 850 Jobs and Outsource Roles to Accenture - SSBCrack - November 11th, 2026
- Dont let the bed bugs bite! Chinas viral hotel map draws 200,000 users and angry hoteliers - Yahoo - November 9th, 2026
- British entomologist sleeps with thousands of bedbugs for scientific research - 24 News HD - November 9th, 2026
- Meet researcher who subjects himself to being bitten by thousands of bedbugs - Pulse Nigeria - November 9th, 2026
- The scientist who sleeps with thousands of bed bugs, letting them drink his blood - NationalWorld - November 9th, 2026
- The man who sleeps with thousands of bedbugs for science - Metro.co.uk - November 9th, 2026
- Experts address what happens when luggage and shoes are put on the bed - The Independent - November 9th, 2026
- Fella sleeps with 60k blood-sucking bed bugs in garden lab - and has feeding days - Daily Star - November 7th, 2026
- Insect fanatic straps bedbugs to himself in the name of science - Gloucestershire Live - November 7th, 2026
- Scientist studies bed bugs - by sleeping with thousands of them in garden lab - Yahoo - November 7th, 2026
- A school in Camagey is closed due to bedbugs following complaints from parents of the children - CiberCuba - November 5th, 2026
- Power BI - Get Data From SharePoint List / Library - November 5th, 2026
- How bad is it to put your luggage on the bed? We asked germ experts. - The Washington Post - November 3rd, 2026
- Let the bedbugs bite: How one scientist has chosen to sleep with critters for the past five years - and straps some of the 60,000 he has bred on his... - November 3rd, 2026
- Indiana Makes a National Top 10 List Thatll Make You Itch - WKFR - November 3rd, 2026
- Noah Kahan 2027 concert dates: Where to get tickets to 'The Last of the Bugs' world tour - Yahoo - November 3rd, 2026
- UK woman finds 40 dead bedbugs in hotel bed, claims she suffered over 100 bites - India Today - November 3rd, 2026
- The scientist who chooses to sleep with bed bugs - BBC - November 3rd, 2026
- Scientist chooses to sleep with bedbugs for years to show what they're really like and has surprising results - UNILAD - November 3rd, 2026
- The man who chooses to sleep with bedbugs - Yahoo News Australia - November 1st, 2026
- The Gloucestershire man who chooses to sleep with bedbugs - BBC - November 1st, 2026
- Bed Bugs Cause Severe Skin Reactions After Hotel Stay, With Medical Guidance on Bites and Treatment - - November 1st, 2026
- Flea or Mosquito Bite? Bug Experts Explain the Key to Telling Them Apart - Prevention - November 1st, 2026
- Putting the Bite on Biting Pests with Coconut Oil Derivatives - USDA (.gov) - October 29th, 2026
- Oberlin library cleared of bedbugs in Raleigh - CBS 17 - October 29th, 2026
- Mum vows never to use Holiday Inn again after Exeter stay leaves her in A&E - Devon Live - October 28th, 2026
- The Problem of Celebrating Mints on Pillows, When You Have Bugs in the Bed - TAPinto - October 28th, 2026
- Tiny web-dwelling bug discovered in China is a brand-new species - Bioengineer.org - October 28th, 2026
- Oakmont Carnegie Library temporarily closed after bed bugs found in part of building - WPXI - October 28th, 2026
- Bed bug cases are on the rise: How to best protect your mattress from the bugs amid the country wide spike - Good Housekeeping - October 28th, 2026
- It Looks Like a Still Image From Paranormal Activity: Man Sleeps on Water Jugs for 2 Months to Escape Bedbugs in Texas - The Nerd Stash - October 28th, 2026
- Bedbugs force prison cells to close as 3,800 spaces lost in overcrowding crisis - Daily Express - October 28th, 2026
- Bedbug infestation forces closure of cells at Norfolk prison amid overcrowding crisis - EDP24 - October 28th, 2026
- Bedbugs force prisons to leave cells empty - The Telegraph - October 26th, 2026
- Bedbugs force prisons to leave cells empty - The Telegraph - October 26th, 2026
- Almost 3,800 prison cells left empty by bedbugs, asbestos and diseases - The Independent - October 26th, 2026
