Synthetix Suhail Release Smart Contract Audit

# 1. Introduction
iosiro was commissioned by [Synthetix]( to conduct a smart contract audit of their Suhail Release, which included [SIP-267](

The audit of SIP-267 was performed from 12 August to 14 August 2022 by two auditors, followed by a retest that was performed between 19 October and 20 October 2022.

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 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 Suhail release.  

[SIP-267]( introduces functionality that allows the Spartan Council to override the exchange parameters for specific integration partners.

Throughout the audit, issues were encountered that prevented all the unit tests from succeeding and were repeatedly raised as a medium risk. Fortunately, the unit tests were fixed on the final commit of the audit. An alternative testing framework was provided by the Synthetix team to test the functionality during the audit, which was very comprehensive and of great assistance.

Two low-risk issues relating to the configuration of the exchange parameters for integration partners were raised. In particular, the ability to censor specific addresses was highlighted. The recommendations for these issues were not implemented as it was deemed that the Spartan Council's oversight of all exchange parameters effectively mitigates the risks. Various informational issues related to gas optimizations and code design were also reported. The team implemented most of the recommendations provided. A few issues remain open but were adequately addressed by the team and noted as potential future improvements.

The code was found to conform to the specification provided.

<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.2 Synthetix SIP-267 smart contracts
**Project Name:** Synthetix<br/>
**Initial commit:** [6c70f4a7](<br/>
**Final commit:** [3f0d4bd](<br/>
**Files:** DirectIntegrationManager.sol, ExchangeRates.sol, ExchangeRatesWithDexPricing.sol, ExchangeSettlementLib.sol, Exchanger.sol, ExchangerWithFeeRecAlternatives.sol, Issuer.sol, MixinSystemSettings.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 test environment, both manually and through the test suite provided. Manual analysis was used to confirm that the code was functional and to identify security issues that could be exploited.

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

## 4.1 SIP-267

The specification of SIP-267 was based on commit hash [eb4051df](

<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 identified during the audit were present at the conclusion of the audit.

## 5.2 Medium risk

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

## 5.3 Low risk

### 5.3.1 Direct Integration can be abused to censor specific addresses


#### Description

A specific address can be censored by suspending the integration for that address. Any attempts to call `exchange()` or `exchangeAtomically()` from a suspended address will revert.

Furthermore, it would be possible to censor a specific address by setting the `ParameterIntegrationSettings` so that any attempt to exchange will revert. As an example, setting the dynamic fee rounds to `type(uint).max` will result in an out-of-gas error.

#### Recommendation

Suspended integrations should default to the system default parameters. It is understood that it might be undesirable to introduce a dependency on `SystemStatus` in `DirectIntegrationManager`. Thus, an alternative would be to check the state in `Exchanger::_exchangeSettings()` and default to `address(0)` if the integration is suspended. This approach should be censorship resistant as `DirectIntegrationManager` prevents overriding parameters for `address(0)`.

Furthermore, by implementing validations on `ParameterIntegrationSettings` as discussed in "No validation of `ParameterIntegrationSettings`", the censorship risk can be reduced.

#### Update

The team accepted the risk, as all Direct Integration parameters will be governed by the Spartan Council and that each Direct Integration will require a separate Synthetix Improvement Proposal (SIP) as documented in [SIP-267](

### 5.3.2 No validation of `ParameterIntegrationSettings`


#### Description

The `DirectIntegrationManager` does not validate the `ParameterIntegrationSettings` in the same manner as `SystemSettingsLib` for exchange parameters. Consequently, it is possible to set the parameters to dangerous or incompatible values.

#### Recommendation
If all the validations in SystemSettingsLib were to be refactored to internal pure library functions, the same validations could be used in `DirectIntegrationManager`. Ideally, these functions would be in a standalone library and be imported by SystemSettingsLib and `DirectIntegrationManager`.
The code snippet below illustrates the concept while keeping the logic in `SystemSettingsLib`:

diff --git a/contracts/DirectIntegrationManager.sol b/contracts/DirectIntegrationManager.sol
index 7c1d13c3..e2f08bf2 100644
--- a/contracts/DirectIntegrationManager.sol
+++ b/contracts/DirectIntegrationManager.sol
@@ -6,6 +6,7 @@ import "./Owned.sol";
import "./MixinResolver.sol";
import "./MixinSystemSettings.sol";
import "./interfaces/IDirectIntegrationManager.sol";
+import "./SystemSettingsLib.sol";

 * SIP-267: Direct Integration
@@ -118,6 +119,8 @@ contract DirectIntegrationManager is Owned, MixinSystemSettings, IDirectIntegrat
    ) internal {
        require(address(integration) != address(0), "Address cannot be 0");

+        if (settings.atomicMaxVolumePerBlock > 0) SystemSettingsLib._validateAtomicMaxVolumePerBlock(settings.atomicMaxVolumePerBlock);
        // TODO: causes `UnimplementedFeatureError`
        _settings[integration][currencyKey] = settings; // overwrites the parameters for a given direct integration
        emit IntegrationParametersSet(integration, currencyKey, settings);
diff --git a/contracts/SystemSettingsLib.sol b/contracts/SystemSettingsLib.sol
index 777e6040..58ca1e0d 100644
--- a/contracts/SystemSettingsLib.sol
+++ b/contracts/SystemSettingsLib.sol
@@ -371,12 +371,16 @@ library SystemSettingsLib {

+    function _validateAtomicMaxVolumePerBlock(uint _maxVolume) internal pure {
+        require(_maxVolume <= MAX_ATOMIC_VOLUME_PER_BLOCK, "Atomic max volume exceed maximum uint192");
+    }
    function setAtomicMaxVolumePerBlock(
        IFlexibleStorage flexibleStorage,
        bytes32 settingName,
        uint _maxVolume
    ) external {
-        require(_maxVolume <= MAX_ATOMIC_VOLUME_PER_BLOCK, "Atomic max volume exceed maximum uint192");
+        _validateAtomicMaxVolumePerBlock(_maxVolume);
        flexibleStorage.setUIntValue(SETTINGS_CONTRACT_NAME, settingName, _maxVolume);

#### Update

The team accepted the risk, as all Direct Integration parameters will be governed by the Spartan Council and that each Direct Integration will require a separate Synthetix Improvement Proposal (SIP) as documented in [SIP-267]( This should provide ample oversight to ensure that the parameters are within sensible ranges and do not expose the system to significant risks.

<!-- No low-risk issues identified during the audit were present at the conclusion of the audit. -->

## 5.4 Informational  

### 5.4.1 Significant gas usage due to repeated SLOADs


#### Description

The manner in which `DirectIntegrationManager::getExchangeParameters()` retrieves the `ParameterIntegrationsSettings` struct results in repeated SLOADs of all the struct members. This is because a storage pointer is used to reference the struct and each struct member is accessed twice for each parameter that is overridden.

ParameterIntegrationSettings storage storedOverrides = _settings[integration][currencyKey];

               storedOverrides.dexPriceAggregator != address(0)
                   ? storedOverrides.dexPriceAggregator


Overall, SIP-267 will increase the gas cost of all exchange functionality, even more significantly for EOAs and protocols that are integration partners. Any gas optimizations that can reduce the cost of transactions should be investigated in order to prevent disincentivizing general users from using the functionality.

#### Recommendation

By using the `memory` keyword, the entire `ParameterIntegrationsSettings` can be loaded from storage only once, reducing the gas cost of the function.

Normally, the use of a `storage` pointer is preferred when accessing only a subset of parameters; however, since all struct members are accessed the benefit of using a storage pointer is diminished.

An overall more efficient approach would be to store a bitmask of the overridden parameters for each integration and revert to using a `storage` pointer, allowing the contract to only access additional storage slots as required.

mask & ATOMIC_EXCHANGE_FEE_RATE_OVERRIDE >= ATOMIC_EXCHANGE_FEE_RATE_OVERRIDE ? storedOverrides.atomicExchangeFeeRate : getAtomicExchangeFeeRate(currencyKey);

A compromise that does not require introducing significant changes to the contract would be to first validate that the `currencyKey` property has been set for any specific integration and only then attempt to load the overridden parameters:

diff --git a/contracts/DirectIntegrationManager.sol b/contracts/DirectIntegrationManager.sol
index 7c1d13c3..0a414115 100644
--- a/contracts/DirectIntegrationManager.sol
+++ b/contracts/DirectIntegrationManager.sol
@@ -46,7 +46,13 @@ contract DirectIntegrationManager is Owned, MixinSystemSettings, IDirectIntegrat
        returns (ParameterIntegrationSettings memory overrides)
-        ParameterIntegrationSettings memory storedOverrides = _settings[integration][currencyKey];
+        // Defaults to all zero values, which will fallback to system settings
+        ParameterIntegrationSettings memory storedOverrides;
+        // Single cold SLOAD if no integration is set
+        if (_settings[integration][currencyKey].currencyKey == currencyKey) {
+            storedOverrides = _settings[integration][currencyKey];
+        }

@@ -117,7 +123,7 @@ contract DirectIntegrationManager is Owned, MixinSystemSettings, IDirectIntegrat
        ParameterIntegrationSettings memory settings
    ) internal {
        require(address(integration) != address(0), "Address cannot be 0");
+        require(currencyKey == settings.currencyKey, "CurrencyKey mismatch");
        // TODO: causes `UnimplementedFeatureError`
        _settings[integration][currencyKey] = settings; // overwrites the parameters for a given direct integration
        emit IntegrationParametersSet(integration, currencyKey, settings);


#### Update

The gas optimization was not implemented as the complexity of the changes required to the testing framework was deemed to outweigh the benefits of the change. Synthetix noted the potential gas improvement and accepted the risk that might be posed by significantly increasing the gas costs.

### 5.4.2 Inconsistent implementations

*[ExchangerWithFeeRecAlternatives.sol#L146](*, *[Exchanger.sol#L288](*

#### Description

The internal function implementation for `ExchangerWithFeeRecAlternatives::_exchangeAtomically()` is inconsistent with other internal functions, as it still accepts `currencyKeys` as function parameters as opposed to the newly introduced `ParameterIntegrationSettings` structs.

To minimize the likelihood of bugs being introduced, the implementation of `exchange()` and `exchangeAtomically()` should not diverge unless necessary.

#### Recommendation

Update the implementation of `_exchangeAtomically()` to adhere to the same coding pattern as other internal functions, specifically that of `_exchange()`.

#### Update

The team attempted to implement the changes as recommended, but encountered stack-too-deep compilation errors. To limit further changes to the codebase, the inconsistencies were noted by the team and deemed as an acceptable risk.

### 5.4.3 Design comments

#### Upgradeability

The `ParameterIntegrationSettings` are kept in the `DirectIntegrationManager` contract's storage and would need to be reconfigured after each redeployment of the contract.
To prevent the `ParameterIntegrationSettings` for integrations from being lost, each integration should be saved in the `params.json` and the `publish` step should reconcile the state and generate the required owner actions for each deployment.
Alternatively, a proxy pattern or `FlexibleStorage` pattern would allow upgradability without the need to reconfigure during deployment.

The team acknowledged the risk but decided to not implement the recommendation before this release as no on-chain changes would be required.

### 5.4.4 Gas optimizations

#### Reuse settings when possible for `usdSettings`

When either `sourceCurrencyKey` or `destinationCurrencyKey` is `sUSD`, reuse the settings for `usdSettings` instead of retrieving the `ParameterIntegrationSettings` again.

IDirectIntegrationManager.ParameterIntegrationSettings memory usdSettings = sourceSettings.currencyKey == sUSD ? sourceSettings : (destinationSettings.currencyKey == sUSD) ? destinationSettings : directIntegrationManager().getExchangeParameters(from, sUSD);

The team acknowledged the issue but decided to not implement the recommendations as the added complexity that the change would introduce outweighed the minimal gas cost benefit.

## 5.5 Closed

### 5.5.1 System status for Direct Integration not enforced (medium risk)


#### Description

The functionality for the Spartan Council to flag an integration as suspended was introduced to the `SystemStatus` contract; however, the status of integration is not validated when exchanging synths. This renders the `SystemStatus` controls ineffectual.

#### Recommendation

When querying the exchange parameters of a specific integration, the status of the integration should be queried. If the integration has been suspended, the system defaults should be returned as if no direction integration has been configured.

#### Update

Checks were added in commit [b94ffd0]( to `Exchanger::exchange` and `ExchangerWithFeeRecAlternatives::_exchangeAtomically()` so that transactions will revert if the integration has been suspended.

### 5.5.2 Code duplication (low risk)


#### Description

The function `deductFeesFromAccount()` is implemented in both `Exchanger` and `ExchangerSettlementLib`. Code duplication increases the likelihood of bugs in the future, as it is possible to overlook the implementations when making modifications.

#### Recommendation

The implementation in `ExchangerSettlementLib` should be reused in `Exchanger`. Since the library function is marked as `internal`, any references within `Exchanger` will be inlined by the compiler. This will result in almost identical bytecode and not introduce an additional `delegatecall` to the library.

#### Update

The code was refactored as per the recommendation in commit [b94ffd](

### 5.5.3 Design comments (informational)

#### Name conventions

The internal functions in `ExchangeSettlementLib` should be prefixed with an underscore.

The recommendations were implemented in commit [7382a8b](

### 5.5.4 Gas optimizations (informational)

#### Introduce internal functions for repeated logic

By using an internal function to query the exchange settings in `Exchanger` and `ExchangerWithFeeRecAlternatives`, the bytecode size of the contracts can be significantly reduced.

function _exchangeSettings(address from, bytes32 currencyKey) internal view returns (IDirectIntegrationManager.ParameterIntegrationSettings memory settings) {
       settings = directIntegrationManager().getExchangeParameters(from, currencyKey);

Internal functions were introduced as per the recommendation in commit [b94ffd](

#### Refactor `ExchangeLib` to minimize the impact on atomic exchanges

Contract size permitting, it would allow for a cleaner separation of concerns to refactor `ExchangerLib` to `ExchangeSettlementLib`, bundling all the settlement-related logic and not arbitrary `Exchanger` functions.

This would keep the gas cost of atomic swaps to a minimum, as interacting with `ExchangerSettlementLib` will no longer be required.

`ExchangerSettlementLib` was introduced in commit [b94ffd]( as per the recommendation.

#### Reuse resolved addresses where possible

This SIP modifies `Exchanger` so that it prefetches required addresses from the `AddressResolver`, but does not always use the prefetched addresses in the following cases:
* `Exchanger::hasWaitingPeriodOrSettlementOwing()` calls both `resolvedAddresses()` and  `exchangeState()`.
* `Exchanger::_exchange()` calls `resolvedAddresses()` and `issuer()`, and `synthetix()`

These optimizations were implemented in commit [b94ffd](

Secure your system.
Request a service
Start Now