Synthetix SIP-37 Smart Contract Audit

# 1. Introduction
iosiro was commissioned by [Synthetix]( to conduct a smart contract audit on the implementation of [SIP-37]( The audit was performed between 10 February 2020 and 14 February 2020. A review of changes related to the audit was performed on 18 February 2020.

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 risk exposure of the smart contracts, and as a guide to improving the security posture of the smart contracts by remediating the issues that were identified. The results of this audit are only a reflection of the source code reviewed at the time of the audit and of the source code that was determined to be in-scope.

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

This report presents the findings of the audit performed by iosiro on the smart contract implementation of SIP-37.

The purpose of this audit was to achieve the following.

* Ensure that the smart contracts functioned as intended.  
* Identify potential security flaws.

Assessing the market effect, economics, game theory, or underlying business model of the platform were strictly beyond 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 very high risk with regards to 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. There are a number of techniques that can help to achieve this, some of which are described below.

* Security should be integrated into the development lifecycle.
* Defensive programming should be employed to account for unforeseen circumstances.
* Current best practices should be followed when possible.  

#### SIP-37
The purpose of SIP-37 is to prevent the front-running of oracles within the Synthetix system. This is achieved by ensuring that Synth exchanges take into account changes to market prices within a certain time window. Any profit made by the user within this time window can be reclaimed by the system. Conversely, if the user makes a loss on the exchange in the time window, the amount of the loss is rebated to the user.

[SIP-12]( introduced a maximum gas limit on certain operations within the system to prevent direct front-running of the system through submitting transactions with high gas prices. However, due to UX and technical concerns around the solution, an alternative approach was required. An area of particular concern was that as the system has started to move to decentralized price oracles on ChainLink, additional latency has been added to the system. While the Synthetix Oracle would update on-chain prices when a 0.3%-0.5% price deviation was detected, the ChainLink network operates closer to 1%. These slower updates due to reduced sensitivity would give front-runners more opportunities to exploit the system. As such, SIP-37 incorporates a waiting time between exchange operations, reducing the likelihood that a front-runner is able to take advantage of any latency in updating exchange rates.

#### Audit Results
The code was found to be of a very high standard, as it was modularised, well-documented, defensive, and generally adhered to best practices. The implementation was found to strictly implement the specification.

At the conclusion of the audit only informational issues were open. These findings included suggestions for ways to improve the performance and readability of the system.

<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 is considered to be out-of-scope. Out-of-scope code that interacts with in-scope code is assumed to function as intended and introduce no functional or security vulnerabilities for the purposes of this audit.

### 3.1.1 Synthetix Smart Contracts
**Project Name:** Synthetix<br/>
**Commit:** [6ac6f4b](<br/>
**Files:** ExchangeRates.sol, ExchangeState.sol, Exchanger.sol, Issuer.sol, Synth.sol, Synthetix.sol

## 3.2  Methodology

A variety of techniques were used in order to perform the audit. These techniques are briefly 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 Ganache test environment, both manually and through the Truffle test suite provided. Manual analysis was used to confirm that the code operated at a functional level, and to verify the exploitability of any potential security issues identified.

### 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. The static analysis results were manually analyzed to remove false-positive results. True positive results would be indicated in this report. Static analysis tools commonly used include Slither, Securify, and MythX. Tools such as the Remix IDE, compilation output, and linters are also used to identify potential issues.

## 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 addressed to a satisfactory level to remove the risk that it posed.

<a name="section-4"></a>
# 4. Design Specification
The following section outlines the intended functionality of the system at a high level.

## 4.1 SIP-37
The following section was taken from [SIP-37]( for the purposes of establishing a specification for the audit.

### 4.1.1 Specification

When a user exchanges `src` synth for `dest` synth, the waiting period of _N_ minutes begins. Any `transfer` of `dest` synth will fail during this window, as will an `exchange` from `dest` synth to any other synth, or a burn of `sUSD` if it was the `dest` synth of any pending exchange. If another exchange into the same `dest` synth is performed before _N_ minutes expires, the waiting period restarts with _N_ minutes remaining.

Once _N_ minutes has expired, the following `exchange` from the `dest` synth to any other, or a burn of `sUSD`, will invoke `settle` - calculating the difference between the exchanged prices and those at the end of the waiting perid. If the user made profit, it is taken to be front-run profit, and the profit is burned from the user's holding of the `dest` synth. If the user made a loss, this loss is issued to them from the `dest` synth. The `exchange` then continues as normal.

In the case of a user trying to `transfer` some `amount` of the `dest` synth after the waiting period has expired, this will always fail if the `amount` + `totalOwing` is more than the user's `balanceOf`. The user has to first invoke `settle` before a synth can be transferred. Otherwise, the `transfer` will continue as normal.

The calculation of `owing` or `owed` is as follows:

`Amount * (1 - feeRate) * (srcRate/destRate - newSrcRate/newDestRate)`

If the result is negative, the amount is `owed` as a rebate, otherwise its `owing` as a

Examples (with `feeRate` at `0.003`):

- 100 sUSD into sETH at a ETHUSD rate of 100:1 (1/100) which raises to 105:1 (1/105), the `owing` would be: `100 * 0.997 * (1/100 - 1/105) = 0.04747619048 sETH`.

- 100 sETH into sBTC at a BTCUSD rate of 10,000:1 and ETHUSD rate of 100:1 which raises to 105:1, the user would be rebated an `owed` amount of: `100 * 0.997 * (100/10000 - 105/10000) = 0.04985 sBTC`

### 4.1.2 Implementation

The implementation should be as follows.

- `` invoked from synth `src` to `dest` by `user` for `amount`

 - _Are we currently within a waiting period for any exchange into `src`?_

   - Yes: ❌ Fail the transaction
   - No: ✅
     - Invoke `settle(src)`
     - Proceed with the `exchange` as per usual
     - Persist this exchange in the user queue for `dest` synth

- `Synthetix.settle(synth)` invoked with `synth` by `user`

 - _Are we currently within a waiting period for any exchange into `synth`?_

   - Yes: ❌ Fail the transaction
   - No: Sum the `owing` and `owed` amounts on all unsettled `synth` exchanges as `totalOwing` and `totalOwed`
     - _Is the totalOwing > 0_
       - Yes: ✅ Reclaim the `totalOwing` of `synth` from the user by burning it
     - _Is the totalOwed < 0_
       - Yes: ✅ Rebate the absolute value `totalOwed` of `synth` to the user by issuing it
     - Finally, remove all `synth` exchanges for the user

- `Synth.transfer()` invoked from synth `src` by `user` for `amount`

 - _Are we currently within a waiting period for any exchange into `src`?_
   - Yes: ❌ Fail the transaction
   - No: Sum the `owing` amounts on all unsettled `synth` exchanges as `totalOwing`
     - _Is the user's balance >= amount + totalOwing_
       - Yes: ✅ Proceed with transfer as usual
       - No: ❌ Fail the transaction

- `Synth.burnSynths()` invoked by `user` for `amount`
 - _Are we currently within a waiting period for any exchange into `sUSD`?_
   - Yes: ❌ Fail the transaction
   - No: ✅
     - Invoke `settle(src)`
     - Proceed with the `burn` as per usual

<a name="section-5"></a>
# 5. Detailed Findings
The following section includes in-depth descriptions of the findings of the audit.

## 5.1 High Risk

No high risk issues were present at the conclusion of the audit.

## 5.2 Medium Risk

No medium risk issues were present at the conclusion of the audit.

## 5.3 Low Risk

No low risk issues were present at the conclusion of the audit.

## 5.4 Informational

### 5.4.1 Design Comments

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

#### Use a Synth-specific Waiting Period
The waiting period for all exchanges was set to a period of `N` minutes, with a default of 3 minutes. However, as the system represents assets with varying volatilities, it may be necessary to use different `N` values to better model the required waiting times of each asset. For example, with sETHsUSD being much more volatile than sXAUsUSD, `N` minutes might be too long for sETHsUSD and too short for sXAUsUSD.

##### Response from Synthetix Team
Yes, this is something that we will be looking at in future deployments. We are considering looking at on-chain volatility to inform this.

#### Inefficient Search for Max Timestamp
The `getMaxTimestamp(...)` iterated through an array of a user's exchanges to find the exchange with the most recent timestamp. However, in the current implementation of the system, the only times when the array was modified was when a new entry was pushed into the array with a timestamp of `now` and when the array was emptied. As such, the last element inserted into the array would always have the most recent time, and could be referenced through `userEntries[userEntries.length - 1]`.

It should be noted that if additional methods of modifying the array are anticipated (e.g. updating the timestamp of an exchange or inserting elements into the array without using `push`), then the more robust current approach should be used, as it would account for an unordered array.

##### Response from Synthetix Team
True it could be improved given the current usage, however as `ExchangeState` is immutable, and we can always fetch the last entry via `getEntryAt(getLengthOfEntries(…) - 1` externally if need be, so we’d prefer to keep the max function for potential future usage.

#### Implement Temporal Validation in `effectiveValueAtRound(...)`
The `effectiveValueAtRound(...)` function was used to determine the exchange rate of two currencies at a certain point in time. As different exchange rates had independent indices, it would be possible to call the function with two exchange rates which were set at vastly different times. Given the intended functionality of the function, it may be beneficial to include validation to ensure that the rounds are within a certain time period of each other.

The only usage of this function was in `settlementOwing(...)` which was not found to be exposed to this risk, as the round IDs were determined based on time values. Furthermore, given that there were two oracle systems and several assets, it would not be straightforward to determine an acceptable time window. As such, no action is necessarily required. However, it should be noted that third parties and future versions of the Synthetix system could be exposed to this risk.  

##### Response from Synthetix Team
This would be too onerous to manage, given that each oracle network under Chainlink will have different lengths of time that they will, at a minimum, guarantee updates.  

## 5.5 Closed

### 5.5.1 Design Comments (Informational)

#### Potential Gas Optimization

A potential gas optimization for the `resolver` pattern was identified during the audit. The pattern at the time of the audit used two external calls to determine the address, e.g.


<code class="language-solidity" >
   function exchanger() internal view returns (IExchanger) {
       require(resolver.getAddress("Exchanger") != address(0), "Resolver is missing Exchanger address");
       return IExchanger(resolver.getAddress("Exchanger"));


In testing a total of 29,159 gas was consumed.

However, it would be possible to store the address to reduce the function to one external call, e.g.


<code class="language-solidity" >
   function exchanger() internal view returns (IExchanger) {
       uint resolved = resolver.getAddress("Exchanger");
       require(resolved != address(0), "Resolver is missing Exchanger address");
       return IExchanger(resolved);


In testing a total of 25,646 was consumed during this function call, 3,513 gas less than the current implementation.

As this functionality was used extensively throughout the codebase, it may have a significant effect on the overall gas consumption.

##### Update
Implemented in [ff931cf](

##### Response from Synthetix Team
Done, and improved slightly with a function `requireAndGetAddress()` that does the require as well, lowering the bytecode each of our contracts that use it require on deployment. ([88f288b](

#### Comment Incorrectly Describes Code
While Synthetix.sol#L246 specified that `settle(...)` returned a `bool`, the function returned `(uint, uint)`. It is recommended that the comment be changed to correctly describe the code.

##### Update
Removed in [baa6d13](

#### Refactoring Suggestions
It is recommended that certain portions of the code be refactored to improve readability.

- ExchangeRates.sol: `roundsForRates` should be `currentRoundForRate` for clarity.
- ExchangeRates.sol: `code`  should be replaced with `currencyKey` throughout the file for consistency.
- ExchangeRates.sol#L288: `rates()` should be `rate()` as it returns a single rate.

##### Update
Implemented in [ca4923f](

#### Fix Spelling and Grammatical Errors
Language mistakes were identified in the comments and revert messages in the codebase. Fixing these mistakes can help improve the end-user experience by providing clear information on errors encountered, and improve the maintainability and auditability of the codebase.

- Exchanger.sol#L107 - `recevied` should be `received`.
- ExchangeRates.sol#L7 - `keys` should be `key`.
- ExchangeRates.sol#L33 - Unnecessary `configure`.
- ExchangeRates.sol#L106 - `MUTITATIVE` should be `MUTATIVE`.
- ExchangeRates.sol#L112 - Unnecessary `.contract` at the end of the sentence.
- ExchangeRates.sol#L221 - `THe` should be `The`.

##### Update
Implemented in [fa6b43d](

Secure your system.
Request a service
Start Now