What is a Blockchain Code Audit?

Crypto education

A smart contract audit is an essential step before launching a dApp: third party auditors can find vulnerabilities that the team itself might miss. Audits use both automatic tools and meticulous manual analysis,  and can prevent the majority of hacks. Find out how audits are conducted and why you shouldn’t put your money in unaudited protocols.

TL;DR

  • The audit process consists of a project review, automated testing, manual code analysis, and peer review. It’s followed by a detailed report with a list of discovered vulnerabilities and recommendations on how to fix them.
  • Automated smart contract testing tools can find common vulnerabilities like reentrancy, transaction reordering, overflow, and timestamp dependency. The most popular tools are Mythril, Manticore, Slither, and Oyente.
  • Automatic testing saves a lot of time, but can miss bugs in the code or deliver false positives. Therefore, manual line-by-line code analysis is essential.
  • Most audit firms work with Solidity and EVM chains, as well as Solana, but a few, like OtterSec and Halborn, already work with Move. Move is  a much safer language than Solidity, but Move dApps still need to be audited: for example, Pontem Wallet is undergoing its third audit.
  • Unaudited dApps are a common target for hackers - or they can simply collapse because of an internal bug. Prominent examples include Nomad, Beanstalk and Yam Finance.
  • Leading smart contract auditors include Hacken, OtterSec, CertiK, ConsenSys Diligence, Halborn, and Quantstamp.

What is a smart contract audit and why does it matter?

A blockchain code or  smart contract audit is an analysis of a blockchain’s or dApp’s code, either by its creators or by a third-party auditor that aims to find errors, vulnerabilities, and bugs.

Blockchain security is part of Vitalik Buterin’s famous trilemma: security, scalability, and decentralization. These three critical aspects of a network or dApp must be held in balance.

As with any software project, a crypto dApp must operate reliably and consistently, or customers will quickly lose faith in it. But for blockchain, the stakes are magnified, as a dApp can hold hundreds of millions of dollars in liquidity - and all that money can be drained in a single attack if a hacker finds a loophole in the contract code.

A key method of preventing this is a code audit provided by an external source. We’ll look at how smart contract audits are structured, what sort of vulnerabilities they can find, which firms operate in this field, and finally, how skipping an audit can lead to catastrophic losses.

Blockchain audit in 5 steps

  1. Project review & top-level code analysis

The external audit team needs to get a good idea of the project: its architecture, business logic, practical application, etc. Many big DeFi exploits target holes in the app’s logic or economic vulnerabilities. It’s great when a reviewer can point out such logic flaws, though it can fall outside of the scope of smart contract audit proper.

The client also needs to describe the goals of the audit, how the tests should be run, which use cases need to be tested, and other key information..

Next, the audit team reads the whole repository to understand how the dApp’s logic is implemented.

  1. Automated testing

There still aren’t many software tools for testing smart contracts, and almost all are for Solidity and EVM chains. They can’t find business logic  or tokenomics flaws, but they do save auditors lots of time. The most popular ones are:

  • Mythril by ConsenSys – a powerful open-source tool that detects many critical errors; part of the MythX security service package.
MythX interface. Credit: Rekt Blog
  • Manticore – a command line tool that goes through different attack scenarios, submitting symbolic inputs to see if they will crash the dApp; finds inputs that will lead to a specific error; finds out what caused a specific crash, etc.
  • Slither – a quick and easy-to-use checker that highlights critical vulnerabilities and provides fixes.
  • Oyente – created in 2016, this tool hasn’t been updated for a couple of years but still gets good reviews for accuracy.

Common vulnerabilities

Smart contract audit software can discover many kinds of vulnerabilities, including:

  • reentrancy – the attacker repeatedly calls the withdraw function to drain funds from a vulnerable smart contract to a malicious one.
  • reordering – the attacker gets their transaction executed before other transactions on the queue to manipulate the price (known as front-running).
  • overflow and underflow – sending wrong data to force the smart contract to make a calculation error (the result is either more than the allowed upper limit or less than the lower limit). The attacker can mint  huge amounts of tokens as a result.
  • timestamp dependency – the attacker feeds the wrong timestamp to the contract to make it look like their transaction happened at a specific moment (for example, to win an auction or lottery)
  • replay – intercepting and then re-submitting data on the blockchain (can be used to steal funds during fork events).
  1. Manual line-by-line code analysis and testing

