DEV Community

Abdullah Sheikh
Abdullah Sheikh

Posted on

How to Write Solidity Smart Contracts That Don't Get Hacked – A Practical Guide

Follow this step‑by‑step playbook to build secure contracts, avoid common pitfalls, and protect your assets

Before We Start: What You'll Walk Away With

By the end of this guide you’ll be able to spot the most common vulnerability patterns, write a contract that passes a professional audit on the first try, and reach for a ready‑made checklist whenever you start a new project.

Think of security like packing a suitcase: you don’t just toss everything in, you arrange the fragile items first, then the heavy ones, and finally seal the bag. The same disciplined order applies to Solidity smart contract security.

  • Core concepts mastered – you’ll know exactly which attack vectors (re‑entrancy, overflow, access control, etc.) must be covered, just like you’d know the rules of the road before driving.

  • Audited‑ready workflow – you’ll follow a repeatable step‑by‑step process that takes you from blank file to deployable code, similar to following a recipe that guarantees a perfect dish every time.

  • Cheat sheet & tool arsenal – you’ll receive a concise reference list of linters, static analyzers, and testing frameworks that you can pull up like a GPS map whenever you start a new contract.

This isn’t theory; it’s a battle‑tested set of actions you can apply immediately to any solidity smart contract security project.

Grab the checklist, fire up the tools, and you’ll spend less time worrying about exploits and more time building the features that matter.

What Solidity Security Actually Is (No Jargon)

Solidity security means building a contract so that nobody can sneak in, drain the balance, or mess with the logic after you deploy it.

Picture the contract as a vault door with several independent locks. One lock might be a re‑entrancy guard, another an overflow check, a third an access control. If any lock is missing or faulty, a thief can pick that weak point and walk out with the loot.

  • Re‑entrancy guard – stops a function from being called again before it finishes.

  • Overflow check – ensures arithmetic can’t wrap around and give you extra tokens.

  • Access control – limits who can call privileged functions.

When you design, code, and test with these locks in place, you’re essentially hardening the vault against every known tool a hacker might use. That’s the core of solidity smart contract security – a habit, not a one‑off checklist.

Think of it like packing a suitcase for a trip: you double‑check every pocket, zip the main compartment, and use a lock if you’re carrying valuables. Skipping any step leaves a gap for theft or loss. The same discipline applies to contracts before they hit the blockchain.

Keep this mental picture handy: a contract without proper locks is just a fancy box anyone can open.

The 5 Mistakes Everyone Makes With Solidity Security

Let’s cut to the chase – these five blunders bite even seasoned developers.

Skipping input validation and trusting external data. It’s like ordering a pizza and assuming the delivery driver will remember your extra cheese request without confirming. Always check msg.value, array lengths, and any user‑supplied parameters before using them.

Using tx.origin for authentication. Think of tx.origin as a family‑wide keycard that opens any door in the building. An attacker can chain contracts to impersonate you. Stick to msg.sender checks and role‑based access control.

Forgetting SafeMath or built‑in overflow checks. In older compilers, adding two large numbers is like packing an oversized suitcase – the zipper bursts and the contents spill. Either import SafeMath or compile with pragma solidity ^0.8.0 where overflow throws automatically.

Leaving external calls unguarded. Calling another contract without a re‑entrancy lock is like handing a stranger your cash register keys while you walk away. Use the Checks‑Effects‑Interactions pattern or ReentrancyGuard to keep the money safe.

Deploying without a formal audit or automated static analysis. Imagine shipping a product without any QA testing – you’ll soon get returns. Alex, a freelance token creator, pushed a token contract straight to mainnet. A static scan later flagged an unchecked delegatecall, which the community exploited for $200k. Run slither and schedule a third‑party audit before the first transaction.

  • Cheat sheet: validate every input, use msg.sender, compile ^0.8.0, apply ReentrancyGuard, run slither + audit.

Fix these, and your Solidity smart contract security will be a lot harder to breach.

How to Write Secure Solidity Contracts: Step‑by‑Step

