What You Need to Know about Smart Contract Security

12 min read
Most Common Hacks And Exploits

Learn smart contract security tips to defend against attacks like MEV, flash loan, and more.

An onslaught of cyberattacks in recent times has cast doubt on the security of smart contracts and the Web3 projects built on them. But where conventional security measures fall short, cover policies can provide a safety net and inspire confidence in the viability of these projects. Find out what kinds of hack and exploit incidents decentralized insurance can protect you against.

On June 18th, 2016, community members of The DAO awakened to the disturbing news that a smart code vulnerability in the protocol had been exploited resulting in the loss of over 3.6 million ETH (around $70 million at the time). Just days before, the blockchain-based cooperative had concluded its fundraising period, closing a whopping $150 million from more than 11,000 enthusiastic members.

In the attack, the hacker was able to exploit a reentrancy attack vulnerability in The DAO’s wallet smart contract code to withdraw Ether multiple times before it could update its balance.

The fallout from this incident was so profound that it ultimately led to the Ethereum network being forked into the Ethereum and Ethereum Classic blockchains.

That was not the first incident of funds being stolen from a blockchain project due to a smart contract vulnerability, and it certainly wasn't the last. In fact, over the years, the news of smart contract exploitations has become even more prevalent. In 2022 alone, nearly $2 billion has been stolen in various crypto hacks, exploits, and smart contract vulnerabilities.

Defi Hack Q1 2022

Chart showing crypto hacks and amounts lost in the first half of 2022 | Source: blockworks.co

Unfortunately, with news of each hack, user confidence in DeFi and Web3 projects becomes increasingly eroded, effectively slowing their adoption.

But why has this remained a largely unsolved issue? More importantly, what can these blockchain projects do to protect themselves and their community members? Here’s what you need to know.

Understanding Smart Contracts and Their Vulnerabilities#

Smart contracts are applications that are deployed on the Ethereum network. The smart contract code cannot be changed after it has been deployed. They are immutable and come with a tamper-proof guarantee.

This brings up a plethora of new opportunities for effective transactional engagement in a low-trust environment. Especially when engaging with strangers publicly through blockchain or distributed ledger technology.

For example, with a public ledger, you may check and trust smart contract(s) code to perform transactions with total strangers that would not have been feasible or practical in traditional finance:
  • Transferring payments based on delivery of goods and services
  • Assigning a trusted third party to act a mediator to resolve conflicts if required
  • Depositing tokens to allow borrowers to take them out as a loan
  • Depositing tokens to borrow stablecoins
  • Purchasing an insurance policy to mitigate risks from hacks and exploits
  • Participating in a decision-making process of a project or protocol
  • Tokenizing traditional stock, assets, and commodities
  • Tokenizing art, music, and collectibles
  • Tokenizing real-world assets such as fiat currencies, precious metals, and minerals
  • Providing discovery services to other smart contracts about events occurring in the real world
  • Getting access to unlimited, or very large amounts, of loan capital without having to provide any collateral

This revolutionary functionality has led to the development of decentralized applications (dApps), which make up most of the projects in the blockchain ecosystem.

Now when talking about vulnerabilities, it’s important to note that blockchains themselves are inherently secure. In the case of decentralized blockchains, it is extremely difficult to take over the network and tamper with the data stored in the blocks. Hackers know this and that is why they are generally more focused on smart contract vulnerabilities than trying to change the data stored in the blockchain itself.

What Makes Smart Contracts Vulnerable to Cyberattacks?#

Smart contracts have several primary attributes – transparent, autonomous, distributed, immutable, and trustless. Ironically, these attributes are also what make smart contracts such a high-interest target among hackers.

Because they can hold so much value at any given time, smart contracts with vulnerabilities are like low-hanging fruits just waiting to be plucked. In recent times, hackers have been concentrating their efforts on cross-chain bridges – protocols that allow users to swap tokens from other blockchains. Over $1 billion has been lost to hackers in these cross-bridge attacks in 2022 alone.

Chart showing total funds lost due to crypto hacks, scams, exploits and rug pulls over the last year | Source: defiyield.app/rekt-database

A conventional contract, unlike smart contracts, may be enforced via the judicial system. Even if parties disagree on the text of a contract, a decision may still be acquired via legal actions and court judgements. Sometimes one party may seek to take advantage of another by introducing unenforceable terms in a contract, which a court can remedy. Meaning, depending on the legal procedures and documented evidence, what is mentioned in conventional contracts may not necessarily be enforceable, or it may be enforced differently depending on the legal jurisdiction under which the contract is governed.

