Security Audit
September 19, 2023
Version 1.0.0
Presented by 0xMacro
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.
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.
Our understanding of the specification was based on the following sources:
The following source code was reviewed during the audit:
99f3dc5ab8492a12af8dce05f9828c639008eefb
Specifically, we audited the following contracts within this repository:
Source Code | SHA256 |
---|---|
src/Engine.sol |
|
src/interfaces/IEngine.sol |
|
src/interfaces/oracles/IPyth.sol |
|
src/interfaces/synthetix/IPerpsMarketProxy.sol |
|
src/interfaces/synthetix/ISpotMarketProxy.sol |
|
src/interfaces/tokens/IERC20.sol |
|
src/interfaces/tokens/IERC721.sol |
|
src/libraries/ConditionalOrderHashLib.sol |
|
src/libraries/MathLib.sol |
|
src/libraries/SignatureCheckerLib.sol |
|
src/utils/EIP712.sol |
|
src/utils/ERC721Receivable.sol |
|
src/utils/Multicallable.sol |
|
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.
Click on an issue to jump to it, or scroll down to see them all.
accountStats
can be inaccurate
verifyConditions()
can cause infinite loop consuming gas
_CONDITIONAL_ORDER_TYPEHASH
ConditionalOrderHashLib
not used with OrderDetails
We quantify issues in three parts:
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. |
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.
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.
accountStats
can be inaccurate
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.
verifyConditions()
can cause infinite loop consuming gas
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
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.
_CONDITIONAL_ORDER_TYPEHASH
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.
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
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.
ConditionalOrderHashLib
not used with OrderDetails
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.
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.
In order for a conditional order to be committed and then executed there are a number of requirements that need to be met.
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.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.
Added documentation
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.