Skip to main content

Smart Contract Code Review And Security Analysis Methodology

Release: Version 3.0

FieldDescription
NameSmart Contract Code Review And Security Analysis Methodology
CreatorsHacken OU
Subjectaudit; security analysis; smart contracts; 
Description The methodology described herein provides specific guidance on how to plan and execute an audit of smart contracts in line with the Smart Contracts Audit and Analysis Requirements provided by Hacken. 
AuthorAtaberk Yavuzer | Principal Smart Contract Auditor, Hacken OU
DateOct 15th, 2025 
RightsHacken OU 

Part 1. Smart Contract Audits

Overview

The Smart Contracts Audit and Analysis Methodology constitutes a response to Hacken customers’ requests and is based on years of experience in conducting smart contract audits. The purpose of this document is to illustrate the audit process to Hacken community and improve the quality of smart contract development to protect Hacken’s customers' funds and their users.

How does the audit help?

Our methodology is designed to meet the needs of our customers, their technical teams, and their communities, to deliver secure and risk free smart contracts.

With our robust methodology, product owners can:

  1. Ensure that development aligns with the specified functional requirements.
  2. Understand the necessary steps to take prior to the audit.
  3. Identify the steps to follow during the audit.
  4. Know what actions are required after the audit.

The value of our methodology for developers:

  1. Provides a clear understanding of the audit process and its phases.
  2. Offers recommendations for ensuring secure development practices.
  3. Describes the most common pitfalls.
  4. Shares best practices for writing safe and secure code.

Alignment with International Standards

Hacken performs all audits and technical assessments in accordance with the NIST SP 800-115 – Technical Guide to Information Security Testing and Assessment and the Penetration Testing Execution Standard (PTES). These assets provide a structured foundation for planning, executing, and documenting technical evaluations such as vulnerability assessments, exploitation activities, and security code reviews. Hacken’s internal penetration testing methodology extends these principles to Web2 and Web3 environments to ensure consistency, repeatability, and verifiable outcomes.

Part 2. Smart Contracts Audit and Analysis Phases

Smart Contracts Audit and Analysis process consists of the following phases:

  1. Onboarding (Preparation)
  2. Testing
  3. Reporting
  4. Remediations check

sc-phases

Preparations for Smart Contracts Audit and Analysis

Preparation establishes a reproducible foundation for the audit. It ensures auditors can conduct focused security analysis instead of spending time on setup or clarifications. Proper onboarding directly improves coverage quality and efficiency.

Functional Requirements

Functional requirements describe what the system is intended to do. Auditors use these as baselines to verify implementation accuracy.

Typical content:

  • Core features and expected behaviors.
  • Rules and constraints.
  • Contract interactions and user flows.

Example:

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

Technical Description

Technical description explains how the system works internally, covering architecture, storage, control flow, dependencies, and security mechanisms. Auditors reference it to understand design intent and assess threat surfaces.

A comprehensive technical description typically includes:

  • Architecture overview – How contracts are organized and interact with each other (modules, proxies, libraries, external protocols).
  • Data structures and storage – Key variables, mappings, arrays, and how data is stored on-chain.
  • Control flow and logic – How functions execute, including checks, loops, and state changes.
  • Dependencies – External contracts, libraries, or oracles used by the system.
  • Security mechanisms – Access control, pausing, upgradeability, and other safeguards.

Development Environment Setup

A development environment for the project should be configured by the customer. Truffle, Hardhat, Foundry or any other comprehensive development environment should be used. A proper description of the environment should be attached.

An example of the project environment configuration can be found here.

Comprehensive Test Cases

The main goal of comprehensive test cases is to demonstrate and verify the intended behavior of the smart contract under all realistic and edge-case scenarios. By providing these test cases, clients:

  • Give auditors full visibility into expected system behavior.
  • Enable identification of uncovered scenarios or hidden vulnerabilities.
  • Provide a security roadmap, helping auditors focus on high-risk areas.
  • Improve audit efficiency, reducing time spent guessing intended functionality and increasing the depth of analysis.

Code Style and Best Practices