This stage helps find any errors missed by the automatic tools. It also identifies false positives: pieces of code that automatic audit software incorrectly flagged as vulnerabilities.

An audit can uncover vulnerabilities of different severity levels: critical-level (allow an attacker to steal tokens, break the dApp, etc.), medium-level (potential damage is limited) and low-level (still a bug, but creates  little risk of financial or structural damage).

A page from Hubble Protocol’s line-by-line audit report by Smart State
  1. Peer review

Ideally, you want several auditors for maximum confidence. Sometimes auditors work in teams and analyze the code together, so that the peer review happens at the same time.

Keep reading to find out about the risks of not doing a peer review.

  1. Audit report

Finally,the results are compiled into a multi-page report that is delivered to the client. It contains  a list of the discovered bugs, as well as recommendations on how to fix them and further improve the project’s security.

The standard practice in blockchain is to make audit reports public: this is actually a good marketing tool for projects, as it showcases both a dApp’s security and transparency. Of course, if any critical vulnerabilities are found, the project will usually fix them first.

A section of the Reef protocol audit report by Halborn

The challenge of smart contract audits in Move vs. Solidity

As we’ve explained in our article on the Ethereum Virtual Machine, EVM and Solidity smart contracts are hard to debug and have a lot of security issues. Add to this the dominance of EVM chains (9 out of the top 10 blockchains by DeFi TVL use EVM), and you’ll see why the smart contract industry is so focused on Solidity. It has both the first-mover advantage AND lots of vulnerabilities that need auditing.

When you move from the Ethereum/EVM ecosystem to an alternative blockchain environment like Move, you face a very interesting challenge. On one hand, the Move language and Move VM are much safer than Solidity and EVM. For example, Move contracts are resistant to reentrancy attacks.

On the other hand, Move-based dApps should still get audited – and there aren’t many blockchain security specialists who work with this language yet. Pontem Wallet’s auditors OtterSec and Halborn are among the pioneers, and Pontem Wallet itself is one of the first fully audited dApps on Aptos – which makes us really proud.

By the way, our auditor OtterSec has published a very interesting blog poston how to build safer dApps with Move,  and some of the code from our Liquidswap DEX is used as an example!

The best smart contract audit companies

Hacken

Created in 2017, Hacken audits whole blockchain protocols, smart contracts, and dApps. The firm also curates bug bounty programs for platforms like CoinGecko.

Hacken works with a wide variety of blockchains: EVM chains, Solana, NEAR, Cosmos, Polkadot, etc.

Its clients include FTX, Gate.io, Crypto.com, KuCoin, Huobi, Ellipsis, IoTex, 1inch, Aurora, Klaytn, Cirus, Victoria VR, WAX, TrustSwap, and dozens of other DeFi, GameFi, infrastructure, and NFT projects.

OtterSec

OtterSec is the premier blockchain audit provider in the Solana ecosystem. Its impressive portfolio includes Wormhole, Serum, Saber, Raydium, Solend, Socean, as well as Anchor, LayerZero, and Proximity on NEAR.

Moreover, it’s one of the few blockchain audit firms that works with the new Move programming language, used by Aptos and Sui. OtterSec has completed the first audit of our Pontem Wallet for Aptos, as well as Hippo Wallet.

OtterSec also has a great blog with expert tips on smart contract security, especially on Solana.

Zellic

Zellic was founded by the internationally renowned team of white-hat hackers called Perfect Blue. They were ranked as the no.1 CTF (Capture the Flag) team in the world in 2020 and 2021, competing in cybersecurity events like Google CTF and Def Con CTF.

The company is known for its speed of execution and ability to find hidden vulnerabilities. Its security engineers identify not only coding engineers but also economic and business logic flaws.

