2024 Web3 Security ReportAccess control exploits account for nearly 80% of crypto hacks in 2024.
Discover report insights
  • Hacken
  • Audits
  • k-bit
  • [SCA] K-BIT / K-BIT--Contracts / Jan2025
K-BIT logo

K-BIT

Audit name:

[SCA] K-BIT / K-BIT--Contracts / Jan2025

Date:

Feb 19, 2025

Table of Content

Introduction
Audit Summary
System Overview
Potential Risks
Findings
Appendix 1. Definitions
Appendix 2. Scope
Appendix 3. Additional Valuables
Disclaimer

Want a comprehensive audit report like this?

Introduction

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

K-BIT is a groundbreaking perpetual DEX solution.

Document

NameSmart Contract Code Review and Security Analysis Report for K-BIT
Audited ByTurgay Arda Usman
Approved ByGrzegorz Trawinski, Ataberk Yavuzer
Websitehttps://app.k-bit.xyz/
Changelog21/01/2025 - Preliminary Report
14/02/2025 - Second Report
19/02/2025 - Final Report
PlatformKAIA
LanguageSolidity
TagsDEX
Methodologyhttps://hackenio.cc/sc_methodology
  • Document

    Name
    Smart Contract Code Review and Security Analysis Report for K-BIT
    Audited By
    Turgay Arda Usman
    Approved By
    Grzegorz Trawinski, Ataberk Yavuzer
    Changelog
    21/01/2025 - Preliminary Report
    14/02/2025 - Second Report
    19/02/2025 - Final Report
    Platform
    KAIA
    Language
    Solidity
    Tags
    DEX

Review Scope

Repositoryhttps://github.com/devKBit/kbitAuditHacken
Inirtial Commit4e6fe5ef6021fc8efe43f686987c64b6e8811594
Second Commitece176ada42dd48194b8e13de5603cc6944e7440
Final Commit40cd44c3b9e2c1c925a5a94b91bc85c1f5836bdc
  • Review Scope

    Inirtial Commit
    4e6fe5ef6021fc8efe43f686987c64b6e8811594
    Second Commit
    ece176ada42dd48194b8e13de5603cc6944e7440
    Final Commit
    40cd44c3b9e2c1c925a5a94b91bc85c1f5836bdc

Audit Summary

18Total Findings
11Resolved
3Accepted
4Mitigated

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

Documentation quality

  • Functional requirements are partially provided.

  • Technical description is provided.

Code quality

  • The code mostly follows best practices and style guides.

    • See informational findings for more details.

  • The development environment is not configured.

Test coverage

Code coverage of the project is 77.88% (branch coverage).

  • The deployment and basic features are tested.

  • Multiple user interactions are partially covered.

System Overview

K-BIT is a perpetual DEX implementation with the following contracts:

LP  — contains the liquidity provider logic.

Fee —contains the fee management logic.

PerpDEX — contains the actual on chain logic for the perpetual DEX.

Privileged roles

  • The owner has the highest level of control, allowing them to pause/unpause trading, upgrade the contract, set oracles, manage protocol settings, and assign admin roles.

  • Liquidation admins can forcibly close positions that no longer meet margin requirements, ensuring risk management and system stability.

  • Limit order admins execute limit orders when price conditions are met, allowing traders' pre-set orders to be triggered automatically.

  • Single open admins can open new positions on behalf of traders by verifying signed data and ensuring price execution.

  • Close admins handle position closures, ensuring traders can exit positions when requested.

  • TPSL admins execute stop-loss and take-profit orders when price conditions are met, automating risk management for traders.

  • The protocol admin manages protocol-level settings, including funding fee distribution, external contract integrations, and protocol fees.

  • The admin of the Fee.sol can set fee percentages and register referrers.

Potential Risks

The functioning of the system significantly relies on specific external contracts. Any flaws or vulnerabilities in these contracts adversely affect the audited project, potentially leading to security breaches or loss of funds.

The implemented PerpDEX logic highly depends on external contracts not covered by the audit. This reliance introduces risks if these external contracts are compromised or contain vulnerabilities, affecting the audited project's integrity.

The project iterates over large dynamic arrays, which leads to excessive gas costs, risking denial of service due to out-of-gas errors, directly impacting contract usability and reliability.

The broad authorization model increases the risk of protocol control loss if any authorized address is compromised, potentially leading to unauthorized actions and significant financial loss.

The lack of multi-signature requirements for key operations centralizes decision-making power, increasing vulnerability to single points of failure or malicious insider actions, potentially leading to unauthorized transactions or configuration changes.

The digital contract architecture relies on administrative keys for critical operations. Centralized control over these keys presents a significant security risk, as compromise or misuse can lead to unauthorized actions or loss of funds.

The smart contract system incorporates governance mechanisms that are not fully decentralized, potentially allowing a small number of participants to exert disproportionate influence over key decisions and changes, limiting community engagement and consensus.

The project's contracts are upgradable, allowing the administrator to update the contract logic at any time. While this provides flexibility in addressing issues and evolving the project, it also introduces risks if upgrade processes are not properly managed or secured, potentially allowing for unauthorized changes that could compromise the project's integrity and security.

Findings

Code
Title
Status
Severity
F-2025-8348Funding Fee Buffer Can Be Abused to Reduce Trading Costs
mitigated

Medium
F-2025-8347Funding Fees Are Not Deducted in Real-Time, Allowing High-Leverage Positions to Avoid Liquidation
mitigated

Medium
F-2025-8346Repeated Position Merging Can Delay Liquidation and Avoid Funding Fees
mitigated

Medium
F-2025-8300Liquidation Front-Running
accepted

Medium
F-2025-8273Missing Funding Fee State Update on Position Rollback
fixed

