• Hacken
  • Blog
  • Discover
  • How To Audit A Smart Contract: ​​A Deep Dive Into Hacken’s Process

How To Audit A Smart Contract: ​​A Deep Dive Into Hacken’s Process

11 minutes

Crypto projects must understand the risks inherent in smart contracts—operational, implementation, and design flaws—which, if exploited, can compromise or destroy a project. Recent data underscores the importance of auditing: nearly 10% of all Web3 losses in Q3 2024 resulted from smart contract exploits, totaling $42.3 million. At the same time, 90% of all hacked projects never had any form of audit.

Since smart contracts are immutable once deployed, even a single flaw can lead to severe consequences, including asset loss. For instance, $1.2 million was stolen within a minute of deployment in the Vow Token exploit, and attackers combined a flash loan and price manipulation to extract $1.5 million from a reentrancy vulnerability in the Minterest hack.

Hacken’s smart contract auditing process, refined through thousands of audits since 2017, ensures developers write secure code, conduct thorough testing, and implement best practices.

What Is A Smart Contract Audit

A smart contract audit is a comprehensive review of the code, logic, architecture, and security measures implemented in a smart contract. The process is structured to identify and address any potential security vulnerabilities, logical errors, or inefficiencies before deployment to the mainnet.

This image is an illustration titled “Smart Contract Audit Process” with a visual representation of the process divided into five phases. Each phase has an icon and a brief description beneath it:

	1.	Phase 1: An icon depicting a document. The description reads, “We gather requirements, set up the environment, and prepare unit tests for a thorough audit.”
	2.	Phase 2: An icon showing a cube with arrows pointing in all directions. The description states, “Auditors review code line-by-line, identifying vulnerabilities using automated and manual methods.”
	3.	Phase 3: An icon of a monitor with lines of code. The text says, “Rigorous tests are run to validate contract security in various scenarios.”
	4.	Phase 4: An icon with an exclamation mark inside a speech bubble. The description notes, “We compile findings, risk levels, and remediation steps in a detailed report.”
	5.	Phase 5: An icon resembling a cube with a heart. The description reads, “We verify that all fixes are effective before the final report.”

With over 2,000 audits completed, the Hacken team has leveraged seven years of experience battling hackers to develop an effective methodology for smart contract code review and security analysis, applicable across various languages and platforms. Here’s a brief breakdown of our auditing process:

  1. Preparation: Auditors gather requirements and set up the development environment to align the project with its intended design.
  2. Code Review: The code is reviewed through initial scans, automated tools, and a detailed line-by-line examination to identify vulnerabilities.
  3. Testing: A comprehensive testing suite, including fuzzing, is utilized to validate code functionality and simulate potential attack scenarios.
  4. Reporting: Findings are compiled into a report detailing the scope, risk assessments, and recommendations.
  5. Remediation Check: Auditors verify fixes, and if resolved, a final report is issued.

Preparation For A Smart Contract Audit 

Good preparation saves both time and money. To ensure you gain the most from your audit, you should consider the following steps:

  1. Establish clear functional requirements
  2. Prepare a detailed technical description
  3. Set up a development environment
  4. Develop comprehensive unit tests
  5. Follow code style and best practices

Proper preparation is crucial for the success of a crypto project. Comprehensive documentation, often overlooked, is essential for effective development, testing, and review. Even if your project isn’t ready for a professional audit, having these measures in place helps with internal reviews, bug bounties, and maintaining a productive development environment.

Prepare Functional Requirements

Functional requirements ensure that the contract performs its intended functions, providing clear guidelines for development.

  • ❌ Ambiguous requirement: Users should be able to earn tokens.
  • ✅ Specific requirement: The contract should enable users to stake ABC tokens and earn XYZ tokens as rewards.

Clear and comprehensive functional requirements are essential for understanding the app and verifying its functionality. While your smart contract code may be secure, it might not align with your intended goals. This is another reason why it’s beneficial to get an external opinion to ensure the application functions as intended. Having as many functional details as possible helps check whether your smart contract code works as intended. Here are a few additional examples of well-defined functional requirements:

  • The contract must enable users to stake HAI tokens and receive other tokens as rewards.
  • The total rewards must be distributed among all users according to their percentage of the total locked HAI volume.
  • Users should be able to withdraw their funds and rewards at their convenience.
  • The total locked balance should be recalculated each time a user withdraws their tokens.

Prepare Technical Description

A comprehensive technical overview plays a vital role in audit preparation. Ideally, your technical description should cover the following areas:

  • Programming languages and technologies utilized.
  • Instructions for deployment.
  • Test-running instructions.
  • Any relevant non-functional requirements.