This is not exactly the case with smart contracts since the terms that are programmed into the contract will determine precisely how the contract is executed.  Furthermore, there is no possibility of misunderstanding or fabrication of facts or evidence since these things do not exist in the context of smart contracts.  If a smart contract has a defect or a mistake, the mistake, too, is executed without any prejudice or recourse.


Although smart contracts are immutable, there are a variety of strategies for achieving "upgradability." It works by deploying a new smart contract and pointing dependents to the newly-deployed contract. A popular DeFi protocol often consists of a variety of smart contracts, the majority of which are capable of being upgraded.

The upgradability feature exposes this kind of decentralized protocol to a variety of flaws that hackers may exploit. If a hacker is able to attack one of the protocol contracts, they may be able to partially or completely change the protocol code to suit their needs. And as long as there is profit to be made, cybercriminals will continue to find new ways to exploit vulnerabilities in smart contracts.


Even without deliberate attacks, bugs present in smart contract codes are a vulnerability just waiting to be exploited. And since most of these protocols are open source, it makes it more accessible for an attacker to examine the source code for possible vulnerabilities. It's only a matter of time before someone finds something in the code that they can use to work their way into the system.

Code: Garbage In, Garbage Out#

One of the primary causes for hacking is poorly written smart contract code. Smart contract audits often last for a brief period of time, and the audit teams may not even fully comprehend the source code in the first place. Although it is necessary to go through numerous rounds of smart contract audits, it provides no security guarantees at all.

Incompetent Teams with Millions of Investor and Community Dollars#

Another attack vector for hackers is to exploit team incompetence, or gross gross negligence, in management of private keys. You've probably heard about private key breaches or hacks. But how can a private key be "hacked" in the first place?

If you're talking about programmatically signing transactions using a private key, it is good security practice to save private keys, access keys, passwords, and so on in a secrets manager rather than environment variables. Even when a secrets manager is utilized, a poorly-written application will cheerfully expose all application secrets. There have been multi-million dollar attacks that might have easily been averted by merely practicing "basic cybersecurity hygiene".

Our security team at Neptune Mutual can assist you with full-stack security, including smart contracts reviews, frontend and backend security, DNS security, and so on. Contact us on social media if you are serious about cybersecurity and have the budget, desire, and feeling of responsibility to do so.

It is much more critical to create smart contracts with RBAC (role-based access control) and to follow the "principle of least privilege" when it comes to access. When you know your signer key will be used in an unsecured "hosted" environment, make sure the wallet has very restricted access to your application.

Leveraging DeFi Insurance Cover Policies to Protect Against Smart Contract Risks#

As the popularity of DeFi, Web3, NFTs, and other blockchain projects increases, so does the need for cover against theft of digital assets by hackers. Global crypto adoption has been growing exponentially in recent years, but many would-be users and investors have been put off by the risk of losses, and the lack of viable safety and mitigation measures to protect against it.

In traditional financial markets, insurance has been a “must have” resource for protecting against all manner of different types of risks. There’s no reason why it cannot be used to mitigate security risks within the blockchain industry.

The rate at which smart contract hacks are growing strongly underlines the need for an effective solution to mitigate these risks. This is why users need decentralized insurance specifically for smart contract risks – a safety net for when something goes wrong.

What Smart Contract Risks Can Decentralized Insurance Cover?#

Before we dive in, you should know that this is by no means an exhaustive list, and does not necessarily represent the smart contract risks that are covered in the Neptune Mutual marketplace.

The risks highlighted here are recognized as industry standards in the Smart Contract Weakness (SWC) registry, a depository for identified vulnerabilities in smart contracts.

Miner Manipulation Vulnerabilities#

This refers to a broad classification of smart contract vulnerabilities in which a miner with malicious intent attempts to manipulate variables existing outside of how the smart contracts were programmed. The end goal is to work the system in their favor.

A common example is the Timestamp dependence vulnerability in which the timestamp of a transaction is influenced by the miner by exploiting the accepted drift or variance between when new blocks are added to a blockchain. While the variance is not in itself a cause for concern, the opening may provide an opportunity for a hacker to alter the timestamp of the block to suit their own nefarious purpose.

