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

Kwenta A-8

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 September 5, 2023 to September 12, 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
High 2 - - 2
Medium 3 - - 3
Low 2 - - 2
Code Quality 2 - - 2
Informational 1 1 - -
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)

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:

Contract SHA256
src/Engine.sol

ed0bb4f6450e4438cd5bb07ec8c9002f0ed08f305b0164c81838a1fe426a1f93

src/interfaces/IEngine.sol

d7f3d9ad980f82e798685b5db4b196460136e6a88d40881a1ad6d0555db929c2

src/interfaces/oracles/IPyth.sol

02d048300b1cad2ea631da3b56b8be503bbd2aac01dc5990347169f866712ade

src/interfaces/synthetix/IPerpsMarketProxy.sol

7b075bdec43b1d19375d8a66805f4ce8c0a33305f4400aeee46386736a0f3b3c

src/interfaces/synthetix/ISpotMarketProxy.sol

3b5d0d4a01f3bc79ba9c41b9320f57670070deaa8e6c42788dc34468cb010351

src/interfaces/tokens/IERC20.sol

64f58bf02597a2f2d941048e262d15e66533c8a6b5566c5a7af284fac94b7a69

src/interfaces/tokens/IERC721.sol

59b65f50d53769b69b8c1bf1d2945509dc3c08a3340d926b98cea2477bad70fb

src/libraries/ConditionalOrderHashLib.sol

6598331d6bfd9d18d23cba4fb0d8a28ff69b7f25830356f1f3f7401e0390a301

src/libraries/MathLib.sol

1f48be33935904a40e6264bfd692e64dfd73515db50a0584ebc821ba3b53b24b

src/libraries/SignatureCheckerLib.sol

5519e55482f973f974525a677f37941235fb150f38bca55ca4df905ba3a95a3a

src/utils/EIP712.sol

a1e8f3e05bd8021b5c195cc32da89c8d9dd08217f334c7f21186b600ddb81a06

src/utils/ERC721Receivable.sol

f447c9a709beaccc36e6dc2a04996bc6001abe43129d0d8e5a782623d5b643d4

src/utils/Multicallable.sol

b2b6fd0567980ee4ac90a96d152682b2ee3de6cc5e579f2c301c62ee1e3c0561

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

H-1

Conditional orders can be blocked

Topic
Griefing
Status
Impact
High
Likelihood
High

In Engine.sol’s execute() function takes in signed conditional orders and executes them if set conditions are satisfied, and if the nonce the order was signed with has yet to be used. However, the nonce used in the conditional order is not tied to anything, and a conditional order can execute with any nonce which can conflict with any other order that was signed with same nonce, preventing its execution.

This can be used maliciously, where someone can front-run a conditional order execution by signing a minimal order with the same nonce and executing the order before the other goes through. This is especially concerning in cases where conditional orders are setup to prevent position liquidation, as an attacker can prevent the order from executing, and setup a position to benefit from the liquidation if the account owner does not realize the order is unable to execute in time.

Remediations to Consider

Instead of mapping the executedOrders from a nonce to a bool, map it from accountId → nonce → bool. Since the signer of the order has to be the owner or admin of the account that is being executed on, the nonce cannot be griefed by any non permissioned source.

H-2

Delegates are granted too high permissions

Topic
Trust Model
Status
Impact
High
Likelihood
Medium

In Engine.sol, delegates setup by the owner of an account are allowed to execute orders on behalf of the owner of the account. However, the permission Engine.sol requires to execute these orders is the highest permission available via Synthetix, the _ADMIN_PERMISSION. The admin permission allows the delegate to do anything the owner of the account can do other than transfer the account, including withdrawing collateral from the account to themselves. Since the only thing Engine.sol allows delegates to do is commit orders and sign conditional orders, the permission required should be limited to that, so that users don't give too high permissions to delegates.

Remediations to Consider In isAccountDelegate() return use the PERPS_MARKET_PROXY.isAuthorised() function using the permission _PERPS_COMMIT_ASYNC_ORDER_PERMISSION which is a permission limited to committing orders for the account, while this also allows users with admin permissions to perform the task as well.

M-1

accountStats can be inaccurate

Topic
Data Consistency
Status
Impact
Medium
Likelihood
Medium

Whenever a order is committed to Synthetix either directly via commitOrder() or by a conditional order via execute(), _commitOrder() is called that updates the accountId’s accountStats by the _sizeDelta and the fees returned by committing the order to Synthetix.