Start with the newest stable compiler so you get automatic overflow checks, just like a modern car comes with built‑in airbags.

  • Set pragma solidity ^0.8.24; at the top of every file. The compiler now throws on arithmetic errors without extra code.

  • Pick a single ownership model. Use OpenZeppelin’s Ownable for simple admin rights or AccessControl for role‑based permissions—think of it as assigning a key‑card to each staff member.

  • Guard every external input. Add require checks that validate ranges, addresses, or enum values before the contract proceeds. It’s like confirming a customer’s order before the kitchen starts cooking.

  • Never mix calls and state changes. Follow the Checks‑Effects‑Interactions pattern and inherit ReentrancyGuard. Replace raw call/transfer/send with the guarded nonReentrant modifier—similar to locking a door before handing over the house keys.

  • Write unit tests that hit edge cases (zero values, max uint, re‑entrancy scenarios). Then run a static analyzer such as MythX or Slither. Think of the tests as a dress rehearsal and the analyzer as a safety inspector.

  • Do a manual line‑by‑line review. Focus on state mutability (view, pure) and visibility (private, internal) just like you’d double‑check a suitcase’s contents before a flight.

  • Schedule a formal audit—internal or third‑party—before any mainnet launch. An audit is the equivalent of a building’s fire safety inspection.

  • Deploy through a multi‑sig wallet and attach a timelock for upgrades. This adds a waiting period, similar to a reservation system that prevents last‑minute overbooking.

Follow these steps and your solidity smart contract security checklist will be ready for the real world.

A Real Example: Securing a Simple ERC‑20 Token

Maya grabs OpenZeppelin’s ERC‑20 starter, sets pragma solidity ^0.8.24;, and begins tailoring it for her community token.

  • She inherits Ownable so only she can call admin functions. Think of it like giving yourself the master key to a clubhouse.

To stop runaway minting, Maya adds a cap check:


