Smart Contract Risk and How to Mitigate It: A Deep-dive

The strengths of smart contracts are also the source of its weaknesses, and will always present opportunities for hackers to exploit. So far, the pace of innovation in counter-measures is struggling to keep pace with innovation in the methods of attack. It’s reasonable to assume that as the Web3 environment stabilizes, an equilibrium will be achieved. However, the threat cannot be eliminated, and vigilance will always be a necessity.


In her seminal book on Web3 fundamentals, The Token Economy, Shermin Voshmgir defines a smart contract as ‘a self-enforcing agreement, formalized as software.’ She also offers the more intuitive example of a snack vending machine, which executes an agreement if and only if a condition is fulfilled (coin deposited → snack delivered).

Smart contracts are the building blocks of dApps (decentralized applications) and DAOs (on-chain self-governing corporate structures). They can therefore be seen as one of the “primitives” for creating a viable on-chain economy for financiers, musicians, and one day – presumably – the consumer public at large.

The advantages of smart contracts versus traditional enforcement mechanisms are obvious. Computer code is cheaper and faster than bureaucratic processes involving (often demotivated) human intermediaries. If correctly written, it eliminates human error, principal-agent problems, and other malicious interventions.

And as with all blockchain-based systems, the two parties can transact safely without the need to know or even trust each other.

This obviously makes it possible to improve existing processes: for example, converting traditional equity shares into cryptographic tokens that automatically dispense dividends to the owner. It also expands the scope of collaborative activities. As the Internet of Things proliferates, more and more transactions and interactions can be delegated to machines collaborating with other machines, based on rules that humans can set and forget.

So far, so utopian.

Now let’s return to the analogy of a vending machine. Vending machines share many of the benefits of smart contracts: being human-free, they are cheap to run, reliable, and always available. But they are not invulnerable.

In fact, it is because they are predictable, always available, and have no on-site human custodian that would-be vending machine hackers can take their time to experiment with different methods to breach their security.

Vending machine manufacturers have therefore had to respond to these breaches by improving their security safeguards over time. Meanwhile, hackers have become more sophisticated and more ambitious. While hacking used to involve a coin and a string, it now involves stealing user credit card information.

Smart contracts are no different, except that the stakes are considerably higher than a few dollars’ worth of candy bars.

Why Smart Contracts are at Risk

The reason that smart contracts will never be completely safe is that it is impossible to eliminate the human element. Smart contracts consist of computer code, and code is written by humans. It simply takes a lapse of judgment for a weakness to appear, following which it is only a matter of time before it is discovered and exploited.

Smart contract errors have become more common in part because of the breakneck pace of evolution in Web3. Because smart contracts are open source, it is quicker to copy existing contracts rather than code from scratch. Making adjustments to another programmer’s code, without careful consideration of the potential for existing flaws or unintended consequences, will inevitably lead to errors.

As observed in the Ethereum whitepaper, financial services is a natural application for smart contract technology, not least because of the pressing need for democratization, transparency, and the elimination of slow processes (such as the need to take several days to ‘settle’ a transfer of electronic funds).

The DeFi explosion of 2020 created a high-risk environment for users relying on the integrity of hurriedly launched projects. During this period, CipherTrace reported that over half of all crypto attacks were made upon DeFi protocols, with millions drained successfully from contracts, including Harvest, Yam Finance, and bZx.

Case Study: The DAO

Even before the DeFi boom, the Ethereum blockchain has been the destination of choice for hackers. It was also home to perhaps the most infamous hack in blockchain history, known as ‘The DAO Attack’.

‘The DAO’ was an early implementation of the decentralized autonomous organization (DAO) concept. Its first task was to raise funds, and it had succeeded in attracting $150m from crowdfunding efforts by the date of the attack on June 18, 2016.

The attacker, using a vector known as ‘Re-entrance’, exploited a recursive weakness in the smart contract holding the treasury funds to remove 3.6m in Ether (~$70m at the time) before being spotted.

Here is a simplified version of the attack. If you are not a Solidity programmer, don’t worry if you don’t understand every expression, just let it wash over you!

Source: “Reentrancy Vulnerability Identification in Ethereum Smart Contracts”, Noama Fatima Samreen, M. Alalfi

The victim contract (containing the targeted funds) contains a ‘withdraw’ function (line 3), which allows an external contract to legitimately remove funds. According to the normal process, the flag would then change to ‘true’ (line 5) and the process would be over.

Thanks to the triggering of a fallback function (lines 4,10), a necessary component to account for unexpected failure, the attacker contract (below) is able to execute another withdrawal before the flag can be changed, and so repeat the process.

And we’ve not got to the worst part yet. As smart contracts are immutable, there was no way to fix the contract, even after the error was discovered. Instead, the Ethereum community took the drastic decision to create an entirely new version of Ethereum, a process known as hard forking.

This created a split in the Ethereum community that persists to this day. To understand the magnitude of the decision, recall the Simpsons episode in which the entire town of Springfield has to be relocated to another part of the US after a scheme by Homer turns the former location into an uninhabitable landfill site. Such a solution is not a feasible solution for most smart contract hacks, and so in most cases, developers are forced to look helplessly on as the funds are drained.

The DAO hack demonstrates how the three distinguishing features of smart contracts – immutability, transparency, and capacity to hold value – can be a catastrophic liability affecting not only the users of a contract but the members of an entire community.

Navigating Smart Contracts Errors

Each smart contract hack pivots on an error in the code, and these errors are often unique. Smart contracts hacks can therefore be hard to categorize.

Furthermore, understanding the precise nature of the error typically requires a familiarity with programming terminology. Cryptic labels such as ‘Call to the unknown’ and ‘Unpredictable state’ are often of little use to the non-technical reader.

There are some examples that commonly recur in lists summarizing the risks.

