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

Kodiak A-1

Security Audit

April 24th, 2024

Version 1.0.0

Presented by 0xMacro

Table of Contents

Introduction

This document includes the results of the security audit for Kodiak-1's smart contract code as found in the section titled ‘Source Code’. The security audit performed by the Macro security team lasted 8 audit days, from March 18th till April 4th, 2024.

The purpose of this audit is to review the source code of certain Kodiak-1 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 2 - - 2
Low 2 - 1 1
Code Quality 5 - 2 3
Informational 1 - - -

Kodiak-1 was quick to respond to these issues.

Specification

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

Note: Since Kodiak project incorporates forks of several different projects, within this audit we reviewed only the code changes from the provided reference commits of individual forked projects. The assumption is that these projects have been audited previously.

For kodiak-core repository base contract references are the following:

Contract Source
UniswapV3Pool c5ccf4d (Uniswap) and ffa4fb2 (Pancake)
UniswapV3Factory 4024732
UniswapV2Pair 1136544
UniswapV2Factory 1136544
UniswapV2ERC20 55ae251
KodiakVaultV1 d2d879e
KodiakFactoryV1 d2d879e
CommunalFarm 58970f5
KodiakToken
XKodiakToken xGRAIL
TokenRewards DividendsV2

For kodiak-periphery repository base contract references are the following:

Contract Source
NonfungiblePositionManager a0e0e58
SwapRouter eb0852f
NonfungibleTokenPositionDescriptor de4e437
UniswapV2Router02 6961711
UniswapV2Router01 87edfdc
SwapRouter02 a56e970
V2SwapRouter 9dc4a9c
V3SwapRouter 9dc4a9c
KodiakV1RouterStaking 28f3685

Source Code

The following source code was reviewed during the audit:

Specifically, we audited the following contract within kodiak-core repository:

Source Code SHA256
src/pools/v3-core/UniswapV3Factory.sol

a23585a3c78d540a45f968d5d418b388e7e77303dcd60732ef84a1d05baf2cdc

src/pools/v3-core/UniswapV3Pool.sol

f564cac03ed70c35ff11e5904db7035e82839e470c10f6f5629373bd0cddf04d

src/pools/v2-core/UniswapV2ERC20.sol

a95c02584edfb5b7299efc7fd8c5d90b66735bc2987f8d5caeb4521a3782eed7

src/pools/v2-core/UniswapV2Factory.sol

c57ae4df1da2d16b8a35b4588ac56e62e572a321712a33c05ac8313cec1ec222

src/pools/v2-core/UniswapV2Pair.sol

196bafde45f80f2ddecb0183371a074276105e72337736f690c10fb046627160

src/vaults/vault-v1-core/KodiakFactoryV1.sol

e2093d67caa300cc0032ea26e865be4ec9949a4ed13ef48d427170c9c22d72e8

src/vaults/vault-v1-core/KodiakVaultV1.sol

a6132d817f2913e9a4e9e8ef7f2689558ad506db49934ea9821d62e8cf3734e0

src/tokens/CommunalFarm.sol

d2bde43cb759998ba240be8875207bf60d836a78582cfe62b9742f4f839f8589

src/tokens/KDK.sol

aa7b51df30687a4ec99e1461ca10189b1d9e09bc7aae153947fbb027e7116cef

src/tokens/TokenRewards.sol

c396c0726dfc5cb6c32b8948b69aec67c2da6e1f30ec721fe71fa8cdb0dfc0f2

src/tokens/xKDK.sol

eb29d3a74ccdddd9207f6963e1c2a58e5c604722e877c7bd27cd56c30a0d9691

We also audited the following contract within kodiak-periphery repository:

Source Code SHA256
src/pools/v3-periphery/NonfungiblePositionManager.sol

6f5c59a2f3e6ec1390ea2fc82db2581fecc9a34e409be136731c24cab15d4631

src/pools/v3-periphery/NonfungibleTokenPositionDescriptor.sol

ca8d2c872bf5f3ab63217fb663215335f91f6f3dadea91439883cf6d20f54511

