Reach out for an audit or to learn more about Macro
or Message on Telegram

Superstate A-3

Security Audit

November 4th, 2024

Version 1.0.0

Presented by 0xMacro

Table of Contents

Introduction

This document includes the results of the security audit for Superstate's smart contract code as found in the section titled ‘Source Code’. The security audit was performed by the Macro security team on October 25th to October 29th, 2024.

The purpose of this audit is to review the source code of certain Superstate Solidity contracts, and provide feedback on the design, architecture, and quality of the source code with an emphasis on validating the correctness and security of the software in its entirety.

Disclaimer: While Macro’s review is comprehensive and has surfaced some changes that should be made to the source code, this audit should not solely be relied upon for security, as no single audit is guaranteed to catch all possible bugs.

Overall Assessment

The following is an aggregation of issues found by the Macro Audit team:

Severity Count Acknowledged Won't Do Addressed
Medium 3 - - 3
Low 2 - - 2
Code Quality 5 1 - 4

Superstate was quick to respond to these issues.

Specification

Our understanding of the specification was based on the following sources:

Source Code

The following source code was reviewed during the audit:

Specifically, we audited the following contracts within these repositories:

Source Code SHA256
liquidation-contracts/src/MorphoLiquidationV1.sol

68a6ab14035646e04bb90a5b60315834661822acb0fbff8ab5c31f0d3cf45f2c

onchain-redemptions/src/oracle/SuperstateOracle.sol

5ce0785ff6aadeb2277b45fb6c8757a3c50185a68c67766bde35d4f139632ae7

ustb/src/SuperstateToken.sol

f88122b1786b08aa5ad6ba232d720e2f0f1f83b289d102f539395c7a76fc6fea

Additionally, the following deployment script was reviewed:

Source Code SHA256
ustb/script/v2/DeployAndUpgradeUsccScriptV2.s.sol

e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

ustb/script/v2/DeployAndUpgradeUstbScriptV2.s.sol

e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

Note: This document contains an audit solely of the Solidity contracts listed above. Specifically, the audit pertains only to the contracts themselves, and does not pertain to any other programs or scripts, including deployment scripts.

Issue Descriptions and Recommendations

Click on an issue to jump to it, or scroll down to see them all.

Security Level Reference

We quantify issues in three parts:

  1. The high/medium/low/spec-breaking impact of the issue:
    • How bad things can get (for a vulnerability)
    • The significance of an improvement (for a code quality issue)
    • The amount of gas saved (for a gas optimization)
  2. The high/medium/low likelihood of the issue:
    • How likely is the issue to occur (for a vulnerability)
  3. The overall critical/high/medium/low severity of the issue.

This third part – the severity level – is a summary of how much consideration the client should give to fixing the issue. We assign severity according to the table of guidelines below:

Severity Description
(C-x)
Critical

We recommend the client must fix the issue, no matter what, because not fixing would mean significant funds/assets WILL be lost.

(H-x)
High

We recommend the client must address the issue, no matter what, because not fixing would be very bad, or some funds/assets will be lost, or the code’s behavior is against the provided spec.

(M-x)
Medium

We recommend the client to seriously consider fixing the issue, as the implications of not fixing the issue are severe enough to impact the project significantly, albiet not in an existential manner.

(L-x)
Low

The risk is small, unlikely, or may not relevant to the project in a meaningful way.

Whether or not the project wants to develop a fix is up to the goals and needs of the project.

(Q-x)
Code Quality

The issue identified does not pose any obvious risk, but fixing could improve overall code quality, on-chain composability, developer ergonomics, or even certain aspects of protocol design.

(I-x)
Informational

Warnings and things to keep in mind when operating the protocol. No immediate action required.

(G-x)
Gas Optimizations

The presented optimization suggestion would save an amount of gas significant enough, in our opinion, to be worth the development cost of implementing it.

Issue Details

M-1

Oracle stops functioning when navs gets smaller

Topic
Specification
Status
Impact
High
Likelihood
Low

In the SuperstateOracle, the calculateRealtimeNavs() function determines the correct oracle price at a particular time based on linear extrapolation of prices from the last two effective checkpoints.