Zellic’s clients include Aptos Labs, Solana Foundation, LayerZero, SushiSwap, 1inch, Wormhole, etc.

CertiK

CertiK is known primarily for its blockchain security leaderboard where 3000+ projects are ranked by their trust score. Security audits are CertiK’s additional area of expertise, together with penetration testing (trying any and all methods to enter parts of a system that should not be accessed), KYC, bug bounties, on-chain monitoring, and wallet tracing.

CertiK has performed 1800+ audits for protocols on Ethereum, Avalanche, BNB Chain, Solana, Algorand, NEAR, and Cosmos. It’s the trusted audit provider of Binance, The Sandbox, Huobi, and OKex.

Halborn

Halborn was created by ethical (white-hat) hackers in 2019 and now includes 50+ blockchain security professionals. Apart from smart contract audit, it specialized in security consulting, penetration testing, and security automation.

Halborn worked with such popular projects as Polygon, Solana, Thorchain, Bancor, Pangolin, Reef, Sushi, BlockFi, Polkadex, and even Bored Apes Yacht Club. It’s also one of the auditors for Pontem Wallet, the first wallet for the Aptos blockchain.

We recommend Halborn’s blog, which features post-mortems of recent DeFi hacks and deep dives into the most common types of blockchain attacks.

Zokyo

Zokyo is an end-to-end security firm with a number of well-known ethical hackers on its team. It specializes not only in smart contract audit but also in penetration testing, data leak discovery, database assessment, and CMS vulnerability audit.

Zokyo has worked with dozens of large blockchain projects, including Fuse, yearn.finance, LayerZero, Qredo, CPRX, Shoyu, Badger DAO, ShapeShift, etc. Moreover, Zokyo’s security engineers are among the top-ranked participants in the bug bounty programs run by Twitter, Facebook, and Uber.

ConsenSys Diligence

ConsenSys is the company behind MetaMask, Truffle, and Infura – the key tools for Web3 developers. Its smart contract audit arm, ConsenSys Diligence, has worked with over 100 teams, such as Aave, OmiseGo, 0x, Aragon, and Horizon.

ConsenSys Diligence provides services beyond audit: threat modeling, continuous vulnerability verification, attack response planning, and others.

Quantstamp

Quantstamp has worked with over 250 projects, securing over $200 billion in assets and locked liquidity. Its portfolio includes OpenSea, Curve, Maker DAO, Compound, NBA TopShot, Lido, SuperRare, Decentraland, Aave, and Axie Infinity.

The firm works with many blockchain ecosystems, such as Solana, Ethereum, BNB Chain, Cardano, Flow, Near, Tezos, and Hedera Hashgraph. It also secures Teku and Prysm clients for Ethereum 2.0.

3 DeFi dApps that collapsed because they didn’t do a smart contract audit

An unaudited DeFi dApp with millions of dollars locked in it basically has a target painted on it, saying ‘Hack Me’. And even if it’s not exploited by a third party, it can fall victim to an internal code problem. Here are three stories that show the consequences of skipping an audit.

Nomad bridge: $200M gone in a free-for-all

Nomad is a bridge connecting Ethereum, Evmos, Moonbeam, Avalanche, and the Milkomeda protocol. The August 2 exploit targeted a recent upgrade to Nomad, which hasn’t been audited, according to Paradigm’s head of security, @samczsun.

The bug in the contract made it possible for users to send small amounts of WBTC from Moonbeam and get 10,000 times more WBTC back on Ethereum. You didn’t need to be a coder: all it took was a copy-paste.

As the news of the loophole spread, more and more people joined the free-for-all. It wasn’t a hack by one person, but rather a chaotic, opportunistic attack by 41 addresses. In total, around $200 million was lost – all of the liquidity held by the bridge.

Nomad said it would work with blockchain security firms to track down and recover the money. However, it should have probably engaged blockchain security specialists before pushing an unaudited contract upgrade on the mainnet!

Beanstalk: hacked for $180 million via a flash loan

Beanstalk is a decentralized stablecoin on Ethereum. Instead of using collateral to maintain the peg of BEAN, it uses credit, encouraging holders to lend their beans in exchange for interest.

