Gyroscope
Protocol & Vaults

Gyroscope is a fully backed stablecoin with autonomous price bounding and diversified reserves. We reviewed the core protocol, including the primary market for minting and redeeming, and the Balancer pools used as secondary markets.
report id
0051
category
Token & RWA
language
Solidity
final report
August 17, 2022
lines of code
0
Content

Download audit report

1

Executive Summary

This document presents the results of the security audit performed by Nethermind on the source code for the Gyroscope protocol. Gyroscope is a fully-backed stablecoin with autonomous price bounding and all-weather reserves.

During this audit two repositories were reviewed: protocol and vaults. The vaults repository contains the implementation for three types of Balancer pools that are used as secondary markets for the protocol. The protocol repository contains the implementation of the core components of the protocol, including the Primary Market where Gyroscope token will be minted and redeemed.

The audit consisted of a manual inspection of the code base. Knowledge of the protocol was obtained from papers provided by the Gyroscope team, multiple walkthroughs from the client and public documentation of the protocol.

This document reports multiple findings uncovered during the review process. A total of 38 findings are reported, no critical issue was found. Most of the findings reported are Informational, these are suggestions that may improve code quality. Some of the main issues reported are related to the use of orders in the Motherboard contract, these orders contain all of the vaults over and above the assets included in the operation’s arguments. Other primary issues are due to differences between the PAMM paper and the implementation. In general, the Gyroscope codebase is well written and has an extensive test suite.

Audit assessment
Audit TypeSecurity Review
Initial ReportMay 18, 2022
Response from ClientAug 10, 2022
Final ReportAug 17, 2022
MethodsManual Review, Automated Analysis
RepositoryVaults, Protocol
Commit Hash Vaults79f42be938
Commit Hash Protocol03f74bd5b3
Documentationhttps://docs.gyro.finance/overview/introduction
Total findings
38
Fixed
37
Acknowledged
1
Mitigated
0
Unresolved
0

Findings by severity

  • Critical0
  • High0
  • Medium6
  • Low9
  • Informational23
  • Best Practices0

2

Audited Files

2.1 Vaults Repository

Reviewed Files

FileGit commit hash
contracts/cpmmv-2/Gyro2PoolErrors.sol79f42be9388d4834cee085f327360f5ead2a66ec
contracts/cpmmv-2/GyroTwoMath.sol79f42be9388d4834cee085f327360f5ead2a66ec
contracts/cpmmv-2/GyroTwoOracleMath.sol79f42be9388d4834cee085f327360f5ead2a66ec
contracts/cpmmv-2/GyroTwoPool.sol79f42be9388d4834cee085f327360f5ead2a66ec
contracts/cpmmv-2/GyroTwoPoolFactory.sol79f42be9388d4834cee085f327360f5ead2a66ec
contracts/cpmmv-3/GyroThreeMath.sol79f42be9388d4834cee085f327360f5ead2a66ec
contracts/cpmmv-3/GyroThreePool.sol79f42be9388d4834cee085f327360f5ead2a66ec
contracts/cpmmv-3/GyroThreePoolErrors.sol79f42be9388d4834cee085f327360f5ead2a66ec
contracts/cpmmv-3/GyroThreePoolFactory.sol79f42be9388d4834cee085f327360f5ead2a66ec
contracts/cemm/GyroCEMMMath.sol79f42be9388d4834cee085f327360f5ead2a66ec
contracts/cemm/GyroCEMMOracleMath.sol79f42be9388d4834cee085f327360f5ead2a66ec
contracts/cemm/GyroCEMMPool.sol79f42be9388d4834cee085f327360f5ead2a66ec
contracts/cemm/GyroCEMMPoolErrors.sol79f42be9388d4834cee085f327360f5ead2a66ec
libraries/GyroPoolMath.sol79f42be9388d4834cee085f327360f5ead2a66ec

2.2 Protocol Repository

Reviewed Files

