Reach out for an audit or to learn more about Macro
or Message on Telegram

Synthetix 2

Security Audit

March 2, 2023

Version 1.0.0

Presented by 0xMacro

Table of Contents

Introduction

This document includes the results of the security audit for Synthetix's smart contract code as found in the section titled ‘Source Code’. The security audit was performed by the Macro security team from January 16, 2023 to January 20, 2023. This was the first of two audits conducted on this codebase and is only a partial audit. The second audit (Synthetix-3) completed the security review for this code.

The purpose of this audit is to review the source code of certain Synthetix Solidity contracts, and provide feedback on the design, architecture, and quality of the source code with an emphasis on validating the correctness and security of the software in its entirety.

Disclaimer: While Macro’s review is comprehensive and has surfaced some changes that should be made to the source code, this audit should not solely be relied upon for security, as no single audit is guaranteed to catch all possible bugs.

Overall Assessment

The following is an aggregation of issues found by the Macro Audit team:

Severity Count Acknowledged Won't Do Addressed
High 3 1 - 2
Code Quality 2 - 1 1

Synthetix was quick to respond to these issues.

Specification

Our understanding of the specification was based on the following sources:

Source Code

The following source code was reviewed during the audit:

Specifically, we audited the following contracts within this repository:

Contract SHA256
contracts/interfaces/INodeModule.sol

470c9a673e41410942ac635498a08d3380c5bd58dfedb837cc0ca60df8576bcc

contracts/interfaces/external/IAggregatorV3Interface.sol

61072bab51528b359469216b6e2e796b26ee5dfb2c98d42f11ad7c28b8d40f4d

contracts/interfaces/external/IExternalNode.sol

bacfcb0985ef0663ed3ed35d7324656a5052236f3b863509c2898b57a7836d58

contracts/interfaces/external/IPyth.sol

e4ab2523344992abc898804ab19977e3e497df06c2bbd4d0b218c96331c46327

contracts/interfaces/external/IUniswapV3Pool.sol

ad6c2aba518ed28b0551e227ae358ede6b277b8cfe64887575945ec4534b4f45

contracts/modules/CoreModule.sol

8d2cfd12070ef36fa904413e20ee91aff0965566a7b84e4970492c1aafde6261

contracts/modules/NodeModule.sol

4ed9bb2a327cf6f9b3b627667b0a08fbd50c9f88f7bfe91ff707fdb67edd924d

contracts/nodes/ChainlinkNode.sol

701135b8c2ec4e7b34698a833ba29627a36c13149845429dc749ffff20303db2

contracts/nodes/ExternalNode.sol

fca0f52c66ff865c255cf46c8433582d39e13fdd7a801a606c70812b5aec23e2

contracts/nodes/ExternalNodeUniswap.sol

536f7139e4c35d123e06b6ef52be24bed6bfcf22fb5dce2e03cbf05dd82c74d3

contracts/nodes/PriceDeviationCircuitBreakerNode.sol

3b833e63b9f47098fdbc4101891b1e9fc7d4bab935c017db51c52fcce5e2a733

contracts/nodes/PythNode.sol

0ccca72bfa65723a47ffe5c03375bd572baf18ff426c5b66376e7df5412680a4

contracts/nodes/ReducerNode.sol

357651c9648e54bf2a43db1f547b770db98817c9b98a8a53b8505030900ba65a

contracts/nodes/StalenessCircuitBreakerNode.sol

1a8fe93cc0ff138df2c4b294b3368f39056a61ff1102283216aa14e72f6e219c

contracts/nodes/UniswapNode.sol

6f8a3a7aaf8d838dcb41b4c5a7153c87f97bd09c728e021cb932ecc45c59a08a

contracts/storage/NodeDefinition.sol

bc313417146b18b3e20b5265c9d1cba541199974cd2f5ebe87586b63c20da6ce

contracts/storage/NodeOutput.sol

e345d3d84c43429822fc9d0cdf90de3e6044985355b3f2c4b2d13d9bb34da0ce

contracts/utils/FullMath.sol

115a0473ef75cbad65de51cd67b2023c64096d5e81633fb9eab8edf28bcac593

contracts/utils/TickMath.sol

668a30ffa50b2d569f4cb2ec971938bb6dbceb34ecec9ca4a7accf8e13e3bec2

Note: This document contains an audit solely of the Solidity contracts listed above. Specifically, the audit pertains only to the contracts themselves, and does not pertain to any other programs or scripts, including deployment scripts.

Issue Descriptions and Recommendations

Click on an issue to jump to it, or scroll down to see them all.

Security Level Reference

We quantify issues in three parts:

  1. The high/medium/low/spec-breaking impact of the issue:
    • How bad things can get (for a vulnerability)
    • The significance of an improvement (for a code quality issue)
    • The amount of gas saved (for a gas optimization)
  2. The high/medium/low likelihood of the issue:
    • How likely is the issue to occur (for a vulnerability)
  3. The overall critical/high/medium/low severity of the issue.