solidity
require(totalSupply + amount 
- Every time she moves tokens she swaps the raw `address.transfer` call for OpenZeppelin’s `_safeTransfer`. Then she wraps `transfer` and `transferFrom` with the `nonReentrant` modifier, like putting a “no‑double‑tap” guard on a door.

- **Static analysis:** Maya runs `slither ./contracts/Token.sol`. The tool spots two warnings about uninitialized storage pointers, which she fixes by explicitly initializing the structs.

- **Audit step:** She sends the cleaned repo to a 2‑day audit service. The report comes back clean, confirming the contract passes the *solidity smart contract security* checklist.

- **Deployment:** With confidence, Maya pushes the bytecode through a Gnosis Safe multisig, ensuring the final launch needs multiple approvals—like requiring two signatures before cashing a big check.

Result: Maya’s token now has a bounded supply, protected transfer logic, and a clean audit trail, ready for the community without the fear of a surprise hack.

## The Tools That Make This Easier

Grab the right toolbox and you’ll feel like you’ve got a GPS for contract safety instead of wandering blind.

- **Foundry** – Think of it as a high‑speed kitchen where your tests bake in seconds. Its built‑in fuzzing throws random inputs at your functions, catching edge‑cases before they hit mainnet.

- **Slither** – This static analyzer works like a security guard scanning luggage. It flags re‑entrancy, unchecked low‑level calls, and other red flags without executing the code.

- **MythX** – Imagine a cloud‑based lab that runs a full suite of checks while you sip coffee. The free monthly quota handles small contracts, surfacing vulnerabilities that slip past local tools.

- **OpenZeppelin Defender** – A task scheduler and upgrade manager that acts like a smart lock for your deployment pipeline. Role‑based access control ensures only authorized keys can trigger upgrades.

- **Remix IDE (with Solidity Analyzer plugin)** – The quick‑draw sketchpad for Solidity. As you type, the analyzer pops up warnings, letting you spot mistakes the same way a spell‑checker highlights typos.

Here’s a quick cheat sheet to get you rolling:

- **Run tests fast:** `forge test` with Foundry’s fuzz mode.

- **Scan statically:** `slither src/` before any commit.

- **Upload to the cloud:** `mythx analyze MyContract.sol` for an extra safety net.

- **Schedule upgrades:** Set up a Defender task to auto‑run your migration script.

- **Prototype instantly:** Open Remix, enable the Analyzer, and watch warnings appear as you code.

With these tools at hand, **solidity smart contract security** becomes a routine, not a gamble.

## Quick Reference: Solidity Security Cheat Sheet

Here’s the cheat sheet you’ll paste into every new repo.

- **Compiler version** – lock to `pragma solidity ^0.8.` or newer. Like choosing a car with airbags built‑in; the compiler catches overflow before it hurts.

- **Access control** – inherit `Ownable` or `AccessControl` for any admin‑only function. Think of a restaurant kitchen: only chefs with the right badge can touch the stove.

- **Input validation** – guard every external argument with `require`. It’s the “check your change” step before you hand over a bill.

- **Checks‑Effects‑Interactions** – update state, then call external contracts, and wrap vulnerable functions with `ReentrancyGuard`. Like packing a suitcase: put the heavy items at the bottom before closing the lid.

- **Static analysis** – run `slither` and `mythx` on every commit. Ava, a freelance security‑enthusiast, makes this a pre‑push hook so nothing slips through.

- **Testing coverage** – aim for >80% line coverage using `forge` (Foundry). It’s the “test‑drive” that catches bugs you missed while coding.

- **Manual + third‑party audit** – walk through the code yourself, then hire an external auditor before mainnet. Like a double‑check before you lock the front door.

- **Deployment safety** – use a multisig wallet and a timelock contract for upgrades. It’s the “two‑key safe” that gives you a cooling‑off period.

- Keep this list in `README.md` and treat it like a checklist before each release.

- Update it whenever you adopt a new library or pattern.

## What to Do Next

Grab a coffee and start tightening the bolts on your contract security.

- **Clone the OpenZeppelin ERC‑20 template and add `nonReentrant`**. It’s like swapping a cheap lock for a deadbolt – five minutes and you’ve blocked a common re‑entrancy exploit.

- **Run a full Slither + MythX scan on your existing contracts and fix the top three issues**. Think of it as running a spell‑check before you hit “send”; the tools will highlight the low‑hanging problems, and you can patch them in about half an hour.

- **Schedule a 2‑hour internal audit or hire a reputable firm for a formal review**. This is the equivalent of getting a professional mechanic to look under the hood – it takes a day or two to arrange, but it catches the subtle bugs that automated tools miss.

- **Tools:** `git clone https://github.com/OpenZeppelin/openzeppelin-contracts`, `npm install -g slither-analyzer`, MythX via `mythx-cli`.

- **Tip:** Keep a *cheat sheet* of the top five warnings each scanner throws; it speeds up future reviews.

Got a contract you’re unsure about? Drop a comment or DM me with the snippet – I’ll help you spot the risk.

---

---

## About the Author

**[Abdullah Sheikh](https://abdullah-sheikh.com/)** is the Founder & CEO at [Exteed](https://exteed.com/), where he leads a team of skilled developers specializing in [Web2](https://abdullah-sheikh.com/) and [Web3 applications](https://abdullah-sheikh.com/), [Custom Smart Contracts](https://abdullah-sheikh.com/), and [Blockchain solutions](https://abdullah-sheikh.com/).

With 6+ years of experience, Abdullah has built [CRMs](https://abdullah-sheikh.com/), [Crypto Wallets](https://abdullah-sheikh.com/), [DeFi Exchanges](https://abdullah-sheikh.com/), [E-Commerce Stores](https://abdullah-sheikh.com/), [HIPAA Compliant EMR Systems](https://abdullah-sheikh.com/), and [AI-powered systems](https://abdullah-sheikh.com/) that drive business efficiency and innovation.

His expertise spans [Blockchain](https://abdullah-sheikh.com/), [Crypto & Tokenomics](https://abdullah-sheikh.com/), [Artificial Intelligence](https://abdullah-sheikh.com/), and [Web Applications](https://abdullah-sheikh.com/); building reliable and smooth web apps that fit the client’s goals and requirements.

📧 [info@abdullah-sheikh.com](mailto:info@abdullah-sheikh.com) · 🔗 [LinkedIn](https://www.linkedin.com/in/-abdullah-sheikh/) · 🌐 [abdullah-sheikh.com](https://abdullah-sheikh.com/)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)