FileGit commit hash
contracts/auth/Governable.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/exchangers/BalancerExchanger.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/exchangers/BalancerPoolRegistry.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/fee_handlers/StaticPercentageFeeHandler.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/FeeBank.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/GydToken.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/GyroConfig.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/LPTokenExchangerRegistry.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/Motherboard.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/oracles/AssetRegistry.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/oracles/balancer/BalancerCEMMPriceOracle.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/oracles/balancer/BalancerCPMMPriceOracle.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/oracles/balancer/BalancerCPMMV2PriceOracle.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/oracles/balancer/BalancerCPMMV3PriceOracle.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/oracles/balancer/BalancerLPSharePricing.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/oracles/balancer/BaseBalancerPriceOracle.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/oracles/BaseChainLinkOracle.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/oracles/BaseVaultPriceOracle.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/oracles/BatchVaultPriceOracle.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/oracles/ChainLinkPriceOracle.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/oracles/CheckedPriceOracle.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/oracles/CrashProtectedChainLinkPriceOracle.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/oracles/TrustedSignerPriceOracle.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/oracles/UniswapV3TwapPriceOracle.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/PrimaryAMMV1.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/Reserve.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/ReserveManager.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/safety/ReserveSafetyManager.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/safety/RootSafetyCheck.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/safety/VaultSafetyMode.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/VaultRegistry.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/vaults/BalancerPoolVault.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
contracts/vaults/BaseVault.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
libraries/DataTypes.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
libraries/Flow.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7
libraries/SignedFixedPoint.sol03f74bd5b3080abf9c684c59458d310ff5fb64d7

3

Summary of Issues

#FindingSeverityUpdate
1Vaults with no fees set would disable minting and redeemingMediumFixed
2getPriceUSD computes the wrong valueMediumFixed
3Price safety for reserves is not correctly verifiedMediumFixed
4Difference between PAMM paper and createDerivedParams functionMediumFixed
5Difference between PAMM paper and isInThirdRegionHigh functionMediumFixed
6Differences between PAMM paper and computeReserveValueRegion functionMediumFixed
7Wrong constant value for Sqrt(1e-17)LowFixed
8Error code duplicatedLowFixed
9_calculateCurrentValues is not always called with upscaled balancesLowFixed
10GyroThreePool.sol allows AssetManagers to be set at constructionLowFixed
11Governance could be lost if wrong address is used in changeGovernorLowFixed
12BPT tokens in BalancerExchanger.sol could be taken by anyoneLowFixed
13deregisterPoolId only deregisters first occurrence of the poolLowFixed
14Disparity between values used in order and values transferred to the reserveLowFixed
15getReserveState can revert without emitting messageLowFixed
16Duplicated code in NewtonSqrt.sol fileInfoFixed
17Non uniform use of term names in commentsInfoFixed
18Division before multiplicationInfoFixed
19Comments are pointing to the wrong sectionInfoFixed
20Comments are not aligned with the codeInfoFixed
21Unused functions in GyroCEEMMath.solInfoFixed
22Typo in commentsInfoFixed
23Comments are not aligned with the codeInfoFixed
24getSqrtParameters can return a tuple of uint256 to save gasInfoFixed
25Duplicated comment in GyroTwoPool.solInfoFixed
26Reduced readability for _onSwapGivenIn and _onSwapGivenOutInfoFixed
27Unused arguments in GyroTwoPool.sol constructorInfoFixed
28Typo in commented equation in GyroTwoMath.solInfoFixed
29Number of operations in _calculateCubicTerms can be reducedInfoAcknowledged
30_calcNewtonDelta has an unused named argumentInfoFixed
31deposit and withdraw do not allow minimum expected amounts to be specifiedInfoFixed
32Use of transferFrom instead of safeTransferFromInfoFixed
33Incorrect casing for variable name in registerPoolId functionInfoFixed
34Unnecessary storage writeInfoFixed
35Defined event is never emitted in VaultSafetyMode.solInfoFixed
36Motherboard.sol can mint tokens directly to msg.sender to save gasInfoFixed
37setInitialPrice can be called multiple times for the same vaultInfoFixed
38Vault metadata is still available after deregistering the VaultInfoFixed

4

System Overview

No system overview is included in this report.

5

Risk Rating Methodology

The risk rating methodology used by Nethermind Security follows the principles established by the OWASP Foundation. The severity of each finding is determined by two factors: Likelihood and Impact.

Likelihood measures how likely the finding is to be uncovered and exploited by an attacker. This factor will be one of the following values:

  1. High: the issue is trivial to exploit and has no specific conditions that need to be met;
  2. Medium: the issue is moderately complex and may have some conditions that need to be met;
  3. Low: the issue is very complex and requires very specific conditions to be met.

When defining the likelihood of a finding, other factors are also considered. These can include but are not limited to motive, opportunity, exploit accessibility, ease of discovery, and ease of exploit.

