Halborn Logo

Exchange V1 - Substance Exchange


Prepared by:

Halborn Logo

HALBORN

Last Updated 04/25/2024

Date of Engagement by: May 25th, 2023 - June 22nd, 2023

Summary

100% of all REPORTED Findings have been addressed

All findings

9

Critical

0

High

0

Medium

2

Low

5

Informational

2


1. INTRODUCTION

Substance Exchange is a Perpetual Decentralized Exchange where users can interact with futures and options and also can be Liquidity Providers earning from traders.

\client engaged Halborn to conduct a security assessment on their smart contracts beginning on 2023-05-25 and ending on 2023-06-22. The security assessment was scoped to the smart contracts provided in the Substance Exchange V3 GitHub repository. Commit hashes and further details can be found in the Scope section of this report.

2. ASSESSMENT SUMMARY

Halborn was provided 4 weeks for the engagement and assigned a full-time security engineer to review the security of the smart contracts in scope. The engineer is a blockchain and smart contract security expert with advanced penetration testing and smart contract hacking skills, and deep knowledge of multiple blockchain protocols.

The purpose of the assessment is to:

    • Identify potential security issues within the smart contracts.

    • Ensure that smart contract functionality operates as intended.

In summary, Halborn identified some improvements to reduce the likelihood and impact of risks, which were addressed and accepted by \client. The most concerning issues were found in the Chainlink integration:

    • Chainlink latestrounddata might be stale or incorrect

    • Chainlink Arbitrum sequencer is not verified to be online

3. TEST APPROACH & METHODOLOGY

Halborn performed a combination of manual and automated security testing to balance efficiency, timeliness, practicality, and accuracy in regard to the scope of this assessment. While manual testing is recommended to uncover flaws in logic, process, and implementation; automated testing techniques help enhance coverage of the code and can quickly identify items that do not follow the security best practices. The following phases and associated tools were used during the assessment:

    • Research into architecture and purpose

    • Smart contract manual code review and walkthrough

    • Graphing out functionality and contract logic/connectivity/functions (solgraph)

    • Manual assessment of use and safety for the critical Solidity variables and functions in scope to identify any arithmetic related vulnerability classes

    • Manual testing by custom scripts

    • Scanning of solidity files for vulnerabilities, security hot-spots or bugs. (MythX)

    • Static Analysis of security for scoped contract, and imported functions. (Slither)

    • Testnet deployment (Foundry, Brownie)

4. SCOPE

Code repositories:

    1. Substance Exchange V1

    2. Repository: SubstanceExchangeV1

    3. Commit ID: 136369e88c04d21a25fecbcf8a4f25d6363ee035

    4. Remediation Plan Commit ID: 7717277a15aef6b703a5cf9670509b2f0b1bd3fc

    5. Smart contracts in scope:

      1. Delegatable (src/core/Delegatable.sol)

      2. DelegationHub (src/core/DelegationHub.sol)

      3. ExchangeManager (src/core/ExchangeManager.sol)

      4. LiquidityPool (src/core/LiquidityPool.sol)

      5. SLPToken (src/core/SLPToken.sol)

      6. SubstanceProxy (src/core/SubstanceProxy.sol)

      7. SubstanceUSD (src/core/SubstanceUSD.sol)

      8. UserBalance (src/core/UserBalance.sol)

      9. BaseFuture (src/core/future/BaseFuture.sol)

      10. FutureFactory (src/core/future/FutureFactory.sol)

      11. FutureLong (src/core/future/FutureLong.sol)

      12. FutureLongV2 (src/core/future/FutureLongV2.sol)

      13. FutureShort (src/core/future/FutureShort.sol)

      14. FutureManager (src/core/future/FutureManager.sol)

      15. Option (src/core/option/Option.sol)

      16. OptionFactory (src/core/option/OptionFactory.sol)

      17. OptionManager (src/core/option/OptionManager.sol)

      18. Swap (src/core/swap/Swap.sol)

      19. SwapManager (src/core/swap/SwapManager.sol)

      20. GradualVester (src/core/token/GradualVester.sol)

      21. StakingReward (src/core/token/StakingReward.sol)

      22. SubstanceXToken (src/core/token/SubstanceXToken.sol)

      23. Struct (src/core/libraries/Struct.sol)

      24. TransferHelper (src/core/libraries/TransferHelper.sol)

    6. Delegatable (src/core/Delegatable.sol)

    7. DelegationHub (src/core/DelegationHub.sol)

    8. ExchangeManager (src/core/ExchangeManager.sol)

    9. LiquidityPool (src/core/LiquidityPool.sol)

    10. SLPToken (src/core/SLPToken.sol)

    11. SubstanceProxy (src/core/SubstanceProxy.sol)

    12. SubstanceUSD (src/core/SubstanceUSD.sol)

    13. UserBalance (src/core/UserBalance.sol)

    14. BaseFuture (src/core/future/BaseFuture.sol)

    15. FutureFactory (src/core/future/FutureFactory.sol)

    16. FutureLong (src/core/future/FutureLong.sol)

    17. FutureLongV2 (src/core/future/FutureLongV2.sol)

    18. FutureShort (src/core/future/FutureShort.sol)

    19. FutureManager (src/core/future/FutureManager.sol)

    20. Option (src/core/option/Option.sol)

    21. OptionFactory (src/core/option/OptionFactory.sol)

    22. OptionManager (src/core/option/OptionManager.sol)

    23. Swap (src/core/swap/Swap.sol)

    24. SwapManager (src/core/swap/SwapManager.sol)

    25. GradualVester (src/core/token/GradualVester.sol)

    26. StakingReward (src/core/token/StakingReward.sol)

    27. SubstanceXToken (src/core/token/SubstanceXToken.sol)

    28. Struct (src/core/libraries/Struct.sol)

    29. TransferHelper (src/core/libraries/TransferHelper.sol)

