Transform your $HAI holdings into Hacken shareholder status. Only 100 slots available. > Learn more and join the waitlist here.

  • Hacken
  • Blog
  • Discover
  • How To Hack Smart Contracts: Choosing The Path Between Attack & Defense

How To Hack Smart Contracts: Choosing The Path Between Attack & Defense

By Malanii Oleh

Share via:

While most hacks in Web3 come as rug pulls and access control compromises, smart contract vulnerability exploits account for a regularly significant share of losses. In Q3 2023, Web3 projects lost nearly $100M due to smart contract hacks.

With so much money at stake, it’s at least understandable why smart contract developers go over the dark side and try themselves in hacking. In this article, let’s try to uncover that perspective and discuss how smart contracts can be exploited. Our goal is to give you the information, and it’s you who makes the hacking vs protecting decision.

Keep an eye out throughout this text for the most helpful resources.

Understanding Smart Contracts

Smart contracts are the backbone of decentralized trading, lending, and staking applications. Developed as deterministic programs in a high-level language (Solidity, Rust, etc.), smart contracts are compiled into bytecode for a runtime environment (EVM, WebAssembly, etc.). Once deployed, they operate continuously on the blockchain like Ethereum, Radix, or NEAR.

Because smart contracts are stored on-chain, hackers can examine the public codebase for vulnerabilities, such as reentrancy or missing checks, and then conduct their attacks. For example, the most recent KyberSwap $47M hack had a reentrancy error in the mint function of their new token implementation. Hackers can even combine their exploits with flash loans for maximum damage, as in the case of the SushiSwap DEX hack.

Hence, knowing how smart contracts operate and the potential weak spots of the most common tech stacks is vital for both hacking and protecting the underlying assets.

Smart Contract Hacking Setup

A robust setup is essential for identifying and exploiting vulnerabilities in smart contract development and security testing. Critical components of this setup include development frameworks and runtime environments.

Development Frameworks

  • Hardhat offers a local Ethereum environment for testing, debugging, and deploying contracts. Many believe the Hardhat stack is the most complete framework today, but you can decide.
  • Truffle, renowned for its comprehensive development suite, provides contract testing and migrations functionalities.
  • On the other hand, Foundry is gaining popularity for its fast and flexible testing capabilities.
  • Remix IDE is a powerful, open-source tool that allows developers to write, deploy, and test smart contracts directly in a web browser. It’s handy for quick prototyping and provides an accessible platform for beginners and experts to experiment with smart contract code.

Runtime Environment

Understanding Ethereum Virtual Machine (EVM) or WebAssembley is critical because it will run your smart contracts on the blockchain. Knowledge of EVM’s inner workings aids in comprehending contract behaviors and potential vulnerabilities.

The Hacker’s Perspective: How Hackers Exploit Vulnerabilities

Let’s discuss the most common ways smart contracts are not secure.


Issue: Functions call external contracts before updating their state.
Scenario: Based on Rari Capital 2022 hack, the attacker exploited a vulnerability in the borrow function, which executed asset transfer before updating the state.
Mitigation: Implement the “Checks-Effects-Interactions” pattern—execute all checks and state updates before external calls, use reentrancy guard, and limit available gas for functions to prevent loop exploits.

Bad Randomness

Issue: Lack of secure, random number generation in Ethereum smart contracts.
Scenario: Attackers manipulate block hashes or timestamps to influence outcomes, like in lotteries.
Mitigation: Avoid reliance on on-chain randomness. Emerging solutions include verifiable delay functions and Randao commit-reveal schemes.

Denial of Service (DoS)

Issue: Contracts performing bulk operations are vulnerable to stalling if a component fails.
Scenario: A failed refund transaction can indefinitely stall the process in an auction contract.
Mitigation: Prefer pull over push mechanisms and efficiently manage loops to handle large data structures.

Forced Ether Reception

Issue: Contracts can unintentionally receive Ether, disrupting their functions.
Scenario: Use of selfdestruct in a contract forcibly sends Ether to another contract.
Mitigation: Design contracts to handle unexpected Ether receipts, avoiding assumptions about contract balances.

Integer Overflow

Issue: Solidity’s integer operations can overflow or underflow, leading to errors.
Scenario: ERC20 tokens without underflow checks can result in attackers gaining excessive tokens.
Mitigation: Use libraries like OpenZeppelin’s SafeMath and validate all arithmetic operations.

Race Condition

Issue: The time gap between transaction creation and acceptance can be exploited.
Scenario: In ERC20 tokens, approve and transferFrom can be manipulated, allowing unintended token transfers.
Mitigation: Implement zero balance approval requirements and design contracts to anticipate and handle front-running scenarios.

See related: Top 6 Smart Contract Vulnerabilities And How to Stop Them

Hands-On Smart Contract Hacking Experience

You won’t be able to hack anything if you don’t know how to create a smart contract in the first place.

Start with setting up a development environment. For example, Remix IDE offers tools for writing, compiling, and deploying smart contracts. The process includes writing the contract code in Solidity, the most popular programming language for smart contracts, and compiling the code to ensure it’s ready for deployment. Next, you should deploy the contract to a test network like Goerli using tools like Metamask to confirm its behavior. Once tested and debugged, which may involve experimenting with various inputs and observing the outcomes to ensure proper functionality, you can go to the mainnent to interact with other contracts. Related resources:

  • How To Create A Smart Contract: A Hacken’s tutorial on creating your first Solidity contract.
  • Crypto Zombies: A foundational course in Solidity, offering insights into the language’s nuances and quirks. Ideal for beginners to grasp the basic concepts of smart contract programming.

