Halborn Logo

Lyra Finance


Prepared by:

Halborn Logo

HALBORN

Last Updated 04/25/2024

Date of Engagement by: May 23rd, 2022 - June 15th, 2022

Summary

100% of all REPORTED Findings have been addressed

All findings

9

Critical

0

High

4

Medium

1

Low

1

Informational

3


1. INTRODUCTION

Lyra Finance engaged Halborn to conduct a security audit on their smart contracts beginning on May 23rd, 2022 and ending on June 15th, 2022. The security assessment was scoped to the smart contracts provided to the Halborn team.

2. AUDIT SUMMARY

The team at Halborn was provided three weeks and a half for the engagement and assigned a full-time security engineer to audit the security of the smart contract. The security engineer is a blockchain and smart-contract security expert with advanced penetration testing, smart-contract hacking, and deep knowledge of multiple blockchain protocols.

The purpose of this audit is to:

    • Ensure that smart contract functions operate as intended

    • Identify potential security issues with the smart contracts

In summary, Halborn identified some security risks that were mostly addressed by the Lyra team. The main ones were the following:

    • Update the calculus of pending delta liquidity to achieve a more accurate delta hedging.

    • Revert transactions that try to update collateral in positions with settled boards.

    • Limit the amount of sUSD that liquidity pool can swap to sETH when closing a position.

    • Cap the differences between sETH balance and locked collateral when opening a position.

3. TEST APPROACH & METHODOLOGY

Halborn performed a combination of manual and automated security testing to balance efficiency, timeliness, practicality, and accuracy in regard to the scope of this audit. While manual testing is recommended to uncover flaws in logic, process, and implementation; automated testing techniques help enhance coverage of the solidity code and can quickly identify items that do not follow security best practices. The following phases and associated tools were used throughout the term of the audit:

    • Research into architecture and purpose.

    • Smart contract manual code review and walkthrough.

    • Graphing out functionality and contract logic/connectivity/functions (solgraph)

    • Manual assessment of use and safety for the critical Solidity variables and functions in scope to identify any arithmetic related vulnerability classes.

    • Manual testing by custom scripts.

    • Scanning of solidity files for vulnerabilities, security hotspots or bugs (MythX).

    • Static Analysis of security for scoped contract, and imported functions (Slither).

    • Testnet deployment (Remix IDE).

4. SCOPE

