Synthetix Mintaka Release Smart Contract Audit

# 1. Introduction
iosiro was commissioned by [Synthetix]( to conduct a smart contract audit of their Mintaka Release, which included the following components:

* [SIP-279](
* [SIP-280](
* [SIP-281](
* [SIP-285](

Several auditors performed the audit from 17 October to 9 December 2022, consuming a total of 60 resource days.

This report is organized into the following sections.

* **[Section 2 - Executive summary:](#section-2)** A high-level description of the findings of the audit.
* **[Section 3 - Audit details:](#section-3)** A description of the scope and methodology of the audit.
* **[Section 4 - Design specification:](#section-4)** An outline of the intended functionality of the smart contracts.
* **[Section 5 - Detailed findings:](#section-5)** Detailed descriptions of the findings of the audit.

The information in this report should be used to understand the smart contracts' risk exposure better and as a guide to improving the security posture of the smart contracts by remediating the issues identified. The results of this audit reflect the in-scope source code reviewed at the time of the audit.

The purpose of this audit was to achieve the following:

* Identify potential security flaws.
* Ensure that the smart contracts function according to the documentation provided.

Assessing the off-chain functionality associated with the contracts, for example, backend web application code, was outside of the scope of this audit.

Due to the unregulated nature and ease of transfer of cryptocurrencies, operations that store or interact with these assets are considered high risk from cyber attacks. As such, the highest level of security should be observed when interacting with these assets. This requires a forward-thinking approach, which takes into account the new and experimental nature of blockchain technologies. Strategies that should be used to encourage secure code development include:

* Security should be integrated into the development lifecycle, and the level of perceived security should not be limited to a single code audit.
* Defensive programming should be employed to account for unforeseen circumstances.
* Current best practices should be followed where possible.

<a name="section-2"></a>
# 2. Executive summary

This report presents the findings of a smart contract audit performed by iosiro of Synthetix's Mintaka release.

[SIP-279]( introduced changes to make the funding rate more stable to allow for funding rate arbitrage. This change was used to provide better incentivizes to market participants to balance market exposure and ultimately reduce the risk exposure of SNX stakers. The improvement was achieved through several changes.
1. The introduction of a premium/discount amount applied to the price of a trade, scaled by the impact of the trade on the market skew. The price impact per trade is a more frequent and active model that incentivises market participants to keep the skew as small as possible.
2. The funding rate was stabilized by removing its dependence on asset price and making it scale using a velocity model, such that changes in the funding rate are slower and more predictable.
3. Finally, the SIP introduced the concept of a hybrid oracle for asset pricing, which is discussed further in SIP-281 and 285 below.

[SIP-280]( updated the architecture of the markets to be upgradeable. It uses a proxy contract to maintain a static address for each market. As such, market actions can only be performed through the proxy. The state for each market is stored in a separate state contract accessed directly by approved market logic contracts. This model requires any new logic deployments to be explicitly linked to the proxy and state contracts for each market by the owner when an update is deployed.

[SIP-281]( introduced the possibility for market orders to be executed after a specified delay. Previously, orders could only be executed at the next Chainlink round. This change made the PerpsV2 market compatible with different pricing oracles, such as Pyth, discussed further in SIP-285 below. The SIP also changed the method for calculating fees to charge on a trade that flips the market skew. The new approach will charge the lower fee for the part of the order that moves the skew toward 0 and the more expensive fee for the remaining part of the order past 0.

[SIP-285]( enabled markets to execute delayed orders using a Pyth price feed. These feeds offer better price resolution and faster updates than the previously used Chainlink. Pyth is an on-demand oracle; hence, the executor of the order is required to submit a price feed update when executing an order. Using Pyth price feeds allows for creating perpetual markets for additional assets beyond what Chainlink currently supports.

iosiro noted one medium-risk and one informational issue still open at the end of the audit. All other issues identified were suitably remediated by the team and verified by iosiro by the end of the audit. Overall, the code quality was found to be of a high standard.

<a name="section-3"></a>
# 3. Audit details

## 3.1 Scope

The source code considered in-scope for the assessment is described below. Code from all other files was considered to be out-of-scope. Out-of-scope code that interacts with in-scope code was assumed to function as intended and not introduce any functional or security vulnerabilities for the purposes of this audit.

### 3.1.1 Smart contracts

* **Project name:** Synthetix<br/>
* **Commits:** [8be56a3](, [4006fd4](, [48923a1](, [5d3bc28](<br/>
* **Files:** FuturesMarketManager.sol, MixinPerpsV2MarketSettings.sol, PerpsV2ExchangeRate.sol, PerpsV2Market.sol, PerpsV2MarketBase.sol, PerpsV2MarketData.sol, PerpsV2MarketDelayedOrders.sol, PerpsV2MarketDelayedOrdersBase.sol, PerpsV2MarketDelayedOrdersOffchain.sol, PerpsV2MarketProxyable.sol, PerpsV2MarketSettings.sol, PerpsV2MarketState.sol, PerpsV2MarketViews.sol, ProxyPerpsV2.sol, StateShared.sol

## 3.2  Methodology

The audit was conducted using a variety of techniques described below.

### 3.2.1 Code review

The source code was manually inspected to identify potential security flaws. Code review is a useful approach for detecting security flaws, discrepancies between the specification and implementation, design improvements, and high-risk areas of the system.

### 3.2.2 Dynamic analysis

The contracts were compiled, deployed, and tested in a test environment, both manually and through the test suite provided. Manual analysis was used to confirm that the code was functional and discover security issues that could be exploited. The coverage report of the provided tests as on the final day of the audit is given below.

| Files                                  | Tracked lines | Covered | Partial | Missed | Coverage % |
| FuturesMarketManager.sol               | 48            | 48      | 0       | 0      | 100.00%    |
| MixinPerpsV2MarketSettings.sol         | 27            | 27      | 0       | 0      | 100.00%    |
| PerpsV2ExchangeRate.sol                | 23            | 23      | 0       | 0      | 100.00%    |
| PerpsV2Market.sol                      | 18            | 18      | 0       | 0      | 100.00%    |
| PerpsV2MarketBase.sol                  | 69            | 69      | 0       | 0      | 100.00%    |
| PerpsV2MarketData.sol                  | 26            | 26      | 0       | 0      | 100.00%    |
| PerpsV2MarketDelayedOrders.sol         | 15            | 15      | 0       | 0      | 100.00%    |
| PerpsV2MarketDelayedOrdersBase.sol     | 13            | 11      | 0       | 2      | 84.62%     |
| PerpsV2MarketDelayedOrdersOffchain.sol | 18            | 18      | 0       | 0      | 100.00%    |
| PerpsV2MarketProxyable.sol             | 21            | 21      | 0       | 0      | 100.00%    |
| PerpsV2MarketSettings.sol              | 63            | 60      | 0       | 3      | 95.24%     |
| PerpsV2MarketState.sol                 | 25            | 25      | 0       | 0      | 100.00%    |
| PerpsV2MarketViews.sol                 | 40            | 39      | 0       | 1      | 97.50%     |
| ProxyPerpsV2.sol                       | 27            | 27      | 0       | 0      | 100.00%    |
| StateShared.sol                        | 10            | 10      | 0       | 0      | 100.00%    |

The test coverage was of a good standard. The code marked as not covered was not considered high-risk functionality.

### 3.2.3 Automated analysis

Tools were used to automatically detect the presence of several types of security vulnerabilities, including reentrancy, timestamp dependency bugs, and transaction-ordering dependency bugs. Static analysis results were reviewed manually and any false positives were removed. Any true positive results are included in this report.

Static analysis tools commonly used include Slither, Securify, and MythX. Tools such as the Remix IDE, compilation output, and linters could also be used to identify potential areas of concern.

## 3.3  Risk ratings

Each issue identified during the audit has been assigned a risk rating. The rating is determined based on the criteria outlined below.

* **High risk**: The issue could result in a loss of funds for the contract owner or system users.
* **Medium risk**: The issue resulted in the code specification being implemented incorrectly.
* **Low risk**: A best practice or design issue that could affect the security of the contract.
* **Informational**: A lapse in best practice or a suboptimal design pattern that has a minimal risk of affecting the security of the contract.
* **Closed**: The issue was identified during the audit and has since been satisfactorily addressed, removing the risk it posed.

<a name="section-4"></a>
# 4. Design specification

The following section outlines the intended functionality of the system at a high level. This specification is based on the implementation in the codebase. Any perceived points of conflict should be highlighted with the auditing team to determine the source of the discrepancy.

## 4.1 SIP-279

The specification of SIP-279 was based on commit hash [c6d6b51](

## 4.2 SIP-280

The specification of SIP-280 was based on commit hash [d1d0c5b](

## 4.3 SIP-281

The specification of SIP-281 was based on commit hash [4a66a5c](

## 4.4 SIP-285

The specification of SIP-285 was based on commit hash [79caf51](

<a name="section-5"></a>
# 5. Detailed findings

The following section details the findings of the audit.

## 5.1 High risk

No identified high-risk issues were open at the conclusion of the review.

## 5.2 Medium risk

### 5.2.1 Perps sUSD issuance cap
*[FuturesMarketManager.sol#L358](, [FuturesMarketManager.sol#L404](*

#### Description
Perps markets can issue new sUSD arbitrarily when a user withdraws their margin or a fee is paid. This is necessary as the withdrawable sUSD can exceed deposited sUSD, in which case sUSD needs to be issued and the debt allocated to Synthetix stakers. If an incorrect amount was ever issued, such as an invalid oracle price or an intentional exploit, there is no control in place to limit the issuance of sUSD. For example, in the identified reentrancy issue, it would have theoretically been possible to issue an infinite amount of sUSD. This would be catastrophic to the broader Synthetix ecosystem as a malicious actor could quickly exit sUSD through exchanges or bridges and leave the remaining debt on stakers, likely leading to insolvency across the system.

#### Remediation
As this functionality affects more than the perps system in isolation, it is advised that an issuance cap be implemented with the following considerations.
* The cap could be hourly, as this timeframe would likely have minimal impact on ordinary UX, but it is still sufficient time for Synthetix to react and pause the perps system.
 * It could be set to an amount very unlikely to be triggered during regular use, such as the size of the largest market.
 * If using a simple time-based mechanism, it would be possible to time the attack to drain at the end of one period and then again a few seconds later as the cap resets.
* An automated task, such as Tenderly alerts, could detect if the issuance cap is close to being reached or if irregular behavior is observed, such as abnormally high levels of withdrawals.

## 5.3 Low risk

No identified low-risk issues were open at the conclusion of the review.

## 5.4 Informational

### 5.4.1 Potential sig4 clashes when adding routes to a market proxy

#### Description
If there is a sig4 clash when adding a route to the `PerpsV2Proxy`, the initial route will be overwritten by the new route. This behavior is due to `addRoute()` defaulting to overwriting the information for a stored route.

#### Remediation
The `addRoute()` function should revert if attempting to overwrite an existing route. The proxy owner would then need to explicitly remove the old route to allow the new one to be set. At the very least, the JavaScript used to generate routes should consider this case.

### 5.4.2 Design comments

Actions to improve the functionality and readability of the codebase are outlined below.

#### `_confirmCanCancel()` period
The  `_confirmCanCancel()` function implementation for off-chain delayed orders uses twice the maximum age accepted for oracle updates. As configuring the value would affect both the cancellation period and maximum age affected, two values that are only loosely correlated, it is advised that a separate SCCP configurable variable be used. Doing so would allow for fine-tuning of the values independently and without requiring a redeployment.

#### Update
Synthetix acknowledged the issue and indicated that it might be implemented in the future.

#### Pyth confidence interval
Pyth suggests using the reported [confidence interval]( for conservative asset pricing (e.g. use `price - confidenceInterval` for entering short positions and use `price + confidenceInterval` for entering long positions). However, as pricing in perps is already based on market conditions, using the suggested pattern may interfere with the intended design.

However, an alternative way to use this the confidence interval would be to validate that it is within a specific range of the asset price when performing price updates. For example, a price update may be ignored if the confidence interval is too large (e.g. 3% of asset price), requiring the system to wait until the confidence interval improves.

This validation could improve existing checks by helping to detect certain types of off-chain black swan events, such as an exchange getting hacked or API bug, which might result in a provider temporarily reporting dramatically incorrect values. Without the check, the reported price could otherwise still validate to be within a valid range of the slower Chainlink price.

#### Update
Synthetix acknowledged the issue and indicated that it might be implemented in the future.

##  5.5 Closed

### 5.5.1 Reentrancy when updating Pyth price-feeds through `PerpsV2ExchangeRate` [high risk]

#### Description
The `PerpsV2ExchangeRate.updatePythPrice()` function was reentrant when refunding the `sender` address with any unused ETH. As the refund was calculated using `msg.value` and not a balance stored in the state, there was no risk of theft of ETH when the function was reentered. However, as the function was called during `PerpsV2MarketDelayedOrdersOffchain.executeOffchainDelayedOrder()`, before the order was deleted from the state, an attacker could reenter the delayed order execution function and repeatedly execute the same order. If the order's trade size was sufficiently small, it could be executed multiple times against the same margin without exceeding leverage limitations. A malicious user could receive the `keeperDeposit` on each execution, allowing the attacker to arbitrarily mint sUSD at the cost of gas.

#### Remediation
OpenZepplin's `ReentrancyGuard` should be used to prohibit reentering the function.

#### Update
This issue was resolved in [93950ce](

### 5.5.2 Slippage protection not enforced on short trades [medium risk]
*[PerpsV2MarketBase.sol#L602](, [PerpsV2MarketProxyable.sol#L102](*

#### Description
Users could set a slippage limit when creating, deleting, or modifying positions to ensure they received an acceptable price. The `PerpsV2MarketBase._maxSlippagePrice()` would be validated to be greater than the trade price in `PerpsV2MarketProxyable._assertPriceSlippage()`. When creating a long trade, a lower starting price is preferable, so it makes sense to set a maximum acceptable price, in which case this functionality works as intended. However, when creating a short position, the user would want to specify the minimum acceptable price, which would require the logic to be inversed.

#### Remediation
The slippage control should consider the direction of the trade (long or short) when calculating and asserting the slippage price limit.

The logic below demonstrates how the slippage control should calculate the correct slippage price depending on the direction of the trade:
if is_long:
  slippage_price = oracle_price * (1 + slippage_factor)
  slippage_price = oracle_price * (1 - slippage_factor)
The logic below demonstrates how the slippage price should be asserted against the trade price depending on the direction of the trade:
if is_long:
  revert when trade_price > slippage_price
  revert when trade_price < slippage_price

#### Update
This issue was resolved in [823da7b](

### 5.5.3 Liquidation premium not considered during trade [medium risk]
#### Description
The `_postTradeDetails()` function does not consider the liquidation premium when determining whether the trade would put the position in the liquidation range. Not considering this premium would allow a trader to intentionally or accidentally put their position into a range that could be liquidated.

#### Remediation
The liquidation check in `_postTradeDetails()` should be updated to consider the liquidation premium. The below is given as an example.
if (newMargin <= _liquidationMargin(newPos.size, params.price) + _liquidationPremium(newPos.size, params.price)) {
   return (newPos, 0, Status.CanLiquidate);

#### Update
This issue was resolved in [f1196d9](

### 5.5.4 ETH fee not forwarded to `PerpsV2ExchangeRate` when executing an off-chain delayed order [low risk]

#### Description
When the `PerpsV2ExchangeRate.updatePythPrice()` function is called from `PerpsV2MarketDelayedOrders._executeDelayedOrder()` the ETH amount in `msg.value` is not forwarded to the exchange rate contract. The feed update would revert without the necessary ETH fee, which would result in the order executions to fail.

#### Remediation
`PerpsV2MarketDelayedOrders._executeDelayedOrder()` should forward `msg.value` when calling `PerpsV2ExchangeRate.updatePythPrice()`.

#### Update
This issue was resolved in [93950ce](

### 5.5.5 Deprecated Pyth function used to get update fee [low risk]

#### Description
The Pyth function `getUpdateFee(uint)` is used to retrieve the fee required to update the price feeds using `updatePythPrice()`. This function is [deprecated]( and should not be used.

#### Remediation
The `getUpdateFee(bytes[])` function should be used when retrieving the fee to perform a Pyth feed update.

#### Update
This issue was resolved in [cac6b52](

### 5.5.6 Restrict `PerpsV2ExchangeRate` arbitrary call target [low risk]

#### Description
If `updatePythPrice()` is called directly, the caller can set an arbitrary target address to be called from the PerpsV2ExchangeRate contract during the ETH refund. This could be used to make calls within the Synthetix ecosystem from the context of a Synthetix contract. Since calldata is not passed during the refund call to the target, only the fallback function could be called. Furthermore, no exploitable instances were identified.

#### Remediation
As a defense-in-depth control, the `updatePythPrice()` function could check whether it was called from a DelayedOrder contract. If not, the function call should set the target address to `msg.sender` instead of the caller-provided address.

#### Update
This issue was resolved in [b47b947](

### 5.5.7 Proxy should fail safe [low risk]

#### Description
The proxy owner can create routes configured with `isView == True`, in which case the `messageSender` value is not updated when the function route is called. If a route is incorrectly set for a function that accesses `messageSender`, the function would be called in the context of the previous `messageSender`. This issue could be introduced whenever route-related changes are made.

#### Remediation
The value for `messageSender` should be updated for every call to the proxy, regardless of whether `isView` is true. As a further improvement, the proxy call should revert if the proxy does not have a route explicitly set for the call. Doing so would prohibit accessing markets through any unintended routes.

#### Update
This issue was resolved as of [7542138](

Secure your system.
Request a service
Start Now