Impact is a measure of the damage that may be caused if an attacker exploits the finding. This factor will be one of the following values:

  1. High: the issue can cause significant damage, such as loss of funds or the protocol entering an unrecoverable state;
  2. Medium: the issue can cause moderate damage, such as impacts that only affect a small group of users or only a particular part of the protocol;
  3. Low: the issue can cause little to no damage, such as bugs that are easily recoverable or cause unexpected interactions that cause minor inconveniences.

When defining the impact of a finding, other factors are also considered. These can include but are not limited to data and state integrity, loss of availability, financial loss, and reputation damage. After defining the likelihood and impact of an issue, the severity is determined according to the table below.

Impact / LikelihoodLowMediumHigh
HighMediumHighCritical
MediumLowMediumHigh
LowInfo / Best PracticesLowMedium
UndeterminedUndeterminedUndeterminedUndetermined

To address issues that do not fit a High, Medium or Low severity, Nethermind Security also uses three more finding severities: Informational, Best Practices, and Undetermined.

  1. Informational findings do not pose any risk to the application, but they carry some information that the audit team intends to pass to the client formally;
  2. Best Practice findings are used when some piece of code does not conform with smart contract development best practices;
  3. Undetermined findings are used when we cannot predict the impact or likelihood of the issue.

6

Issues

6.1 Vaults with no fees set would disable minting and redeeming

In the contract StaticPercentageFeeHandler.sol the function applyFees will revert if at least one of the vaults in order does not have its fees set. This function is called from the mint and redeem functions in the Motherboard.sol contract, the Order passed as an argument contains all the vaults registered up until the call. If at least one of these vaults does not have registered fees the mint or redeem call will fail. The process for registering a vault does not include any calls to setVaultFees. This increases the possibilities of a vault being registered without any fees being set.

Recommendation

Use default values for fees when registering a vault.

Resolution

Fixed in commit b06eb9fba50a42a3b49d25ba48d3272779063928

6.2 getPriceUSD computes the wrong value

FileFix commitTypeStatus
BaseVaultPriceOracle.sol#12385ea8aMediumFixed

The getPriceUSD function returns the value of a vault token in USD using the value in USD of the underlying token. To compute the price of the vault token, the total value of the pool should be computed, this can be done by multiplying the price of the underlying token by the amount of underlying token in the vault. After computing the total value of the vault, it can be divided by the total amount of vault tokens and the result will be the price of vault tokens in USD. This reasoning can be expressed as pu ∗ tu/tv where pu is the price of the underlying token, tu is the amount of underlying tokens in the vault and tv is the total amount of vault tokens. The exchange rate is defined as totalUnderlying_ divided by totalSupply of the vault, so the value computed by the getPriceUSD function can be expressed as pu/tu/tv which is not equivalent to the previous formula.

Recommendation

Apply the following change on the indicated line

- return poolTokenPriceUSD.divDown(vault.exchangeRate());
+ return poolTokenPriceUSD.mulDown(vault.exchangeRate());

Resolution

Fixed in commit 385ea8a6082eef2622f23f8cb80e8ef1b0ccb7b8

6.3 Price safety for reserves is not correctly verified

FileFix commitTypeStatus
ReserveSafetyManager.sol#L186a504026
e6643a5
MediumFixed

The comments for the function _updateVaultWithPriceSafety state that all prices for non-stable tokens must be bigger than minTokenPrice. The variable vaultMetadata.allTokenPricesLargeEnough stores a boolean indicating if this condition holds. This variable is initialised to false, but is updated to true every time a token with the correct price is analyzed. If there are multiple tokens of which at least one has a price above the minimum token price, then the final value of vaultMetadata allTokenPricesLargeEnough will still be true.

Recommendation

Use the same approach used in _updateMetaDataWithEpsilonStatus: initially set the value of vaultMetadata.allTokenPricesLargeEnough to true, and, if some token has an incorrect price, set it to false.

Resolution

Fixed in commits a504026302737b9c77bc897f91fa46ca72dab365 and e6643a51000513d46c714a5c9b4d2749170fd89e

6.4 Difference between PAMM paper and createDerivedParams function

FileFix commitTypeStatus
PrimaryAMMV1.sol#L22871ae18cMediumFixed

In the PAMM paper, algorithm 1 describes how DerivedParams is computed. This algorithm uses alphaThresholdIIIHL as the alpha argument, but the code in createDerivedParams uses params.alpha.

Recommendation

Review inconsistencies between the paper and the implementation and fix as appropriate.

Resolution

Fixed in commit 71ae18c366b7a455fd4d7521ea612abae592b8b7

6.5 Difference between PAMM paper and isInThirdRegionHigh function