\begin{enumerate} \item Solidity Smart Contracts \begin{enumerate} \item Repository: \href{https://github.com/lyra-finance/lyra-protocol}{lyra-protocol} \item Commit ID: \href{https://github.com/lyra-finance/lyra-protocol/tree/a834eb7b2dc044fc26964072f8e0d3cd414faa61}{a834eb7b2dc044fc26964072f8e0d3cd414faa61} \item Contracts in scope: \begin{enumerate} \item LiquidityPool.sol \item LiquidityTokens.sol \item OptionGreekCache.sol \item OptionMarket.sol \item OptionMarketPricer.sol \item OptionToken.sol \item PoolHedger.sol \item ShortCollateral.sol \item SynthetixAdapter.sol \item Contracts in interfaces, lib and synthetix folders \end{enumerate} \end{enumerate} \end{enumerate}

Out-of-scope: External libraries and financial related attacks.

5. RISK METHODOLOGY

Vulnerabilities or issues observed by Halborn are ranked based on the risk assessment methodology by measuring the LIKELIHOOD of a security incident and the IMPACT should an incident occur. This framework works for communicating the characteristics and impacts of technology vulnerabilities. The quantitative model ensures repeatable and accurate measurement while enabling users to see the underlying vulnerability characteristics that were used to generate the Risk scores. For every vulnerability, a risk level will be calculated on a scale of 5 to 1 with 5 being the highest likelihood or impact.
RISK SCALE - LIKELIHOOD
  • 5 - Almost certain an incident will occur.
  • 4 - High probability of an incident occurring.
  • 3 - Potential of a security incident in the long term.
  • 2 - Low probability of an incident occurring.
  • 1 - Very unlikely issue will cause an incident.
RISK SCALE - IMPACT
  • 5 - May cause devastating and unrecoverable impact or loss.
  • 4 - May cause a significant level of impact or loss.
  • 3 - May cause a partial impact or loss to many.
  • 2 - May cause temporary impact or loss.
  • 1 - May cause minimal or un-noticeable impact.
The risk level is then calculated using a sum of these two values, creating a value of 10 to 1 with 10 being the highest level of security risk.
Critical
High
Medium
Low
Informational
  • 10 - CRITICAL
  • 9 - 8 - HIGH
  • 7 - 6 - MEDIUM
  • 5 - 4 - LOW
  • 3 - 1 - VERY LOW AND INFORMATIONAL

6. SCOPE

Out-of-Scope: New features/implementations after the remediation commit IDs.

7. Assessment Summary & Findings Overview

Critical

0

High

4

Medium

1

Low

1

Informational

3

Impact x Likelihood

HAL-03

HAL-01

HAL-02

HAL-05

HAL-04

HAL-06

HAL-09

HAL-07

HAL-08

Security analysisRisk levelRemediation Date
MISCALCULATION OF PENDING DELTA LIQUIDITY LEADS TO AN INCORRECT HEDGEHighSolved - 06/14/2022
COLLATERAL CAN BE UPDATED IN SETTLED BOARDSHighSolved - 06/20/2022
LIQUIDITY POOL COULD RUN OUT OF SUSD TOKENSHighSolved - 06/14/2022
DIFFERENCES BETWEEN LOCKED COLLATERAL AND SETH BALANCE ARE NOT ADEQUATELY CAPPEDHighPartially Solved
SKEW UPDATE COULD CREATE DATA INCONSISTENCIES WITH GWAV ORACLEMediumRisk Accepted
WITHDRAWALS GET TEMPORARILY BLOCKED WHEN CREATING BOARDSLowSolved - 06/21/2022
INACCURATE VALIDITY CHECKSInformationalAcknowledged
CHANGES CAN BE MADE IN EXPIRED BOARDSInformationalAcknowledged
USING ++I CONSUMES LESS GAS THAN I++ IN LOOPSInformationalSolved - 06/21/2022

8. Findings & Tech Details

8.1 MISCALCULATION OF PENDING DELTA LIQUIDITY LEADS TO AN INCORRECT HEDGE

// High

Description

The _getLiquidity function in the LiquidityPool contract miscalculates the value of pendingDeltaLiquidity when pendingDelta > freeLiquidity.

Consequently, in the aforementioned situation, the liquidity pool cannot be used for withdrawals nor use the available liquidity for delta hedging, as shown in the following comparison table:

Scenario 2 shows that pendingDeltaLiquidity, the amount is used for delta hedging, could be up to 20 instead of just 5. This latter value is the incorrect amount proposed by Scenario 1.

Code Location

LiquidityPool.sol

uint usedQuote = totalOutstandingSettlements + totalQueuedDeposits + lockedCollateral.quote + pendingBaseValue;

uint totalQuote = quoteAsset.balanceOf(address(this));

liquidity.freeLiquidity = totalQuote > (usedQuote + reservedTokenValue)
  ? totalQuote - (usedQuote + reservedTokenValue)
  : 0;

// ensure pendingDelta <= liquidity.freeLiquidity
liquidity.pendingDeltaLiquidity = liquidity.freeLiquidity > pendingDelta ? pendingDelta : liquidity.freeLiquidity;
liquidity.freeLiquidity -= liquidity.pendingDeltaLiquidity;

liquidity.burnableLiquidity = totalQuote > (usedQuote + pendingDelta) ? totalQuote - (usedQuote + pendingDelta) : 0;
Score
Impact: 4
Likelihood: 5
Recommendation

SOLVED: The issue was fixed in commit d8d2e902c6d368313d9e04bec40c21fbf70b870b.

8.2 COLLATERAL CAN BE UPDATED IN SETTLED BOARDS

// High

Description

The _doTrade and addCollateral functions from OptionMarket contract allow updating collateral on positions, even if the board is settled. As a consequence, unexpected situations may happen:

  • The added collateral could be forever stuck in ShortCollateral contract and the liquidity pool would never get it.

  • If the result is not favorable for users once a board is settled, they can reduce their collateral and negatively affect the liquidity of the protocol.

  • Even in some edge scenarios of volatility, the collateral on positions can be reduced to less than expected.

Code Location

addCollateral function will update position's collateral without previously verifying if board is settled:

OptionMarket.sol

function addCollateral(uint positionId, uint amountCollateral) external nonReentrant notGlobalPaused {
  int pendingCollateral = SafeCast.toInt256(amountCollateral);
  OptionType optionType = optionToken.addCollateral(positionId, amountCollateral);
  _routeUserCollateral(optionType, pendingCollateral);
}

\color{black}\color{white}When opening / closing a position, if trade amount is 0, _doTrade function won't verify is board is settled and will return earlier, which allows updating position's collateral:

OptionMarket.sol

// don't engage AMM if only collateral is added/removed
if (trade.amount == 0) {
  if (expectedAmount != 0) {
    revert TradeIterationsHasRemainder(address(this), iterations, expectedAmount, 0, 0);
  }
  return (0, 0, 0, new OptionMarketPricer.TradeResult[](0));
}

if (board.frozen) {
  revert BoardIsFrozen(address(this), board.id);
}
if (board.expiry < block.timestamp) {
    revert BoardExpired(address(this), board.id, board.expiry, block.timestamp);
Score
Impact: 4
Likelihood: 5
Recommendation

SOLVED: The issue was fixed in the following commits:

8.3 LIQUIDITY POOL COULD RUN OUT OF SUSD TOKENS

// High

Description

When closing a position long call, the _maybeExchangeBase function is called with the argument revertBuyOnInsufficientFunds set to false. As a consequence, the liquidity pool will be able to swap sUSD for sETH without limits and could eventually run out of sUSD tokens.

This situation could affect some relevant operations such as withdrawal, premium payment, settlement, etc.

Proof of Concept:

Initial liquidity info for the test:

The attacker opens a long call position of 120 sETH. There is a big difference between lockedCollateral.base and sETH balance because of \vulnref{DIFFERENCES BETWEEN LOCKED COLLATERAL AND SETH BALANCE ARE NOT ADEQUATELY CAPPED}:

Because of the difference, the owner decides to set maxFeePaid = MAX_UINT to enable sETH repurchase.

On the other hand, a user withdraws sUSD from liquidity pool. The image shows liquidity info after withdrawal:

Finally, the attacker closes the 82.6 sETH long call position:

Since the swap is not limited by any parameter, the protocol uses all available sUSD. In the end, the new sUSD balance is almost 0 (0.29037... in the example):

Code Location

LiquidityPool.sol

(uint quoteSpent, uint baseReceived) = synthetixAdapter.exchangeToExactBaseWithLimit(
  exchangeParams,
  address(optionMarket),
  amountBase,
  revertBuyOnInsufficientFunds ? freeLiquidity : type(uint).max
);
emit BasePurchased(quoteSpent, baseReceived);
Score
Impact: 4
Likelihood: 4
Recommendation

SOLVED: The issue was fixed in commit d8d2e902c6d368313d9e04bec40c21fbf70b870b. With the update to the _getLiquidity function in the LiquidityPool contract, this attack vector is not feasible.

8.4 DIFFERENCES BETWEEN LOCKED COLLATERAL AND SETH BALANCE ARE NOT ADEQUATELY CAPPED

// High

Description

The differences between lockedCollateral.base and sETH balance in the liquidity pool are not limited to opening long call positions. These differences could create distorted liquidity values with the following consequences:

  • In some scenarios, the liquidity pool can run out of sUSD, which could affect some operations such as withdrawals, payment of premiums, settlement, etc. See \vulnref{LIQUIDITY POOL COULD RUN OUT OF SUSD TOKENS} for more details.

  • Distorted liquidity values will erroneously affect protocol decisions, for example: more liquidity to withdraw, less amount to hedge, etc. See Proof of Concept below for more details.

Proof of Concept:

Initial situation for the test:

Scenario 1: quoteBaseFeeRate <= maxFeePaid The user opens a long call position of 100 sETH. Due to the swap, sETH balance and lockedCollateral.base have the \underline{same value}:

Scenario 2: quoteBaseFeeRate > maxFeePaid The user opens a long call position 100 sETH. Because there is no swap, \underline{differences} between sETH balance and lockedCollateral.base \underline{will increase}:

Comparative table of liquidity info between both scenarios:

Scenario 2 shows that freeLiquidity and burnableLiquidity have increased, but pendingDeltaLiquidity has decreased.

These distorted liquidity values (compared to Scenario 1) will erroneously affect protocol decisions, e.g: more liquidity to withdraw, less amount to hedge, etc.

Code Location

lockBase function increases the value of lockedCollateral.base and then calls _maybeExchangeBase:

LiquidityPool.sol

function lockBase(
  uint amount,
  SynthetixAdapter.ExchangeParams memory exchangeParams,
  uint freeLiquidity
) external onlyOptionMarket {
  lockedCollateral.base += amount;
  _maybeExchangeBase(exchangeParams, freeLiquidity, true);
  emit BaseLocked(amount, lockedCollateral.base);
}

\color{black}\color{white}_maybeExchangeBase function could return earlier without swapping, which creates a big difference between lockedCollateral.base and sETH balance:

LiquidityPool.sol

} else if (currentBaseBalance < lockedCollateral.base) {
  // Buy base for quote
  uint amountBase = lockedCollateral.base - currentBaseBalance;
  if (exchangeParams.quoteBaseFeeRate > lpParams.maxFeePaid) {
    uint estimatedExchangeCost = synthetixAdapter.estimateExchangeToExactBase(exchangeParams, amountBase);
    if (revertBuyOnInsufficientFunds && estimatedExchangeCost > freeLiquidity) {
      revert InsufficientFreeLiquidityForBaseExchange(
        address(this),
        amountBase,
        estimatedExchangeCost,
        freeLiquidity
      );
    }
    return;
  }
Score
Impact: 3
Likelihood: 5
Recommendation

PARTIALLY SOLVED: Commit d8d2e902c6d368313d9e04bec40c21fbf70b870b partially fixes this security issue by not allowing the liquidity pool to run out of sUSD.

8.5 SKEW UPDATE COULD CREATE DATA INCONSISTENCIES WITH GWAV ORACLE

// Medium

Description

The _addNewStrikeToStrikeCache and _updateStrikeSkew functions of the OptionGreekCache contract update strikeSkewGWAV with the value of a new skew.

If this new skew is outside the gwavSkewFloor / gwavSkewCap range, strikeSkewGWAV will store a capped skew (not the actual value), which feeds the GWAV oracle inconsistent data.

Code Location

OptionGreekCache.sol

function _addNewStrikeToStrikeCache(
  OptionBoardCache storage boardCache,
  uint strikeId,
  uint strikePrice,
  uint skew
) internal {
  // This is only called when a new board or a new strike is added, so exposure values will be 0
  StrikeCache storage strikeCache = strikeCaches[strikeId];
  strikeCache.id = strikeId;
  strikeCache.strikePrice = strikePrice;
  strikeCache.skew = skew;
  strikeCache.boardId = boardCache.id;

  emit StrikeCacheUpdated(strikeCache);

  strikeSkewGWAV[strikeId]._initialize(
    _max(_min(skew, greekCacheParams.gwavSkewCap), greekCacheParams.gwavSkewFloor),
    block.timestamp
  );

OptionGreekCache.sol

function _updateStrikeSkew(
  OptionBoardCache storage boardCache,
  StrikeCache storage strikeCache,
  uint newSkew
) internal {
strikeCache.skew = newSkew;

strikeSkewGWAV[strikeCache.id]._write(
  _max(_min(newSkew, greekCacheParams.gwavSkewCap), greekCacheParams.gwavSkewFloor),
  block.timestamp
);
Score
Impact: 3
Likelihood: 3
Recommendation

\textbf{RISK ACCEPTED:} The Lyra team accepted the risk of this finding and stated that feeding the GWAV oracle with a capped skew value (different from the one cached) in edge cases is intentional behavior of the protocol.

8.6 WITHDRAWALS GET TEMPORARILY BLOCKED WHEN CREATING BOARDS

// Low

Description

When the owner creates a new board, the addBoard function from OptionGreekCache contract is called. This function triggers _updateGlobalLastUpdatedAt, which sets the value of minUpdatedAtPrice to 0.

As a consequence, users will not be able to withdraw from the liquidity pool (processWithdrawalQueue) because _canProcess will always return false until someone explicitly calls the updateBoardCachedGreeks function to update the cache with the actual values.

Code Location

addBoard function triggers _updateGlobalLastUpdatedAt:

OptionGreekCache.sol

boardCache.expiry = board.expiry;
boardCache.iv = board.iv;
boardCache.updatedAt = block.timestamp;
emit BoardCacheUpdated(boardCache);
boardIVGWAV[board.id]._initialize(board.iv, block.timestamp);
emit BoardIvUpdated(boardCache.id, board.iv, globalCache.maxIvVariance);

liveBoards.push(board.id);

for (uint i = 0; i < strikes.length; i++) {
 _addNewStrikeToStrikeCache(boardCache, strikes[i].id, strikes[i].strikePrice, strikes[i].skew);
}

_updateGlobalLastUpdatedAt();

\color{black}\color{white}_updateGlobalLastUpdatedAt function sets minUpdatedAtPrice to 0:

OptionGreekCache.sol

for (uint i = 1; i < liveBoards.length; i++) {
 boardCache = boardCaches[liveBoards[i]];
 if (boardCache.updatedAt < minUpdatedAt) {
   minUpdatedAt = boardCache.updatedAt;
 }
 if (boardCache.updatedAtPrice < minUpdatedAtPrice) {
   minUpdatedAtPrice = boardCache.updatedAtPrice;
 }
 if (boardCache.updatedAtPrice > maxUpdatedAtPrice) {
   maxUpdatedAtPrice = boardCache.updatedAtPrice;
 }
 if (boardCache.maxSkewVariance > maxSkewVariance) {
   maxSkewVariance = boardCache.maxSkewVariance;
 }
 if (boardCache.ivVariance > maxIvVariance) {
   maxIvVariance = boardCache.ivVariance;
 }
}

globalCache.minUpdatedAt = minUpdatedAt;
globalCache.minUpdatedAtPrice = minUpdatedAtPrice;
Score
Impact: 2
Likelihood: 3
Recommendation

SOLVED: The issue was fixed in commit 1e04d54b12c4faf0378b54b67f93d5de2b7c6e68.

8.7 INACCURATE VALIDITY CHECKS

// Informational

Description

The updateCacheAndGetTradeResult function in the OptionMarketPricer contract contains the following inaccurate validity checks:

  • newSkew includes min / max values in its validity check. As a consequence, the function will revert incorrectly when dealing with edge values.

  • pricing.callDelta does not include min / max values in its validity check. As a consequence, the function will not revert when dealing with edge values, as it should.

This issue is categorized as informational because it could cause the aforementioned function to not work as expected in edge cases.

Code Location

OptionMarketPricer.sol

// If it is a force close and skew ends up outside the "abs min/max" thresholds
if (
  trade.tradeDirection != OptionMarket.TradeDirection.LIQUIDATE &&
  (newSkew <= tradeLimitParams.absMinSkew || newSkew >= tradeLimitParams.absMaxSkew)
) {
   revert ForceCloseSkewOutOfRange(

OptionMarketPricer.sol

// delta must fall BELOW the min or ABOVE the max to allow for force closes
if (
  pricing.callDelta > tradeLimitParams.minForceCloseDelta &&
  pricing.callDelta < (int(DecimalMath.UNIT) - tradeLimitParams.minForceCloseDelta)
) {
   revert ForceCloseDeltaOutOfRange(
Score
Impact: 1
Likelihood: 2
Recommendation

\textbf{ACKNOWLEDGED:} The Lyra team acknowledged this finding.

8.8 CHANGES CAN BE MADE IN EXPIRED BOARDS

// Informational

Description

The following operations in OptionMarket contract affect boards, even if they are already expired:

  • Base IV can be set on an expired board
  • Skew can be set on a strike from an expired board
  • Strikes can be added on an expired board

It is worth noting that this issue is classified as informational because it does not affect the settlement process, but could cause the owner to spend more gas unnecessarily if they mistakenly interact with an expired board.

Code Location

OptionMarket.sol

function setBoardBaseIv(uint boardId, uint baseIv) external onlyOwner {
  OptionBoard storage board = optionBoards[boardId];
  if (board.id != boardId) {
   revert InvalidBoardId(address(this), boardId);
  }
  if (baseIv == 0) {
   revert ExpectedNonZeroValue(address(this), NonZeroValues.BASE_IV);
  }
  if (!board.frozen) {
   revert BoardNotFrozen(address(this), boardId);
  }

  board.iv = baseIv;
  greekCache.setBoardIv(boardId, baseIv);
  emit BoardBaseIvSet(boardId, baseIv);

OptionMarket.sol

function setStrikeSkew(uint strikeId, uint skew) external onlyOwner {
  Strike storage strike = strikes[strikeId];
  if (strike.id != strikeId) {
   revert InvalidStrikeId(address(this), strikeId);
  }
  if (skew == 0) {
   revert ExpectedNonZeroValue(address(this), NonZeroValues.SKEW);
  }

  OptionBoard memory board = optionBoards[strike.boardId];
  if (!board.frozen) {
   revert BoardNotFrozen(address(this), board.id);
  }

  strike.skew = skew;
  greekCache.setStrikeSkew(strikeId, skew);
  emit StrikeSkewSet(strikeId, skew);
} 

OptionMarket.sol

function addStrikeToBoard(
  uint boardId,
  uint strikePrice,
  uint skew
) external onlyOwner {
  OptionBoard storage board = optionBoards[boardId];
  if (board.id != boardId) revert InvalidBoardId(address(this), boardId);
  Strike memory strike = _addStrikeToBoard(board, strikePrice, skew);
  greekCache.addStrikeToBoard(boardId, strike.id, strikePrice, skew);
}
Score
Impact: 1
Likelihood: 2
Recommendation

\textbf{ACKNOWLEDGED:} The Lyra team acknowledged this finding.

8.9 USING ++I CONSUMES LESS GAS THAN I++ IN LOOPS

// Informational

Description

In the following loops, the i variable is incremented using i++. It is known that, in loops, using ++i costs less gas per iteration than i++.

Proof of Concept:

For example, based on the following test contract:

Test.sol

//SPDX-License-Identifier: MIT
pragma solidity 0.8.9;

contract test {
    function postiincrement(uint256 iterations) public {
        for (uint256 i = 0; i < iterations; i++) {
        }
    }
    function preiincrement(uint256 iterations) public {
        for (uint256 i = 0; i < iterations; ++i) {
        }
    }
}

We can see the difference in the gas costs:

Code Location

LiquidityPool.sol

function processDepositQueue(uint limit) external nonReentrant {
    (uint tokenPrice, bool stale, ) = _getTokenPriceAndStale();

    for (uint i = 0; i < limit; i++) {
      QueuedDeposit storage current = queuedDeposits[queuedDepositHead];
      if (!_canProcess(current.depositInitiatedTime, lpParams.depositDelay, stale, queuedDepositHead)) {
        return;
      }

LiquidityPool.sol

function processWithdrawalQueue(uint limit) external nonReentrant {
    for (uint i = 0; i < limit; i++) {
      (uint totalTokensBurnable, uint tokenPriceWithFee, bool stale) = _getTotalBurnableTokens();

Other resources affected

 GWAV: L#136
 OptionGreekCache: L#332, 348, 352, 726, 816, 878, 913, 922, 1000
 OptionMarket: L#236, 393, 415, 458, 744, 972, 1009
 OptionToken: L#300, 509, 591, 605, 616
 ShortCollateral: L#172
Score
Impact: 1
Likelihood: 1
Recommendation

SOLVED: The issue was fixed in commit 1e04d54b12c4faf0378b54b67f93d5de2b7c6e68.

Halborn strongly recommends conducting a follow-up assessment of the project either within six months or immediately following any material changes to the codebase, whichever comes first. This approach is crucial for maintaining the project’s integrity and addressing potential vulnerabilities introduced by code modifications.

© Halborn 2024. All rights reserved.