This information aids code navigation, especially when your smart contracts are complex and interrelated. Again, it’s important to note that documenting vital aspects of your code is beneficial even if you have no plans to engage external security researchers.

Set Up Development Environment

We consistently encourage our clients to configure a development environment for their projects. Tools like Truffle or Hardhat make this task easier. This step brings many advantages:

  • Enhanced debugging: Facilitates tracking down and fixing coding errors efficiently.
  • Simplified testing: You can freely test and break things without affecting the live code.
  • Better version control: Helps manage different versions of your code and track changes.
  • Reduced risk of accidental live deployment: Avoids premature or accidental deployment of unfinished code.

Skipping the setup of a dedicated development environment would be a missed opportunity.

Prepare Unit Tests

Your smart contract code must include unit tests, as thorough testing is crucial for security and helps save resources.

We suggest striving for 100% test coverage, with both positive and negative scenarios. Furthermore, we encourage the development of multi-user tests to evaluate the system’s resilience against potential DoS attacks. Another step is to run simulations with multiple concurrent users to ensure that their operations remain isolated unless designed to interact.

Unit tests can detect security vulnerabilities even before initiating your crypto audit. Projects that include tests significantly reduce audit time and cost, allowing auditors to focus on more complex issues.

Code Style and Best Practices

Follow official code style guides and formatting before audits. It will improve readability, expedite bug-fix verification, and reduce the risk of missing errors. It’s a practical approach that saves both time and resources.

Follow @hackenclub on 𝕏 (Twitter)

How To Audit A Smart Contract

Now, let’s get to the main part: the process of auditing your smart contracts.

At Hacken, we’ve refined our methodology over the years and recommend the following steps to catch all errors:

  1. Pre-audit
  2. Line-by-line review
  3. Analysis and verification
  4. Report and remediation

Step 1: Pre-Audit

The initial phase of our audit aims to spot any problem areas needing attention before the in-depth review begins. In the pre-audit stage, we peruse your provided repository, ensuring a comprehensive audit scope. The pre-auditor evaluates the development environment for any potential compilation problems, executes the provided tests, and verifies both the functional and non-functional requirements.

Smart Contract Audit Tools

For Solidity smart contracts:

  • Slither: This static analysis tool examines Solidity source code for security vulnerabilities and checks compliance with best practices.
  • Mythril: A bug-hunting framework that helps to identify potential vulnerabilities in Solidity smart contracts.
  • Solgraph: A tool generating a DOT graph, visualizing the function control flow of a Solidity contract and highlighting potential security threats.
  • Echidna: A program designed for fuzzing and property-based testing of Solidity smart contracts.
  • Mythx: A security analysis platform for Solidity smart contracts, combining static and dynamic analysis to detect vulnerabilities and generate detailed reports.

For Rust smart contracts:

  • Clippy: A set of lints designed to catch common mistakes and enhance your Rust code.
  • Cargo-udeps: This tool is used to detect unused dependencies in Cargo.toml.
  • Cargo-audit: Used to audit dependencies for crates with security vulnerabilities as reported in the RustSec Advisory Database.
  • Cargo-geiger: Helps detect usage of unsafe Rust.
  • Cargo-crev: Offers a cryptographically verifiable code review system for cargo.

Moreover, we run several in-house security analysis programs, details of which we don’t disclose, but with the aforementioned tools, you can achieve substantial results.

At the end of this stage, we provide you with a preliminary report, giving you the chance to make any last-minute modifications before the official audit commences.

Step 2: Line-By-Line Review

Let the audit begin! Our aim at this stage is to equip you with validated insights that guide your decision-making process on the necessary modifications for enhanced code security.

Finding & documenting issues. In the exhaustive line-by-line review – independently conducted by a pair of skilled auditors – we meticulously examine each segment of your code for all possible vulnerabilities, including:

  • Issues outlined in the SWC registry
  • Data and price manipulations
  • Access violations
  • Flash loans
  • Complex vulnerabilities emerging from contract interactions

At this point, we manually check the code against all critical aspects common to smart contract programming languages. The table lists some of the checked items.

ItemDescription
Default VisibilityFunctions and state variables visibility should be explicitly set.
Integer Overflow and UnderflowAll math operations should be safe from overflows and underflows if unchecked math is used.
Outdated Compiler VersionA recent version of the respective compiler (Solidity or Rust) is recommended.
Access Control & AuthorizationAll crucial functions should be protected to prevent ownership takeover.
Assets integrityFunds are protected and cannot be withdrawn without proper permissions or be locked in the contract.
Data ConsistencySmart contract data should be consistent all over the data flow.