FileFix commitTypeStatus
PrimaryAMMV1.sol#296558739dMediumFixed

In the PAMM paper, algorithm 2 describes how to detect the region. To check if the actual region is Third Region High, the algorithm computes the reserves using xlThresholdIIIHL, but in the implementation xlThresholdIIHL is used.

Recommendation

Review inconsistencies between paper and implementation and fix as appropriate.

Resolution

Fixed in commit 558739d57bf5d290bf8fa388d25946d5eda097ca

6.6 Differences between PAMM paper and computeReserveValueRegion function

FileFix commitTypeStatus
PrimaryAMMV1.sol#321fcdaa3aMediumFixed

In the PAMM paper, algorithm 2 describes how to detect the region. For detecting case I) ii), the condition from the paper is b/y ≤ 1 − ᾱ(x − x̄U), where b corresponds to the program variable reserveValue, y to totalGyroSupply, ᾱ to alphaBar, x to redemptionLvel and x̄U to xuBar. However, the implementation uses redemptionLevel ≤ xlThresholdAtThresholdI.

Recommendation

Review inconsistencies between the paper and the implementation and fix as appropriate.

Resolution

Fixed in commit fcdaa3a112ecbcef6c5c05d8a57de7e3a019f4f2

6.7 Wrong constant value for Sqrt(1e-17)

FileFix commitTypeStatus
GyroPoolMath.sol#L320c23f27LowFixed

SQRT_1E_NEG_17 is missing a 0, sqrt(1e − 17) = 3.16...e − 09 but the number indicated is 3.16...e − 10

Recommendation

- uint256 private constant SQRT_1E_NEG_17 = 316227766;
+ uint256 private constant SQRT_1E_NEG_17 = 3162277660;

Resolution

Constant was incorrect. Fixed in commit 0c23f27724abc5b43a9c43ac5c5a9138cd7ff752.

6.8 Error code duplicated

FileFix commitTypeStatus
GyroCEMMPoolErrors.sol#L27cff42ffLowFixed

The DERIVED_ZETA_WRONG and STRETCHING_FACTOR_WRONG errors share the same Error Code. This could be misleading for users.

Recommendation

Change the error code representing DERIVED_ZETA_WRONG or STRETCHING_FACTOR_-

WRONG.

Resolution

Fixed in commit cff42fff9407223ccb00e2de869c47846d0941c9.

6.9 _calculateCurrentValues is not always called with upscaled balances

FileFix commitTypeStatus
GyroTwoPool.sol#L77
GyroTwoPool.sol#207
7a39ce7LowFixed

calculateCurrentValues and getVirtualParameters call _calculateCurrentValues without upscaling balances. getVirtualParameters gets the balances from the vault and does not upscale these balances before calling _calculate- CurrentValues. calculateCurrentValues is a public function and is not called from inside the contract, it should be documented that balances need to be upscaled.

Recommendation

  • Upscale balances received from the vault in getVirtualParameters before calling _calculateCurrentValues.
  • Document that calculateCurrentValues expects upscaled balances.

Resolution

Fixed in commit 7a39ce7daa5844535e7b69ec0ceae193a4d67258.

6.10 GyroThreePool.sol allows AssetManagers to be set at construction

FileFix commitTypeStatus
GyroThreePool.sol#L58fd83c63LowFixed

GyroThreePool.sol allows AssetManagers to be set, GyroTwoPool.sol does not allow this and the documentation does not specify their use. AssetManagers are used in the Balancer Protocol to invest funds from the pool. If they are going to be used, this should be correctly documented.

Recommendation

  • Set AssetsManagers to zero as done by GyroTwoPool.
  • Document the use cases of these AssetManagers.

Resolution

Fixed in commit fd83c63e3d0871c942de89005d6c62be67b58db3.

6.11 Governance could be lost if wrong address is used in changeGovernor

FileFix commitTypeStatus
Governable.sol#L22adb52bbLowFixed

If changeGovernor is called with a wrong address as an argument, Governance of contracts could be lost.

Recommendation

Use a two step process for changing the governor. First propose the new governor and after that claim the governance with the proposed address.

Resolution

Fixed in commit adb52bb849d6c3b499706f96efddfad86de5f92a.

6.12 BPT tokens in BalancerExchanger.sol could be taken by anyone

FileFix commitTypeStatus
BalancerExchanger.sol#105—LowFixed

Any BPT token in BalancerExchanger.sol can be withdrawn by any user. The withdraw function calls exitPool using its own balance of BPT tokens. This contract should not hold any BPT tokens, but if it holds any, they can be stolen.