Out-of-scope:

    • third-party libraries and dependencies

    • economic attacks

5. RISK METHODOLOGY

Every vulnerability and issue observed by Halborn is ranked based on two sets of Metrics and a Severity Coefficient. This system is inspired by the industry standard Common Vulnerability Scoring System.
The two Metric sets are: Exploitability and Impact. Exploitability captures the ease and technical means by which vulnerabilities can be exploited and Impact describes the consequences of a successful exploit.
The Severity Coefficients is designed to further refine the accuracy of the ranking with two factors: Reversibility and Scope. These capture the impact of the vulnerability on the environment as well as the number of users and smart contracts affected.
The final score is a value between 0-10 rounded up to 1 decimal place and 10 corresponding to the highest security risk. This provides an objective and accurate rating of the severity of security vulnerabilities in smart contracts.
The system is designed to assist in identifying and prioritizing vulnerabilities based on their level of risk to address the most critical issues in a timely manner.

5.1 EXPLOITABILITY

Attack Origin (AO):
Captures whether the attack requires compromising a specific account.
Attack Cost (AC):
Captures the cost of exploiting the vulnerability incurred by the attacker relative to sending a single transaction on the relevant blockchain. Includes but is not limited to financial and computational cost.
Attack Complexity (AX):
Describes the conditions beyond the attacker’s control that must exist in order to exploit the vulnerability. Includes but is not limited to macro situation, available third-party liquidity and regulatory challenges.
Metrics:
EXPLOITABILIY METRIC (mem_e)METRIC VALUENUMERICAL VALUE
Attack Origin (AO)Arbitrary (AO:A)
Specific (AO:S)
1
0.2
Attack Cost (AC)Low (AC:L)
Medium (AC:M)
High (AC:H)
1
0.67
0.33
Attack Complexity (AX)Low (AX:L)
Medium (AX:M)
High (AX:H)
1
0.67
0.33
Exploitability EE is calculated using the following formula:

E=meE = \prod m_e

5.2 IMPACT

Confidentiality (C):
Measures the impact to the confidentiality of the information resources managed by the contract due to a successfully exploited vulnerability. Confidentiality refers to limiting access to authorized users only.
Integrity (I):
Measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of data stored and/or processed on-chain. Integrity impact directly affecting Deposit or Yield records is excluded.
Availability (A):
Measures the impact to the availability of the impacted component resulting from a successfully exploited vulnerability. This metric refers to smart contract features and functionality, not state. Availability impact directly affecting Deposit or Yield is excluded.
Deposit (D):
Measures the impact to the deposits made to the contract by either users or owners.
Yield (Y):
Measures the impact to the yield generated by the contract for either users or owners.
Metrics:
IMPACT METRIC (mIm_I)METRIC VALUENUMERICAL VALUE
Confidentiality (C)None (I:N)
Low (I:L)
Medium (I:M)
High (I:H)
Critical (I:C)
0
0.25
0.5
0.75
1
Integrity (I)None (I:N)
Low (I:L)
Medium (I:M)
High (I:H)
Critical (I:C)
0
0.25
0.5
0.75
1
Availability (A)None (A:N)
Low (A:L)
Medium (A:M)
High (A:H)
Critical (A:C)
0
0.25
0.5
0.75
1
Deposit (D)None (D:N)
Low (D:L)
Medium (D:M)
High (D:H)
Critical (D:C)
0
0.25
0.5
0.75
1
Yield (Y)None (Y:N)
Low (Y:L)
Medium (Y:M)
High (Y:H)
Critical (Y:C)
0
0.25
0.5
0.75
1
Impact II is calculated using the following formula:

I=max(mI)+mImax(mI)4I = max(m_I) + \frac{\sum{m_I} - max(m_I)}{4}

5.3 SEVERITY COEFFICIENT

Reversibility (R):
Describes the share of the exploited vulnerability effects that can be reversed. For upgradeable contracts, assume the contract private key is available.
Scope (S):
Captures whether a vulnerability in one vulnerable contract impacts resources in other contracts.
Metrics:
SEVERITY COEFFICIENT (CC)COEFFICIENT VALUENUMERICAL VALUE
Reversibility (rr)None (R:N)
Partial (R:P)
Full (R:F)
1
0.5
0.25
Scope (ss)Changed (S:C)
Unchanged (S:U)
1.25
1
Severity Coefficient CC is obtained by the following product:

C=rsC = rs

The Vulnerability Severity Score SS is obtained by:

S=min(10,EIC10)S = min(10, EIC * 10)

The score is rounded up to 1 decimal places.
SeverityScore Value Range
Critical9 - 10
High7 - 8.9
Medium4.5 - 6.9
Low2 - 4.4
Informational0 - 1.9

6. SCOPE

Out-of-Scope: New features/implementations after the remediation commit IDs.

7. Assessment Summary & Findings Overview

Critical

0

High

0

Medium

2

Low

5

Informational

2