We strongly recommend following the official code style guides and formatting your code before submitting it for audits. Code readability and compliance with the language style guide are some of the factors that determine the code recommendations. Furthermore, to expedite the bug-fix verification process, it is essential to format the code before the initial audit.

  • The code adheres to an official language style guide. Some popular style guides: Solidity, Vyper, Rust, etc.
  • The code can be compiled.
  • All TODO and FIX comments are resolved and do not occur in the code.

The Audit Lifecycle

Our audit process is designed to ensure maximum security, transparency, and efficiency. It combines manual review, automated tools, and structured testing, supported by a robust reporting and QA workflow.

1. Manual Code Review

Every audit is conducted by a team of auditors lead by the leading security engineer. The team manually reviews the code, following a structured checklist to cover all critical areas:

  • Auditors perform manual line-by-line review simultaneously to ensure double coverage.
  • Such approach minimizes human error and improves the quality, depth, and consistency of the audit.
  • Auditors may also collaborate on specialized tests, such as fuzzing or invariant testing, while continuing manual review.

2. Scan by Automated Tools

We use industry-standard automated tools to complement manual review. These tools quickly detect common vulnerabilities, insecure patterns, and known attack vectors:

  • Static and dynamic analysis tools are applied depending on the project type.
  • Automated scanning saves time and helps auditors focus on deeper, logic-based issues.

3. Fuzz/Invariant Testing

  1. Fuzz testing is an automated testing technique used to identify unexpected behaviors, crashes, or vulnerabilities in smart contracts. It works by generating random or semi-random inputs and applying them to contract functions to observe how the system reacts. a. Tool Selection: The first step is to select the appropriate fuzzing tool based on the project's protocol and programming language. For instance, Echidna or Foundry is often used for Solidity-based smart contracts, while cargo-fuzz is suitable for projects written in Rust.

  2. Invariant testing focuses on verifying critical rules or conditions that must always hold true within a smart contract, regardless of the sequence of transactions or state changes. Examples of invariants include ensuring that token balances never become negative, total supply remains constant, or only authorized accounts can perform certain actions. By systematically testing these rules under a variety of scenarios, auditors can confirm that the contract maintains its intended behavior and that its fundamental logic cannot be broken, even under unusual or adversarial conditions. a. Identifying Invariants: An invariant is a condition or property that should always hold true, regardless of the contract’s state or the inputs it receives. Mostly, Functional Requirements and Technical Description contains set of project invariants. Common examples include “token balances should never be negative” or “the total supply of tokens should not exceed a predefined limit.”

fuzz-invariant

For projects where fuzz or invariant testing is part of the scope:

  • Both auditors can participate in writing and executing tests.
  • While running these tests, auditors may continue manual code review, maintaining comprehensive coverage and improving the audit’s effectiveness.

4. Reporting

All findings are recorded and shared via our secure reporting portal:

  • Clients receive access to results in real time, without waiting for the audit to finish.
  • This provides flexibility, enabling early discussions, prioritization, and remediation planning.
  • Clear, structured reports make it easy to understand vulnerabilities and recommended actions.

After all code review, analysis, and tests, auditors prepare a report. Reports have the following structure:

  1. Introduction
  2. Scope
  3. Audit Summary
  4. System Overview
  5. Risks
  6. Findings
  7. Definitions
  8. Disclaimers
  9. Additional Values (Fuzz or Invariant Testing results, if applicable)

For High and Critical issues, our methodology requires the inclusion of Proof of Concept (PoC) test cases to audit reports. A Proof of Concept is a concrete test case or exploit scenario that demonstrates how a vulnerability can be triggered under real conditions. It ensures that severe issues are both verifiable and actionable for development teams.

5. Quality Assurance (QA)

The Quality Assurance (QA) phase is a dedicated step to ensure that the audit is thorough, consistent, and of the highest standard. A QA auditor oversees the process, independently reviewing both the findings and the audit workflow.