This third part – the severity level – is a summary of how much consideration the client should give to fixing the issue. We assign severity according to the table of guidelines below:

Severity Description
(C-x)
Critical

We recommend the client must fix the issue, no matter what, because not fixing would mean significant funds/assets WILL be lost.

(H-x)
High

We recommend the client must address the issue, no matter what, because not fixing would be very bad, or some funds/assets will be lost, or the code’s behavior is against the provided spec.

(M-x)
Medium

We recommend the client to seriously consider fixing the issue, as the implications of not fixing the issue are severe enough to impact the project significantly, albiet not in an existential manner.

(L-x)
Low

The risk is small, unlikely, or may not relevant to the project in a meaningful way.

Whether or not the project wants to develop a fix is up to the goals and needs of the project.

(Q-x)
Code Quality

The issue identified does not pose any obvious risk, but fixing could improve overall code quality, on-chain composability, developer ergonomics, or even certain aspects of protocol design.

(I-x)
Informational

Warnings and things to keep in mind when operating the protocol. No immediate action required.

(G-x)
Gas Optimizations

The presented optimization suggestion would save an amount of gas significant enough, in our opinion, to be worth the development cost of implementing it.

Issue Details

H-1

UniswapNode does not handle scaling correctly

Topic
Spec
Status
Impact
High
Likelihood
High

All nodes are supposed to return prices denominated in USD with 18 decimal places. Currently, the Uniswap node is not doing so. The issue arises from the decimal places of the underlying ERC20 tokens not being used to determine how to scale.

For example, consider the following tokens on Ethereum and their used decimals:

  • WBTC uses 8 decimal places
  • WETH uses 18 decimal places
  • USDC uses 6 decimal places
  • DAI uses 18 decimal places

The current market price for ETH/USD is about 1559494200000000000000 with 18 decimal places. With testing on a fork of mainnet, the current UniswapNode returns the following prices:

  • ETH/USDC = 0
  • ETH/DAI = 1555002674

The current market price for BTC/USD is about 21118320000000000000000 with 18 decimal places. Testing with the same setup, the UniswapNode returns the following prices:

  • BTC/USDC = 210678334
  • BTC/DAI= 210046722485431108603

Note that none of the returned prices are correct in scale.

The UniswapNode's code is wrong in its hardcoded use of 1e6 as the base amount in the call to getQuoteAtTick():

if (tickCumulativesDelta < 0 && (tickCumulativesDelta % secondsAgo.to256().toInt() != 0)) {
            tick--;
        }

int256 price = getQuoteAtTick(tick, 1e6, token0, token1).toInt();

return NodeOutput.Data(price, 0, 0, 0);

Instead, this base amount value should take into account (1) the desired scale of 18 decimals, (2) the decimals used in token0, and (3) the decimals used in token1. The formula for the scaled base amount could look something like this: 10 ** (18 - (token1 decimals - token0 decimals)).

For example, proper scaling occurs for the pairs when the following base amounts are used instead of 1e6:

  • ETH/USDC’s base amount is 1e30 (30 = 18 - (6 - 18)) = 1590707322797356032948
  • ETH/DAI’s base amount is 1e18 (18 = 18 - (18 - 18)) = 1587366312409757218705
  • BTC/USDC’s base amount is 1e20 (20 = 18 - (6 - 8)) = 21341355218589758060905
  • BTC/DAI’s base amount is 1e8 (8 = 18 - (18 - 8)) = 21203037103870610510463

Remediations to Consider:

  • Redoing the scaling logic to account for differences in the target token and stable coin token pairs.

Note: the function getQuoteAtTick() will overflow when larger base amounts are used. Scaling might need to be done post price querying.

H-2

Ethereum/Optimism Pyth prices not currently maintained

Topic
3rd Party Behavior
Status
Acknowledged
Impact
High
Likelihood
High

The Pyth EVM network is a ‘pull’ oracle model instead of a ‘push’ oracle model, meaning, prices are not maintained by Pyth for EVM chains. Rather, they are maintained by users pushing the prices on-chain themselves using this Pyth Repo.

If Synthetix would like to pull EVM prices from Pyth, participating in the Pyth community to pull prices will be necessary, as the current on-chain Pyth prices are very stale.

For example, when querying the Pyth EVM mainnet price IDs:

  • The ETH/USD pair was last updated on December 6th, 2022
  • The BTC/USD pair was last updated on December 6th, 2022
  • Some pairs, like DAI/USD do not return a price at all

Similar issues exist on the Pyth EVM Optimism chain, with the last price update being on December 8th, 2022 for any price.

See Pyth’s Ethereum’s price feed contract activity here and Optimism’s here.

Remediations to Consider:

  • Plan to ‘pull’ prices on-chain for Pyth when you’d like to query them on-chain, or,
  • Do not assume Pyth on Ethereum/Optimism will have useable data.
H-3

PythNode prices are being interpreted incorrectly

Topic
Spec
Status
Impact
High
Likelihood
High

The Pyth network returns prices in a fixed-point numeric interpretation, encoded with a significand and an exponent. See from the docs:

// Both the price and confidence are stored in a fixed-point numeric representation,
// `x * (10^expo)`, where `expo` is the exponent.
struct Price {
    // Price
    int64 price;
    // Confidence interval around the price
    uint64 conf;
    // Price exponent
    int32 expo;
    // Unix timestamp describing when the price was published
    uint publishTime;
}

Currently, the code in PythNode.sol ignores the exponent piece and only uses the significand:

function process(bytes memory parameters) internal view returns (NodeOutput.Data memory) {
        (address pythAddress, bytes32 priceFeedId, bool useEma) = abi.decode(
            parameters,
            (address, bytes32, bool)
        );
        IPyth pyth = IPyth(pythAddress);
        PythStructs.Price memory pythData = useEma
            ? pyth.getEmaPriceUnsafe(priceFeedId)
            : pyth.getPriceUnsafe(priceFeedId);
        return NodeOutput.Data(pythData.price, pythData.publishTime, 0, 0);
    }

This will lead to incorrect price interpretations.

For example, let’s use the latest Pyth data for the ETH-USD pair. The mainnet queried Pyth Struct returns a price at 125537479000, exponent at -8, and publishTime at 1670329551 (which is December 6th 2022). The price of ETH then was about 1271.36 according to Coindesk, which makes sense.

Currently, the code is just returning 125537479000, which is ignoring the exponent piece of data and is not scaled to 10**18.

Remediations to Consider:

  • Using the exponent piece of the return data to interpret the price data correctly, and, scaling the data to 18 decimals as desired.
Q-1

Inconsistent Tolerance Thresholds

Topic
Protocol Design
Status
Quality Impact
Low

The documentation for Price Deviation Circuit Breaker Node states:

The Price Deviation Circuit Breaker Node passes through value of the first parent if the prices between the first two parents are within the deviation tolerance.

and the documentation for Staleness Circuit Breaker states:

The Staleness Circuit Breaker Node passes through the value of the first parent if the timestamp associated with it is within the staleness tolerance.

Although they both say they pass through the value of the first parent if the node’s concern is within the tolerance, they behave differently. The tolerance threshold for the Price Deviation Circuit Breaker Node is inclusive, while the tolerance threshold for the Staleness Circuit Breaker is non-inclusive. The code behavior should match or be better documented to help users know how the code will behave.

Remediations to Consider:

  1. Make the tolerances consistent: inclusive or non-inclusive, and update the docs, or,
  2. Document clearly that the deviation tolerance is inclusive, and the staleness tolerance is non-inclusive.
Q-2

Chainlink Node’s documentation for TWAP implementation is unclear

Topic
Documentation Clarity
Status
Wont Do
Quality Impact
Low

The Chainlink Node’s documentation on the twapTimeInterval states:

The duration (in seconds) of the lookback window for price reports to be incorporated in a time-weighted average price calculation.

From reading this sentence, it is unclear which prices will be included in the lookback window.

For example, if the twapTimeInterval is 35 minutes, and there were updates to the price 10 minutes ago, 25 minutes ago, and 50 minutes ago, it’s unclear if the 50 minutes mark (which was the price at 35 minutes) will be included.

Currently, the node grabs the price 10 minutes ago and 25 minutes ago and not the price at the 35 minute mark to calculate the TWAP. This could be unintuitive to some developers.

Remediations to Consider:

  • Document that the price only includes updates that happened during the window and not the price at the start of the window.
Response by Synthetix

We decided not to address this, because we think that the existing documentation is clear enough.

Disclaimer

Macro makes no warranties, either express, implied, statutory, or otherwise, with respect to the services or deliverables provided in this report, and Macro specifically disclaims all implied warranties of merchantability, fitness for a particular purpose, noninfringement and those arising from a course of dealing, usage or trade with respect thereto, and all such warranties are hereby excluded to the fullest extent permitted by law.

Macro will not be liable for any lost profits, business, contracts, revenue, goodwill, production, anticipated savings, loss of data, or costs of procurement of substitute goods or services or for any claim or demand by any other party. In no event will Macro be liable for consequential, incidental, special, indirect, or exemplary damages arising out of this agreement or any work statement, however caused and (to the fullest extent permitted by law) under any theory of liability (including negligence), even if Macro has been advised of the possibility of such damages.

The scope of this report and review is limited to a review of only the code presented by the Synthetix team and only the source code Macro notes as being within the scope of Macro’s review within this report. This report does not include an audit of the deployment scripts used to deploy the Solidity contracts in the repository corresponding to this audit. Specifically, for the avoidance of doubt, this report does not constitute investment advice, is not intended to be relied upon as investment advice, is not an endorsement of this project or team, and it is not a guarantee as to the absolute security of the project. In this report you may through hypertext or other computer links, gain access to websites operated by persons other than Macro. Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such websites’ owners. You agree that Macro is not responsible for the content or operation of such websites, and that Macro shall have no liability to your or any other person or entity for the use of third party websites. Macro assumes no responsibility for the use of third party software and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software.