function calculateRealtimeNavs(
    uint128 targetTimestamp,
    uint128 earlierCheckpointNavs,
    uint128 earlierCheckpointTimestamp,
    uint128 laterCheckpointNavs,
    uint128 laterCheckpointTimestamp
) public pure returns (uint128 answer) {
    answer = laterCheckpointNavs
        + ((laterCheckpointNavs - earlierCheckpointNavs) * (targetTimestamp - laterCheckpointTimestamp))
            / (laterCheckpointTimestamp - earlierCheckpointTimestamp);
}

However, implementation incorrectly assumes that the later checkpoint will always have a navs value higher than the earlier checkpoint. While this would be the case in most situations, there is a non-zero probability that navs may be reduced. In this scenario, the price oracle will stop functioning as calculateRealtimeNavs() would revert due to an underflow error.

Remediations to consider

  • Update calculateRealtimeNavs() implementation to properly handle case when navs is reduced.
M-2

Use SafeERC20.forceApprove() in liquidate()

Topic
Specification
Status
Impact
High
Likelihood
Low

In the MorphoLiquidationV1 contract, the liquidate() function includes approving the max amount of loanToken to the morpho contract for performing the corresponding liquidation. The regular approve() method is used in the implementation, which is adequate for most ERC20 implementations.

uint256 balanceLoanToken = IERC20(marketParams.loanToken).balanceOf({account: address(this)});
if (balanceLoanToken == 0) revert InsufficientLoanTokenBalance();
IERC20(marketParams.loanToken).approve({spender: address(morpho), value: type(uint256).max});

However, USDT, a popular stablecoin ERC20, will revert the approve() if the spender's previous approved balance is non-zero. See the snippet below (source).

/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) {

    // To change the approve amount you first have to reduce the addresses`
    //  allowance to zero by calling `approve(_spender, 0)` if it is not
    //  already 0 to mitigate the race condition described here:
    //  https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
    require(!((_value != 0) && (allowed[msg.sender][_spender] != 0)));

    allowed[msg.sender][_spender] = _value;
    Approval(msg.sender, _spender, _value);
}

As a result, the above implementation would not be appropriate for USDT when it is being used as a loanToken or for any other token that follows a similar implementation approach.

Remediations to consider

  • Replace approve() with forceApprove() from the SafeERC20 lib, which correctly handles this edge case.
M-3

Deploy scripts have incorrect caller

Topic
Specification
Status
Addressed
Impact
Medium
Likelihood
Medium

In the DeployAndUpgradeUstbScriptV2 and DeployAndUpgradeUsccScriptV2 upgrade scripts, the upgrade procedure involves calling methods on other contracts that contain authorization checks.

In the current implementation, the implicit assumption is that the deployer (executor of deploy scripts) is the same as an authorized party in called contracts, such as admin/owner in USTB and USCC contracts.

However, this is not the case in mainnet contracts, and as a result, scripts are not directly executable.

Remediations to consider

  • Update upgrade scripts to execute upgrade operations with proper permissions, or
  • Use alternative methods based on the current infrastructure for managing authorizations.
L-1

Missing validation for navs value change

Topic
Specification
Status
Impact
Low
Likelihood
Low

In the SuperstateOracle, _addCheckpoint() function contains multiple input validation constraints that enforce proper values set. One of these validates that the new navs value is never smaller than the MINIMUM_ACCEPTABLE_PRICE.

However, there is no corresponding validation that enforces that the provided navs value is not unexpectedly large, which would impact all downstream systems using this oracle.

Remediations to consider

  • Add validation for provided navs to never have a balance change greater than MAX_NAVS_CHANGE.
L-2

Reset loanToken approval after liquidate()

Topic
Specification
Status
Impact
Low
Likelihood
Low

In the MorphoLiquidationV1 contract, the liquidate() function includes approving the max amount of loanToken to the morpho contract for performing the corresponding liquidation. When liquidate() is successfully processed, the morpho contract will still be authorized to spend almost the whole MorphoLiquidationV1's loanToken balance.

In case of an unexpected morpho contract compromise, this would put at risk all loanToken balances of the MorphoLiquidationV1 contract.