function _commitOrder(
    uint128 _perpsMarketId,
    uint128 _accountId,
    int128 _sizeDelta,
    uint128 _settlementStrategyId,
    uint256 _acceptablePrice,
    bytes32 _trackingCode,
    address _referrer
) internal returns (IPerpsMarketProxy.Data memory retOrder, uint256 fees) {
    (retOrder, fees) = PERPS_MARKET_PROXY.commitOrder(
        IPerpsMarketProxy.OrderCommitmentRequest({
            marketId: _perpsMarketId,
            accountId: _accountId,
            sizeDelta: _sizeDelta,
            settlementStrategyId: _settlementStrategyId,
            acceptablePrice: _acceptablePrice,
            trackingCode: _trackingCode,
            referrer: _referrer
        })
    );

    _updateAccountStats(_accountId, fees.castU128(), _sizeDelta.abs128());
}

Reference: Engine.sol#L279-L297

However, orders do not get executed when they are committed, and pricing values are pulled off-chain, delaying the execution. When the order is attempted to be executed later, it can revert for multiple reasons. If the price is no longer a _acceptablePrice that is set by the user, or if the value of collateral the accountId holds is no longer within acceptable bounds, or even if the order does not settle within a settlement window. This means that an order is not guaranteed to execute after it is committed, but the accountStats are updated with the assumption that the order will execute. The fees returned when committing an order to Synthetix may also not be accurate, as they are calculated again when the the order is executed based on the price of the assets and state of the market.

If the accountStats are used to determine a users rewards, or there is any value tied to having high accountStats, there may be an incentive to commit orders via the engine that are unlikely to execute, potentially by setting the _acceptablePrice of the order to be just valid on commit, but could be outside the price range once the order attempts to execute as the price may change.

Remediations to Consider

Since there is no way to determine if an order committed via the Engine gets executed, it may make sense to keep track of orders off-chain, ideally emitting an event when an order is committed via the engine, and listen to Synthetix events for OrderSettled, OrderCommitted and OrderCanceled. Doing so can allow the accurate values fees and sizeDelta of executed orders to be determined.

M-2

verifyConditions() can cause infinite loop consuming gas

Topic
Griefing
Status
Impact
Medium
Likelihood
Medium

verifyConditions() takes in a ConditionalOrder’s array of conditions and executes a static call to itself with the payload defined by the condition bytes. This allows any external function in the contract to be called, with any payload. Since verifyConditions() is public, it can end up calling itself, with another ConditionalOrder's array of conditions, each of which can call verifyConditions() again, with more calls, eventually terminating or running out of gas. This can allow someone to grief order executors that don’t restrict gas consumption of conditional orders.

Remediations to Consider

Either

  • Limit the calls to only desired conditional functions
  • Ensure that all executors are aware of this and check the gas cost of the simulation before executing, or ensure only accepted condition calls are made
M-3

Users cannot cancel signed conditional orders

Topic
Protocol Design
Status
Impact
Medium
Likelihood
Low

Once a conditional order is signed, anyone allowed to execute the order that knows about it can execute it as long as the set conditions are met. However, there is the possibility where an account owner or delegate no longer wants a conditional order to execute. Currently there is no on-chain way to ensure that a signed order won’t execute in the future, which may cause unwanted orders to be committed, effecting the desired state or strategy of the account.

Remediations to Consider

Add a function that allows the owner or delegate of an account to cancel a previously signed order.

L-1

Invalid _CONDITIONAL_ORDER_TYPEHASH

Topic
Protocol Design
Status
Impact
Low
Likelihood
Low

ConditionalOrderHashLib.sol follows EIP712 and generates type hashes for the OrderDetails and ConditionalOrder structs. In the case of the _CONDITIONAL_ORDER_TYPEHASH it includes the struct info of ConditionalOrder, and includes the values of OrderDetails at the end, as defined in EIP712 since a ConditionalOrder it contains the OrderDetails struct as a parameter.

As defined in EIP712 “If the struct type references other struct types (and these in turn reference even more struct types), then the set of referenced struct types is collected, sorted by name and appended to the encoding. An example encoding is Transaction(Person from,Person to,Asset tx)Asset(address token,uint256 amount)Person(address wallet,string name).”

However, the reference to the OrderDetails struct type differs to its actual definition:

/// @notice pre-computed keccak256(OrderDetails struct)
bytes32 public constant _ORDER_DETAILS_TYPEHASH = keccak256(
    "OrderDetails(uint128 marketId,uint128 accountId,int128 sizeDelta,uint128 settlementStrategyId,uint256 acceptablePrice,bool isReduceOnly,bytes32 trackingCode,address referrer)"
);