Recommendation

We recommend a pull pattern to be used as done in the deposit function, before calling exitPool to transfer BPT tokens from the caller to the contract.

Resolution

Code not used anymore.

6.13 deregisterPoolId only deregisters first occurrence of the pool

FileFix commitTypeStatus
BalancerPoolRegistry.sol#40dfc6784LowFixed

The deregisterPoolId function stops when the first pool with the indicated poolId is found. If a pool was registered more than once, only the first occurrence will be deregistered.

Recommendation

Because of the needs of the registry we would recommend an Enumerable Map like structure be used instead of a bytes32[] for storing the poolIds for a specific token.

Resolution

Fixed in commit dfc67845c5f5767be00e30faa70095a0789721ae.

6.14 Disparity between values used in order and values transferred to the reserve

FileFix commitTypeStatus
Motherboard.sol#L53PR #74LowFixed

If the argument assets used in the mint function contains repeated tokens, the order created will not reflect this, only the first version of the asset will be accounted for. This could cause issues because all of the accounting and computations of the amounts of tokens to mint are based on the order, while the tokens to be transferred to the reserves are defined by the argument assets.

Recommendation

Use a different approach where order correctly reflects the values in assets.

Resolution

Fixed in pull request #74.

6.15 getReserveState can revert without emitting message

FileFix commitTypeStatus
ReserveManager.sol#43378c4ffLowFixed

If options.includeIdealWeight is true, but options.includePrice is false. The value of vaultInfo.price will be 0 causing returnsSum to be 0. Because returnsSum is 0 this line will revert the transaction.

Recommendation

Require the value of options.includePrice to be true if options.includeIdealWeight is true. In the same way as options.includeCurrentWeight.

Resolution

Fixed in commit 378c4ffa35263b8bcac9f82d5aa095fab7be9308.

6.16 Duplicated code in NewtonSqrt.sol file

FileFix commitTypeStatus
NewtonSqrt.sol6477d7dInfoFixed

All the content of this file is duplicated in GyroPoolMath.sol.

Recommendation

Remove NewSqrt.sol file.

Resolution

Fixed in commit 6477d7d3310fac1489f46e0923e0f580334bb026.

6.17 Non uniform use of term names in comments

FileFix commitTypeStatus
GyroPoolMath.sol#L42d8fe54dInfoFixed

The comments defines terms within formulas using the pattern term_name = description. These can then be used within the formula in the comment. In the case of totalBpt the term_name is bpt in the definition but totalBpt in the formula.

Recommendation

Use bpt in the formula to keep term_names and description uniform.

Resolution

Fixed in commit d8fe54d67f4076ab757657ae4bc1f4a8c74c73b9.

6.18 Division before multiplication

FileFix commitTypeStatus
GyroPoolMath.sol#L37
GyroPoolMath.sol#L63
a976c3dInfoFixed

In both _calcAllTokensInGivenExactBptOut and _calcTokensOutGivenExactBptIn, divisions are done before multiplications, doing it in reverse order may improve precision. Our understanding is that this is done in this way because it results in N + 1 operations being performed, where N is the number of assets. Whereas, if multiplications are done first, the number of operations is 2N. When this is used in the GyroTwoPool, N is 2, so the difference in the number of operations is only 1. In this case, perhaps the gains in precision are worth the extra operation? In any case, it is not a big issue because any rounding done favors the protocol and the losses caused by the loss of precision to the clients may be mitigated by the gas savings.

Resolution

Fixed in commit a976c3d80297c5aefef2ddbc896cca7cc4da5219.

6.19 Comments are pointing to the wrong section

FileFix commitTypeStatus
GyroPoolMath.sol#L268
GyroPoolMath.sol#L289
5259965InfoFixed

Function comments may be pointing to the wrong section.

Recommendation

Change section pointed to in the comments by 3.1.3.

Resolution

Fixed in commit 5259965244ae7e8abab00c0e5cbe9188e477c425.

6.20 Comments are not aligned with the code

The comments of _getDueProtocolFeeAmounts(uint256 previousInvariant, uint256 currentInvariant) state that this function returns uint256[], but the function instead returns (uint256,uin256,address,address). The comments also mention this function overrides getDueProcolFeeAmounts from the parent contract, but this contract does not have a method with the same signature, because the version in the parent contract receives different arguments.

Recommendation

Update the comment.

Resolution