Security analysisRisk levelRemediation Date
CHAINLINK LATESTROUNDDATA MIGHT BE STALE OR INCORRECTMediumSolved - 07/11/2023
MISSING CHAINLINK ARBITRUM SEQUENCER HEALTH CHECKMediumRisk Accepted - 07/15/2023
USING TRANSFER INSTEAD OF SAFETRANSFERLowRisk Accepted - 07/15/2023
FEEONTRANSFER AND BURNONTRANSFER TOKENS ARE NOT SUPPORTEDLowRisk Accepted - 07/15/2023
CENTRALIZATION RISK: PRODUCT MANAGER CAN WITHDRAW ARBITRARY AMOUNTS FROM LIQUIDITY POOLSLowRisk Accepted - 07/15/2023
CENTRALIZATION RISK: PRODUCT MANAGER CAN ALTER TOKEN RESERVES INDICATORSLowRisk Accepted - 07/15/2023
POTENTIAL ACCESS CONTROL BYPASSLowRisk Accepted - 07/15/2023
USING ERC721A INSTEAD OF ERC721 FOR MINTING ONLY 1 NFT AT A TIMEInformationalSolved - 07/10/2023
MISSING FEE RATES SANITY CHECKSInformationalAcknowledged - 07/15/2023

8. Findings & Tech Details

8.1 CHAINLINK LATESTROUNDDATA MIGHT BE STALE OR INCORRECT

// Medium

Description

Substance Exchange uses Chainlink as its price oracle. When buying or selling sUSD, the SubstanceUSD contract queries Chainlink for the underlying token price using the latestRoundData() function. This function returns uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt and uint80 answeredInRound. roundId denotes the identifier of the most recent update round, answer is the price of the asset, startedAt is the timestamp at which the round started and updatedAt is the timestamp at which the feed was updated. The getPrice() function does not check if the feed was updated at the most recent round nor does it verify the update timestamp against the current time, and this can result in accepting stale data which may threaten the stability of the exchange in a volatile market.

Code Location

SubstanceUSD.sol#L92

SubstanceUSD.sol

    function getPrice(address token, bool min) public view returns (uint256 price) {
        address oracle = underlyingToken[token].oracle;
        if (oracle == address(0)) {
            revert SubstanceUSD__InvalidToken();
        }
        (, int256 oraclePrice, , , ) = AggregatorV3Interface(oracle).latestRoundData();
        if (oraclePrice <= 0) {
            revert SubstanceUSD__InvalidOraclePrice();
        }
        uint8 pDecimals = AggregatorV3Interface(oracle).decimals();
        price = (uint256(oraclePrice) * PRECISION) / (10**pDecimals);
        price = min ? Math.min(PRECISION, price) : Math.max(PRECISION, price);
    }
BVSS
Recommendation

SOLVED: The \client team solved this issue in commit 7717277a.

8.2 MISSING CHAINLINK ARBITRUM SEQUENCER HEALTH CHECK

// Medium

Description

Arbitrum is a L2 blockchain leveraging Optimistic Rollups to integrate with the underlying L1. A node called sequencer is tasked with submitting user transactions to the L1 and if it fails, communication between the two is impossible. The exchange does not verify if the sequencer is online, which may lead to unexpected behavior if submitting transactions to the Ethereum mainnet is blocked.

Code Location

SubstanceUSD.sol#L92

SubstanceUSD.sol

    function getPrice(address token, bool min) public view returns (uint256 price) {
        address oracle = underlyingToken[token].oracle;
        if (oracle == address(0)) {
            revert SubstanceUSD__InvalidToken();
        }
        (, int256 oraclePrice, , , ) = AggregatorV3Interface(oracle).latestRoundData();
        if (oraclePrice <= 0) {
            revert SubstanceUSD__InvalidOraclePrice();
        }
        uint8 pDecimals = AggregatorV3Interface(oracle).decimals();
        price = (uint256(oraclePrice) * PRECISION) / (10**pDecimals);
        price = min ? Math.min(PRECISION, price) : Math.max(PRECISION, price);
    }
BVSS
Recommendation

RISK ACCEPTED: The \client team accepted the risk of this issue.

8.3 USING TRANSFER INSTEAD OF SAFETRANSFER

// Low

Description

Using transfer() instead of safeTransfer() when interacting with ERC20 tokens is not recommended because transfer() does not provide the same level of error handling and safety measures.

Code Location

The following contracts use transfer() function:

  • ExchangeManager.sol
  • LiquidityPool.sol
  • SubstanceUSD.sol
  • UserBalance.sol
  • BaseFuture.sol
  • FutureManager.sol
  • Option.sol
  • OptionManager.sol
  • SwapManager.sol
  • StakingReward.sol
BVSS
Recommendation

RISK ACCEPTED: The \client team accepted the risk of this issue.

8.4 FEEONTRANSFER AND BURNONTRANSFER TOKENS ARE NOT SUPPORTED

// Low

Description

Whenever a transfer of tokens is executed (in a swap, a deposit, or while adding liquidity), there's no check if the amount sent is equal to the amount actually received by the contract.

The safeTransferFrom function calls transferFrom internally in the token contract to execute the transfer. However, the balance is not verified before and after the transfer and the actual amount transferred may not be the same as the amount received in the case of a fee applied in the token contract. In the case of using a token of this kind, the liquidity providers may not be able to withdraw all of their liquidity.

Code Location

UserBalance.sol#L78

