Synthetix Spica Release Smart Contract Audit

# 1. Introduction

iosiro was commissioned by [Synthetix]( to conduct a smart contract audit on the implementation of the [Spica release](, which included [SIP-44](, [SIP-54](, [SIP-65](, and [SIP-68]( SIP-44 was audited between 26 March 2020 and 1 April 2020. SIP-54 was audited between 7 and 9 July 2020, and a review of changes was performed on 28 July 2020. SIP-65 was audited between 13 and 14 July 2020. SIP-68 was audited between 6 July 2020 and 10 July 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.

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.

<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-44](, [SIP-54](, [SIP-65](, and [SIP-68](  

The purpose of [SIP-44]( was to add the ability to suspend and resume certain functionality within the system. Reasons for suspending the system might include system upgrades, issuance and exchange controls, disabling synths for security purposes, or potentially suspending synths during the underlying assets' out-of-trading hours. At the conclusion of the audit only one informational issue that did not require further action was open. A consideration for future developments would be that the suspension controls implemented in SIP-44 were generally implemented in the external functions. Thus it is important that if new functionality is added to the system that interacts with the underlying sensitive internal functions, it be properly locked down. An example of this is `Synthetix.issueSynths(...)` which used `requireIssuanceActive`, exposing `Issuer._internalIssueSynths(...)` to potential misuse.

The purpose of [SIP-54]( was to add limit order functionality to the Synthetix exchange without modifying the core exchange contracts. Limit orders allow users to buy or sell a synth at a specified price or better. At the conclusion of the audit, only minor informational issues relating to best practices and improving readability were open.

The purpose of [SIP-65]( was to integrate a circuit breaker into exchange operations. A circuit breaker is a mechanism to suspend a synth if the exchange rate changes by more than some threshold, which would indicate a failure in one of the oracle systems. No issues were found during the audit; however, some design recommendations were made. Overall, the implementation was of a high standard.

The purpose of [SIP-68]( was to update apply minor enhancements to the `StakingRewards` contract. These enhancements included adding a configurable `rewardsDuration` as well as a `recoverERC20` function to claim other liquidity mining rewards. Three informational issues were identified during the audit. These issues were closed at the conclusion of the audit. Overall, the implementation was 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 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 SIP-44 Smart Contracts

**Project Name:** Synthetix<br/>

**Commits:** [8288a47](<br/>

**Files:** DappMaintenance.sol, EtherCollateral.sol, Exchanger.sol, FeePool.sol, Issuer.sol, Synth.sol, Synthetix.sol, SystemStatus.sol

### 3.1.2 Synthetix SIP-54 Smart Contracts

**Project Name:** snx-limit-orders<br/>

**Commit:** [df3d25c](<br/>

**Review Commit:** [950ac9b](<br/>

**Files:** Implementation.sol, ImplementationResolver.sol, Proxy.sol

### 3.1.3 Synthetix SIP-65 Smart Contracts

**Project Name:** Synthetix<br/>

**Commits:** [cb15e88](<br/>

**Files:** ExchangeState.sol, Exchanger.sol, SystemStatus.sol

### 3.1.4 Synthetix SIP-68 Smart Contracts

**Project Name:** Synthetix<br/>

**Commits:** [83d8c1f](<br/>

**Files:** RewardsDistribution.sol, StakingRewards.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 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-44

The following specification was taken from [SIP-44](

The following areas can be suspended:

1. **System**: All synth and SNX transfers disabled. All exchange, issue, burn, claim, loan and mint functionality disabled. This is both for system upgrades and under possible emergency situations.

2. **Issuance**: All sUSD issuance, burning and claiming disabled, along with any loan actions.

3. **Exchange**: All synth exchanges and settlement.

4. **Synth**: For the synth in question, all transfers of, settlement of, and exchanges into or out of disabled.

Access to the above controls will be restricted to an `accessControlList`, a whitelist of addresses that for each section above, can `suspend` and/or `resume`. This whitelist will be managed by the `owner`.

Furthermore, each suspension must include a `uint reason`. Apart from the single reason `1` for `SYSTEM_UPGRADE`, these reasons are purely for dApps and scripts to indicate to users why certain parts of the system are unavailable.

## 4.2 SIP-54

The specification of SIP-54 was based on commit hash [3a60708](

## 4.3 SIP-65

The specification of SIP-65 was based on commit hash [9273b99](

## 4.4 SIP-68

The specification of SIP-68 was based on commit hash [ebd1644](

<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 Potentially Unsafe Arithmetic Used

*SIP-54: [Implementation.sol#L93](, [Implementation.sol#L94](, [Implementation.sol#L107](*

#### Description

Potentially unsafe mathematical operators were found in the codebase.

#### Remedial Action

While no high risk instances were identified, use of the SafeMath library for all arithmetic as a defensive coding practice is encouraged.  

### 5.4.2 Use of `transfer` Function

*SIP-54: [Implementation.sol#L77](, [Implementation.sol#L96](*

#### Description

The `cancelOrder` and `executeOrder` functions made use of the `transfer` function to send ether. While `transfer` is commonly used to prevent reentrancy attacks due to its 2300 gas limit, this relies on the receiving contract having a fallback functions below this limit. However, gas costs should not be considered constant, as demonstrated in EIP-1884, which changed the gas cost of the `SLOAD` operation. Should a contract's fallback use more gas than the 2300 limit due to such changes, it would be incompatible with the system.

#### Remedial Action

It is recommended that the `call` function be used to send ether instead of `transfer`. Since `call` does not prevent reentrancy attacks, it is necessary to move the order deletion (Implementation.sol#L78) to before the ether is sent (Implementation.sol#77). It would also be possible to use OpenZeppelin's ReentrancyGuard modifier on the necessary functions to protect against this class of attack.

#### Further Reading

[Consensys On Avoiding `transfer()`](

### 5.4.3 Design Considerations

Additional suggestions to enhance the overall system design are outlined below.

#### For Loop Optimization


The `for` loop in the MixinResolver constructor could `break` once a null address is detected, as long as no null addresses are expected. Doing so would avoid unnecessarily iterating through the full array, which would result in saving gas during deployment.

##### Update

Implemented in [9caca24](

#### Inline Values Used Instead of Constants


- Synth.sol#L158,162,166,170 use inline strings rather than the constants variables declared in the contract.

- MixinResolver.sol#L16 uses an inline value rather than the defined `MAX_ADDRESSES_FROM_RESOLVER` constant.

##### Update

Implemented in [9caca24](

#### Deprecated Pattern Usage


FeePool.sol#L242 uses the deprecated `resolver.getAddress(..)` pattern and should be replaced with the caching pattern.

##### Update

Implemented in [9caca24](

#### Refactoring Suggestions


It is recommended that certain portions of the code be refactored to improve readability, as indicated below.  

- `MixinResolver.updateAddressCache(...)` should be renamed to `appendToAddressCache(...)`, as it is intended to append another address to the address cache, instead of updating existing entries.

- `MixinResolver.getResolverAddresses()` should be renamed to `getResolverContracts()` or `getResolverAddressesRequired()` and the return variable should be renamed from `addresses` to contracts, `names`, or `addressesRequired`, as the function returns an array of contract names required by the resolver.

##### Update

Implemented in [9caca24]( and [2662222](

#### 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.

- SystemStatus.sol#L55: `Issuance` → `Exchange`

- SystemStatus.sol#L154: `INTERNL` → `INTERNAL`

##### Update

Implemented in [9caca24](

#### Potential Overflow Issue


A possible overflow existed in `SystemStatus.suspendSystem(...)` by downcasting a `uint256` parameter to `uint248`. However, the functionality was restricted to only privileged accounts and was not obviously exploitable. As this is was found to be potentially advantageous from a storage perspective, no change is recommended.

#### Resuming Synth Trading


It may be advantageous to add a call to `Exchanger.isSynthRateInvalid` in the `SystemStatus.resumeSynth` function. However, while this would prevent invalid rates from being used when resuming synth trading, the added complexity may be undesirable.

#### Clear Cached Rate when Suspending


If a synth is suspended for a significant amount of time, the `lastRateFromExchange` may breach the `priceDeviationThreshold` factor despite being previously valid. As such, it may be worthwhile to reset the value of `lastExchangeRate[currencyKey]` to `0` when suspending the synth so that the `_isSynthRateInvalid` function defaults to using current rates to establish a baseline.  

#### High Deviation Factor


The `priceDeviationThreshold` factor was initialized to `3e18`, which corresponded to a factor of 3. While this value seemed excessive, it was configurable via an SCCP, so it could be adjusted if deemed necessary by the community.

#### Refactoring Suggestions


It is recommended that the following contracts are renamed to improve readability, as indicated below.

1. `Implementation` should be `LimitOrders`.

2. `Proxy` should be `LimitOrderProxy`.

#### Orders Indexed from 1


Limit orders were found to have a starting index of 1 rather than 0. This is an uncommon approach, which may complicate the integration of third party tools, such as analytics platforms. It is recommended that `latestID` be indexed from 0 by incrementing it at the end of `Implementation.newOrder` and then returning a value of `latestID - 1`.

## 5.5 Closed

### 5.5.1 Limit Order Implementation Conflict (High Risk)

*SIP-54: [Implementation.sol#L87](, [Implementation.sol#L109](*

#### Description

When executing a limit order, an exchange is made from the `source` synth to the `dest` synth as per the limit order specifications. Due to front-running protections put in place from [SIP-37](, a waiting period is initiated. During this waiting period, the user in context is prevented from exchanging from the `dest` synth to any other synth. However, since the `Proxy` contract calls the exchange function on behalf of the user, the waiting period is shared between all users. This prevents all users from making an exchange from the `dest` synth to any other synth. Moreover, if another exchange is made into the same `dest` synth, the waiting period will reset.

Furthermore, as `destinationAmount` is set when calling ``, any fees or rebates are neglected. This is because when calling `destinationSynth.transferAndSettle` during the withdrawal process, the tokens held in the contract are burned instead of the tokens held by the user calling the function. As a result, another user's tokens are effectively burned, which could lead to there not being enough tokens in the contract for the last user to be able to withdraw their requisite amount.

#### Remedial Action

It is recommended that a factory contract be used to generate a per user instance of the proxy to ensure users are only exposed to their own waiting period and fees.

#### Update

Mosendo changed the logic to use the `Synthetix.exchangeOnBehalf` function instead of the `` function. This approach largely simplified the existing implementation by removing the need for users to escrow their tokens and avoiding the issues related to SIP-37. The change was implemented in [950ac9b](

### 5.5.2 Defensive Coding Practices (Informational)


Defensive coding practices should be used wherever possible to further increase the security posture of the contract. As discussed in the remedial action of 5.4.2, the ether transfer should take place after the order deletion. In general, ether transfers should take place as late as possible to prevent possible reentrancy attacks.

As a further example, [Implementation.sol#L96]( should be moved to after [Implementation.sol#L96]( despite not necessarily being exploitable.

#### Update

Implemented in [950ac9b](

### 5.5.3 Design Comments (Informational)


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

#### Gas Optimization

[Implementation.sol#L49]( checked if `msg.value > 0`, while [Implementation.sol#L50]( checked `msg.value > executionFee`. Given that `executionFee` is at least 0 or more, [Implementation.sol#L49]( should be removed to save on gas costs.

#### Update

Implemented in [950ac9b](

#### Change Owner Validation


ImplementationResolver.sol#L22: It is recommended to add validation in the `changeOwner` function to prevent the owner from becoming the null address. While setting the owner to the null address is a common practice for proving that there is no owner, this comes at the expense of potentially accidentally setting the owner to a null address through a faulty front-end. Any other vanity address, such as Synthetix's fee address, could be used as the new owner address and be an equal demonstration of the contract having no owner.

#### Update

Implemented in [950ac9b](

#### Fix Spelling and Grammatical Errors

Language mistakes were identified 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.

1. SIP-54: [Implementation.sol#L73]( `my` should be `by`.

2. SIP-68: [RewardsDistribution.sol#L48]( `autority` should be `authority`

#### Update

1. Removed in [950ac9b](

2. Corrected in [54b9123](

#### Refactoring Suggestions


It is recommended that certain portions of the code be refactored to improve readability and consistency, as indicated below.

1. [StakingRewards.sol#L96]( `getReward` should be renamed to `claimReward`.

##### Update

The recommendation was declined to avoid breaking any potential existing external integrations.

#### Gas Optimization


The `getReward` function in `StakingRewards` computes `earned(msg.sender)` twice. [StakingRewards.sol#L96]( should be replaced with the following line to save on gas costs:

```uint256 reward = rewards[msg.sender];```

#### Update

Implemented in [22548cf](

Secure your system.
Request a service
Start Now