During this phase, the QA auditor:

  • Validates findings – Confirms that identified vulnerabilities are accurately described, correctly classified by severity, and reproducible.
  • Checks consistency – Ensures that all sections of the audit follow the same methodology, reporting format, and internal standards.
  • Reviews recommendations – Verifies that suggested mitigations are practical, actionable, and aligned with security best practices.
  • Ensures completeness – Cross-references audit checklists, test coverage, and manual review notes to confirm no critical areas were missed.
  • Monitors workflow compliance – Ensures that automated scans, and specialized testing (fuzzing, invariants) were applied consistently.

6. Remediation Check

After the initial audit report is delivered, clients have 10 business days to review the findings and implement fixes according to the recommendations and severity classification.

  • This timeframe allows teams to address critical and high-priority issues promptly while planning for medium and low-priority improvements.
  • Early visibility via the reporting portal helps teams track progress, ask clarifying questions, and discuss remediation strategies with auditors.

remediation-check

7. Review of Fixes and Final Report

Once fixes are applied:

  • Auditors verify that all critical issues have been resolved and that changes have not introduced new vulnerabilities.
  • A final, comprehensive report is issued, documenting all findings, actions taken, and recommendations for future improvements.
  • This report serves as the formal record of the audit and can be shared with stakeholders, investors or community.

During the auditing, an issue can have one of the following statuses:

issue-status

Part 3. Smart Contract Auditing Coverage

Our methodology systematically evaluates smart contracts across discrete, non-overlapping categories of vulnerabilities.
Each category defines its Audit Objectives, ensuring complete and consistent coverage.


Access Control Issues

Access-control vulnerabilities occur when privileged operations are not properly restricted, allowing unauthorized users or contracts to perform critical actions.

Audit Objectives

  • Validate correctness of role-based and ownership-based permissions.
  • Ensure only authorized accounts can execute administrative functions.
  • Confirm safe implementation of onlyOwner, AccessControl, and multisig patterns.
  • Review revocation, transfer, and emergency procedures for privilege management.
  • Detect potential privilege escalation through delegatecall or proxy misconfiguration.

Reentrancy Attacks

Reentrancy vulnerabilities enable repeated execution of sensitive logic before internal state changes are finalized.

Audit Objectives

  • Verify state updates occur before external calls.
  • Identify any nested or cross-function reentrancy paths.
  • Ensure consistent usage of mutexes or nonReentrant guards.
  • Confirm adherence to the checks-effects-interactions pattern.
  • Validate secure handling of callbacks, fallback functions, and token hooks.

Arithmetic & Calculation Errors

Arithmetic or calculation vulnerabilities occur when numeric operations behave unexpectedly due to overflow, rounding, or data type inconsistencies.

Audit Objectives

  • Detect overflows, underflows, and division-by-zero conditions.
  • Validate correct precision and scaling factors across tokens and formulas.
  • Ensure proper rounding and percentage calculations.
  • Confirm safe arithmetic libraries or compiler-checked operations are used.
  • Check all counters and accumulators for off-by-one and boundary errors.

Initialization & Upgradeability Risks

Improper initialization or unsafe upgrade patterns can compromise contract control or lead to permanent misconfiguration.

Audit Objectives

  • Ensure initializer functions are protected and callable only once.
  • Validate proxy-implementation storage layout consistency.
  • Confirm upgrade authorization is limited to defined governance.
  • Review delegatecall and fallback patterns for hijacking potential.
  • Detect re-initialization or forgotten setup functions.

Business Logic Vulnerabilities

Business-logic vulnerabilities occur when the contract behavior diverges from the intended design or expected process flow.

Audit Objectives

  • Compare implementation with documented functional specifications.
  • Validate lifecycle rules, state transitions, and order of operations.
  • Detect incorrect or missing enforcement of time locks, cooldowns, or access rules.
  • Ensure that invariants (e.g., total assets = user balances + reserves) always hold.
  • Review internal condition sequencing and state synchronization between modules.

Economic Attacks

Economic vulnerabilities exploit weaknesses in tokenomics, reward formulas, or market dependencies to gain unfair value extraction.

Audit Objectives

  • Review incentive, emission, and fee mechanisms for economic consistency.
  • Validate oracle integrations for update frequency, latency, and manipulation resistance.
  • Assess exposure to flash-loan, arbitrage, or liquidity-manipulation attacks.
  • Confirm stability of staking, lending, and reward-rate logic under extreme conditions.
  • Evaluate MEV (Miner Extractable Value) resistance in trading or reward systems.

