Synthetix Castor Release Smart Contract Audit

# 1. Introduction
iosiro was commissioned by [Synthetix](https://www.synthetix.io) to conduct a smart contract audit on changes introduced in the [Castor Release](https://blog.synthetix.io/the-castor-release/), which included [SIP-60](https://sips.synthetix.io/sips/sip-60), [SIP-102](https://sips.synthetix.io/sips/sip-102) and [SIP-105](https://sips.synthetix.io/sips/sip-105). The audit was performed between 6 and 14 January 2021.

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 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 the Synthetix Castor release. The following Synthetix Improvement Proposals (SIPs) were included in the audit.

#### SIP-60

[SIP-60](https://sips.synthetix.io/sips/sip-60) introduced a new, more flexible method for escrowing SNX staking rewards, which can also be used by users to escrow arbitrary amounts of SNX for arbitrary periods of time up to two years. This mechanism was also intended to facilitate continuous, incremental vesting and allow liquidators to access escrowed SNX for liquidations, but these features were removed during the audit due to liquidity concerns.

[SIP-60](https://sips.synthetix.io/sips/sip-60) also introduced functionality for users to migrate their escrowed SNX from L1 to OVM L2. This one-way migration allowed users to take advantage of OVM L2's faster transaction speeds and lower gas costs.

During the audit, one medium risk, three low risk and a number of informational issues were discovered. The medium and low risk issues related to account merging and migration, and to the removed liquidation functionality. All medium and low risk issues were resolved by the completion of the audit, with only informational issues relating to test coverage and design suggestions remaining.

#### SIP-102

[SIP-102](https://sips.synthetix.io/sips/sip-102) integrated Synthetix with the Optimism Virtual Machine (OVM) to enable staking on Ethereum Layer 2, to enable faster transactions and lower gas costs.

The code assessed was of a high standard and only a small number of informational issues were found.

#### SIP-105

A bug identified by the Marqet team in the multi-collateral loan functionality was fixed in [SIP-105](https://sips.synthetix.io/sips/sip-105). The bug resulted in certain positions being fully liquidated, when they should have only been partially liquidated. The fix entailed converting the amount of tokens to liquidate into the loan currency from the sUSD value. More information on the bug can be found in [#1025](https://github.com/Synthetixio/synthetix/issues/1025).

The fix was found to correctly address the issue and did not introduce any new issues.

<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-60 smart contracts

**Project Name:** Synthetix<br/>
**Commit:** Initial commit: [ca4fe87](https://github.com/Synthetixio/synthetix/commit/ca4fe87b70c4172cdcc9e72c6944707e36c174fd), Final commit: [bbe6cdb](https://github.com/Synthetixio/synthetix/commit/bbe6cdbea95ead8ea1f4270cdc5433ed968e3a96)<br/>
**File(s):** BaseRewardEscrowV2.sol, BaseSynthetix.sol, FeePool.sol, ImportableRewardEscrow.sol, Issuer.sol, MixinSystemSettings.sol, RewardEscrowV2.sol, Synthetix.sol, SystemSettings.sol

### 3.1.2 Synthetix SIP-102 smart contracts

**Project Name:** Synthetix<br/>
**Commit:** Initial commit: [ca4fe87](https://github.com/Synthetixio/synthetix/commit/ca4fe87b70c4172cdcc9e72c6944707e36c174fd), Final commit: [bbe6cdb](https://github.com/Synthetixio/synthetix/commit/bbe6cdbea95ead8ea1f4270cdc5433ed968e3a96)<br/>
**File(s):** SynthetixBridgeToBase.sol, SynthetixBridgeToOptimism.sol

Note that code for SIP-102 was intertwined with code for SIP-60.

### 3.1.3 Synthetix SIP-105 smart contracts

**Project Name:** Synthetix<br/>
**Commit:** [86a97e1](https://github.com/Synthetixio/synthetix/commit/86a97e1da1a6b60b7f141b26d97025218d5e6a50)<br/>
**File(s):** Collateral.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-60

During the audit, the specification of the SIP was changed. The initial specification of SIP-60 was based on commit hash [38f3c5c](https://github.com/Synthetixio/SIPs/blob/38f3c5cd24a0291577dc57c1c152802de2c8056c/sips/sip-60.md), and the final specification on commit hash [c36bf4b](https://github.com/Synthetixio/SIPs/blob/c36bf4b9e07b38cb85a0480fb722f4ad5276eb4f/sips/sip-60.md). A document entitled [RewardEscrowV2](https://docs.google.com/document/d/1p3BDyvKYNxxvkkh3fMD8r9w6u9WMESfeeU8UEm4Msc0/edit) provided further details.

The following functionality was removed between the initial and final specifications:

* Continuous streaming of the escrowed SNX for each vesting entry.
* Liquidation of escrowed SNX.

Both of these features were removed due to liquidity concerns.

## 4.2 SIP-102

The specification of SIP-102 was based on commit hash [1fc711b](https://github.com/Synthetixio/SIPs/blob/1fc711b735a29c6de766ae327c781b6cfb65899e/sips/sip-102.md).

## 4.3 SIP-105

The specification of SIP-105 was based on commit hash [dd75e3d](https://github.com/Synthetixio/SIPs/blob/dd75e3db881c9197d121563cc787e549a7eda71c/sips/sip-105.md).

<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 remained open at the conclusion of the audit.

## 5.2 Medium risk

No medium risk issues remained open at the conclusion of the audit.

## 5.3 Low risk

No low risk issues remained open at the conclusion of the audit.

## 5.4 Informational

### 5.4.1 Inability to generate test coverage report (Informational)
*SIP-60, SIP-102*

#### Description

Issues pertaining to generating the coverage report for the unit tests covering SIP-60 and SIP-102 were persistent throughout the audit. A coverage report can aid in auditing by determining the full extent of testing performed, indicating areas without sufficient unit test coverage. While additional diagnosis was performed, iosiro was unable to generate the coverage report.

#### Recommendation

It is recommended to diagnose and remediate the issue preventing the coverage report from being generated.

### 5.4.2 Insufficient unit test coverage (Informational)
*SIP-60*

#### Description

Several functions were found to have insufficient unit test coverage. Well written unit tests aid in independently testing certain functionality in order to confirm the existence of functional bugs. The following code was found to have insufficient unit test coverage:

- `BaseRewardEscrowV2.getVestingSchedules()` unit tests did not cover cases for:
   - `pageSize = 0`
   - `index + pageSize` overflows
   - `pageSize > n`, where `n` is the number of entries

- `RewardEscrowV2` did not sufficiently test the following functions:
   - `importVestingSchedule()`
   - `migrateAccountEscrowBalances()`
   - `burnForMigration()`

#### Recommendation

It is recommended to extend the test suite to cover the cases mentioned, as well as any further cases identified.

### 5.4.3 Unsafe arithmetic used (Informational)
*SIP-60: [getVestingSchedules()](https://github.com/Synthetixio/synthetix/blob/ca4fe87b70c4172cdcc9e72c6944707e36c174fd/contracts/BaseRewardEscrowV2.sol#L131), [_timeSinceLastVested()](https://github.com/Synthetixio/synthetix/blob/ca4fe87b70c4172cdcc9e72c6944707e36c174fd/contracts/BaseRewardEscrowV2.sol#L278)*

#### Description

The `getVestingSchedules()` and `_timeSinceLastVested()` functions made use of potentially unsafe mathematical operators. In particular, it was possible for the `_timeSinceLastVested()` function to underflow during the usual user flow if the `lastVestingTimeStamp` was greater than the `_entry.endTime`.  

#### Recommendation

It is recommended that the SafeMath library be used to protect against potential issues. As reverts from view functions are generally avoided, it is further recommended to cap the `lastVestedTimestamp` to be at most the `_entry.endTime`.

##### Update

The `_timeSinceLastVested()` function was removed in [7869df7](https://github.com/Synthetixio/synthetix/commit/7869df763e020ab94ed5b9d9ddecf8ad2889ae45#diff-546b9858ccf5a0c8256113951fc95d2bcd364070c0a9400d513dec85465b78aaL281).

### 5.4.4 Design comments

#### Inconsistent length of accountVestingEntryIDs after merging
*SIP-60: [BaseRewardEscrowV2.sol#L384](https://github.com/Synthetixio/synthetix/blob/ca4fe87b70c4172cdcc9e72c6944707e36c174fd/contracts/BaseRewardEscrowV2.sol#L384)*

The `accountVestingEntryIds` mapping kept track of which `entryIds` a user had, with each `entryId` corresponding to an vesting entry. However, after account merging, the corresponding `entryIds` were not removed from the user's `accountVestingEntryIds` entry. While there was no associated risk to having additional `entryIds` corresponding to empty vesting entries, it may be an issue from a UI/UX perspective.

#### Refactoring suggestions
*SIP-60*

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

* [BaseRewardEscrowV2.sol#L230](https://github.com/Synthetixio/synthetix/blob/dde7b8005506dbd09beab12307677e4fd3a7865e/contracts/BaseRewardEscrowV2.sol#L230): Update the comparison to `>=` to match the comment on the line above, or update the comment to match the comparison.
* [BaseRewardEscrowV2.sol#L226](https://github.com/Synthetixio/synthetix/blob/dde7b8005506dbd09beab12307677e4fd3a7865e/contracts/BaseRewardEscrowV2.sol#L226): Move the `_claimableAmount` function to the view functions section
* [BaseRewardEscrowV2.sol](https://github.com/Synthetixio/synthetix/blob/dde7b8005506dbd09beab12307677e4fd3a7865e/contracts/BaseRewardEscrowV2.sol): Two structs, `VestingEntry` and `VestingEntryWithID`, were used. All uses of `VestingEntry` can be replaced by `VestingEntryWithID`.

### Additional comment suggestion
*SIP-102:  [SynthethixBridgeToOptimism.sol#L30](https://github.com/Synthetixio/synthetix/blob/dde7b8005506dbd09beab12307677e4fd3a7865e/contracts/SynthetixBridgeToOptimism.sol#L30)*

Code comments detailing how the `MAX_ENTRIES_MIGRATED_PER_MESSAGE` constant value was determined would provide useful context.

#### Fix spelling and grammar errors
*SIP-60*

Spelling and grammar 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.

* [RewardEscrowV2.sol#L114](https://github.com/Synthetixio/synthetix/blob/dde7b8005506dbd09beab12307677e4fd3a7865e/contracts/RewardEscrowV2.sol#L114): "past" in the comment should be "passed".

## 5.5 Closed

### 5.5.1 Potential out-of-bounds access (Medium risk)
*SIP-60: [RewardEscrowV2.sol#L90-L111](https://github.com/Synthetixio/synthetix/blob/9399fc7d347f1437acf07bbd43241a305a193bc5/contracts/RewardEscrowV2.sol#L90-L111)*

#### Description

The unbounded `for` loop in the `migrateVestingSchedule()` function was found to revert in the case that it was called by a user with more than 1,000 SNX and fewer than 53 escrow entries, as it would attempt to access an out-of-bounds element. This would prevent the user from being able to migrate to the new reward escrow.

#### Recommendation

iosiro suggested the following code to simplify the `for` loop:

```solidity
for (uint i = 1; i <= numEntries; i++) {
   uint[2] memory vestingSchedule = oldRewardEscrow().getVestingScheduleEntry(addressToMigrate, numEntries - i);

   uint time = vestingSchedule[TIME_INDEX];
   uint amount = vestingSchedule[QUANTITY_INDEX];

   /* The list is sorted, when we reach the first entry that can be vested stop */
   if (time < block.timestamp) {
       break;
   }

   /* import vesting entry */
   _importVestingEntry(
       addressToMigrate,
       VestingEntries.VestingEntry({endTime: uint64(time), escrowAmount: amount})
   );

   /* subtract amount from totalBalancePendingMigration - reverts if insufficient */
   totalBalancePendingMigration[addressToMigrate] = totalBalancePendingMigration[addressToMigrate].sub(amount);
}
```

#### Update

Implemented in [3109718](https://github.com/Synthetixio/synthetix/commit/310971833c18a42add3fe4ca9b8e6c55fb89b8eb#diff-bf475697e393c53bf84225364071a9569d0a235d1012d18f3dc229b0c0e39791R89-R108).

### 5.5.2 Accounts can merge with themselves (Low risk)
*SIP-60: [BaseRewardEscrowV2.sol#L365](https://github.com/Synthetixio/synthetix/blob/ca4fe87b70c4172cdcc9e72c6944707e36c174fd/contracts/BaseRewardEscrowV2.sol#L365)*

#### Description

The account merging functionality allowed users to merge an account with itself. This would delete all vesting schedule entries for the account, resulting in the loss of escrowed funds.

#### Recommendation

It is recommended to disallow a user to merge with themselves to prevent accidental deletion of their vesting entries. A require statement should be added to `nominateAccountToMerge` which validates that `msg.sender` has not been supplied as the `account` parameter.

#### Update

Fixed in [8c94f4a](https://github.com/Synthetixio/synthetix/commit/8c94f4af433b7a175da460b4d66694932777bba1#diff-546b9858ccf5a0c8256113951fc95d2bcd364070c0a9400d513dec85465b78aaR362)

### 5.5.3 Partial liquidation increases reward emission rate (Low risk)
*SIP-60: [BaseRewardEscrowV2.sol#L430](https://github.com/Synthetixio/synthetix/blob/59c580ba56698fc03cf8b90b7b22df3ea8c26154/contracts/BaseRewardEscrowV2.sol#L430)*

#### Description

When a user's escrowed SNX were partially liquidated, a portion of the remaining amount of last escrow entry gets removed from the delinquent and allocated to the liquidator. In both entries, the remaining escrow parameters, such as the escrow amount and duration, remained the same. As the emission rate was based on the escrowed amount, both accounts would retain the original rate of emission, which would increase the overall rate of emission. In particular, this could theoretically be exploited by a user to liquidate themselves to vest their tokens faster.

#### Recommendation

Following a partial liquidation, it is recommended to reset the escrow duration of both entries for the delinquent and liquidator to ensure that the remaining amount will be fully emitted by the original duration.

##### Update

Escrow liquidation functionality was removed in [76fd6b8](https://github.com/Synthetixio/synthetix/commit/76fd6b8684491b947c5cf954622ba8405d51baa1#diff-546b9858ccf5a0c8256113951fc95d2bcd364070c0a9400d513dec85465b78aaL406).

### 5.5.4 Accounts can liquidate themselves (Low risk)
*SIP-60: [BaseRewardEscrowV2.sol#L406](https://github.com/Synthetixio/synthetix/blob/59c580ba56698fc03cf8b90b7b22df3ea8c26154/contracts/BaseRewardEscrowV2.sol#L406)*

#### Description

It was possible for accounts to liquidate their own escrow entries if they were under-collateralized. If the amount liquidated was more than the amount from one vesting entry, the liquidated entry would get deleted from the user.

#### Recommendation

It is recommended to disallow a user to liquidate themselves to prevent accidental deletion of their vesting entries. A require statement should be added to the `Issuer.liquidateEscrowedSNX()` function to ensure that the liquidator and the delinquent are not the same.

##### Update

Escrow liquidation functionality  was removed in [76fd6b8](https://github.com/Synthetixio/synthetix/commit/76fd6b8684491b947c5cf954622ba8405d51baa1#diff-546b9858ccf5a0c8256113951fc95d2bcd364070c0a9400d513dec85465b78aaL406).

### 5.5.5 `getVestingSchedules(...)` did not include the lastVested timestamp (Informational)
*SIP-60: [BaseRewardEscrowV2.sol#L158](https://github.com/Synthetixio/synthetix/blob/ca4fe87b70c4172cdcc9e72c6944707e36c174fd/contracts/BaseRewardEscrowV2.sol#L158)*

#### Description

The `getVestingSchedules()` did not include the `lastVested` timestamp in any of the `VestingEntries` returned. As rewards are streamed continuously, this information may be useful for a user to determine whether it would be worthwhile to vest their entries compared to the current gas costs.

#### Recommendation

It is recommended to include the `lastVested` timestamp with `lastVested: entry.lastVested`.

##### Update

As continuous reward streaming functionality was removed, the `lastedVested` timestamp was no longer required and subsequently removed in [7869df7](https://github.com/Synthetixio/synthetix/commit/7869df763e020ab94ed5b9d9ddecf8ad2889ae45#diff-546b9858ccf5a0c8256113951fc95d2bcd364070c0a9400d513dec85465b78aaL478).

### 5.5.6 Hard-coded constant used (Informational)
*SIP-102: [SynthetixBridgeToOptimism.sol#L121](https://github.com/Synthetixio/synthetix/blob/48eaabc624045b051c86469761ff92f650f187fc/contracts/SynthetixBridgeToOptimism.sol#L121)*

#### Description

The `depositAndMigrateEscrow()` function made use of a hard-coded constant for the `gasLimit` when relaying a message to L2. This constant may sufficient for use in the current version of the contract, but may not be in future versions.

#### Recommendation

As gas limits may change in the future, it is recommended to make use of the `getCrossDomainMessageGasLimit()` `SystemSettings` mixin to dynamically fetch the current gas limit.

##### Update

Implemented in [48b026e](https://github.com/Synthetixio/synthetix/commit/48b026ed5e2e27fad696344f2474863aad30e062#diff-6a6f59dccbfaec9aaf214451e44e01a329a3da06f642a8d11581b26d8943035eR124).

### 5.5.7 Design comments (Informational)

#### Fix spelling and grammar errors
*SIP-60*

Spelling and grammar 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.

* [BaseRewardEscrowV2.sol#L287](https://github.com/Synthetixio/synthetix/blob/ca4fe87b70c4172cdcc9e72c6944707e36c174fd/contracts/BaseRewardEscrowV2.sol#L287): Extra "given" in comment

##### Update

* Fixed in [bbe6cdb](https://github.com/Synthetixio/synthetix/commit/bbe6cdbea95ead8ea1f4270cdc5433ed968e3a96#diff-546b9858ccf5a0c8256113951fc95d2bcd364070c0a9400d513dec85465b78aaR236)

Secure your system.
Request a service
Start Now