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

Kwenta A-7

Security Audit

September 19, 2023

Version 1.0.0

Presented by 0xMacro

Table of Contents

Introduction

This document includes the results of the security audit for Kwenta's smart contract code as found in the section titled ‘Source Code’. The security audit was performed by the Macro security team from August 15, 2023 to August 28, 2023.

The purpose of this audit is to review the source code of certain Kwenta 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 1 - - 1
Low 3 - 1 2
Code Quality 6 - - 6
Gas Optimization 1 - - 1

Kwenta was quick to respond to these issues.

Specification

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

Trust Model, Assumptions, and Accepted Risks (TMAAR)

There are a couple of changes related to trust assumption being introduced in V2 contracts that have not been present in V1:

  1. Upgradability:

    StakingRewardsV2, RewardEscrowV2, and EscrowMigrator are now upgradable using the UUPS proxy.

  2. Pausability:

    • For StakingRewardsV2, unstake and unstakeEscrow can now be paused by the owner (in addition to stake and stakeEscrow which were already pausable in V1)
    • For RewardEscrowV2, depositing escrowed KWENTA (via importEscrowEntry, createEscrowEntry, appendVestingEntry), vesting (via vest), and transferring escrowed KWENTA can be paused by the owner
    • For EscrowMigrator, registering and migrating entries can be paused by the owner.
  3. Cooldown period:

    Cooldown period was added to lock staked amount for a meaningful amount of time (default: 2 weeks) to discourage disruptive short term action (such as buying of votes).

In Addition, users migrating their KWENTA from V1 to V2 contracts need to be aware that there is a potential footgun where users need to overpay for migration. According to the Kwenta team, users are encouraged to follow the migration process provided on the Kwenta website to avoid loosing funds.

Source Code

The following source code was reviewed during the audit:

Specifically, we audited the following contracts within this repository:

Contract SHA256
EarlyVestFeeDistributor.sol

39dca853d1bbbb779d742f77a73a674494d50f4e98130499c166e63bf3ee71fd

EscrowMigrator.sol

a10d95561d4316c49e09205c423f61bdc6e92df65c3303353705ca7656ed8a23

RewardEscrowV2.sol

6f3a72a8f11951c9fadee448baa3e37e2bfec1265ea3058df3b12cd653cb9197

StakingRewardsV2.sol

e7b6634fe1ac9365397c0c9c23bbbb9e6933dbf3e8c76993546f4b12406e7fd6

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

Early vest fees can get locked in Migrator contract

Topic
Locked Funds
Status
Impact
Medium
Likelihood
High

Reference: RewardEscrowV2.sol#L405, RewardEscrowV2.sol#L410

Once migration starts, treasuryDAO address in RewardEscrow.sol is set to the address of the EscrowMigrator contract, thus transferring all early vesting fees to the migrator. This is required for users who want to migrate their escrowed KWENTAs to the V2 contracts.

However, if a user has no intention to migrate, but only wants to vest the escrowed KWENTAs (without registering any entries on the migrator), any vesting fees will be transferred to the migrator contract where there is no possibilities to withdraw those KWENTAs and give it back to the treasuryDAO.

Remediations to Consider

Consider adding a function to EscrowMigrator.sol that allows to withdraw leftover KWENTAs that haven't been registered.

Note: The Kwenta team was already aware of this issue and had considered the plan of upgrading and sweeping the contract at a later date. After the recommendation from the Macro team, Kwenta decided to fix the issue preemptively.

L-1

Missing zero address checks for staking contracts

Topic
Validation
Status
Impact
Medium
Likelihood
Low

Reference: EscrowMigrator.sol#L92-L93

EscrowMigrator.sol checks for zero address in the constructor for the parameters _rewardEscrowV1 and _rewardEscrowV2, but is missing the zero address check for the staking parameters:

  • _stakingRewardsV1
  • _stakingRewardsV2

Remediation to Consider

Consider adding the missing zero address checks for above parameters.

L-2

getVestingQuantity doesn’t consider duplicates

Topic
Accounting
Status
Wont Do
Impact
Medium
Likelihood
Low

Reference: RewardEscrowV2.sol#L296

In RewardEscrowV2, getVestingQuantity doesn’t work with duplicate entryIDs. Off-chain components and other contracts can call this function and might unintentionally pass duplicate entryIDs into the _entryIDs array. As getVestingQuantity double counts duplicate entries, a caller can make false assumption based on the wrong total and totalFee values returned.