On April 17, 2022, a hacker exploited a bug in Beanstalk’s governance code. They took out flash loans on Uniswap, SushiSwap, and Aave, borrowing around $1 billion in DAI, USDC, USDT, and BEAN. The hacker put that liquidity in the BEAN pools on Curve, receiving enough LP tokens to give them the majority voting power in the Beanstalk DAO.

The attacker then submitted a new Beanstalk Improvement Proposal (BIP) to transfer all the funds from the protocol to their own address – and voted for it, so that it automatically passed. In total, the attacker received up to $182 million in BEAN, ETH, and Curve LP tokens. All they had to do now was repay the flash loans.

Beanstalk’s smart contracts had been audited by Omnicia. But the code that contained the flash loan vulnerability was added later without being audited. The lesson here is that smart contract audit is an ongoing process: every new feature needs to be reviewed.

Yam Finance: down 99% because of a bug

Launched in August 2020, Yam Finance was an early experiment in rebasing: the supply of YAM increased or contracted depending on the price. The project paid high yield farming rewards, but what really attracted users were the cute yam potato emojis and memes (YAM = YFI + Ampleforth, two DeFI protocols whose ideas Yam Finance borrowed).

The whole project came together in just 10 days as the founders were ‘kicking ideas around’. As it was just an experiment, the team deployed Yam Finance without an audit. It came as a shock when $400 million in TVL poured into the protocol in a single day.

But just two days after launch, Yam Finance collapsed. The reason was a bug in the rebase feature: the contract minted too much YAM to a specific pool on Uniswap. A lot of that YAM was sent to the treasury, and that, in turn, made the governance module unusable, because the amount of YAM held by the users was now insufficient to reach quorum for any vote.

There was a potential fix, but it had to be pushed through a DAO vote. The team rallied the community to delegate all their YAM for voting, but the result wasn’t enough. Co-founder Brock Elmore tweeted that he was ‘sick with grief’.

Yam Finance lives on with just $200k in TVL. The lesson it teaches is that a DeFi protocol can go viral so fast that there won’t be time to look for bugs and fix them. An audit needs to be completed before launch.

An audit is not a security guarantee

A single smart contract audit is never a 100% guarantee that the project won’t be exploited – for a few reasons:

1. For example, Grim Finance lost $30 million to a hacker in December 2021, even though it had been audited by Solidity Finance.

It turned out that the analyst responsible for the audit was new; while auditors normally check each other’s work, the team was ‘overwhelmed’ and the peer review process didn’t go as it should. To Solidity’s credit, this was only the second exploit among the 900+ projects they have reviewed.

2. An attacker can steal/phish a wallet key instead of hacking a contract. This is what happened to bZX ($55 million lost) and EasyFi ($90 million). In the latter case the criminal gained access to the MetaMask wallet of the protocol’s CEO himself.

3. Some exploits use holes in a third-party dApp (unaudited) to target another protocol integrated with it.  

4. Future changes to the blockchain. As the chain on which the dApp lives goes through upgrades, new attack vectors can arise.

For all these reasons, audit agreements and reports always include a disclaimer. From the dApp team’s perspective, the best way to minimize these risks is to go through multiple independent audits – to have an ‘audit redundancy,’ if you like.

This is our strategy at Pontem Network, as we want our dApps for Aptos to be the most secure in the ecosystem. Even though our auditors at Ottersec didn’t find any vulnerabilities in Pontem Wallet, we are now working with Halborn on another review, with a third one on the way.

Of course, this does slow down the scaling process somewhat, but we believe that user safety is a higher priority than rapid growth. After all, we are building a suite of foundational dApps for an ecosystem that can onboard the first billion blockchain users, and Aptos itself is the safest L1 blockchain in the world. So it’s only fitting that we focus on security above all else.

Check out Pontem’s latest AMA live streams with the Core Protocol Contributor Alejo Pinto to learn more about security in Pontem Wallet and Aptos. And don’t forget to follow us on Twitter and Telegram for more updates on the audit process!

Install our wallet and try DEX