UserBalance.sol

    function userDeposit(address _token, uint256 _amount) external {
        _validTokenAddress(_token);
        address user = msgSender();
        IERC20(_token).safeTransferFrom(user, address(this), _amount);
        userBalance[user][_token] += _amount;
        emit Deposit(user, _token, _amount);
    }
BVSS
Recommendation

RISK ACCEPTED: The \client team accepted the risk of this issue.

8.5 CENTRALIZATION RISK: PRODUCT MANAGER CAN WITHDRAW ARBITRARY AMOUNTS FROM LIQUIDITY POOLS

// Low

Description

The LiquidityPool contract implements the external transfer function, which allows any account with the ProductManger role to withdraw arbitrary amounts of tokens from existing liquidity pools. In case such an account is compromised, the entire protocol liquidity is at risk.

Code Location

LiquidityPool.sol#L499

LiquidityPool.sol

    function transfer(address _token, address _dist, uint256 _amount) external isProductManager {
        poolAmount[_token] -= _amount;
        IERC20(_token).transfer(_dist, _amount);
    }
BVSS
Recommendation

RISK ACCEPTED: The \client team accepted the risk of this issue.

8.6 CENTRALIZATION RISK: PRODUCT MANAGER CAN ALTER TOKEN RESERVES INDICATORS

// Low

Description

The LiquidityPool contract implements the increaseLiquidity() and decreaseLiquidity() functions. If called by the Product Manager (which is a role assigned by the contract owner) they can alter the values reported by the token reserves trackers without actually touching the reserves, putting the exchange out of balance. This directly affects protocol accounting and may have negative consequences on the protocol and its users.

A good example of this could be a liquidity provider withdrawing their liquidity from the pool, where the transaction would revert.

Code Location

LiquidityPool.sol#L489

LiquidityPool.sol

    function increaseLiquidity(address _token, uint256 _amount) external isProductManager {
        _validTokenCheck(_token);
        poolAmount[_token] += _amount;
    }

LiquidityPool.sol#L494

LiquidityPool.sol

    function decreaseLiquidity(address _token, uint256 _amount) external isProductManager {
        _validTokenCheck(_token);
        poolAmount[_token] -= _amount;
    }
BVSS
Recommendation

RISK ACCEPTED: The \client team accepted the risk of this issue.

8.7 POTENTIAL ACCESS CONTROL BYPASS

// Low

Description

The ProductManager role is used to grant access from some contracts to other contract's functions. There exists a scenario in which any user can be the owner of the entire protocol by means of using the hub contract's delegate calls to call any other protocol contract if the Delegation Hub contract is assigned the ProductManager role for those other contracts, effectively granting anyone privileged access to many sensitive functions.

Code Location

OwnableUpgradeable.sol

    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }
BVSS
Recommendation

RISK ACCEPTED: The \client team accepted the risk of this issue.

8.8 USING ERC721A INSTEAD OF ERC721 FOR MINTING ONLY 1 NFT AT A TIME

// Informational

Description

The StakingReward contract uses the ERC721A standard to store the users' staking weight and the corresponding rewards. ERC721A is designed to allow multiple mints at the same time with so-called batch transfers (the more tokens minted at the same time, the more gas efficient the operation is) and Substance Exchange is not implementing this core functionality in their protocol. In ERC721A, NFT transfers are more expensive because of the way NFT owner accounts are stored.

Code Location

StakingReward.sol#L21

StakingReward.sol