Fixed in commit c61dcbac9362b8ec877e59ddf2ee02b84a0c33d1.

6.21 Unused functions in GyroCEEMMath.sol

Functions validateNormed, validateParams and validateDerivedParams are internal functions, but are not used in the code. Calls to these functions are commented out in the GyroCEEMPool.sol constructor. The Function mkDerivedParams is not used either.

Recommendation

Use these functions to validate the constructor’s arguments. If this is not necessary, remove these functions.

Resolution

The functions have been removed.

6.22 Typo in comments

FileFix commitTypeStatus
GyroCEEMMath.sol#L399
GyroCEEMMath.sol#L448
09ca68aInfoFixed

Comments for lines 400 and 449 may have a typo. They say "need to to /dSq in a way so ...". From the code it appears that it should be "need to 1/dSq in a way so ...".

Recommendation

Check comments and update if necessary.

Resolution

Fixed in commit 09ca68a3b4755c7b6b678b9e370149d6d6c1c4d5.

6.23 Comments are not aligned with the code

FileFix commitTypeStatus
GyroCEMMMath.sol#L6321ff1c83InfoFixed

Comments for function calcXpXpDivLambdaLambda say x′ ∗ x′ is computed, but the code computes

x′ ∗ x′lambda ∗ lambda

and the name indicates this too.

Recommendation

Review comments and code and update accordingly if they are not aligned.

Resolution

Fixed in commit 1ff1c83c34ac63bf80445a6d9f4ff18c91f486a5.

6.24 getSqrtParameters can return a tuple of uint256 to save gas

The sqrtParameters() function returns a uint256[], but it always returns two values and these values are always passed independently to every function. The signature of this function could be change to return (uint256, uint256) to save some gas.

Resolution

Function has been adjusted, as well as _sqrtParameters() and _getVirtualParameters(). To minimize the amount of refactoring required, this have been refactored to use fixed-width arrays instead of multiple variables. Fixed in commit f4635e1f4e32e0594d919d7423f810861a719314.

6.25 Duplicated comment in GyroTwoPool.sol

FileFix commitTypeStatus
GyroTwoPool.sol#L319
GyroTwoPool.sol#325
c142290InfoFixed

Comments in _onJoinPool are duplicated.

Recommendation

Remove duplicated comments.

Resolution

Fixed in commit c142290aafec96f046afa6915c1f28b78d9c1d1b.

6.26 Reduced readability for _onSwapGivenIn and _onSwapGivenOut

FileFix commitTypeStatus
GyroTwoPool.sol#L170
GyroTwoPool.sol#L182
7e91b62InfoFixed

ExtensibleWeightedPool2Tokens.sol contains private definitions for functions _onSwapGivenIn and _onSwap- GivenOut. Because these functions are not virtual they can not be overriden and the new functions in GyroTwoPool.sol add an unused argument to change the signature. This makes the codebase error prone.

Recommendation

We recommend the functions in ExtensibleWeightedPool2Tokens.sol be made virtual and then be overridden in

GyroTwoPool.sol.

Resolution

Fixed in commit 7e91b62b8ba42d29e08a484f3835ba686bf96996.

6.27 Unused arguments in GyroTwoPool.sol constructor

FileFix commitTypeStatus
ExtensibleWeighted2TokenPool.sol#L139630c9aeInfoFixed

The constructor for GyroTwoPool.sol receives two arguments, the first one is a struct with multiple parameters for creating the pool. From these parameters one can compute the weights of the tokens. In GyroTwoPools.sol tokens always have 0.5 weight. Receiving these values in the constructor may cause the pool to be initialized with different weights. This does not affect the workings of the pool because they do not rely on these values, but it may cause external interactions to work unexpectedly.

Recommendation

Always set weights to 0.5 in the constructor without relying on the arguments.

Resolution

The _normalizedWeight0 and _normalizedWeight1 variables are now essentially constants with value 0.5 (they are immutable and not set in the constructor, thus keeping their default values of 0.5). Fixed in commit 630c9ae55aafb10a623f827f946a3b2d6fc0a66a.

6.28 Typo in commented equation in GyroTwoMath.sol

FileFix commitTypeStatus
GyroTwoMath.sol#L1669a14fa0InfoFixed

The numerator of the most derived equation in the comments for the _calcOutGivenIn function should be ’y instead of ’z.

Recommendation

Change ’z to ’y.

Resolution

Fixed in commit 9a14fa0bc8174283616a2e7f07b530c86458841c.

6.29 Number of operations in _calculateCubicTerms can be reduced