Remediations to consider

  • Reset morpho approval to 0 for loanToken after liquidation is performed.
Q-1

The tokenProxy variable in the deploy scripts is unnecessary

Topic
Best practices
Status
Quality Impact
Low

In the DeployAndUpgradeUsccScriptV2 and DeployAndUpgradeUstbScriptV2 contracts, there’s a tokenProxy variable declared with the TransparentUpgradeableProxy type, which is later used by being wrapped in the address type. This is identical to the declared tokenProxyAddress variable. Consider removing the tokenProxy variable in the deploy script contracts

            ...		
-   TransparentUpgradeableProxy tokenProxy = TransparentUpgradeableProxy(tokenProxyAddress);

    vm.startBroadcast(deployer);

    // 1
    USCC tokenV2Implementation = new USCC(admin, wrappedPerms);

    // 2
    tokenProxyAdmin.upgrade(ITransparentUpgradeableProxy(tokenProxyAddress), address(tokenV2Implementation));

    // 3
-   USCC tokenV2 = USCC(address(tokenProxy));
+   USCC tokenV2 = USCC(tokenProxyAddress);

        ...
}
Q-2

Public function initializeV2() not present in ISuperstateToken

Topic
Best practices
Status
Quality Impact
Low

In the SuperstateToken contract, with the recent changes, the initializeV2() public function has been introduced. However, diverging from the established practice this method does not have its declaration present in ISuperstateToken interface.

Consider updating ISuperstateToken to include initializeV2().

Q-3

OwnableUpgradeable contains extra functionality

Topic
Best practices
Status
Quality Impact
Low

The SuperstateToken inherits from OwnableUpgredeable. As a result, it contains the unnecessary functionality of renounceOwnership().

Consider overriding it and reverting whenever it is called so it is clear that it is not supported.

Q-4

Unnecessary constant in SuperstateOracle

Topic
Best practices
Status
Acknowledged
Quality Impact
Low

In the SuperstateOracle, the USTB_TOKEN_PROXY_ADDRESS immutable variable is set and never used.

Consider removing it unless it is necessary.

Q-5

MorphoLiquidationV1.liquidate() natspec is incorrect

Topic
Best practices
Status
Quality Impact
Low

In the MorphoLiquidationV1 contract, the natspec documentation for liquidate() is incorrect.

  1. It is missing param description for the morphoMarketId argument

  2. It contains a dev comment, which does not apply to this implementation since it doesn't use the callback feature.

    @dev The function uses callbacks, so the sender doesn't need to hold tokens to perform this operation
    

Consider updating natspec documentation for liquidate() to describe the current implementation properly.

Disclaimer

Macro makes no warranties, either express, implied, statutory, or otherwise, with respect to the services or deliverables provided in this report, and Macro specifically disclaims all implied warranties of merchantability, fitness for a particular purpose, noninfringement and those arising from a course of dealing, usage or trade with respect thereto, and all such warranties are hereby excluded to the fullest extent permitted by law.

Macro will not be liable for any lost profits, business, contracts, revenue, goodwill, production, anticipated savings, loss of data, or costs of procurement of substitute goods or services or for any claim or demand by any other party. In no event will Macro be liable for consequential, incidental, special, indirect, or exemplary damages arising out of this agreement or any work statement, however caused and (to the fullest extent permitted by law) under any theory of liability (including negligence), even if Macro has been advised of the possibility of such damages.

The scope of this report and review is limited to a review of only the code presented by the Superstate team and only the source code Macro notes as being within the scope of Macro’s review within this report. This report does not include an audit of the deployment scripts used to deploy the Solidity contracts in the repository corresponding to this audit. Specifically, for the avoidance of doubt, this report does not constitute investment advice, is not intended to be relied upon as investment advice, is not an endorsement of this project or team, and it is not a guarantee as to the absolute security of the project. In this report you may through hypertext or other computer links, gain access to websites operated by persons other than Macro. Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such websites’ owners. You agree that Macro is not responsible for the content or operation of such websites, and that Macro shall have no liability to your or any other person or entity for the use of third party websites. Macro assumes no responsibility for the use of third party software and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software.