Remediation to Consider

Consider handling duplicate entryIDs appropriately.

Response by Kwenta

Decided it is not worth the gas costs to check for duplicates - hence we are pushing the responsibility to the calling contract not to pass in duplicate values.

L-3

balanceAtTime, escrowedbalanceAtTime, and totalSupplyAtTime can return different values for not-finalized block.

Topic
Accounting
Status
Impact
Low
Likelihood
Medium

Reference: StakingRewardsV2.sol#L509, StakingRewardsV2.sol#L519, StakingRewardsV2.sol#L529

In StakingRewards.sol, the function balanceAtTime, escrowedbalanceAtTime, and totalSupplyAtTime can be used to retrieve the balance at a certain time in the past.

However, when those functions are called with a timestamp that equals the current block timestamp, then the functions might return inaccurate values as further transactions changing the balances can still occur within the same block.

Remediation to Consider

Consider reverting with an appropriate error if a timestamp is passed that equals block.timestamp. If this is a scenario that should be supported, consider documenting it appropriately to prevent misinformation.

Response by Kwenta

This is intended behaviour but we have added documentation to clarify it as suggested (rather than the reverting option - as this requires callers to implement extra logic, rather than just understanding the implications)

Q-1

Use of override is not required

Topic
Best Practices
Quality Impact
Low

Since Solidity 0.8.8, when implementing an interface, those functions don't require the override keyword anymore. In fact, this is misleading, as the function don't actual override any parent functions.

Consider removing the override keyword from functions that only implement the function definition from the derived interface.

Q-2

Inaccurate comment

Topic
Specification
Status
Quality Impact
Low
  • In EscrowMigrator.sol#L51, the comment says:

    /// @notice Contract for RewardEscrowV1
    

    But it should be RewardEscrowV2 instead.

  • In RewardEscrowV2.sol#L64, the comment says:

    /// @notice Contract for StakingRewardsV2
    IEscrowMigrator public escrowMigrator;
    

    But it should be EscrowMigrator instead of StakingRewardsV2.

Q-3

Inconsistent behavior between getVestingSchedules and getAccountVestingEntryIDs

Topic
Protocol Design
Status
Quality Impact
Medium

In RewardEscrowV2.sol, getVestingSchedules reverts with InvalidIndex when endIndex < index, while getAccountVestingEntryIDs returns an empty array in this case.

Consider implementing consistent behavior across those two functions.

Q-4

Import of IERC20.sol

Topic
Best Practices
Status
Quality Impact
Low

In StakingRewardsV2.sol, IERC20 is imported from SafeERC20.sol:

import {IERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

However, SafeERC20 is not used anymore in V2 and thus it is preferred to directly import from IERC20.sol interface:

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
Q-5

Missing natspec param description in constructors

Topic
Specification
Status
Quality Impact
Low

In StakingRewardsV2.sol, RewardEscrowV2.sol, and EscrowMigrator.sol, the constructor arguments are missing natspec param descriptions. Consider adding proper natspec param descriptions for the constructor arguments.

Q-6

escrowedbalanceAtTime incorrectly spelled according to naming convention

Topic
Best Practices
Status
Quality Impact
Low

In StakingRewardsV2.sol, functions and state variables use the lowerCamelCase naming convention. However, this is not the case for the newly introduced function escrowedbalanceAtTime, which uses a lower b for balance (as opposed to e.g. escrowedBalanceOf).

Consider renaming the function to escrowed**B**alanceAtTime to follow the naming convention.

G-1

Tracking block number in Checkpoint struct is not necessarily needed

Topic
Gas Optimizations
Status
Gas Savings
Medium

In StakingRewardsV2.sol, the following Checkpoint struct is used:

struct Checkpoint {
        // The timestamp when the value was generated
        uint256 ts;
        // The block number when the value was generated
        uint256 blk;
        // The value of the checkpoint
        uint256 value;
    }

In its current state, Checkpoint.blk is not required anywhere in the code and checkpointing entirely relies on the timestamp Checkpoint.ts.

Consider removing blk from Checkpoint struct to save gas.

Response by Kwenta

We want to store the block number because incase we need it in the future. However to make this more agreeable we have used storage packing to fit the whole Checkpoint struct into a single slot so that it doesn’t make much difference anyway.

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