contract StakingReward is Ownable, Delegatable, ERC721A {

For the purposes of this PoC, two different types of NFTs were created, one based on the ERC721A standard and one based on ERC721.

HalbornERC721A.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import "../lib/erc721a/contracts/ERC721A.sol";

contract HalbornERC721A is ERC721A{

    constructor() ERC721A("Substance Exchange Stake Azuki", "SEXSTAKE") {}

    function mint(uint256 _quantity) external payable {
        _mint(msg.sender, _quantity);
    }

    function transfer(address _to, uint256 tokenId) external {
        transferFrom(msg.sender, _to, tokenId);
    }
}

HalbornERC721.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import "../lib/openzeppelin-contracts/contracts/token/ERC721/ERC721.sol";

contract HalbornERC721 is ERC721{

    constructor() ERC721("Substance Exchange Stake OZ", "SEXSTAKE") {}

    function mint(uint256 _tokenId) public{
        _mint(msg.sender, _tokenId);
    }

    function transfer(address _to, uint256 _tokenId) public {
        _transfer(msg.sender, _to, _tokenId);
    }
}

The following scenario was simulated:

  • Minting an ERC721 (ozNFT) with tokenId = 0
  • Minting an ERC721A (azukiNFT) with quantity param = 1
  • Transfer the ozNFT (tokenId = 0) from Alice to Bobby
  • Transfer the azukiNFT (tokenId = 0) from Alice to Bobby
7.png
BVSS
Recommendation

SOLVED: The \client team solved this issue by replacing the ERC721A standard with ERC721 in commit e45003fe.

8.9 MISSING FEE RATES SANITY CHECKS

// Informational

Description

The exchange charges handling fees on certain operations. Fee rates are set by the contract owner and can be updated anytime. None of the setter functions does the sanity check of the provided fee rates, which may lead to contract owners introducing prohibitive or zero fees accidentally or by design.

Code Location

SubstanceUSD.sol#L54

SubstanceUSD.sol

    function setFee(uint256 _mintFee, uint256 _burnFee) external onlyOwner {
        mintFee = _mintFee;
        burnFee = _burnFee;
    }

SwapManager.sol#L45

SwapManager.sol

    function setMinExecutionFee(uint256 _minExecutionFee) external onlyOwner {
        minExecutionFee = _minExecutionFee;
    }

OptionManager.sol#L59

OptionManager.sol

    function setMinExecutionFee(uint256 _minExecutionFee) external onlyOwner {
        minExecutionFee = _minExecutionFee;
    }

BaseFuture.sol#L167

BaseFuture.sol

    function setMinExecutionFee(uint256 _minExecutionFee) external onlyOwner {
        minExecutionFee = _minExecutionFee;
    }
BVSS
Recommendation

ACKNOWLEDGED: The \client team acknowledged this issue.

9. Review Notes

The manual testing phase included isolated testing and integration testing to assure the correct functionality of the whole protocol. Whether it is an isolated test or an integration test, all of them are focused on checking a particular component, feature or functionality is working as expected. They can be summarized and categorized as follows:

  • Tokens used in the protocol:

    • Substance USD (sUSD): That users can use safely buy() and sell() returning the correct value from the oracles.
    • Substance Liquidity Pool (SLP): That SLP is correctly minted and burned depending on the actions in the liquidity pool and it is correctly managed.
    • Substance Exchange (SEX): That the governance is working properly while vesting and staking.
  • Core contracts:

    • It was checked that the UserBalance contract is properly handling deposits and users balances.
    • It was checked that the DelegationHub contract is properly making the delegateCalls handling the delegations and keeps the entire protocol stable.
    • The LiquidityPool contract was tested to make sure the liquidity providers have their liquidity stored securely, and that users cannot act maliciously against any of the stakeholders. Furthermore, that the user's balances are correctly calculated by the protocol.
  • Futures and Options:

    • That all the future trades are handled correctly there in the correct epoch and cannot be doubled or double spent.
    • That the yield obtained from a successful trade are within the expected ranges
    • That the fees cannot be bypassed
    • That the incentives scheme is correctly implemented to incentivise the liquidations
    • That slippage tolerance is correctly handled
  • Swaps:

    • That swaps are working correctly with stable prices
    • That there are no problems with slippage
    • That the slippage of the price from the time the swap order is made until when it's executed is correctly handled
  • Substance USD (sUSD): That users can use safely buy() and sell() returning the correct value from the oracles.

  • Substance Liquidity Pool (SLP): That SLP is correctly minted and burned depending on the actions in the liquidity pool and it is correctly managed.
  • Substance Exchange (SEX): That the governance is working properly while vesting and staking.

  • It was checked that the UserBalance contract is properly handling deposits and users balances.

  • It was checked that the DelegationHub contract is properly making the delegateCalls handling the delegations and keeps the entire protocol stable.
  • The LiquidityPool contract was tested to make sure the liquidity providers have their liquidity stored securely, and that users cannot act maliciously against any of the stakeholders. Furthermore, that the user's balances are correctly calculated by the protocol.

  • That all the future trades are handled correctly there in the correct epoch and cannot be doubled or double spent.

  • That the yield obtained from a successful trade are within the expected ranges
  • That the fees cannot be bypassed
  • That the incentives scheme is correctly implemented to incentivise the liquidations
  • That slippage tolerance is correctly handled

  • That swaps are working correctly with stable prices

  • That there are no problems with slippage
  • That the slippage of the price from the time the swap order is made until when it's executed is correctly handled

SETUP

For the tests 3 types of users were created: - Owner / Deployer (who has the ownership of and permissions for the protocol) - Liquidity Providers: The users interested on providing liquidity and obtaining yield passively (liqPr1, liqPr2, liqPr3, and liqPr4 in the protocol) - Traders: The users interested interacting with options and futures to obtain earnings actively (alice, bobby, carla, and edgar in the protocol)

The tests always start at the following state:

Below are given some examples of the tests performed:

BUY SCENARIO

  • All the users are approving, depositing in the contract and buying sUSD
  • liqPr1 is buying USD with all their stablecoins.
  • liqPr2 is buying USD with half of their stablecoins.
  • alice deposits all her balance in the UserBalance contract but is only buying USD with 7000 USDT, 3000 USDC, 1000 DAI and 1000 FRAX

RESULTS

SHORT SCENARIO

STRATEGY:

  • Alice has $12000 USD as initial balance
  • Opens a x10 Short to BTC with $3000 USD Collateral
  • BTC decreases the value for a 75%, with a value of $7500USD
  • Alice closes the position, having to return around 0.9WBTC and making a $22.5k profit
  • Expected output: $12000 + $22500 = 34500$
  • Result: $34462.5

RESULTS

LIQUIDITY POOL SCENARIO

  • Alice is shorting BTC with $3000 of collateral
  • LiqPr1 is depositing $40k USD in stablecoins to buy 4$0k sUSD and then provide it to the liquidity pool.
  • BTC decreases the value for a 75%, with a value of $7500USD
  • Alice closes the position, winning the trade and obtaining rewards
  • LiqPr1 is withdrawing the liquidity again to their stablecoins
  • Result: LiqPr1 is losing

RESULTS

10. Automated Testing

STATIC ANALYSIS REPORT

Description

Halborn used automated testing techniques to enhance the coverage of certain areas of the smart contracts in scope. Among the tools used was Slither, a Solidity static analysis framework. After Halborn verified the smart contracts in the repository and was able to compile them correctly into their abis and binary format, Slither was run against the contracts. This tool can statically verify mathematical relationships between Solidity variables to detect invalid or inconsistent usage of the contracts' APIs across the entire code-base. The security team assessed all findings identified by the Slither software, however, findings with severity Information and Optimization are not included in the below results for the sake of report readability.

Results

\small \begin{longtable}{| >{\raggedright}p{13cm} | c |} \hline \rowcolor{darkgray} \multicolumn{2}{| c |}{Slither results for Delegatable.sol}\ \hline \multicolumn{1}{| c |}{\textbf{Finding}} & \multicolumn{1}{| c |}{\textbf{Impact}}\ \hline \endfirsthead

\hline \multicolumn{1}{| c |}{\textbf{Finding}} & \multicolumn{1}{| c |}{\textbf{Impact}}\ \hline \endhead

\hline \multicolumn{2}{| c |}{End of table for Delegatable.sol}\ \hline \endlastfoot\hline \textcolor{green}{Delegatable._checkOperator() (src/core/Delegatable.sol#25-30) is never used and should be removed } & \textcolor{green}{Low} \ \hline \end{longtable}

\small \begin{longtable}{| >{\raggedright}p{13cm} | c |} \hline \rowcolor{darkgray} \multicolumn{2}{| c |}{Slither results for DelegationHub.sol}\ \hline \multicolumn{1}{| c |}{\textbf{Finding}} & \multicolumn{1}{| c |}{\textbf{Impact}}\ \hline \endfirsthead

\hline \multicolumn{1}{| c |}{\textbf{Finding}} & \multicolumn{1}{| c |}{\textbf{Impact}}\ \hline \endhead

\hline \endfoot

\hline \multicolumn{2}{| c |}{End of table for DelegationHub.sol}\ \hline \endlastfoot\hline \textcolor{red}{Reentrancy in DelegationHub._aggregate(address,DelegationHub.Call[]) (src/core/DELEGATIONHUB.sol#109-148): External calls: (success,retData) = calli.target.call{value: val}(calli.payload) (src/core/DELEGATIONHUB.sol#127) State variables written after the call(s): senderOverride = address(0) (src/core/DELEGATIONHUB.sol#147) DelegationHub.senderOverride (src/core/DELEGATIONHUB.sol#21) can be used in cross function reentrancies: DelegationHub._aggregate(address,DelegationHub.Call[]) (src/core/DELEGATIONHUB.sol#109-148) DelegationHub.msgSender() (src/core/DELEGATIONHUB.sol#80-86) DelegationHub.receiveEthFromUserBalance() (src/core/DELEGATIONHUB.sol#49-54) } & \textcolor{red}{High} \

\hline \textcolor{red}{DelegationHub (src/core/DELEGATIONHUB.sol#16-151) is an upgradeable contract that does not protect its initialize functions: DelegationHub.initialize() (src/core/DELEGATIONHUB.sol#41-43). Anyone can delete the contract with: UUPSUpgradeable.upgradeTo(address) (lib/openzeppelin-contracts/contracts-upgradeable/proxy/utils/ UUPSUpgradeable.sol#74-77) UUPSUpgradeable.upgradeToAndCall(address,bytes) (lib/openzeppelin-contracts/contracts-upgradeable/proxy/utils/ UUPSUpgradeable.sol#89-92) } & \textcolor{red}{High} \

\hline \textcolor{yellow}{DelegationHub.setOperator(address[],bool[]).i (src/core/DELEGATIONHUB.sol#61) is a local variable never initialized ERC1967UpgradeUpgradeable._upgradeToAndCallUUPS(address,bytes,bool).slot (lib/openzeppelin-contracts/contracts-upgradeable/proxy/ERC1967/ ERC1967UpgradeUpgradeable.sol#84) is a local variable never initialized } & \textcolor{yellow}{Medium} \

\hline \textcolor{green}{DelegationHub.setOperator(address[],bool[]).i (src/core/DELEGATIONHUB.sol#61) is a local variable never initialized ERC1967UpgradeUpgradeable._upgradeToAndCallUUPS(address,bytes,bool).slot (lib/openzeppelin-contracts/contracts-upgradeable/proxy/ERC1967/ ERC1967UpgradeUpgradeable.sol#84) is a local variable never initialized } & \textcolor{green}{Low} \ \hline \end{longtable}

\small \begin{longtable}{| >{\raggedright}p{13cm} | c |} \hline \rowcolor{darkgray} \multicolumn{2}{| c |}{Slither results for ExchangeManager.sol}\ \hline \multicolumn{1}{| c |}{\textbf{Finding}} & \multicolumn{1}{| c |}{\textbf{Impact}}\ \hline \endfirsthead

\hline \multicolumn{1}{| c |}{\textbf{Finding}} & \multicolumn{1}{| c |}{\textbf{Impact}}\ \hline \endhead

\hline \endfoot

\hline \multicolumn{2}{| c |}{End of table for ExchangeManager.sol}\ \hline

\endlastfoot\hline \textcolor{red}{ExchangeManager (src/core/ExchangeManager.sol#16-100) is an upgradeable contract that does not protect its initialize functions: ExchangeManager.initialize(UserBalance, LiquidityPool, OptionManager, FutureManager, SwapManager) (src/core/ExchangeManager.sol#30-44). } & \textcolor{red}{High} \ \hline

\textcolor{yellow}{ExchangeManager.userClaimWithdrawLiquidity(uint256).i (src/core/ExchangeManager.sol#89) is a local variable never initialized } & \textcolor{yellow}{Medium} \ \hline

\textcolor{green}{ExchangeManager.setHub(address).hub (src/core/ExchangeManager.sol#46) shadows: Delegatable.hub (src/core/Delegatable.sol#10) (state variable) } & \textcolor{green}{Low} \ \hline

\end{longtable}

\small \begin{longtable}{| >{\raggedright}p{13cm} | c |} \hline \rowcolor{darkgray} \multicolumn{2}{| c |}{Slither results for LiquidityPool.sol}\ \hline \multicolumn{1}{| c |}{\textbf{Finding}} & \multicolumn{1}{| c |}{\textbf{Impact}}\ \hline \endfirsthead

\hline \multicolumn{1}{| c |}{\textbf{Finding}} & \multicolumn{1}{| c |}{\textbf{Impact}}\ \hline \endhead

\hline \endfoot

\hline \multicolumn{2}{| c |}{End of table for LiquidityPool.sol}\ \hline

\endlastfoot\hline \textcolor{red}{LiquidityPool.adminWithdrawBurnFees(address) (src/core/LiquidityPool.sol#183-190) ignores return value by IERC20(token).transfer(_collection,feesAvailable[token]) (src/core/LiquidityPool.sol#187) } & \textcolor{red}{High} \ \hline

\textcolor{red}{LiquidityPool.globalWithdrawToken(int256) (src/core/LiquidityPool.sol#315-384) ignores return value by IERC20(token_scope_1).transfer(userBalance,withdrawAmount) (src/core/LiquidityPool.sol#377) } & \textcolor{red}{High} \ \hline

\textcolor{red}{LiquidityPool.transfer(address,address,uint256) (src/core/LiquidityPool.sol#510-513) ignores return value by IERC20(_token).transfer(_dist,_amount) (src/core/LiquidityPool.sol#512) } & \textcolor{red}{High} \ \hline

\textcolor{yellow}{LiquidityPool.getSLPDiscountRatio(uint256,uint256,uint256) (src/core/LiquidityPool.sol#574-594) performs a multiplication on the result of a division: averageDiff = (initDiff + nextDiff) / 2 (src/core/LiquidityPool.sol#583) taxBps = (taxBasisPoints * averageDiff) / targetRatio (src/core/LiquidityPool.sol#589) } & \textcolor{yellow}{Medium} \ \hline

\textcolor{yellow}{Reentrancy in LiquidityPool.adminWithdrawBurnFees(address) (src/core/LiquidityPool.sol#183-190): External calls: IERC20(token).transfer(_collection,feesAvailable[token]) (src/core/LiquidityPool.sol#187) State variables written after the call(s): feesAvailable[token] = 0 (src/core/LiquidityPool.sol#188) LiquidityPool.feesAvailable (src/core/LiquidityPool.sol#61) can be used in cross function reentrancies: LiquidityPool.adminWithdrawBurnFees(address) (src/core/LiquidityPool.sol#183-190) LiquidityPool.feesAvailable (src/core/LiquidityPool.sol#61) LiquidityPool.globalWithdrawToken(int256) (src/core/LiquidityPool.sol#315-384) } & \textcolor{yellow}{Medium} \ \hline

\textcolor{yellow}{LiquidityPool.claimCurrentEpochLiquidityTokenPrices(uint256[]).i (src/core/LiquidityPool.sol#250) is a local variable never initialized } & \textcolor{yellow}{Medium} \ \hline

\textcolor{yellow}{LiquidityPool.globalWithdrawToken(int256).i (src/core/LiquidityPool.sol#331) is a local variable never initialized } & \textcolor{yellow}{Medium} \ \hline

\textcolor{green}{LiquidityPool._addValidLiquidityToken(address,uint8) (src/core/LiquidityPool.sol#161-169) has external calls inside a loop: IERC20(_tokenAddress).totalSupply() (src/core/LiquidityPool.sol#168) } & \textcolor{green}{Low} \ \hline

\end{longtable}

\small \begin{longtable}{| >{\raggedright}p{13cm} | c |} \hline \rowcolor{darkgray} \multicolumn{2}{| c |}{Slither results for SLPToken.sol}\ \hline \multicolumn{1}{| c |}{\textbf{Finding}} & \multicolumn{1}{| c |}{\textbf{Impact}}\ \hline \endfirsthead

\hline \multicolumn{1}{| c |}{\textbf{Finding}} & \multicolumn{1}{| c |}{\textbf{Impact}}\ \hline \endhead

\hline \endfoot

\hline \multicolumn{2}{| c |}{End of table for SLPToken.sol}\ \hline

\endlastfoot\hline

\textcolor{green}{SLPToken.setPool(address)._pool (src/core/SLPToken.sol#15) lacks a zero-check on : - pool = _pool (src/core/SLPToken.sol#16) } & \textcolor{green}{Low} \ \hline

\end{longtable}

\small \begin{longtable}{| >{\raggedright}p{13cm} | c |} \hline \rowcolor{darkgray} \multicolumn{2}{| c |}{Slither results for SubstanceProxy.sol}\ \hline \multicolumn{1}{| c |}{\textbf{Finding}} & \multicolumn{1}{| c |}{\textbf{Impact}}\ \hline \endfirsthead

\hline \multicolumn{1}{| c |}{\textbf{Finding}} & \multicolumn{1}{| c |}{\textbf{Impact}}\ \hline \endhead

\hline \endfoot

\hline \multicolumn{2}{| c |}{End of table for SubstanceProxy.sol}\ \hline

\endlastfoot\hline

\textcolor{yellow}{ERC1967Upgrade._upgradeToAndCallUUPS(address,bytes,bool).slot (lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Upgrade.sol#78) is a local variable never initialized } & \textcolor{yellow}{Medium} \ \hline

\textcolor{yellow}{ERC1967Upgrade._upgradeToAndCall(address,bytes,bool) (lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Upgrade.sol#59-64) ignores return value by Address.functionDelegateCall(newImplementation,data) (lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Upgrade.sol#62) } & \textcolor{yellow}{Medium} \ \hline

\textcolor{green}{ERC1967Upgrade._upgradeToAndCallUUPS(address,bytes,bool) (lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Upgrade.sol#71-85) ignores return value by IERC1822Proxiable(newImplementation).proxiableUUID() (lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Upgrade.sol#78-82) } & \textcolor{green}{Low} \ \hline

\end{longtable}

\small \begin{longtable}{| >{\raggedright}p{13cm} | c |} \hline \rowcolor{darkgray} \multicolumn{2}{| c |}{Slither results for SubstanceUSD.sol}\ \hline \multicolumn{1}{| c |}{\textbf{Finding}} & \multicolumn{1}{| c |}{\textbf{Impact}}\ \hline \endfirsthead

\hline \multicolumn{1}{| c |}{\textbf{Finding}} & \multicolumn{1}{| c |}{\textbf{Impact}}\ \hline \endhead

\hline \endfoot

\hline \multicolumn{2}{| c |}{End of table for SubstanceUSD.sol}\ \hline

\endlastfoot\hline \textcolor{red}{SubstanceUSD (src/core/SubstanceUSD.sol#23-151) is an upgradeable contract that does not protect its initialize functions: SubstanceUSD.initialize(IUserBalance,uint256,uint256,address) (src/core/SubstanceUSD.sol#44-52). } & \textcolor{red}{High} \ \hline

\textcolor{yellow}{Math.mulDiv(uint256,uint256,uint256) (lib/openzeppelin-contracts/contracts/utils/math/Math.sol#55-134) performs a multiplication on the result of a division: - denominator = denominator / twos (lib/openzeppelin-contracts/contracts/utils/math/Math.sol#101) } & \textcolor{yellow}{Medium} \ \hline

\textcolor{green}{SubstanceUSD.setHub(address).hub (src/core/SubstanceUSD.sol#78) shadows: - Delegatable.hub (src/core/Delegatable.sol#10) (state variable) } & \textcolor{green}{Low} \ \hline

\end{longtable}

\small \begin{longtable}{| >{\raggedright}p{13cm} | c |} \hline \rowcolor{darkgray} \multicolumn{2}{| c |}{Slither results for UserBalance.sol}\ \hline \multicolumn{1}{| c |}{\textbf{Finding}} & \multicolumn{1}{| c |}{\textbf{Impact}}\ \hline \endfirsthead

\hline \multicolumn{1}{| c |}{\textbf{Finding}} & \multicolumn{1}{| c |}{\textbf{Impact}}\ \hline \endhead

\hline \endfoot

\hline \multicolumn{2}{| c |}{End of table for UserBalance.sol}\ \hline

\endlastfoot\hline \textcolor{red}{UserBalance.transfer(address,address,address,uint256) (src/core/UserBalance.sol#148-156) ignores return value by IERC20(_token).transfer(_to,_amount) (src/core/UserBalance.sol#155) } & \textcolor{red}{High} \ \hline

\end{longtable}

Results summary

The findings obtained as a result of the Slither scan were reviewed. The majority of Slither findings were determined false-positives.

AUTOMATED SECURITY SCAN

Description

Halborn used automated security scanners to assist with detection of well-known security issues and to identify low-hanging fruits on the targets for this engagement. Among the tools used was MythX, a security analysis service for Ethereum smart contracts. MythX performed a scan on the smart contracts and sent the compiled results to the analyzers in order to locate any vulnerabilities.

Results

src/core/DelegationHub.sol

src/core/ExchangeManager.sol

src/core/LiquidityPool.sol

src/core/SLPToken.sol

src/core/SubstanceProxy.sol

src/core/SubstanceUSD.sol

src/core/UserBalance.sol

src/core/future/BaseFuture.sol

src/core/future/FutureLong.sol

src/core/future/FutureLongV2.sol

src/core/future/FutureShort.sol

src/core/future/FutureManager.sol

src/core/option/Option.sol

src/core/option/OptionFactory.sol

src/core/option/OptionManager.sol

src/core/swap/Swap.sol

src/core/swap/SwapManager.sol

src/token/GradualVester.sol

src/token/SubstanceXToken.sol

src/libraries/Struct.sol

src/libraries/TransferHelper.sol

MythX did not identify any vulnerabilities in the contracts.

The findings obtained as a result of the MythX scan were examined, and they were not included in the report as they were determined false positives.

Halborn strongly recommends conducting a follow-up assessment of the project either within six months or immediately following any material changes to the codebase, whichever comes first. This approach is crucial for maintaining the project’s integrity and addressing potential vulnerabilities introduced by code modifications.

© Halborn 2024. All rights reserved.