Medium
F-2025-8394Insufficient of Fee-on-Transfer Token Handling
accepted

Low
F-2025-8393Lack of Balance Validation
fixed

Low
F-2025-8270Inaccurate Stop Loss (SL) and Take Profit (TP) Handling in Merged Positions
mitigated

Low
F-2025-8218Unsafe Casting from int256 to uint256
fixed

Low
F-2025-8147Missing Validations In Fee Setter
fixed

Low
1-10 of 18 findings

Identify vulnerabilities in your smart contracts.

Appendix 1. Definitions

Severities

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

Potential Risks

The "Potential Risks" section identifies issues that are not direct security vulnerabilities but could still affect the project’s performance, reliability, or user trust. These risks arise from design choices, architectural decisions, or operational practices that, while not immediately exploitable, may lead to problems under certain conditions. Additionally, potential risks can impact the quality of the audit itself, as they may involve external factors or components beyond the scope of the audit, leading to incomplete assessments or oversight of key areas. This section aims to provide a broader perspective on factors that could affect the project's long-term security, functionality, and the comprehensiveness of the audit findings.

Appendix 2. Scope

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

Scope Details

Repositoryhttps://github.com/devKBit/kbitAuditHacken
Initial Commit4e6fe5ef6021fc8efe43f686987c64b6e8811594
Second Commitece176ada42dd48194b8e13de5603cc6944e7440
Final Commit40cd44c3b9e2c1c925a5a94b91bc85c1f5836bdc
WhitepaperN/A
Requirementsprovided as an external file
Technical Requirementsprovided as an external file
  • Scope Details

    Initial Commit
    4e6fe5ef6021fc8efe43f686987c64b6e8811594
    Second Commit
    ece176ada42dd48194b8e13de5603cc6944e7440
    Final Commit
    40cd44c3b9e2c1c925a5a94b91bc85c1f5836bdc
    Whitepaper
    N/A
    Requirements
    provided as an external file
    Technical Requirements
    provided as an external file

Assets in Scope

File: fee.sol - File: fee.sol
File: lp.sol - File: lp.sol
File: perpDex.sol - File: perpDex.sol

Appendix 3. Additional Valuables

Verification of System Invariants

During the audit of K-BIT, Hacken followed its methodology by performing fuzz-testing on the project's main functions. Foundry , a tool used for fuzz-testing, was employed to check how the protocol behaves under various inputs. Due to the complex and dynamic interactions within the protocol, unexpected edge cases might arise. Therefore, it was important to use fuzz-testing to ensure that several system invariants hold true in all situations.

Fuzz-testing allows the input of many random data points into the system, helping to identify issues that regular testing might miss. A specific Echidna fuzzing suite was prepared for this task, and throughout the assessment, 3 invariants were tested over 3500000 runs. This thorough testing ensured that the system works correctly even with unexpected or unusual inputs.

Invariant

Test Result

Run Count

Tests fee payments with randomized fee amounts to ensure correct handling and protocol fee balance updates.Passed500000+
Verifies that the protocol fee can be claimed correctly after various fee deposits.Passed500000+
Ensures that users can claim referral fees correctly after multiple fee payments.Passed500000+
Ensures that opening a position under random parameters either succeeds (creating a valid Open position) or reverts correctly if input constraints fail.Passed500000+
Verifies that limit orders can be created and executed with random parameters, transitioning to Open or Merged on success, or reverting to stay as LimitOrderOpen on failurePassed500000+
Checks that opening a second position with the same trader, token type, and side causes margins and sizes to merge into the first position, or reverts safely if merging fails.Passed500000+
Ensures that positions opened under random parameters can be liquidated correctly (becoming Liquidated with updated final price) or remain Open on revert if liquidation conditions are not met.Passed500000+
  • Invariant

    Tests fee payments with randomized fee amounts to ensure correct handling and protocol fee balance updates.

    Test Result

    Passed

    Run Count

    500000+

    Invariant

    Verifies that the protocol fee can be claimed correctly after various fee deposits.

    Test Result

    Passed

    Run Count

    500000+

    Invariant

    Ensures that users can claim referral fees correctly after multiple fee payments.

    Test Result

    Passed

    Run Count

    500000+

    Invariant

    Ensures that opening a position under random parameters either succeeds (creating a valid Open position) or reverts correctly if input constraints fail.

    Test Result

    Passed

    Run Count

    500000+

    Invariant

    Verifies that limit orders can be created and executed with random parameters, transitioning to Open or Merged on success, or reverting to stay as LimitOrderOpen on failure

    Test Result

    Passed

    Run Count

    500000+

    Invariant

    Checks that opening a second position with the same trader, token type, and side causes margins and sizes to merge into the first position, or reverts safely if merging fails.

    Test Result

    Passed

    Run Count

    500000+

    Invariant

    Ensures that positions opened under random parameters can be liquidated correctly (becoming Liquidated with updated final price) or remain Open on revert if liquidation conditions are not met.

    Test Result

    Passed

    Run Count

    500000+

Additional Recommendations

The smart contracts in the scope of this audit could benefit from the introduction of automatic emergency actions for critical activities, such as unauthorized operations like ownership changes or proxy upgrades, as well as unexpected fund manipulations, including large withdrawals or minting events. Adding such mechanisms would enable the protocol to react automatically to unusual activity, ensuring that the contract remains secure and functions as intended.

To improve functionality, these emergency actions could be designed to trigger under specific conditions, such as:

  • Detecting changes to ownership or critical permissions.

  • Monitoring large or unexpected transactions and minting events.

  • Pausing operations when irregularities are identified.

These enhancements would provide an added layer of security, making the contract more robust and better equipped to handle unexpected situations while maintaining smooth operations.

Disclaimer