Synthetix Mintaka Release Smart Contract Audit

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

* [SIP-279](https://sips.synthetix.io/sips/sip-279)
* [SIP-280](https://sips.synthetix.io/sips/sip-280)
* [SIP-281](https://sips.synthetix.io/sips/sip-281)
* [SIP-285](https://sips.synthetix.io/sips/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](https://sips.synthetix.io/sips/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](https://sips.synthetix.io/sips/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](https://sips.synthetix.io/sips/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](https://sips.synthetix.io/sips/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](https://github.com/Synthetixio/synthetix/commit/8be56a319ed4cdd06eb7944c333eff7fb6ad0cfe), [4006fd4](https://github.com/Synthetixio/synthetix/commit/4006fd44b34eb832bf414bc19a3317250ea7c3bd), [48923a1](https://github.com/Synthetixio/synthetix/commit/48923a1a5cd6d3561f7344d6ac4886be97af5a05), [5d3bc28](https://github.com/Synthetixio/synthetix/commit/5d3bc2849ca52fbfc2d087b918307fa9fcd56f9c)<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](https://github.com/Synthetixio/SIPs/blob/c6d6b510a31ec0b0273bd6bd19b04262a01afb48/content/sips/sip-279.md).

## 4.2 SIP-280

The specification of SIP-280 was based on commit hash [d1d0c5b](https://github.com/Synthetixio/SIPs/blob/d1d0c5b93305c0aef058e070f2c9b5ee2396e837/content/sips/sip-280.md).

## 4.3 SIP-281

The specification of SIP-281 was based on commit hash [4a66a5c](https://github.com/Synthetixio/SIPs/blob/4a66a5c339dc0ff479626cd81f4213903c9207b9/content/sips/sip-281.md).

## 4.4 SIP-285

The specification of SIP-285 was based on commit hash [79caf51](https://github.com/Synthetixio/SIPs/blob/79caf514351452459d28b27a1e83e81420f57312/content/sips/sip-285.md).

<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](https://github.com/Synthetixio/synthetix/blob/8be56a319ed4cdd06eb7944c333eff7fb6ad0cfe/contracts/FuturesMarketManager.sol#L358), [FuturesMarketManager.sol#L404](https://github.com/Synthetixio/synthetix/blob/8be56a319ed4cdd06eb7944c333eff7fb6ad0cfe/contracts/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
*[ProxyPerpsV2.sol#L76](https://github.com/Synthetixio/synthetix/blob/8be56a319ed4cdd06eb7944c333eff7fb6ad0cfe/contracts/ProxyPerpsV2.sol#L76)*

#### 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](https://docs.pyth.network/consume-data/best-practices#confidence-intervals) 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]
*[PerpsV2ExchangeRate.sol#L55](https://github.com/Synthetixio/synthetix/blob/0cb70e5a7cc182f510e64dbe9a84b7070de2304d/contracts/PerpsV2ExchangeRate.sol#L55)*

#### 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](https://github.com/Synthetixio/synthetix/pull/1893/commits/93950ce2f137c384792a72737cee4a266fdef093).

### 5.5.2 Slippage protection not enforced on short trades [medium risk]
*[PerpsV2MarketBase.sol#L602](https://github.com/Synthetixio/synthetix/blob/f59f3c49aa916448d0ef34505f7802adc43fadb8/contracts/PerpsV2MarketBase.sol#L602), [PerpsV2MarketProxyable.sol#L102](https://github.com/Synthetixio/synthetix/blob/f59f3c49aa916448d0ef34505f7802adc43fadb8/contracts/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)
else:
  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
else:
  revert when trade_price < slippage_price
```

#### Update
This issue was resolved in [823da7b](https://github.com/Synthetixio/synthetix/pull/1948/commits/823da7b0cb5a058aec535b1c98c5d698a43a0f86).

### 5.5.3 Liquidation premium not considered during trade [medium risk]
*[PerpsV2MarketBase.sol#L546](https://github.com/Synthetixio/synthetix/blob/8be56a319ed4cdd06eb7944c333eff7fb6ad0cfe/contracts/PerpsV2MarketBase.sol#L546)*
#### 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](https://github.com/Synthetixio/synthetix/pull/1970/commits/f1196d9216376903da9a1413559906e88bc65153).

### 5.5.4 ETH fee not forwarded to `PerpsV2ExchangeRate` when executing an off-chain delayed order [low risk]
*[PerpsV2MarketDelayedOrders.sol#L336](https://github.com/Synthetixio/synthetix/blob/0cb70e5a7cc182f510e64dbe9a84b7070de2304d/contracts/PerpsV2MarketDelayedOrders.sol#L336)*

#### 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](https://github.com/Synthetixio/synthetix/pull/1893/commits/93950ce2f137c384792a72737cee4a266fdef093).

### 5.5.5 Deprecated Pyth function used to get update fee [low risk]
*[PerpsV2ExchangeRate.sol#L58](https://github.com/Synthetixio/synthetix/blob/8be56a319ed4cdd06eb7944c333eff7fb6ad0cfe/contracts/PerpsV2ExchangeRate.sol#L58)*

#### Description
The Pyth function `getUpdateFee(uint)` is used to retrieve the fee required to update the price feeds using `updatePythPrice()`. This function is [deprecated](https://github.com/pyth-network/pyth-crosschain/blob/4821b877e361c8532befcf20824812351fec8b15/ethereum/contracts/pyth/Pyth.sol#L81) 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](https://github.com/Synthetixio/synthetix/pull/1965/commits/cac6b52e7bb43c0f29d4eb941917e19f42cb481e).

### 5.5.6 Restrict `PerpsV2ExchangeRate` arbitrary call target [low risk]
*[PerpsV2ExchangeRate.sol#L67](https://github.com/Synthetixio/synthetix/blob/8be56a319ed4cdd06eb7944c333eff7fb6ad0cfe/contracts/PerpsV2ExchangeRate.sol#L67)*

#### 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](https://github.com/Synthetixio/synthetix/pull/1970/commits/b47b9470fdf31e743c1c5e2540a024e558db03e0).

### 5.5.7 Proxy should fail safe [low risk]
*[ProxyPerpsV2.sol#L227](https://github.com/Synthetixio/synthetix/blob/7a0056d43365a8d17a2a9559a876b4c8d35fae2b/contracts/ProxyPerpsV2.sol#L227)*

#### 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](https://github.com/Synthetixio/synthetix/pull/1939/commits/754213836a0d010e2facf1f21e67429175542d0b).

Secure your system.
Request a service
Start Now