Timestamp and Transaction order dependence are hacks that stem from the ability of a block miner to exercise discretion in terms of how a transaction is recorded or executed. If a smart contract is dependent on the timing of a transaction, the miner can manipulate the outcome in their own favour.

DelegateCall attacks, like the Reentrance strategy used to hack The DAO, induce the target contract to connect with an external contract, which then executes a malicious function to withdraw or freeze the value it contains.

Overflow/Underflow attacks are based on a manipulation of the arithmetic logic of certain functions within the language used to code a contract. By invoking a number that falls outside the expected range, a parameter (such as a lock-in time) can be reduced to zero, or radically inflated.

A Short Address Attack is an exploit of an idiosyncratic flaw that entitles a hacker to withdraw 256 times the stated amount if the last two zeros of the blockchain address are omitted when making the request.

It is not surprising that smart contract errors are complex, as they would be unlikely to escape the notice of developers and the wider (benevolent) community if this were not the case.

How to protect yourself

As smart contract risk rises in prominence, particularly where large sums are involved, work has begun to develop solutions for reducing or at least offsetting the potential dangers.

3rd party audits

A smart contract audit, as the name implies, is a methodical examination of the contract code for coherence, errors, and vulnerabilities.

Audits are important not only to improve contract performance and detect errors, but also to allow market participants to transact with greater peace of mind. A thorough, documented audit may also be a necessary step in securing smart contract insurance coverage (see below).

As already mentioned, once a smart contract is written to the blockchain, it can no longer be changed. A ‘launch and learn’ strategy is neither advisable nor possible. All errors must be fixed prior to launch.

Developers should therefore be sure to have a comprehensive smart contract audit performed prior to any commercial launch, and users, for their part, should include as part of their due diligence that any institution they do business with, whether buying, selling, or lending, has been audited by a reputable firm.

Audit firms include general IT security services providers such as Hacken, as well as blockchain-specialized firms such as Quantstamp and Trail of Bits.

An audit will typically comprise three parts:

  • Scope definition: The developer provides the auditors with a clear specification of the smart contract’s architecture, purpose and important functions.
  • Testing phase:
    • Stress-testing: The auditor will typically begin by running a suite of standard tests to uncover common errors (e.g. re-entrancy). Depending on the outcome of these tests, it may make sense to make fundamental alterations to the code and postpone the launch.
    • Manual review: In addition to running a battery of tests and running bug-detection software, it is good practice to perform a manual code review. Manual code reviews are important because a human auditor is able to take into account the intentions behind the smart contract, unlike AI.
  • Recommendations: The audit team will communicate their findings to the developer team, who will take action to address any errors or areas of potential improvement. These actions will be documented alongside the recommendations in the final audit report.

It is important to be aware that there is no standard process for approaching a smart contract audit. This lack of universally agreed standards is due in part to the heterogenous nature of smart contracts themselves, but mainly to the early-stage nature of blockchain technology,

Security Tools

Security firms that offer audit services often grant commercial access to the security tools they use to assist them in their work. Such tools include Slither (Trail of Bits) and MythX (ConsenSys) and are typically distinctive in their approaches, as well as their strengths and weaknesses.

While not a substitute for a professional engagement with a dedicated team, smart contract analytics tools can be used by clients to monitor and fix errors independently in between audits.


Another effective form of audit that developers can use is a bounty program (just as in standard web applications). A bounty contest involves hackers being challenged to find errors in smart contracts prior to launch, in return for a reward.

The major protocols have bounties in place, with the size of the prize depending on the severity of the flaw uncovered. The Layer 2 protocol Polygon recently paid its maximum bounty of $2m to a hacker who uncovered a potentially seismic exploit in the platform’s code after just four days of testing.

Organizing such programs is one of the many services offered by security firms. OpenZeppelin launched a war game called Ethernaut, which incentivizes gamers to progress through the ‘levels’ of the game by hacking smart contracts. Gamification is a common trope in bounty programs, with leaderboards and personal glory playing a significant role.

Oddly enough, it is not uncommon for genuine hacks to be followed by the hacker returning part of the stolen funds, implying that there is a sense of gamesmanship among programmers that supersedes criminal motives!


As long as smart contracts continue to evolve, and blockchain-based firms continue to innovate, it is impossible to guarantee that smart contract errors or exploits will not occur, irrespective of the sophistication of auditor and their tools.

Logically, therefore, a nascent insurance industry is springing up to help address this.

The initial charge has not been led by traditional insurance companies. One of the earliest pioneers was a startup called Nexus Mutual established in 2017. Its coverage is currently in excess of $400m.

As the firm is built on Web3 principles, it not only allocates risk amongst its policyholders, but also offers access to governance via its native token (NXM).

Tokens can be used to vote on whether to approve claims, exchanged for coverage, or staked to earn a share of the policy premiums (for unhacked contracts). Members also vote on whether to insure new projects, and teams with a poor reputation or lax procedures have been refused coverage.

Following its lead, other smart contract insurers are emerging such as Insurace, offering competitive pricing and more aggressive rewards from mining programs. Let the best insurer win!


Despite their many benefits, it should be obvious that smart contracts are far from perfect. That said, the transparency of these flaws makes them – one might argue – easier to fix, or at least learn from once exposed.

The pace of on-chain development has certainly not slowed as a result of the many high-profile hacks that have taken place, and with the growth of a dedicated blockchain insurance industry, it seems reasonable to look forward to a more stable future, in which smart contrast risk is – like other perennial hazards such as earthquakes and flooding – accepted as a fact of life.

Those least likely to suffer loss are the vigilant, and we hope that this article has gone some way to heightening the reader’s awareness of these risks.


For an overview of blockchain threats see Security Threats to Blockchain Networks – A Holistic Overview