Denial of Service (DoS)

DoS vulnerabilities prevent intended users or functions from executing by exhausting gas or creating deadlocked states.

Audit Objectives

  • Identify unbounded loops or excessive gas consumption per transaction.
  • Detect state-locking conditions or frozen queues.
  • Validate input validation and resource-limiting logic.
  • Confirm fail-safe recovery via admin functions or pause mechanisms.
  • Ensure dependency failures do not halt essential protocol operations.

Asset & Balance Safety

Asset-safety vulnerabilities cause loss, misallocation, or permanent locking of funds.

Audit Objectives

  • Validate correctness of deposit, withdrawal, and transfer logic.
  • Confirm full reconciliation between internal accounting and token balances.
  • Ensure recovery procedures for stuck or failed transfers.
  • Check that contract can gracefully handle non-standard ERC20 behavior.
  • Review emergency withdrawal and migration processes.

Front-Running & MEV Risks

Front-running vulnerabilities arise from predictable transaction order or transparent pending-state information.

Audit Objectives

  • Evaluate susceptibility of key functions to transaction reordering or sandwiching.
  • Confirm use of commit–reveal, randomized execution, or slippage limits.
  • Assess whether price updates, auctions, or oracle reads are safely sequenced.
  • Verify all trade, mint, and burn functions are atomic and order-independent.

Randomness Vulnerabilities

Predictable randomness can lead to unfair outcomes or manipulation of lottery, game, or validator-selection logic.

Audit Objectives

  • Detect reliance on blockhash, timestamp, or sequential seeds.
  • Validate integration with secure randomness oracles (e.g., Chainlink VRF).
  • Ensure random values are consumed immediately after generation.
  • Confirm entropy is immutable and not influenced by miners or validators.

Time Manipulation

Timestamp and block-number dependencies can be influenced by miners to affect critical timing behavior.

Audit Objectives

  • Identify direct dependency on block.timestamp or block.number.
  • Validate use of duration-based calculations instead of absolute timestamps.
  • Ensure time-based functions tolerate minor drift or reordering.
  • Confirm synchronization of timing between related contracts.

External Interaction Risks

External calls and integrations can introduce reentrancy, dependency, or trust-boundary vulnerabilities.

Audit Objectives

  • Identify all external calls and validate safe usage patterns.
  • Confirm return values and errors are properly handled.
  • Review address configurability and upgrade procedures for third-party dependencies.
  • Validate oracles and external data feeds for integrity and authenticity.
  • Ensure fallback and receive functions cannot trigger unintended behavior.

Chain/Ecosystem-Specific Risks

Each blockchain’s architecture introduces unique operational and security assumptions.

Audit Objectives

  • Validate compatibility with chain-specific gas models and execution semantics.
  • Detect misuse of chain-specific opcodes, precompiles, or storage behavior.
  • Review bridge, relayer, and cross-chain message handling.
  • Confirm handling of reorgs, finality delays, and timestamp precision.
  • Ensure protocol safety under network upgrades or forks.

Gas & Efficiency Optimizations

Excessive gas usage can increase user costs and expose contracts to operational failure under heavy load.

Audit Objectives

  • Identify redundant storage operations and computational overhead.
  • Recommend data-structure and logic optimizations that preserve clarity.
  • Validate bounded loops and minimal storage writes in critical paths.
  • Ensure cost-efficiency under real-world transaction volumes.

Documentation and Code Mismatch

Documentation inconsistencies reduce audit reliability and create misunderstandings about protocol behavior.

Audit Objectives

  • Cross-check code implementation with documentation, whitepapers, and specs.
  • Identify deprecated or undocumented functionality.
  • Ensure deployment parameters match public documentation.
  • Recommend updates to maintain synchronization between technical and user materials.

Part 4. Finding Severity Classification

The Hacken OU - Severity Formula Standart is a tool designed to assess the severity of software issues based on four key metrics: Likelihood, Impact, Complexity, and Exploitability.

Metrics