FileFix commitTypeStatus
GyroThreeMath.sol#L70—InfoAcknowledged

In the function _calculateCubicTerms, multiple expressions contain root3alpha ∗ root3alpha as a subexpression. Similarly for balances[0] ∗ balances[1]. These common subexpressions could be eliminated, reducing the number of operations and resulting in gas savings.

Recommendation

Change the comments to be updated with the code.

Resolution

The order of operations is chosen intentionally this way to minimize the amplification of rounding errors. This is relevant for the mb value, for instance. Assume for ease of writing that balances = [x, y, z] and write short α′ := root3Alpha. Then the variable mb is computed essentially as ((x + y + z) ∗ α′) ∗ α′. The inner multiplication implies an error of 1e−18, which is then multiplied by α′, so that the total error is 1e−18 ∗ α′ + 1e−18 ≤ 2e − 18. In contrast, if we were to pre-compute α′ ∗ α′ with an error of 1e − 18, and we would then compute (x + y + z) ∗ (α′ ∗ α′), leading to an error of (x + y + z) ∗ 1e − 18 + 1e − 18, which can potentially be significant. Experimentally, such an error would indeed have a noticeable effect on the final result of the invariant calculation. We agree that a common term balances[0] ∗ balances[1] could be isolated, but we decided not to do this small optimization in the interest of readability.

6.30 _calcNewtonDelta has an unused named argument

FileFix commitTypeStatus
GyroThreeMath#L16039f2fc6InfoFixed

_calcNewtonDelta has an argument called a, but this argument is not used in the function. If the argument is not used, it should be removed.

Recommendation

Check if argument is unnecessary, if yes, remove it.

Resolution

This parameter was historical baggage and have been removed from this method and also from _runNewtonIteration(). Fixed in commit 39f2fc60b42dbb1471101aed510473034d49784c.

6.31 deposit and withdraw do not allow minimum expected amounts to be specified

FileFix commitTypeStatus
BalancerExchanger.sol#L66
BalancerExchanger.sol#105
—InfoFixed

The deposit and withdraw functions call joinPool and exitPool respectively in a Balancer pool. These processes cannot be reverted, users should be able to specify the minimum amounts that they are expecting. Our understanding is that this contract should not be used directly by any users, therefore this is not supported. However, it can still be used by anyone.

Recommendation

We recommend an argument to specify the minimum amounts be added and, every time these functions are called from other places within the protocol, the value 0 be passed as a minimum amount. This avoids changing the actual behavior of the protocol.

Resolution

Code is not used anymore.

6.32 Use of transferFrom instead of safeTransferFrom

FileFix commitTypeStatus
BalancerExchanger.sol#71f22d59cInfoFixed

In the deposit function in BalancerExchanger.sol, transferFrom is used instead of safeTransferFrom. Different checks are performed. The rest of the code uses safeTransferFrom from the OpenZeppelin libraries.

Recommendation

We recommend safeTransferFrom be used to maintain the uniformity of the code.

Resolution

Fixed in commit f22d59c1fa361dbbadf331140c9a14cf37891293.

6.33 Incorrect casing for variable name in registerPoolId function

FileFix commitTypeStatus
BalancerPoolRegistry.sol#L33174171aInfoFixed

Variable name poolIdsforToken does not follow the variable naming convention with respect to casing.

Recommendation

Change variable name to poolIdsForToken.

Resolution

Fixed in commit 174171ad9549f1808ae1bfd455d8bf3e96732ba0.

6.34 Unnecessary storage write

FileFix commitTypeStatus
BalancerPoolRegistry.sol#L35bbd6201InfoFixed
poolIdRegistry[underlyingTokenAddress] = poolIdsforToken;

This write is unnecessary because poolIdRegistry is a storage pointer, it can be removed to save a storage write.

Recommendation

Remove indicated line.

Resolution

Fixed in commit bbd6201969934abbba04cc00e2fa246bbb84f946.

6.35 Defined event is never emitted in VaultSafetyMode.sol

FileFix commitTypeStatus
VaultSafetyMode.sol#L353c10173InfoFixed

In the VaultSafetyMode.sol contract, the event MotherboardAddressChanged(address,address) is defined but never emitted.

Recommendation

Remove the event definition if is not going to be used.

Resolution

Fixed in commit 3c10173803728751611f6471b95a1950d74e7af1.

6.36 Motherboard.sol can mint tokens directly to msg.sender to save gas

FileFix commitTypeStatus
Motherboard.sol#L8481478a3InfoFixed