It’s essential to recognize that issues are not identical. For this reason, we utilize more than 50 language-specific parameters for EVM (Solidity, Vyper, Yul) and Rust-based contracts (Solana, Near, CosmWas).

Testing. In addition, we thoroughly assess the test coverage. If we identify any gaps, no matter how small, we develop and implement additional cases to accommodate all potential positive and negative scenarios.

Bear in mind that some problems can only be replicated with incorrect configurations of dependent contracts. Accordingly, our auditors intentionally devise such configurations and run associated tests.

Each issue is classified as either Passed, Failed, or Not Related.

Step 3: Analysis & Verification

This crucial stage of the audit process truly showcases the merits of our unique methodology. Until this point, our auditors have been conducting their examinations independently, allowing for unbiased scrutiny and in-depth exploration of the code from their respective perspectives.

Now, these auditors come together, bringing their individual insights and discoveries into a joint discussion under the guidance of a lead auditor. The team cross-examines identified issues, fostering a well-rounded understanding of your project’s vulnerabilities.

Moreover, the team compiles an internal document spotlighting the key aspects and possible weak spots of your project, in tandem with a detailed advisory report suggesting recommended measures.

The lead auditor thoroughly reviews all the materials to ensure they are complete, accurate, and accurately represent the collective audit findings. After this final check, the consolidated audit report is delivered to you, serving as a robust assessment of your project’s security.

Testing, Fuzzing and Gas Optimization

As a final step in our process, every audit we conduct includes fuzz testing and invariant testing, alongside extensive unit tests. This comprehensive approach features static, dynamic, fuzz, stress, mutation, and invariant testing, as well as gas optimization steps.

Step 4: Report

After an intensive cross-review of the findings, our team collectively formulates a detailed final report covering crucial issues, vulnerabilities, and executed tests. Essentially, the report presents a comprehensive review of the audit, empowering you with verified information to bolster your smart contract’s security and dependability.

External users. The final audit report is also an invaluable resource for external stakeholders such as your community and investors.

How Many People Should Be Involved In The Audit

Some security companies may employ a streamlined workforce, where only 1-2 employees handle all responsibilities. Although this may cut labor costs, it compromises consistent quality and places an undue load.

At Hacken, we take a focused approach with specialists dedicated to specific areas of expertise, maximizing efficiency and allowing them to concentrate on resolving the most critical issues. Every audit is led by a Lead Auditor, providing top-tier expertise throughout the process. Additionally, our Delivery Manager serves as your dedicated point of contact, facilitating seamless communication and addressing all your needs and concerns.

Our specialized teams cover all major smart contract languages and blockchain networks, ensuring comprehensive and precise audits tailored to your project.

Undoubtedly, this method demands a higher investment in human resources, but over time we have found that the long-term benefits for both us and our clients are worthwhile.

Post-Audit Security

Your audit is complete, but defending against hacks doesn’t stop there. In the post-audit security phase, Hacken offers solutions to enhance post-deployment security. Extractor continuously monitors your smart contract for potential threats, ensuring real-time detection and response. DualDefense provides an additional layer of protection at no additional cost, with a 30-day crowdsourced audit by independent security researchers. Together, these services ensure your project remains secure even after deployment.

Conclusions

At Hacken, we emphasize the absolute necessity of regular smart contract audits. With the immutable nature of blockchain applications, an undiscovered flaw in your smart contract can spell lasting issues.

Proactive audits help identify such vulnerabilities early, enabling you to secure your applications effectively and reliably.

Here’s a brief overview of our audit process for any blockchain:

  • Preparation & Pre-audit: We start by vetting your requirements and tests while gaining an intimate understanding of your project and its code.
  • Line-by-Line Review: Our auditors conduct two separate assessments to catch every possible issue and scrutinize your contract’s performance.
  • Analysis & Verification: The team discusses findings internally, after which our lead auditor verifies everything independently for a thorough assessment.
  • Report & Remediation: We consolidate our findings, key details, and security recommendations into a transparent report for you and your community.

Join us in our mission to make Web3 a safer space, one audit at a time!

Follow @hackenclub on 𝕏 (Twitter)

Subscribe
to our newsletter

Be the first to receive our latest company updates, Web3 security insights, and exclusive content curated for the blockchain enthusiasts.

Speaker Img

Table of contents

Tell us about your project

Follow Us

Read next:

More related

Trusted Web3 Security Partner