1. Likelihood

  • Description: Reflects the probability of the issue occurring.
  • Scale:
    1. [1] - Very unlikely
    2. [2] - Low risk (e.g., exposure of protocol owner's private key)
    3. [3] - Medium risk (e.g, conditionally possible but likely to occur)
    4. [4] - High risk (e.g, not certain but very likely to occur)
    5. [5] - Certain risk
  • Example Scenarios:
    • High Likelihood: Frequent occurrence, easily triggered.
    • Low Likelihood: Rare events, difficult to trigger.

2. Impact

  • Description: Represents the potential consequences or harm caused by the issue.
  • Scale:
    1. [1] - No impact at all
    2. [2] - Insignificant impact (e.g., contract fails to deliver promised returns without value loss)
    3. [3] - Minor or recoverable impact on balances, yields, or protocol rewards; or recoverable impact on availability, integrity, and confidentiality (e.g., DoS on protocol contracts, easy recovery)
    4. [4] - Significant and irrecoverable loss; or high impact on availability, integrity, and confidentiality (e.g., DoS on protocol contracts, no recovery possible)
    5. [5] - Catastrophic loss (e.g., >10% of Total Value Locked)
  • Example Scenarios:
    • High Impact: Loss of huge amount of assets.
    • Low Impact: Minimal impact on functionality or data.

3. Exploitability

  • Description: Indicates whether an issue can be directly exploited by an unprivileged user.
  • Scale:
    1. [0] Independent - The exploit can be executed at any time, without requiring a state change from any privileged user.
    2. [1] Semi-Dependent - The exploit requires a user who has been verified or authenticated by the system through additional security measures such as KYC or compliance checks. While these users have more privileges than unprivileged users, they do not possess the full range of privileges available to the most privileged users.
    3. [2] Dependent - The exploit depends on a call from the most privileged user on the system.
  • Example Scenarios:
    • High Exploitability: Only exploitable by protocol owner.
    • Low Exploitability: Any protocol user can exploit the finding.

4. Complexity

  • Description: Measures the level of difficulty in addressing and resolving the issue.
  • Scale:
    1. [0] Simple - The attack vector is evident to anyone, and minimal protocol know-how is required to detect and understand the finding. (ie. Missing Access Control issues)
    2. [1] Medium - Intermediate protocol know-how is required to detect and understand the finding. (ie. Reentrancy issues)
    3. [2] Complex - Very advanced protocol know-how is required to detect and understand the finding. (ie. Findings with very complicated mathematical operations)
  • Example Scenarios:
    • High Complexity: Requires significant time and resources to detect.
    • Low Complexity: Anyone can detect the finding in a short time.

Severities

There are five distinct risk levels associated with issue severity:

  1. Critical
  2. High
  3. Medium
  4. Low
  5. Informational

Mathematical Expression

ExploitabilityCoeff=1+0.25Exploitability\text{Exploitability}_{\text{Coeff}} = 1 + 0.25 \cdot \text{Exploitability}Severity=0.5Likelihood+0.5Impact0.2Issue ComplexityExploitabilityCoeff\text{Severity} = \sqrt[\text{Exploitability}_{\text{Coeff}}]{\, 0.5 \cdot \text{Likelihood} + 0.5 \cdot \text{Impact} - 0.2 \cdot \text{Issue Complexity}\,}Severity>4.5    Severity=Critical\text{Severity} > 4.5 \;\Rightarrow\; \text{Severity} = \text{Critical}4.5Severity>3.5    Severity=High4.5 \ge \text{Severity} > 3.5 \;\Rightarrow\; \text{Severity} = \text{High}3.5Severity>2.5    Severity=Medium3.5 \ge \text{Severity} > 2.5 \;\Rightarrow\; \text{Severity} = \text{Medium}2.5Severity>1.7    Severity=Low2.5 \ge \text{Severity} > 1.7 \;\Rightarrow\; \text{Severity} = \text{Low}1.7Severity    Severity=Informational1.7 \ge \text{Severity} \;\Rightarrow\; \text{Severity} = \text{Informational}

Stay in Touch

We’re excited to share our expertise and help you build a safer web3 future. If you have any questions, feel free to contact us.