The mint function in Motherboard.sol mints tokens to the contract itself, after which it sends the tokens to msg.sender. Tokens could be minted to msg.sender directly to save gas.

Recommendation

Call gydToken.mint with msg.sender as receiver.

Resolution

Fixed in commit 81478a32fd0143db2ac0baa854a43ae6b3f1e3af.

6.37 setInitialPrice can be called multiple times for the same vault

FileFix commitTypeStatus
VaultRegistry.sol#L73]eae7032InfoFixed

The setInitialPrice function in the VaultRegistry.sol contract can be called multiple times for the same vault. The name suggest this function should be only called once per vault.

Recommendation

Check if initialPrice for the specified vault is 0 before setting the new value.

Resolution

Fixed in commit eae7032318214a836529cf01ed6ec8d0a3bef961.

6.38 Vault metadata is still available after deregistering the Vault

FileFix commitTypeStatus
VaultRegistry.sol#9195799d3InfoFixed

The deregisterVault function does not remove the metadata for the specified vault. Even after deregistering, the vault metadata for this can be fetched through getVaultMetadata.

Recommendation

Remove vault metadata in the deregisterVault function.

Resolution

Fixed in commit 95799d35a291b5c995c55181c017f217c375f80f.

7

Documentation Evaluation

Software documentation refers to the written or visual information that describes the functionality, architecture, design, and implementation of software. It provides a comprehensive overview of the software system and helps users, developers, and stakeholders understand how the software works, how to use it, and how to maintain it. Software documentation can take different forms, such as user manuals, system manuals, technical specifications, requirements documents, design documents, and code comments. Software documentation is critical in software development, enabling effective communication between developers, testers, users, and other stakeholders. It helps to ensure that everyone involved in the development process has a shared understanding of the software system and its functionality. Moreover, software documentation can improve software maintenance by providing a clear and complete understanding of the software system, making it easier for developers to maintain, modify, and update the software over time. Smart contracts can use various types of software documentation. Some of the most common types include:

  • Technical whitepaper: A technical whitepaper is a comprehensive document describing the smart contract’s design and technical details. It includes information about the purpose of the contract, its architecture, its components, and how they interact with each other;
  • User manual: A user manual is a document that provides information about how to use the smart contract. It includes step-by-step instructions on how to perform various tasks and explains the different features and functionalities of the contract;
  • Code documentation: Code documentation is a document that provides details about the code of the smart contract. It includes information about the functions, variables, and classes used in the code, as well as explanations of how they work;
  • API documentation: API documentation is a document that provides information about the API (Application Programming Interface) of the smart contract. It includes details about the methods, parameters, and responses that can be used to interact with the contract;
  • Testing documentation: Testing documentation is a document that provides information about how the smart contract was tested. It includes details about the test cases that were used, the results of the tests, and any issues that were identified during testing;
  • Audit documentation: Audit documentation includes reports, notes, and other materials related to the security audit of the smart contract. This type of documentation is critical in ensuring that the smart contract is secure and free from vulnerabilities.

These types of documentation are essential for smart contract development and maintenance. They help ensure that the contract is properly designed, implemented, and tested, and they provide a reference for developers who need to modify or maintain the contract in the future.

8

Remarks & Test Suite

No documentation or test suite remarks are included in this report.

As auditors, we recommend that any changes or updates made to the audited codebase undergo a re-audit or security review to address potential vulnerabilities or risks introduced by the modifications. By conducting a re-audit or security review of the modified codebase, you can significantly enhance the overall security of your system and reduce the likelihood of exploitation. However, we do not possess the authority or right to impose obligations or restrictions on our clients regarding codebase updates, modifications, or subsequent audits. Accordingly, the decision to seek a re-audit or security review lies solely with you.

This report is based on the scope of materials and documentation provided by you to Nethermind in order that Nethermind could conduct the security review outlined in 1. Executive Summary and 2. Audited Files. The results set out in this report may not be complete nor inclusive of all vulnerabilities. Nethermind has provided the review and this report on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Blockchain technology remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond the programming language, or other programming aspects that could present security risks. This report does not indicate the endorsement of any particular project or team, nor guarantee its security. No third party should rely on this report in any way, including for the purpose of making any decisions to buy or sell a product, service or any other asset. To the fullest extent permitted by law, Nethermind disclaims any liability in connection with this report, its content, and any related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. Nethermind does not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third-party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked websites, any websites or mobile applications appearing on any advertising, and Nethermind will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE.