Synthetix Phase 1 Smart Contract Audit

# 1. Introduction
iosiro was commissioned by [Synthetix]( (formerly Havven) to conduct an audit on their Synthetix stablecoin smart contracts. The audit was performed between 23 October 2018 and 23 November 2018.

#### Update
This report reflects in-scope [changes]( between the version of the codebase that was audited ([97de330]( and an updated version ([22ca406](, which is a response to the issues identified during the audit.

**Note: At the time of the audit, Synthetix was referred to as Havven. The table below can be used to interpret the results of this report in the context of the current implementation.**

| Formerly              | Currently|
|:--------------------- |:----------|
| Havven                | Synthetix|
| havvens, HAV          | SNX|
| Havven Drawing Rights (HDRs) | Synthetix Drawing Rights (XDRs)|
| Nomins (e.g. nUSD)    | Synths (e.g. sUSD)|

This report is organised 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 improve 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 an audit performed by iosiro on the Havven platform smart contracts. The purpose of the audit was to achieve the following.

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

Assessing the economics, game theory, and underlying business model of the platform were 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.  

At the conclusion of the audit, two low risk issues, and several informational level and design comments remained open. One low risk issue could result in dramatic spikes in the Havven Drawing Rights (HDRs) exchange rate. The other low risk issue could result in an incorrect maximum exchange fee being enforced in future implementations of the system. The informational level findings included excessive owner privileges, as well as minor deviations from best practice and suggestions that may improve the functionality or readability of the code.

Despite the findings presented in this report, the code was found to be of a very high standard. This was evident in the use of modularised, well-documented code, using defensive programming, as well as general adherence to best practices.

A number of critical components were explicitly removed from the scope of this assessment, as they had been tested in prior security audits. This could result in blind spots that emerge as a result of individual components operating superficially as expected, but the system as a whole not integrating correctly. Specific areas of concern include the following.

* Escrow functionality.
* Proxy functionality.
* Oracle functionality.
* Upgrade (state transfer) functionality.

The risk posed by the smart contracts can be further mitigated by using the following controls prior to releasing the contracts in a production environment.

* Perform an additional audit with the entire system in scope.
* Use a public bug bounty program to crowdsource the process of identifying security vulnerabilities.
* Extend the test suite coverage.

<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 security vulnerabilities for the purposes of this audit.

### 3.1.1 Havven Smart Contracts
**Project Name:** Havven<br/>
**Commits:** [97de330](<br/>
**Files:**  ExchangeRates.sol, FeePool.sol, Havven.sol, Nomin.sol, ReentrancyPreventer.sol, SafeDecimalMath.sol, TokenFallbackCaller.sol

## 3.2  Methodologyy

A variety of techniques were used while conducting the audit. These techniques are briefly described below.

### 3.2.1 Code Review
The source code was manually reviewed to identify potential security flaws. Code review is useful for detecting business logic flaws and high risk areas of the code.

### 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 any potential security issues identified. The coverage report generated by solidity-coverage of the Truffle tests included in the project is given below.

| File                       | % Statements  | % Branch |  % Functions | % Lines  |
| contracts                  |     81.7 |    63.31 |    82.89 |    82.39 |
|  ExchangeRates.sol         |    92.16 |      100 |    92.86 |    92.45 |
|  ExternStateToken.sol      |       90 |       50 |    81.82 |    88.89 |
|  FeePool.sol               |    99.08 |    77.08 |      100 |    99.18 |
|  Havven.sol                |       92 |    69.74 |    91.67 |    92.26 |
|  HavvenEscrow.sol          |    22.73 |    22.73 |    18.75 |    21.15 |
|  HavvenState.sol           |    39.29 |       10 |    84.62 |    40.63 |
|  IssuanceController.sol    |      100 |      100 |      100 |      100 |
|  LimitedSetup.sol          |      100 |       50 |      100 |      100 |
|  Nomin.sol                 |      100 |     62.5 |      100 |      100 |
|  Owned.sol                 |      100 |      100 |      100 |      100 |
|  Pausable.sol              |        0 |        0 |        0 |        0 |
|  Proxyable.sol             |    63.64 |       50 |       50 |    64.29 |
|  ReentrancyPreventer.sol   |      100 |       50 |      100 |      100 |
|  SafeDecimalMath.sol       |      100 |      100 |      100 |      100 |
|  SafeMath.sol              |     87.5 |       75 |       80 |     87.5 |
|  SelfDestructible.sol      |    17.65 |     12.5 |       20 |    17.65 |
|  State.sol                 |      100 |      100 |      100 |      100 |
|  TokenFallbackCaller.sol   |      100 |      100 |      100 |      100 |
|  TokenState.sol            |      100 |      100 |      100 |      100 |
| contracts/test-helpers/    |       80 |      100 |       80 |       80 |
| PublicSafeDecimalMath.sol |       80 |      100 |       80 |       80 |
| All files                   |    81.66 |    63.31 |    82.74 |    82.35 |

### 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 analysed to remove false positive results. True positive results would be indicated in this report.  

Static analysis was conducted using Mythril, Securify, and Oyente. Tools such as the Remix IDE, compilation output, and linters were also used to identify potential areas of concern.

## 3.3  Risk Ratings

Each issue identified during the audit is 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 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 Havven Smart Contract
The Havven contract is described below.

#### ERC-20 Token

The token should be ERC-20 compliant with the following values.

|Field        | Value|
|Symbol       | HAV|
|Name         | Havven|
|Decimals     | 18|

#### Locking Mechanism

A user should be able to lock havvens within the Havven system in order to issue a proportionate number of nomins, up to the issuance ratio (initially 20%). The user should then earn fees from transactions of nomins within the system, relative to their percentage stake in the system as a whole.

If the price of havvens increases such that the collateralisation ratio for a user goes below the minimum specified amount (also initially 20%), a portion of their locked tokens should be unlocked up to the point where the collateralisation ratio reaches the minimum required collateralisation ratio again.

Alternatively, if the price of havvens drops, then the user's havvens should be locked within the contract and be penalised on fees withdrawn from the system until either the price corrects itself or the user purchases enough havvens to correct their collateralisation ratio.

#### Fee Collection and Distribution

Fees collected through transfers and exchanges of nomins should be tracked through a fee pool. The fee pool should track when havvens are locked within the system to provide collateral for the nomins and should pay out fees proportionately to users depending on the amount of havvens locked and when they locked their tokens. If a user's collateralisation ratio goes above an amount specified in the contract, the user should be penalised when trying to withdraw fees. The structure of the penalty should be as indicated in the following table.

|Collateralisation Ratio | Penalty|
|----------------------- | -------|
|0% - 20%                | No reduction in fees.|
|20% - 30%               | 25% reduction in fees.|
|30% - 40%               | 50% reduction in fees.|
| <40%                | 75% reduction in fees.|

#### Escrow Integration

It should be possible for the Havven system to integrate with an escrow system.

*Note: This functionality was beyond the scope of this assessment.*

#### Nomin Integration

It should be possible for the owner of the Havven contract to add and remove nomins to the Havven system.

#### Issue, Burn, and Exchange Nomins

It should be possible for an owner of havvens to burn or issue nomins from the Havven contract. Additionally, a holder of nomins should be able to exchange their nomins held in one currency key into another currency denominated Nomin flavour for a small exchange fee.

#### Exchange Rates

It should be possible for the Havven system to integrate with an exchange rate contract, which should control the various exchange rates within the system. The rates should be set by an oracle contract. Rates should be considered stale if they have not been updated in more than a specified time.

*Note: Oracle functionality was beyond the scope of this assessment.*

#### Preferred Currency

It should be possible for users to set a preferred currency, automatically converting any funds that they receive in nomins to their preferred currency. If no preferred currency is set for a receiving address, the default currency should be the original currency. No fee should be charged on this exchange, as the user should be charged a fee for the transfer.  

#### Havven Drawing Rights (HDRs)

The Havven Drawing Rights is a flavour of nomins that is loosely based on Special Drawing Rights. Its exchange rate is based on a basket aggregate of currencies to minimise exposure towards any particular fiat currency. Fees are stored in this currency, and users can hold these nomins if they want to lessen their exposure to any particular fiat currency.

#### Proxy and Upgrade Functionality

It should be possible to store the token balances in an external state contract to allow for seamless upgrades to the main functionality while preserving the state of the tokens and the Havven ecosystem.

*Note: This functionality was beyond the scope of this assessment.*

## 4.2 Nomin Token Smart Contract
The functionality of the Nomin token smart contract is described below.

#### ERC-20 Token

The token should be ERC-20 compliant with the following values.

|Field        | Value|
|:------------ |:-------------|
|Symbol       | `_tokenSymbol` constructor parameter|
|Name         | `_currencyKey` constructor parameter|
|Decimals     | 18|

#### Proxy and Upgrade Functionality

It should be possible to store token balances in an external state contract to allow for seamless upgrades to the main functionality while preserving the state of the tokens and the Havven ecosystem.

*Note: This functionality was beyond the scope of this assessment.*

#### Transfer Types

It should be possible to perform ERC-20 transfers with tokens, however, a fee should be reserved on each transfer. It should be possible for either the sender or receiver to pay the fee. Additionally, the token should implement functionality similar to the ERC-223 standard, in that it should trigger a token fallback function in a smart contract that supports the functionality. However, unlike ERC-223, the transfer should not revert if the receiving contract does not support token fallback functionality.

<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

### 5.3.1 Dangerous Method for Maintaining Havven Drawing Rights (HDRs) Rate

#### Description

The HDR exchange rate was found to spike when adding or removing currencies from the basket. This could result in inconsistencies in the system.

The HDR exchange rate was calculated as the summation of the exchange rates within the basket, e.g.

nUSD = 1, nEUR = 1.25, nAUD = 0.5
HDR = 1+1.25+0.5 = 2.75

While the HDR currencies were hardcoded in ExchangeRates.sol, the basket could be modified through a system upgrade or by calling `deleteRate(...)`.

For example, if in an early version of the exchange rates contract 1,000 HDRs were issued with an exchange rate of 2.75, there would be 2,750 USD worth of HDRs in the system. Then an upgrade to the exchange rate contract adds nGBP to the basket with an exchange rate of 1.25, resulting in the HDR rate being 4. The existing holding of HDR would then suddenly become worth 4,000 USD, increasing the value represented by HDRs in the system by 1,250 USD.

This example highlights the point that it should not be possible to at any stage change the basket given the current method for calculating the HDR exchange rate. This includes adding or removing a currency.

While the impact of this issue is severe, it would be possible to incorporate logic in the new contract handling exchange rates to scale the existing HDR holdings proportionately. However, this would introduce additional complexity into the system for a one-time operation that could pose a substantial risk to the integrity of the system.

#### Remedial Action

It is recommended that the HDR algorithm be modified to use weighting factors to better accommodate changes in the HDR basket to avoid potential future functional or security issues.

#### Synthetix Response
Our plan for upgrading the XDR rate is to introduce a replacement XDR Synth with its own rate, then allow people to exchange between these tokens using existing mechanisms. FeePool would need to handle balances in both for a transition period.

## 5.4 Informational

### 5.4.1 Excessive Owner Capabilities

The owners of the contracts in the system were found to hold a substantial amount of control over the system. This was a design decision that allows for maintenance, upgradeability, and administration of the system. While this decision might be necessary for a certain stage of the project, it does introduce risk in the form of single points of failure throughout the system. Examples of this include being able to arbitrarily update and control the states of tokens (e.g. modifying the balances of accounts holding havvens and nomins) and changing the way that the mechanics of the system work.

This functionality could be exploited by a rogue actor (e.g. a Havven team member with malicious intent) or by a compromised private key and is noted as it extends the potential attack surface of the system. Ideally, the extent of owner capabilities should be limited over time and eventually removed. While the Havven team could conspire against their users, it would undermine the integrity of the system and would act against their best interests in ensuring the stability and long-term viability of the network.

As a user of the Havven system, it is important to keep in mind that this increases the risk of real-world influence, as a centralised system is more likely to be affected by legislative or political events. Recent examples of this include IDEX and ShapeShift introducing Know Your Customer (KYC) requirements for their users.

The risk of a single rogue actor or a compromised private key can be mitigated by ensuring that a high standard of security is observed by the owner account. For example, the owner account should be a multi-signature wallet, signed by properly secured hardware backed addresses.

#### Synthetix Response
In order to support the upgradability of the contracts the owner requires these privileges, once the system is stable these capabilities will be removed.

### 5.4.2 Design Comments

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

#### Length of `currencyKeys` should be required to match the length of `hdrParticipants`

*ExchangeRates.sol: Line 83*

It was found that the constructor of ExchangeRates could contribute to predictable spikes in the HDR rate value if not correctly initialised with all the currencies in `currencyKeys`. By not validating the length of `currencyKeys` against the length of `hdrParticipants`, it opens the possibility for the HDR rate to incorrectly reflect the HDR price until the missing value is added. This problem is apparent when we consider line 169 of ExchangeRates.sol where each `hdrParticipant` currency is totalled. In the case when the missing `currencyKey` rate is finally added, after initially being un-initialised, the rate of HDR spikes as a result of `total` now accounting for the newly added `currencyKey` rate. It is recommended that the `require` on line 83 of ExchangeRates.sol be changed to also verify the initial value of each constituent `currencyKey` is present upon initialisation:

require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match.");
require(_currencyKeys.length == hdrParticipants.length, "Currency key length and HDR participants length must match");

#### Synthetix Response
We have decided not to action this feedback because even if we specified an opening rate for each one of the XDR currencies, they can always go stale, which would impact that rate in any case. The oracle protects against this, but we can’t enforce this in the constructor, so we felt like it would add additional complexity to the deployment without providing a benefit.

#### Impractical to remove a Nomin once it is in use

*SafeMath.sol: Line 1*

The `removeNomin(...)` function required the total supply of the Nomin being removed to be zero. This was presumably a protective measure to prevent a Nomin from being removed if user funds were stored in it. However, on a practical level, this would likely prevent a Nomin from ever being removed once it was in use by users. One potential workaround to this problem would be to exploit the `burn(...)` functionality to manually exchange a user's tokens, however, this could be deemed as an abuse of power. While this is not a security issue, it is noted as it may introduce functional issues down the line.

#### Synthetix Response
The idea behind this code was to give us a way to remove a Synth as long as it was only being tested, once people hold it, we no longer have the ability to remove it. The code prevents removal of a synth from the network without a larger contract upgrade.

#### Use of implicit integer sizes in contract implementations

It was found that the implicit type `uint` was used consistently throughout the project. It is suggested that these `uint` type declarations be replaced with the more explicit `uint256` type declaration, where appropriate, in order to adhere to best practice.

#### Synthetix Response
While the size of default uint could change between solidity versions, it would be a significant breaking change. At this stage we have quite a few of these around the code base, so rather than changing it, we believe the best approach is to leave it for the time being, changing it to a more specific type if required (e.g. if uintchanges in a breaking solidity version).

#### Inexact Solidity compiler version used


The pragma version was not fixed to a specific version, as it specified `^0.4.24`, which would result in using the highest non-breaking version (highest version below `0.5.0`). According to best practice, where possible, all contracts should use the same compiler version, which should be fixed to a specific version. This helps to ensure that contracts do not accidentally get deployed using an alternative compiler, which may pose the risk of unidentified bugs. An explicit version also helps with code reuse, as users would be able to see the author's intended compiler version. It is recommended that the pragma version is changed to a fixed value, for example `0.4.25`.

#### Synthetix Response
As the SafeMath.sol contract is a dependency managed via NPM, it’d be best to feed this back up to the OpenZeppelin team. I suspect they would want to manage it more comprehensively for their whole library. The rest of our contracts use a hard 0.4.25 peg, so it wouldn’t be possible to compile and deploy these without using 0.4.25, so we didn't see any specific action to take other than to suggest feeding this back to OpenZeppelin.

#### Unaudited compiler version

Version 0.4.25 of the Solidity compiler was used throughout the project. At the time of writing, no publicly available security reviews of the target version were available. A [comprehensive security review]( was performed by the Zeppelin team on version 0.4.24 with several issues being identified and rectified in 0.4.25. As a result, no change is recommended. However, it is worth noting that there is a possibility that new, unknown vulnerabilities exist in the version used.

#### Synthetix Response
Noted, we’ll keep an eye out for audits / future versions.

## 5.5 Closed

### 5.5.1 Incorrect Exchange Fee Rate Validation (Low Risk)

*FeePool.sol: Line 124*

#### Description
It was found that the `setExchangeFeeRate(...)` function incorrectly used `MAX_TRANSFER_FEE_RATE` for validation rather than `MAX_EXCHANGE_FEE_RATE`. As the constants were set to the same value it did not present a security or functional risk in this version of the contract. If in future contract upgrades or versions these rates are not equal, this incorrect validation may inadvertently impact the functionality of the contract.

#### Remedial Action
It is recommended that the `MAX_EXCHANGE_FEE_RATE` be used to determine the maximum fee exchange rate.

#### Comment
Fixed in [65c9169](

### 5.5.2 Design Comments (Informational)

#### Type declaration of `decimals` does not match ERC-20 standard

*ExternStateToken.sol: Line 54*
*Havven.sol: Line 151*
*Nomins.sol: Line 47*

It was found that the `decimals` variable was defined using an implicit `uint` (an alias for `uint256`) type as opposed to the `uint8` type as in the ERC-20 standard. Although not strictly a security or functional issue, it is recommended that the type be changed to adhere to the ERC-20 standard and as a minor optimisation.

#### Comment
Fixed in [fc436da](

#### Inconsistent case used on external method `sethavvenState`

*Havven.sol: Line 261*

It was found that the `sethavvenState(...)` function did not match the case conventions of other function names. While not a functional or security issue, it is recommended that the function name be changed to `setHavvenState(...)` to be more consistent with the function case convention present elsewhere.

#### Comment
Fixed in [ca772fd](

#### Comments incorrectly describe code

Certain comments in the code were found to incorrectly describe the intended functionality of the codebase, these are detailed below.

* *Nomins.sol: Lines 89 - 93, 111-115, 132-133, 155-156 -* these comments allude to the fact that nomins have the ability to freeze tokens. However, the freeze functionality that was included in previous versions of the code had been removed in the version of the code being assessed.
* *Havven.sol: Lines 422-433 -* The comment implies that exchanges with a destination address of `address(0)` or the message sender incur no fee. However, calls to `exchange(...)` always incur a fee, and if `exchange(...)` is called with a destination of `address(0)`, the destination is changed to the message sender.

#### Comment
Fixed in [5a2772b]( and [2d00ab9](

#### Missing comment blocks

While most of the codebase contained high-quality comments, some portions of the code had no comments. While in some cases the intention of the code was apparent in the naming conventions (e.g. `transferSenderPaysFee(...)`), in other instances the code was highly complex and had no supporting comments. In order to improve the readability, maintainability, and extensibility of the codebase, it is recommended that comments are added to the affected areas. These areas are listed below.

- FeePool.sol: missing module description.

- Havven.sol: missing function description for `collateralisationRatio(...)` and `debtBalanceOf(...)`.

- FeePool.sol: missing function description for `claimFees(...)`, `_recordFeePayment(...)`, and `_payFees(...)`.

#### Comment
Fixed in [7cbf0e3]( and [234e98b](

#### No validation on whether a rate is older than the existing rate

*ExchangeRates.sol: Line 139*

While validation logic was included to ensure that the oracle did not set values too far into the future, no validation was performed to ensure that the rate was, in fact, a more recent exchange rate than the current one. This would allow an oracle to potentially update the exchange rate with an older exchange rate. A mitigating factor was that the old rate would still require that the older rate be more recent than the stale period specified in the contract.

#### Comment
Fixed in [b20b75f](

#### Several critical operations not covered in Truffle tests

Review of the code coverage results revealed several critical operations in the smart contract logic that were untested in what was otherwise a relatively comprehensive test suite. It is recommended that the test suite be expanded to cover the remaining uncovered branches:

- Havven.sol: no test cases for the case when `chargeFee` is `true` in the function `_internalExchange(...)` (line 531).
- HavvenEscrow.sol: poor coverage in general, most functions untested.
- HavvenState.sol: no tests for legacy functionality in functions `importIssuerData(...)` and `_addToDebtRegister(...)`.
- SelfDestructable.sol: no tests for time-based functionality.

#### Comment
- Havven.sol: fixed in [003f89b](
- HavvenEscrow.sol: not fixed.
- HavvenState.sol: not fixed.
- SelfDestructable.sol: fixed in [00e2384](

#### No event when changing Havven State

*Havven.sol: Line 265*

Lines 266 through 268 of Havven.sol mentioned that an event indicating that the Havven State had been changed was removed to reduce the contract size. However, it is recommended that this functionality be included if possible. From a transparency perspective, it would be helpful for users to be able to track when the Havven State is updated given the amount of trust placed in the Havven team for governance and maintenance of the project.

#### Comment
Fixed in [4876fd3](

#### Comment typos

Typos were identified within certain comments in the codebase, these are outlined below.

- *FeePool.sol: Line 482 -*
**`>40% -`**` 75% reduction in fees` should read as **`>40%: `**`75% reduction in fees` in order to follow the format of the lines that preceed it.
- *FeePool.sol: Line 518 -* `... fee period `**`does is not`**` yet ready... ` should be `... fee period `**`is not `**` yet ready...`.
- *ExchangeRates.sol: Line 67 -* incorrectly refers to `currencyKeys` array as 'rates' instead of 'keys'.

#### Comment
Fixed in [4c7a90c](, [f26f1e5](, and [80da301](

Secure your system.
Request a service
Start Now