/// @notice pre-computed keccak256(ConditionalOrder struct)
bytes32 public constant _CONDITIONAL_ORDER_TYPEHASH = keccak256(
    "ConditionalOrder(OrderDetails orderDetails,address signer,uint128 nonce,bool requireVerified,address trustedExecutor,bytes[] conditions)OrderDetails(uint128 marketId,uint128 accountId,int128 sizeDelta,uint128 settlementStrategyId,uint256 acceptablePrice)"
);

Reference: ConditionalOrderHashLib.sol#L10-L18

The _CONDITIONAL_ORDER_TYPEHASH is missing the isReduceOnly, trackingCode and referrer parameters.

Remediations to Consider

Add isReduceOnly, trackingCode and referrer parameters to the OrderDetails section of the _CONDITIONAL_ORDER_TYPEHASH to properly follow EIP712.

L-2

Static calls can consume all gas

Topic
Griefing
Status
Impact
Low
Likelihood
Low

In Engine.sol’s verifyConditions() function, a static call is made on all conditions, requiring each to return true.

(success, response) = address(this).staticcall(_co.conditions[i]);

if (!success || !abi.decode(response, (bool))) return false;

Reference: Engine.sol#L463-L465

Static calls ensure that there is no state change made in the call, however if there is a state change all gas provided to the call is consumed. By default static calls send 63/64 of the remaining gas, and if that is consumed then there is little gas remaining to execute the rest of the transaction, typically leading to the transaction running out of gas, consuming all gas provided.

Since a condition can make any provided static call to the engine, a call to createAccount() can be made, which will revert due to state change, consuming all gas provided. This allows a user to sign a conditional order with the intent of griefing a order executor.

Remediations to Consider

Consider any of the following remediations

  • Explicitly set the amount of gas to send into the static call, to reduce gas consumption of state change, ensuring that the gas sent in can execute all proper condition calls.
  • Simulate all calls off-chain and verify they execute without reverting
  • Limit the calls to the specific condition checking functions, rather than allowing calls function.
Q-1

Inaccurate comments

Topic
Code Quality
Status
Quality Impact
Low

In MathLib.sol’s abs128() there are comments referencing operations with a variable x however the code is operating on y.

/// shr(255, x):
/// shifts the number x to the right by 255 bits:
/// IF the number is negative, the leftmost bit (bit 255) will be 1
/// IF the number is positive,the leftmost bit (bit 255) will be 0

/// sub(0, shr(255, x)):
/// creates a mask of all 1s if x is negative
/// creates a mask of all 0s if x is positive
let mask := sub(0, shr(255, y))

/// If x is negative, this effectively negates the number
// if x is positive, it leaves the number unchanged, thereby computing the absolute value
z := xor(mask, add(mask, y))

Reference: MathLib.sol#L18-L30

Remediations to Consider

Replace references to x with y where applicable.

Q-2

ConditionalOrderHashLib not used with OrderDetails

Topic
Code Quality
Status
Quality Impact
Low

In Engine.sol ConditionalOrderHashLib is set to be used with the OrderDetails struct, but there are no functions in ConditionalOrderHashLib that are directly used with OrderDetails

using ConditionalOrderHashLib for OrderDetails;

Reference: Engine.sol#L25

Remediations to Consider

Remove this line as it is not used.

G-1

Use bits to represent nonces

Topic
Gas Optimizationcd content/collections/private
Status
Gas Savings
Medium

When a conditional order is executed its a mapping of nonce to bool is set to true. However, although a bool is only 1 bit of information it takes up a whole storage slot of 256 bits. If instead of writing to a bool, a bit is flipped from a uint256 or bytes32 value, where the bit position represents the nonce. Doing so allows 256 nonces to be used before writing to a new storage slot, which after the first write reduces gas costs on the subsequent 255 nonce writes, at the cost of additional operations required to read and write the specific bits. This will benefit users that use conditional orders multiple times, but adds additional gas cost for the first conditional order, assuming the nonces are mapped by accountId as mentioned in the solution to H-1

Remediations to Consider

Use bits to represent nonces rather than using a bool in order to save gas on most conditional order executions.

I-1

Conditional Orders may not execute, even if conditions are met

Topic
Informational
Status
Acknowledged
Impact
Informational

In order for a conditional order to be committed and then executed there are a number of requirements that need to be met.

  • The account must have sufficient collateral to handle the order.
  • The account must not have another order committed
  • The order’s set acceptablePrice needs to be met both on committing the order and when it gets executed, users should choose a value for this that is likely to execute based on the conditions set.
  • The order may not execute within Synthetix’s set settlement window.
  • There may be no-one that executes a conditional order.

For these reasons users of conditional orders should make sure they have enough collateral, set a reasonable acceptablePrice for the order, and have no active orders. They must also be aware that there is no guarantee it will be executed.

Response by Kwenta

Added documentation

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.