Deploying your first smart contract is only the beginning, and you really have to master a smart contract programming language and learn a lot about the DeFi business even to spot unprotected liquidity. Here are the best resources to learn:

Standard and Testing:

Assuming you excel in these steps, it’s time to hone your offensive skills. Participate in wargames and playgrounds. Here are a few resources that are definitely worth your time:

  • Capture the Ether: A dozen of challenges to get into the basics of doing miscellaneous things.
  • Damn Vulnerable DeFi: A series of 15 hacking offensive security challenges for Ethereum smart contracts covering all major aspects of decentralized applications: flash loans, price oracles, governance mechanisms, NFTs, decentralized exchanges, lending pools, smart contract wallets, and timelocks. One of the best wargames out there.
  • Ethernaut: 29 fun and challenging tasks for you to hack the smart contract, allowing for hands-on practice in identifying and exploiting smart contract weaknesses.

Smart Contract Security – Turning The Tables 

Even ignoring the ethical and legal considerations, smart contract hacking is an extremely challenging and risky endeavor. A successful hack requires a perfect alignment of factors – finding unaudited and/or vulnerable contracts, being the first to discover and act, having the right skills for an attack, and managing to evade detection while vanishing with the stolen assets. As a result, the path of a smart contract hacker will be largely unrewarding for most people.

Yet, software engineers passionate about discovering vulnerabilities can engage in a more rewarding path. Independent ethical hackers, auditors, and bug hunters have all discovered that Web3 offers a different way of challenging your snooper character.

See related: How To Become A Smart Contract Auditor

Learning from Smart Contract Hacks

Every smart contract hack always offers valuable learning opportunities. Let’s take Onyx Protocol exploit, for example. Onyx, a Compound Finance fork, lost $2.1 million due to a rounding error when creating new liquidity markets. But there’s a catch. The exact same vulnerability had already hit Hundred Finance and Midas earlier this year. It wasn’t the first time that projects didn’t implement simple workarounds to high-profile vulnerabilities.

So the implication is clear: read about hacks and learn from them. Resources like rekt and Hacken Insights may help.

Tools for Security Analysis

A multi-stage approach is essential for thorough vulnerability discovery. Here are some key tips and smart contract audit tools used in this process:

1. Preliminary Assessment:

  • Tool Integration: Begin with tools like Slither for Solidity contracts, which analyze source code for vulnerabilities, and Clippy for Rust contracts, designed to catch common mistakes.
  • Initial Analysis: Use tools like Mythril and Solgraph to identify potential vulnerabilities and visualize function control flows in Solidity contracts. For Rust, Cargo-udeps and Cargo-audit can help in detecting unused dependencies and auditing crates for security vulnerabilities.
  • Functional Testing: Incorporate Echidna for fuzzing and property-based testing of Solidity contracts, and Cargo-geiger to detect the usage of unsafe Rust code.

2. In-Depth Review:

  • Line-by-Line Analysis: Conduct a thorough review of the code. This includes using tools like Mythx for Solidity, which combines static and dynamic analysis, to detect a wide range of vulnerabilities.
  • Parameter Checking: Apply over 50 language-specific parameters for EVM (Solidity, Vyper, Yul) and Rust-based contracts (Solana, Near, CosmWasm) to ensure comprehensive coverage.
  • Testing Gaps: Assess test coverage rigorously. If gaps are found, develop and implement additional test cases to cover both positive and negative scenarios.

3. Verification:

Reference authoritative resources to verify found vulnerabilities in Solidity and other programming languages:

See related: Smart Contract Audit Process Followed By Top Auditors

Best Practices for Secure Smart Contract Development

Secure smart contract development rests on several key pillars, each contributing to a robust defense against potential vulnerabilities:

  1. Defensive Programming: This strategy proactively checks for and limits access in smart contracts to avert financial losses.
  1. Principle of Least Privilege: This principle limits system access to only what’s necessary for each task, preventing unauthorized actions through access control and role-based authorizations.
  1. Proactive Checks: These checks validate inputs and outputs, preventing erratic contract behavior and ranging from basic balance validations to intricate business logic constraints.
  1. Utilization of Well-Known Libraries: Using proven libraries like OpenZeppelin, PRBMath, and Gnosis Safe enhances smart contract security and functionality.
  1. Purposeful Delays: Deliberate action delays in contracts, especially in DeFi, offer a time-based buffer against threats and allow community response.
  1. Concrete Types Usage: Using the most secure default types in smart contracts ensures type safety, efficiency, and intended functionality.

Community Engagement & Knowledge Sharing

Stay updated with blockchain language and network advancements, actively engage in open-source communities, and share knowledge for professional growth in this dynamic field.


The challenges and risks associated with hacking, coupled with legal and ethical considerations, make it a largely unrewarding option for most engineers. Instead, aspiring ethical hackers can find a rewarding career in safeguarding blockchain technology. Engaging in security analysis, learning from past vulnerabilities, and joining communities like Hackenproof are ways to contribute positively to the Web3 ecosystem. Choosing security over hacking offers a fulfilling career and is crucial in building a safer digital blockchain world.

Follow @hackenclub on 𝕏 (Twitter)

subscribe image
promotion image

Subscribe to our newsletter

Enter your email address to subscribe to Hacken Reseach and receive notifications of new posts by email.

Read next:

More related
  • Blog image
    Smart Contract Auditing Tools Reviewed: Pros, Cons, And The Need For Manual Checks Saylık S.Malanii O.
  • Blog image
  • Blog image

Get our latest updates and expert insights on Web3 security