src/pools/v3-periphery/SwapRouter.sol

c627a74eea2ce2a0065d43af2e87371c54ca4955d3a228e17988a1cd932882f2

src/pools/v2-periphery/UniswapV2Router01.sol

452643f17ec1c07c598497bc0c460f3923001b0a847862deb05e526c3dc6cc9e

src/pools/v2-periphery/UniswapV2Router02.sol

a5a2135eb2561f2cf9d5e4513a333d350bfec67f45f2bfa1acf62bcf8ce3e239

src/pools/swap-router-contracts/SwapRouter02.sol

7dbf088a33df7d6973ff2f813da8157af2e576058c3114e7b7ceaab263c420b8

src/pools/swap-router-contracts/V2SwapRouter.sol

c76ee175e9d2c57689fa682bfbff8f184125807888830263250745014174b125

src/pools/swap-router-contracts/V3SwapRouter.sol

faa8711c705238e7c182e75aa7c311f6dd0d35e1f5fba8437ede6a3d512518a9

src/vaults/vault-v1-periphery/KodiakV1RouterStaking.sol

a4c820a2aff86d381c3d137bf793c737b43cf65d817a4bbb7e0205756b1e54cd

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

Missing guard in withdrawLockedMultiple() and withdrawLockedAll() functions

Topic
Spec breaking
Status
Impact
Medium
Likelihood
Medium

In the CommunalFarm contract, withdrawLockedMultiple() and withdrawLockedAll() allow a caller to withdraw earned rewards and previously provided stakes. On the other hand, withdrawLocked() and emergencyWithdraw(), functions with similar capabilities, have an additional guard that checks if withdrawalsPaused is not set.

Since withdrawalsPaused guard in withdrawLocked() can be circumvented with calls to withdrawLockedMultiple() and withdrawLockedAll() its purpose is undermined.

Remediations to Consider

  • Add withdrawalsPaused guard to withdrawLockedMultiple() and withdrawLockedAll(), or
  • Remove withdrawalsPaused guard from all functions.
M-2

Incorrect implementation of setStakingTokenCap validation

Topic
Spec breaking
Status
Impact
High
Likelihood
Low

In the CommunalFarm contract, input validation references stakingTokenCap instead of input argument _stakingTokenCap. As a result, if setStakingTokenCap() is called with 0 by mistake update will succeed. However, processing any further staking requests or changing stakingTokenCap will not be possible anymore.

function setStakingTokenCap(uint256 _stakingTokenCap) external onlyOwner {
    require(stakingTokenCap > 0, "Must be greater than 0");
    stakingTokenCap = _stakingTokenCap;
    emit StakingTokenCapUpdated(_stakingTokenCap);
}

Remediations to Consider

  • Update input validation to reference function argument _stakingTokenCap instead of the current state configuration variable.
L-1

Multiple locked stakes with the same kek_id

Topic
Spec breaking
Status
Wont Do
Impact
Low
Likelihood
Low

In the CommunalFarm contract, the LockedStake structure contains information about specific locked stake positions. The identifier of a specific position is kek_id, which is generated in the following way.

bytes32 kek_id = keccak256(
    abi.encodePacked(
        staker_address,
        start_timestamp,
        liquidity,
        _locked_liquidity[staker_address]
    )
);

However, with a specific set of actions multiple locked stake positions of the same staker may end up having the same kek_id value.

Consider scenario:

  • Staker already has one locked stake position A of size X
    • at this point _locked_liquidity[staker_address] is X which is one of inputs for kek_id in next step
  • At the time t the staker stakes at position B of the same size X
    • at this point _locked_liquidity[staker_address] is 2X
  • At the same time t staker withdraws position A of size X
    • at this point _locked_liquidity[staker_address] is again X
  • At the time t, the staker stakes at position C of the same size X
    • both positions B and C end up having the same kek_id

While having multiple staked positions with the same kek_id is not in line with the specification, the impact is limited to potential effects on off-chain monitoring and tracking tools, which may not expect that when locked stake position with specific kek_id is closed, others with the same kek_id may remain active.

