Q2 2026 Security & Compliance Report67 incidents, $764M in losses, 88% from operational failures.
Get the report →

Audit name:

[SCA] Nezha | Gambling + Farming + Staking | Oct2023

Date:

Oct 26, 2023

Table of Content

→Introduction
→Audit Summary
→Document Information
→System Overview
→Executive Summary
→Risks
→Findings
→Appendix 1. Severity Definitions
→Appendix 2. Scope
→Disclaimer

Want a comprehensive audit report like this?

Introduction

We express our gratitude to the Nezha team for the collaborative engagement that enabled the execution of this Smart Contract Security Assessment.

Nezha brings a kind of collective farming where the crop yield is distributed among farmers through a lottery system.

titlecontent
PlatformSolana
LanguageRust
TagsFarming, Staking, Lottery
Timeline11/05/2023 - 25/10/2023
Methodologyhttps://hackenio.cc/sc_methodology→

    Review Scope

    Repositoryhttps://github.com/NezhaLabs/nezha-contracts→
    Commit43ec25983e83bcd0b15723f742a962e24691a5ff

    Audit Summary

    Total9.3/10
    Security Score

    10/10

    Test Coverage

    90%

    Code Quality Score

    8.5/10

    Documentation Quality Score

    10/10

    25Total Findings
    20Resolved
    0Accepted
    5Mitigated

    The system users should acknowledge all the risks summed up in the risks section of the report

    Document Information

    This report may contain confidential information about IT systems and the intellectual property of the Customer, as well as information about potential vulnerabilities and methods of their exploitation.

    The report can be disclosed publicly after prior consent by another Party. Any subsequent publication of this report shall be without mandatory consent.

    Document

    NameSmart Contract Code Review and Security Analysis Report for Nezha
    Audited ByHacken
    Websitehttps://www.nezha.fi/→
    Changelog11/05/2023 – Initial Review
    04/07/2023 – Second Review
    06/09/2023 – Third Review
    22/09/2023 – Fourth Review
    25/10/2023 – Fifth Review
    • Document

      Name
      Smart Contract Code Review and Security Analysis Report for Nezha
      Audited By
      Hacken
      Changelog
      11/05/2023 – Initial Review
      04/07/2023 – Second Review
      06/09/2023 – Third Review
      22/09/2023 – Fourth Review
      25/10/2023 – Fifth Review

    System Overview

    The primary function of Nezha is collective farming, wherein the crop yield is distributed among farmers through a lottery system.

    The smart contracts within the scope manage user funds, integrate with farming, and integrate with the lottery. The back-ends of the farming and the lottery themselves are not subject to the audit.

    User interactions commence with the staking of funds into the contract. Users may increase their stake by creating specific request records, which require subsequent approval or enactment by an administrator. Users may decrease their stake in case the funds are not currently in use by the profit generation subsystem.

    Two farming methods are available: Francium, an on-chain investment system, and a manual method (an out-of-scope dev feature). The Francium method is entirely on-chain and automated, while the manual method involves the system administrator withdrawing the entire investment pool (total staked funds) and then reinvesting it, ideally with a profit.

    The lottery's winning combination is determined on-chain using Switchboard VRF, and the results, presented as a list of winners and their prizes, are subsequently recorded in the contract.

    The system encompasses several key funds-bearing accounts or vaults:

    • Pending deposit vault: Users deposit stake increases when they create such requests. Once the requests are approved and executed, the value is transferred to the deposit vault.

    • Deposit vault: This is where the total staked funds are held and periodically used for farming.

    • Treasury vault: In the event of a profitable farming cycle, a portion of the profit is allocated to this vault. The funds here can be directly withdrawn by an administrator and can be regarded as a protocol profit share.

    • Insurance vault: Likewise, if a farming cycle concludes with a profit, a share of the profit is placed in this vault. These funds are intended to pay the jackpot insurance provider for their service. An administrator may directly withdraw these funds for the purpose of paying the insurer (the mechanic is outside the audit scope).

    • Tier 1-3 prize vaults: A share of the profit from a successful farming cycle is distributed among these vaults. Tier 1 represents the "jackpot," and the funds in these vaults are meant to be distributed to stakers as lottery winnings.

    The primary operational sequence is as follows:

    • An "epoch" is initiated by an administrator, dividing the system's operation into distinct periods known as “epochs”. At epoch creation, a yield split configuration is provided, specifying how the yield will be distributed to the vaults.

    • Epoch status: Running \-Stake change requests can be enacted. \-Funds can be invested to generate profit (admin-only).

    • Epoch status: Yielding \-This phase begins as the deposit vault funds are transferred to a farming method. \-The total number of issued lottery tickets is declared at this point. \-Funds invested can be withdrawn (admin-only).

    • Epoch status: Finalizing \-This phase starts when the invested funds are returned to the contract. \-If there are profits, they are distributed to the vaults according to the yield split configuration. Losses are shared among all stakers, and the funds are returned to the deposit vault. Note the mention of "pending funds" and insurance. \-A "winning combination" is retrieved from the VRF provider and pushed to the contract. The specific meaning is not within the contract's scope, and its value is irrelevant to the contract. \-A "winner meta" is pushed into the contract, providing the sizes of winner lists by tier and the number of winning tickets by tier. This determines the prize pool sizes per tier.  For tier 1, it is the jackpot amount declared in the yield split config.  For tiers 2-3, it is how much funds are there in the respective prize vaults. \-Winners are pushed to the contract batch-by-batch. Each winner record contains info on who is the winner, which tier is the win, and how many winning tickets the winner has for the tier. The prize amount is calculated as the ratio of winner tickets to the total number of tier winning tickets multiplied by the tier prize pool.

    • Epoch status: Ended \-This phase begins once all winners are announced \-Winners can claim their prize. For tier 2-3 wins, funds are transferred from the respective prize vault to the winner upon claiming. \-If it is a jackpot win, the prize funds are not readily available in the prize vault. An off-chain process is required to enable prize claims. This involves notifying the jackpot/insurance provider, obtaining their approval, and finally transferring the funds to the jackpot vault, from which they can be transferred to the winner upon claiming.

    Importantly, there are "pending funds" which may include tier 2-3 prize funds and insurance funds.

    • Tier 2-3 prize funds that are not fully distributed in the lottery are carried over to the next epochs.

    • Insurance, which serves as a periodic tax to enable the jackpot, may not be fully covered if an epoch's farming cycle ends with losses or insufficient profits. In such cases, the outstanding insurance tax is recorded as a debt, and the lottery will not be played until the insurance debt is covered in subsequent epochs.

    Privileged roles

    System owners have the authority to:

    • Invest/withdraw funds into the Francium protocol.

    • Create lottery tickets for users.

    • Provide lottery results data.

    • Approve/cancel stake increase requests.

    • Withdraw user funds (an out-of-scope dev feature).

    • Withdraw funds designated as treasury or insurance.

    • Fund the jackpot.

    • Request randomness from Switchboard VRF.

    • Change contract status according to the lifecycle.

    Executive Summary

    Documentation quality

    The total Documentation quality score is 10 out of 10.

    • Functional requirements are provided. User interaction flows and system architecture description are included.

    • Technical description is not finalized. Essential commands are provided within just cli.

    Code quality

    The total Code quality score is 8.5 out of 10.

    • The entry functions are overwhelmed with template checks and deep branching of possible states.

    • Missing functions modularity / insufficient code comments provided.

    Test coverage

    Code coverage of the project is 90%.

    • The code has a low percentage of coverage with unit tests.

    Security score

    Upon auditing, the code was found to contain 2 critical, 6 high, 9 medium, and 8 low severity issues. Out of these, 20 issues have been addressed and resolved, leading to a security score of 10 out of 10.

    All identified issues are detailed in the “Findings” section of this report.

    Summary

    The comprehensive audit of the customer's smart contract yields an overall score of 9.3. This score reflects the combined evaluation of documentation, code quality, test coverage, and security aspects of the project.

    Risks

    Centralization Concerns:

    The funding of the jackpot is not guaranteed.

    The reward distribution for tier 2 and tier 3 prizes is calculated based on parameters injected and stored on-chain at the start of each epoch and distributed manually.

    Unless the smart contracts are deployed with the --final parameter, their functionality can be altered arbitrarily at any moment.

    The protocol has functionalities that show signs of centralization, but most of them were eliminated during the audit process by the Customer team.

    Third-party Integration Considerations:

    Integration with Francium constitutes a vital component of the on-chain system; however, it falls outside the scope of this audit. The creators have not provided the source code for Francium, and its official documentation lacks depth to comprehend the implementation thoroughly. The most specific insight into its functioning can be found in the official SDK's code: Francium SDK on GitHub →. This code encompasses Typescript routines for constructing and issuing Francium program calls. Nezha's codebase maintains its own Rust code, similar to the official SDK, for interaction with the desired Francium programs/functions. We have verified that this Rust code aligns with the respective parts of the Francium Typescript SDK. Nonetheless, Francium programs and their interaction should be viewed as opaque.

    The Francium protocol assumes control over user funds and may impose fees or other charges.

    Given that Francium is a leverage farming protocol, high borrowing interest rates could impede the withdrawal of staked funds until borrowing rates become more favorable.

    Findings

    F-2023-134Unauthorized Funds Draining
    Status
    fixed
    Severity

    Critical
    F-2023-1348Unauthorized Funds Draining
    Status
    fixed
    Severity

    Critical
    F-2023-1355 Requirements Violation
    Status
    fixed
    Severity

    High
    F-2023-1354Missing Validation
    Status
    fixed
    Severity

    High
    F-2023-1353Highly Permissive Role
    Status
    fixed
    Severity

    High
    F-2023-1352Unverifiable Logic
    Status
    mitigated
    Severity

    High
    F-2023-1351 Denial of Service
    Status
    fixed
    Severity

    High
    F-2023-1350Weak Auth System
    Status
    fixed
    Severity

    High
    F-2023-1364Missing Validation
    Status
    fixed
    Severity

    Medium
    F-2023-136Unfair Behavior
    Status
    mitigated
    Severity

    Medium
    Code
    ―
    Title
    Status
    Severity
    F-2023-134Unauthorized Funds Draining
    fixed

    Critical
    F-2023-1348Unauthorized Funds Draining
    fixed

    Critical
    F-2023-1355 Requirements Violation
    fixed

    High
    F-2023-1354Missing Validation
    fixed

    High
    F-2023-1353Highly Permissive Role
    fixed

    High
    F-2023-1352Unverifiable Logic
    mitigated

    High
    F-2023-1351 Denial of Service
    fixed

    High
    F-2023-1350Weak Auth System
    fixed

    High
    F-2023-1364Missing Validation
    fixed

    Medium
    F-2023-136Unfair Behavior
    mitigated

    Medium
    1-10 of 25 findings

    Identify vulnerabilities in your smart contracts.

    Appendix 1. Severity Definitions

    When auditing smart contracts, Hacken is using a risk-based approach that considers Likelihood, Impact, Exploitability and Complexity metrics to evaluate findings and score severities.

    Reference on how risk scoring is done is available through the repository in our Github organization:

    Severity

    Description

    Critical
    Critical vulnerabilities are usually straightforward to exploit and can lead to the loss of user funds or contract state manipulation.

    High
    High vulnerabilities are usually harder to exploit, requiring specific conditions, or have a more limited scope, but can still lead to the loss of user funds or contract state manipulation.

    Medium
    Medium vulnerabilities are usually limited to state manipulations and, in most cases, cannot lead to asset loss. Contradictions and requirements violations. Major deviations from best practices are also in this category.

    Low
    Major deviations from best practices or major Gas inefficiency. These issues will not have a significant impact on code execution, do not affect security score but can affect code quality score.
    • Severity

      Critical

      Description

      Critical vulnerabilities are usually straightforward to exploit and can lead to the loss of user funds or contract state manipulation.

      Severity

      High

      Description

      High vulnerabilities are usually harder to exploit, requiring specific conditions, or have a more limited scope, but can still lead to the loss of user funds or contract state manipulation.

      Severity

      Medium

      Description

      Medium vulnerabilities are usually limited to state manipulations and, in most cases, cannot lead to asset loss. Contradictions and requirements violations. Major deviations from best practices are also in this category.

      Severity

      Low

      Description

      Major deviations from best practices or major Gas inefficiency. These issues will not have a significant impact on code execution, do not affect security score but can affect code quality score.

    Appendix 2. Scope

    The scope of the project includes the following smart contracts from the provided repository:

    Scope Details

    Repositoryhttps://github.com/NezhaLabs/nezha-contracts→
    Commit43ec25983e83bcd0b15723f742a962e24691a5ff
    WhitepaperProvided→
    RequirementsProvided→
    Technical RequirementsProvided

    Contracts in Scope

    nezha-staking-lib
    src
    accounts
    account_type.rs - nezha-staking-lib › src › accounts › account_type.rs
    mod.rs - nezha-staking-lib › src › accounts › mod.rs
    pda.rs - nezha-staking-lib › src › accounts › pda.rs
    error
    conversions.rs - nezha-staking-lib › src › error › conversions.rs
    mod.rs - nezha-staking-lib › src › error › mod.rs
    fixed_point
    mod.rs - nezha-staking-lib › src › fixed_point › mod.rs
    francium
    accounts.rs - nezha-staking-lib › src › francium › accounts.rs
    constants.rs - nezha-staking-lib › src › francium › constants.rs
    instruction.rs - nezha-staking-lib › src › francium › instruction.rs
    mod.rs - nezha-staking-lib › src › francium › mod.rs
    instruction
    fns.rs - nezha-staking-lib › src › instruction › fns.rs
    mod.rs - nezha-staking-lib › src › instruction › mod.rs
    lib.rs - nezha-staking-lib › src › lib.rs
    state
    epoch

    Disclaimer