• 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

In the evolving Web3 era, the critical role of smart contracts in powering decentralized applications and ecosystems cannot be overstated. As these systems expand in complexity and scale, the risk of errors multiplies correspondingly. For Web3 developers aiming for seamless, error-free operations, smart contract audits are not merely an option, but a necessity.

In this article, we take you through the tried-and-tested audit process at Hacken, a methodology that we’ve continually fine-tuned since our first audit in 2017. Notably, this approach has helped us maintain a track record of zero exploits among all the projects we audited in 2022, underscoring the reliability and effectiveness of our methods.

What Is A Smart Contract Audit

A smart contract audit refers to the process of scrutinizing the underlying code of a smart contract with the goal to pinpoint and rectify any latent security vulnerabilities, errors, or inefficiencies. This audit is designed to guarantee that your contract operates as expected, offers robust security, and is fully compliant with the recognized industry standards and best practices.

Put simply, a smart contract audit is an assurance that your contract is primed for smooth, safe operation once it is deployed.

Preparation For A Smart Contract Audit 

The significance of thorough preparation and meticulous documentation cannot be overstated. It promotes clarity, economizes resources, and makes the entire process more efficient.

To ensure you gain the most from your audit, you should consider the following steps:

  1. Clearly establish the functional requirements for your project.
  2. Prepare a detailed technical description of your project.
  3. Set up a development environment for the project.
  4. Develop comprehensive unit tests.
  5. Ensure that the code complies with best practices and security standards.

Meeting these criteria enables us to conduct an in-depth review of your project and accurately evaluate the code against your specifications. This level of preparation is necessary even if you don’t intend to pursue an external audit.

Prep 1: Functional Requirements

Functional requirements serve as a roadmap for auditors to grasp the specific objectives of your project. They need to be articulate, succinct, and devoid of ambiguity.

❌ 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.

Providing as many functional details as possible can help auditors confirm the code performs 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.

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.

How can auditors verify functionality and guarantee anything if they don’t understand what the app is about? Exactly! Clear and comprehensive functional requirements act as a yardstick to measure success. This is the only way to really benefit from an external review.

Prep 2: Technical Description

A comprehensive technical overview plays a vital role in audit preparation. Your focus should be on the following:

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

This information helps us navigate through your code, 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 specialists.

Prep 3: Development Environment

We consistently encourage our clients to configure a development environment for their projects. Tools like Truffle or Hardhat offer a comprehensive suite of automation tools, removing any justification for avoiding this step.

A dedicated development environment allows for:

  • 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.

Given these advantages, bypassing the creation of a development environment would be a missed opportunity.

Prep 4: Unit Tests

Creating comprehensive unit tests to cover your code is not just advisable, it’s indispensable. It optimizes the auditing process, saves resources, and bolsters your app’s security.

We suggest striving for 100% test coverage, encompassing both positive and negative scenarios. Furthermore, we encourage the development of multi-user tests to evaluate the system’s resilience against potential DoS attacks. Simulating contracts for multiple concurrent users also guarantees that user operations remain unaffected by each other unless it’s part of your design.

By following these steps, you can detect security vulnerabilities even before initiating the audit. As a result, during the audit, we can leverage these tests, concentrating our efforts on the more complicated problems, thereby reinforcing your security measures.

Prep 5: Best Practices and Security Standards

Following official language style guides and formatting norms is yet another cost-effective and straightforward way to facilitate both auditing and any planned upgrades to your contract.

Adherence to these best practices decreases the time devoted to problem detection and lessens the likelihood of error oversight in fresh code additions. To put it simply, complying with best practices is an effective strategy for saving both time and money.

Follow @hackenclub on 𝕏 (Twitter)

How To Audit A Smart Contract

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

At Hacken, we’ve honed our methodology over the years and suggest adhering to the following steps for the most effective and efficient error detection:

  1. Pre-audit
  2. Line-by-Line Review
  3. Analysis & Verification
  4. Report & Scoring

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 contracts, we employ the following security analysis tools to unearth basic issues and gain a deeper understanding of the 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 contracts, we rely on the following tools:

  • 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 manipulations
  • Access violations
  • Flash loans
  • Complex vulnerabilities emerging from contracts interactions

While the complete list of checked items is too lengthy to enumerate here, rest assured that key items for most programming languages are duly checked:

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 all 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 for the first time, bringing their individual insights and discoveries into a joint discussion under the guidance of the lead auditor. We examine, converse about, and even argue over the identified issues in an open dialogue, fostering a more well-rounded understanding of your project’s potential 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 measures to bolster your project’s security and improve its audit rating.

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

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.

Report outline:

  • Executive Summary
  • Checked Items
  • System Overview
  • Findings
  • Disclaimers

The Executive Summary in the audit report offers a snapshot of key findings and overall assessment. The Checked Items section lists all reviewed elements, while the Findings provides detailed insights into identified issues and remedial recommendations. And the Disclaimers clarify the scope of the audit.

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 community members and investors. They peruse it to make informed decisions when considering depositing/investing in your project.

Audit score. We also assign a final audit score based on three criteria:

  • Documentation quality (D) – 1.0
  • Code quality (C) – 2.0
  • Security level (S) – 7.0

This score provides an accessible way for external and non-technical users to get a picture of your project’s viability. 

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 risks quality compromise and places an undue load on those few individuals.

At Hacken, we embrace a more focused strategy where each professional is devoted to a singular key task. We advocate for role specialization, as it enables us to dedicate more valuable time to resolve problems at hand.

  • Pre-Auditor: The auditor assigned to the initial phase, responsible for examining project requirements, confirming the project scope, and deploying automated tools.
  • Auditors: The primary auditors who conduct an in-depth, line-by-line review, settle any discrepancies, and supply all required materials to the lead auditor.
  • Lead Auditor: The senior auditor who reviews all materials prepared by the auditors, ensuring no security concerns are overlooked.
  • Proofreader: The person tasked with ensuring the final report is free from errors and adheres to our established structure.
  • Delivery Manager: The individual responsible for maintaining direct communication between our teams, making sure all concerns and suggestions are addressed.

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.

Conclusion

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 & Scoring: We consolidate our findings, key details, security recommendations, and scoring metrics 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