Remediations to Consider

  • Add validation to prevent creating locked stake positions for the same staker with the same kek_id
Response by Kodiak-1

Acceptable risk, since specific scenario is a rare corner case.

L-2

Missing validation for duplicate token reward entries

Topic
Input validation
Status
Impact
Low
Likelihood
Low

In the CommunalFarm contract, reward token configuration can be added on contract deployment and at a later point through addNewRewardToken(), which is accessible to the contract owner.

However, if the same reward token is added multiple times intentionally or by mistake, it will corrupt related storage variables, and rewardTokenAddrToIdx[_rewardToken] will be overwritten. As a result, it would not be possible to update the reward rate for the previous token entry only for the last one.

function setRewardRate(address reward_token_address, uint256 new_rate, bool sync_too) external onlyTknMgrs(reward_token_address) {
    rewardRates[rewardTokenAddrToIdx[reward_token_address]] = new_rate;

    if (sync_too){
        sync();
    }
}

Remediations to Consider

  • Add validation to check if the reward token has already been added, both in the constructor and addNewRewardToken() function.
Q-1

Renamed external function

Topic
Use case
Status
Quality Impact
Low

In the TokenRewards contract, the updateDividendsInfo() function from the original contract was renamed to updateRewards(), which may be unexpected for clients who expect the new function to be named updateRewardsInfo().

Consider renaming updateRewards() to updateRewardsInfo()

Q-2

Unnecessary argument in withdrawLockedAll()

Topic
Use cases
Status
Quality Impact
Low

In the CommunalFarm contract, withdrawLockedAll() accepts a single argument user, whose value must always be equal to the msg.sender for successful operation processing.

function withdrawLockedAll(address user) nonReentrant public {
    _getReward(msg.sender, msg.sender);
    LockedStake[] memory locks = lockedStakes[user];
    for(uint256 i = 0; i < locks.length; i++) {
        if(locks[i].liquidity > 0 && block.timestamp >= locks[i].ending_timestamp){
            _withdrawLocked(msg.sender, msg.sender, locks[i].kek_id, false);
        }
    }
}

Consider removing the argument and using msg.sender everywhere within the function implementation to make code intention clearer.

Q-3

Unused import and missing inherit

Topic
Use cases
Status
Wont Do
Quality Impact
Low

In the pools/v2-core/UniswapV2Pair contract, IUniswapV2Pair import is present. However, the UniswapV2Pair contract doesn’t inherit from it, nor is it used anywhere else.

Consider using the imported interface or removing the import.

Q-4

Unnecessary use of SafeMath

Topic
Unnecessary code
Status
Wont Do
Quality Impact
Low

In contracts xKDK.sol and TokenRewards.sol, implementation relies on Solidity versions 0.8+ which have built-in overflow checks for Math operations. As a result, SafeMath library usage and corresponding operations from the SafeMath library are unnecessary. However, the current implementation uses it, which increases gas costs for regular operations.

Consider removing the SafeMath library and updating implementation to rely on standard Math operations with built-in overflow/underflow checks.

Q-5

Incorrect Natspec comments

Topic
Documentation
Status
Quality Impact
Low
  1. Incorrect inline comment in CommunalFarm.sol
uint256 public lock_time_min = 0; // 1 * 86400  (1 day)
  1. Incorrect renaming updates in TokenRewards.sol.
    • IxKDKTokenUsage strings in natspec comments should be replaced with the correct interface name IXKdkTokenUsage (2x instances in natspec comments)
  2. Potentially incorrect string in KodiakFactoryV1.
    • In the _preDeploy() function, the string used to initialize the LP token name of a new Vault is Kodiak Island V1
I-1

Ownable contains extra functionality

Topic
Use cases
Impact
Informational

In the CommunalFarm contract, owned.sol was replaced with Ownable openzeppelin library implementation.

An ownable library adds extra functionality for renouncing ownership, which may or may not be desired depending on the expected use cases.

Consider adding renounceOwnership override with revert if called, in case this functionality is not meant to be supported.

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 Kodiak-1 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.