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

Kwenta A-10

Security Audit

December 6, 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 November 20, 2023 to November 22, 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 1 - - 1
Code Quality 1 - - 1
Informational 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)

Entities

Trust Model

Accepted Risks

Source Code

The following source code was reviewed during the audit:

Specifically, we audited the following contracts within this repository:

Source Code SHA256
src/Engine.sol

a366633aef8723cc5d29751155b61d31abbad1a7bf45a2c1325e3f8d5464d561

src/interfaces/IEngine.sol

97c6c9699361566d9e1674afca93c25a8cd169b2e4f2e588094efbcc8928b5e9

src/libraries/ConditionalOrderHashLib.sol

93db551010ae28d88eef34edf7722e381e6c32c696346a312259d2037938b930

src/libraries/SignatureCheckerLib.sol

e0f0f2c5dbb73ece7cc7eb634040b75a5c20863afe0b9b103bedf745f5827829

src/utils/EIP712.sol

b8f38b8dde803484e8d424c8a4b823abe65fab5acf7b2d394f54e9b9232225ea

src/utils/EIP7412.sol

bd905a2bfa4aa3b497423b484fbeafc17b56b2db1ca483f0eb4a3735e635c47e

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

fulfillOracleQuery does not send value to update the oracle

Topic
Protocol Design
Status
Impact
Medium
Likelihood
Low

Engine.sol inherits EIP7412, which allows for on-demand, off-chain data retrieval, allowing a caller to provide pricing data to update an oracle using an off-chain verified source in order to deal with pricing as required.

function fulfillOracleQuery(
    address EIP7412Implementer,
    bytes calldata signedOffchainData
) external payable {
    IERC7412(EIP7412Implementer).fulfillOracleQuery(signedOffchainData);
}

Reference: EIP7412.sol#L14-L22

However, EIP7412 implementations can expect a native token fee to be paid with the call to fulfillOracleQuery(), and would otherwise revert with error FeeRequired(**uint** amount) if the required fee isn’t provided with the call.

Since EIP7412.sol’s fulfillOracleQuery() is payable but does not pass on the calls msg.value, it would not be able to call any EIP7412 implementation that expects a fee.

Remediations to Consider

Send msg.value along with the call to EIP7412Implementer:fulfillOracleQuery().

L-1

Can deposit ETH to non-existent account

Topic
Input Validation
Status
Impact
Medium
Likelihood
Low

In Engine.sol’s depositEth() function, it takes an _accountId and updates the deposited balance associated with the account with the value sent into the call. This deposited ETH is used to pay for the execution of conditional orders. There is, however, no check to ensure the _accountId passed in exists or is owned by the sender, which could potentially lead to balances sent to the wrong _accountId. This could lead to the ETH sent in being taken by someone that creates an account with that id, since _accountId’s that are greater than or equal to type(uint128).max/2 anyone can create an account with that id and withdraw the ETH accidentally deposited to that account.

function createAccount(uint128 requestedAccountId) external override {
    FeatureFlag.ensureAccessToFeature(_CREATE_ACCOUNT_FEATURE_FLAG);

    if (requestedAccountId >= type(uint128).max / 2) {
        revert InvalidAccountId(requestedAccountId);
    }

    IAccountTokenModule accountTokenModule = IAccountTokenModule(getAccountTokenAddress());
    accountTokenModule.safeMint(ERC2771Context._msgSender(), requestedAccountId, "");

    Account.create(requestedAccountId, ERC2771Context._msgSender());

    emit AccountCreated(requestedAccountId, ERC2771Context._msgSender());
}

Reference: AccountModule.sol#L57-L70

Remediations to Consider

Ensure an account exists before depositing ETH for that account. This prevent ETH being accidentally being lost or stolen in case of a mistake. Also consider limiting deposits to owners or permissioned users of the account to further ensure the ETH deposited is going to the correct account.

Q-1

Unnecessary use of payable

Topic
Code Quality
Status
Quality Impact
Low

In Engine.sol’s withdrawEth() and _withdrawEth() the caller address is cast as payable.

address payable caller = payable(_msgSender());

Reference: Engine.sol#L173

function _withdrawEth(
    address payable _caller,
    uint128 _accountId,
    uint256 _amount
) internal {
    if (_amount > ethBalances[_accountId]) revert InsufficientEthBalance();

    // decrement the ETH balance of the account prior to transferring ETH to the caller
    ethBalances[_accountId] -= _amount;

    (bool sent,) = _caller.call{value: _amount}("");

    if (!sent) revert EthTransferFailed();
}

Reference: Engine.sol#L186-L199

However, the transfer of native tokens uses a low level call rather than the functions casting an address to payable provides.

Remediations to Consider

Don’t cast the address as payable as it is not required.

I-1

The maxExecutorFee fee will likely be consumed when not using a trusted executor

Topic
Informational
Impact
Informational

In Engine.sol’s execute() function, the caller can set the _fee they would like to receive for executing the conditional order. This set _fee is only limited by the users maxExecutorFee that was signed with the conditional order, when verifying if the order can execute.

// verify fee does not exceed the max fee set by the conditional order
if (_fee > _co.maxExecutorFee) return false;

Reference: Engine.sol#L527-L528

This means that as long as conditions to execute the order are met, the fee paid to the executor can, and will likely, be set to equal the maxExecutorFee. In the case where the order requires a trustedExecutor, then there may be logic setup to determine a fair _fee to charge, but that depends on the trustedExecutor set.

This means that users may end up spending more fees than the fair execution cost when a conditional order is executed. To help remedy this, users should consider using a trusted executor that will charge a fair fee, rather than allowing anyone to execute the order and risk being charged the max amount.

Response by Kwenta

This is understood and is an acceptable trade-off for more fee accuracy when the executor is trusted: No change

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.