Arithmetic Error of Integers#

This is also known as Integer overflow and underflow error. An overflow occurs when a defined output exceeds the maximum size that was allotted to it at the time the code was executed. Conversely, an integer underflow occurs when the output is lower than the minimum allotted size.

The simplest way to understand this is to picture a car's odometer. The maximum size allotted is usually 6 digits – 999999. But what happens when the odometer clocks 7 digits (1,000,000)? It will be unable to display this output accurately or properly.

Failing to account for integer overflows and underflows can lead to smart contracts with inaccurate data and unintended outputs, which can pave the way for malicious activities.

Reentrancy Attacks#

This is one of the most destructive smart contract exploits. A reentrancy attack occurs when a function makes an external call to another untrusted contract. Then the untrusted contract makes a recursive call back to the original function thereby creating a loophole that allows hackers to overtake the system and continuously exploit the function to drain funds from the smart contract. 

In addition to the infamous The DAO hack, reentrancy attacks have been used to exploit the following protocols:

Logic Bugs#

This refers to basic errors in the logic of the smart contract. These can result from simple typographical errors or misunderstandings regarding business assumptions. Regardless of how they are caused, logic bugs can have a serious impact on the security of a network and its applications.

Unhandled Exceptions#

In Solidity, an exception can arise in a variety of situations, but the way these exceptions are handled is not always consistent. Interaction between contracts is the basic foundation of exception handling. As a result, contracts are vulnerable to malicious user attacks, and transactions will be rolled back if these exceptions are not handled properly.

Incorrect ERC-20 Standard Implementation#

The ERC-20 token has an availability of the well-known OpenZeppelin standard implementation. In most cases, it is fully applicable, and its functionality is sufficient for proper financial operations. Nonetheless, there's a place for custom token standard implementations.

As a result, it creates a space for inconsistencies between the newly created token and the actual ERC20 standard. However, such a minor change may result in the contract's method becoming non-functional because it will be unable to recognize the interface. It's a minor error that goes unnoticed during testing, but it causes stuck funds and blocked contracts in production.

Flash Loan Attacks#

Flash loans are a type of unsecured loan in DeFi. No collateral is required to access huge amounts of cryptocurrencies and tokens, but the amount borrowed must be returned in a single transaction and within the same block on the blockchain. If the loan is not returned within the stipulated period, the entire transaction is annulled. Crypto traders typically use flash loans to leverage arbitrage (price differences) opportunities. The principle is simple, practical, and automated by smart contracts.

In a flash loan attack, the perpetrator takes out a flash loan and exploits vulnerabilities in the smart contract to manipulate the price of a crypto asset in their favor, usually by creating an artificial sell-off to profit immensely from the resulting price movements. From 2020 to 2022, over $300 million has been lost due to flash loan attacks across various DeFi platforms and applications.

How Does Decentralized Insurance Work on Neptune Mutual?#

For the avoidance of confusion, you should note that Neptune Mutual is not an insurance provider. Rather, it is a marketplace for onchain parametric solutions  to protect against smart contract risks in the DeFi, CeFi, NFT, and Web3 spaces.

Here, blockchain projects can create cover policies against smart contract risks. Users and community members can purchase these policies to safeguard their digital assets over a defined period.

The underwriting capital for cover policies provided in part by the project creators and by liquidity providers who earn income from the cover fee premiums paid by policy purchasers and staking rewards.

Because it is a parametric cover, claims payouts are triggered by predefined parameters. Once the occurrence of these parameters has been verified by incident reporters (NPM tokenholders), payouts are disbursed to policyholders without needing to prove individual loss. This makes the entire claims process much simpler and more efficient.

Learn more about DeFi insurance on Neptune Mutual.

The Bottom Line#

Even with comprehensive audits and other security measures, smart contracts are still vulnerable to various risks. Whether by poor quality code, unintentional software bugs, or a whole variety of sources of vulnerability from dependencies to oracle failure, these vulnerabilities can result in expensive financial losses and diminished investor confidence across the board.

That means at best the security of DeFi and Web 3 projects is a delicate balance – the development team’s skill versus the skill of the hacker(s).

As such, it’s important to be proactive about safeguarding  digital assets with well-defined crypto insurance policies. Check out Neptune Mutual’s parametric cover marketplace now to reduce your exposure to crypto market security risks.