Download audit report
This document presents the security review performed by Nethermind on the Gyroscope CEMM written in the Solidity Language. Gyroscope proposes an infrastructure for DeFi based on an internal coin, where each unit of this internal coin is backed by 1 USD in collateral. The protocol proposes a novel strategy with multiple lines of defense to maintain price stability.
The primary focus of this audit is on the implementation of the mathematics behind the Constant-Ellipse Market Maker (CEMM) used in the Gyroscope protocol, including an analysis of numerical issues like rounding directions and precision errors. The Gyroscope team provided two detailed papers explaining the mathematical concepts used in the protocol design. The provided papers are titled The Constant-Ellipse Market Maker (CEMM) and CEMM High Precision Calculations. The Gyroscope team also provided a precision analysis document explaining decisions made by the team to prevent numerical issues.
As an overall assessment, no significant issues were identified. However, we have raised 13 minor issue findings relating to the overall quality and maintainability of the protocol indicated in the figure below. When considering the developer/auditor/user perspective, the quality and volume of inline documentation is sufficient although the code could benefit from improved external technical documentation that specifically focuses on the CEMM component of the protocol.
| Audit assessment | |
| Audit Type | Security Review |
| Initial Report | Jul 18, 2022 |
| Response from Client | Aug 10, 2022 |
| Final Report | Aug 17, 2022 |
| Methods | Manual Review, Automated Analysis |
| Repository | Gyroscope CEMM |
| Commit Hash (Initial Audit) | 110229131d |
| Documentation | https://docs.gyro.finance/overview/introduction |
Findings by severity
| # | Contract | LoC | Comments | Ratio | Blank | Total |
| 1 | libraries/GyroPoolMath.sol | 192 | 87 | 45.3% | 32 | 311 |
| 2 | libraries/SignedFixedPoint.sol | 161 | 105 | 65.2% | 46 | 312 |
| 3 | contracts/cemm/GyroCEMMOracleMath.sol | 27 | 45 | 166.7% | 11 | 83 |
| 4 | contracts/cemm/GyroCEMMMath.sol | 417 | 200 | 48.0% | 76 | 693 |
| 5 | contracts/cemm/GyroCEMMPoolErrors.sol | 15 | 13 | 86.7% | 5 | 33 |
| 6 | contracts/cemm/GyroCEMMPool.sol | 345 | 182 | 52.8% | 86 | 613 |
| Total | 1157 | 632 | 54.6% | 256 | 2045 |
| # | Finding | Severity | Update |
| 1.1 | Privileged Roles | Info | Acknowledged |
| 1.2 | Unused state variables | Info | Fixed |
| 1.3 | Application using old Solidity version | Best Practices | Acknowledged |
| 1.4 | Unlocked version pragma | Best Practices | Fixed |
| 2.1 | Contract exceeding the size limit | Info | Acknowledged |
| 2.2 | Application Monitoring Can Be Improved by Emitting More Events | Best Practices | Fixed |
| 2.3 | Sanitize input address in GyroCEMMPool.constructor(...) | Best Practices | Fixed |
| 2.4 | Weak validation of token pair in GyroCEMMPool.onSwap(...) | Best Practices | Fixed |
| 3.1 | Review the rounding strategy for the GyroPoolMath.sol constants | Info | Acknowledged |
| 4.1 | Gas optimization opportunities in Functions mulUpXpToNp(...) and mulDownXpToNp(...) | Best Practices | Fixed |
| 4.2 | Gas optimization opportunities in division functions | Best Practices | Fixed |
| 4.3 | Gas optimization opportunities in functions divUpMag(...) and divUpMagU(...) | Best Practices | Fixed |
| 4.4 | Unnecessary branching in multiplication functions | Best Practices | Fixed |
No system overview is included in this report.
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:
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:
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 / Likelihood | Low | Medium | High |
| High | Medium | High | Critical |
| Medium | Low | Medium | High |
| Low | Info / Best Practices | Low | Medium |
| Undetermined | Undetermined | Undetermined | Undetermined |
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.
| File | Fix commit | Type | Status |
contracts/cemm/* | — | Info | Acknowledged |
Smart contracts will often have owner variables to designate the person with special privileges to make modifications to the smart contract. The owner can set fees, incentives, and pause contracts.
Recommendation
This centralization of power needs to be made clear to the users in public-facing documentation.
Resolution
We will ensure to communicate the control aspects of the smart contracts in public-facing documentation.
| File | Fix commit | Type | Status |
contracts/cemm/* | 5b702c3 | Info | Fixed |
The following state variables are declared but not used in the CEMM.
GyroPoolMath.MIN_NEWTON_STEP_SIZE (libraries/GyroPoolMath.sol)
SignedFixedPoint.MAX_POW_RELATIVE_ERROR (libraries/SignedFixedPoint.sol)
SignedFixedPoint.MIN_POW_BASE_FREE_EXPONENT(libraries/SignedFixedPoint.sol)Recommendation
Ensure that the listed state variables are unused by the protocol outside of the CEMM. If they are unused, then consider removing these state variables.
Resolution
Fixed in commit 5b702c30fd32e61050d3fb6a290adbaf4a0f0390.
| File | Fix commit | Type | Status |
contracts/cemm/* | — | Best Practices | Acknowledged |
The application is using Solidity 0.7.x. Since the application makes extensive use of arithmetics, adopting Solidity 0.8.x appears to be a safer solution as it has built-in overflow and underflow checks. By using version 0.8.x, there is no need to use the SafeMath.sol library. Reference. Moreover, the cost of the revert operation is proportional to the string length passed as parameter. Solidity 0.8.x also introduces the Error object, which can be passed as a parameter to the revert instruction. Notice that such objects can be defined outside of the contract, allowing the developer to create one single file defining a list of errors for all modules, which can be very convenient. Errors also accept parameters. More information is available here.
Recommendation
Consider adopting Solidity 0.8.x.
Resolution
The underlying Balancer contracts are using 0.7.
| File | Fix commit | Type | Status |
contracts/cemm/* | 6d4fab5 | Best Practices | Fixed |
The application has pragma ˆ0.7.0. Unlocked pragmas could cause the contracts to accidentally be compiled or deployed using an outdated or buggy compiler version.
Recommendation
Consider locking pragmas to a specific compiler version.
Resolution
Fixed solidity version to 0.7.6. Fixed at commit 6d4fab52364a0a0551d86b3f4c9df928c91c3e22.
contracts/cemm/GyroCEMMPool.sol| File | Fix commit | Type | Status |
contracts/cemm/GyroCEMMPool.sol | — | Info | Acknowledged |
The contract GyroCEMMPool.sol is 28,006 bytes, exceeding the EIP-170 limit of 24,577 bytes. There are some actions that can help in reducing the contract size. Whenever we declare a public state variable, the Solidity compiler automatically generates the corresponding getter() function. The contract size can also be optimized by turning modifiers into functions, as shown in the example below:
modifier checkStuff() {}
function doSomething() checkStuff {}The function doSomething() can be rewritten without modifiers as:
function checkStuff() private {}
function doSomething() { checkStuff(); }Still focusing on optimizing the contract size, we must declare the correct visibility for functions and state variables. Functions or variables that are only called from the outside must be external instead of public. Functions or variables called only from within the contract must be private or internal instead of public. For more info, check this reference.
Recommendation
Double-check the code and turn all possible public variables into private variables. Also place the proper visibility of functions in order to optimize the contract size and reduce the deployment cost.
Resolution
We will ensure that the deployed contracts do not exceed the size limit.
| File | Fix commit | Type | Status |
contracts/cemm/GyroCEMMPool.sol | 52b33f0 | Best Practices | Fixed |
The contract GyroCEMMPool.sol is not emiting events in important state changes. In order to validate the proper deployment and initialization of the contracts, it is a good practice to emit events. Also, any important state transition can be logged, which is beneficial for monitoring the contract, as well as tracking bugs or hacks. Below we present a list of functions that could benefit from event emission to improve protocol monitoring and management.
function GyroCEMMPool.constructor(...)
function GyroCEMMPool._onInitializePool(...)
function GyroCEMMPool._onJoinPool(...)
function GyroCEMMPool.onSwap(...)
function GyroCEMMPool._onExitPool(...)
function GyroCEMMPool._updateOracle(...)Recommendation
Consider emitting events in the functions listed above.
Resolution
Events added for each of the suggested functions. Fixed in commit 52b33f04943a374f54a5a63021ec1c6808b4dbc2.
GyroCEMMPool.constructor(...)| File | Fix commit | Type | Status |
contracts/cemm/GyroCEMMPool.sol | d5a3ee4 | Best Practices | Fixed |
The constructor in GyroCEMMPool is not checking if configAddress is different from address(0x0). Most of the time, this does not represent any risk, since constructors are typically called by initialization scripts. However, validating input parameters is a good programming practice, and can reduce the chances of deploying contracts with wrong input parameters.
Recommendation
Consider checking if configAddress is not address(0x0).
Resolution
Input now checked. Fixed at commit d5a3ee4019891fc03a2dffa862c33befd7392219.
GyroCEMMPool.onSwap(...)| File | Fix commit | Type | Status |
contracts/cemm/GyroCEMMPool.sol | a5b458d | Best Practices | Fixed |
The function GyroCEMMPool.onSwap(...) receives the structure request as an input parameter. It assumes that the pair of tokens is properly filled in SwapRequest.tokenIn and SwapRequest.tokenOut. The value of tokenInIsToken0 is defined by only comparing if request.tokenIn==_token0. Since the pair of tokens is not validated, this can lead to unexpected behavior. A better practice would be to ensure that the pair of tokens really matches the expected one. This check increases the robustness of the function, and prevents human errors. The code is reproduced below.
function onSwap(
SwapRequest memory request,
uint256 balanceTokenIn,
uint256 balanceTokenOut
) public virtual override whenNotPaused onlyVault(request.poolId) returns (uint256) {
bool tokenInIsToken0 = request.tokenIn == _token0;
...
}Recommendation
Consider validating if the pair of tokens passed as arguments match the expected pair of tokens. Revert otherwise.
Resolution
Pair validation strengthened. Fixed at commit a5b458d55d909527e262734d816456793504379a.
libraries/GyroPoolMath.solGyroPoolMath.sol constants| File | Fix commit | Type | Status |
libraries/GyroPoolMath.sol | — | Info | Acknowledged |
The constants in GyroPoolMath.sol are being truncated, instead of being rounded-up, rounded-down, or rounded towards the closest value. From the provided specification, we could not infer the best behavior for these constants. Below we show the actual definition of constants (according to the code).
uint256 private constant SQRT_1E_NEG_1 = 316227766016837933;
uint256 private constant SQRT_1E_NEG_3 = 31622776601683793;
uint256 private constant SQRT_1E_NEG_5 = 3162277660168379;
uint256 private constant SQRT_1E_NEG_7 = 316227766016837;
uint256 private constant SQRT_1E_NEG_9 = 31622776601683;
uint256 private constant SQRT_1E_NEG_11 = 3162277660168;
uint256 private constant SQRT_1E_NEG_13 = 316227766016;
uint256 private constant SQRT_1E_NEG_15 = 31622776601;
uint256 private constant SQRT_1E_NEG_17 = 3162277660;For instance, should the constant SQRT_1E_NEG_7 be defined as 316227766016837 or rounded-up to 316227766016838? If we round these constants towards the closest value, some constants have their values modified. The constants with modified values are listed below.
uint256 private constant SQRT_1E_NEG_7 = 316227766016838;
uint256 private constant SQRT_1E_NEG_9 = 31622776601684;
uint256 private constant SQRT_1E_NEG_15 = 31622776602;
uint256 private constant SQRT_1E_NEG_17 = 3162277660;Recommendation
This is not an issue, but a design decision that should be made by the Gyro team, according to the mathematical model, and the intended behavior of the application. Our only recommendation is to ensure if these constants are properly defined.
Resolution
The square root calculation is already subject to a small margin of error in the last digit so this error is already contained within that.
libraries/SignedFixedPoint.solmulUpXpToNp(...) and mulDownXpToNp(...)| File | Fix commit | Type | Status |
libraries/SignedFixedPoint.sol | 4d9399c | Best Practices | Fixed |
The functions SignedFixedPoint.mulUpXpToNp(...) and SignedFixedPoint.mulDownXpToNp(...) are computing the variables b1 and b2. Then, those variables are checked if no overflow has occurred. The variable b2 could be calculated after first require(...) statement, and before computing the value of the variable prod2, so if an overflow occurs when computing the value of b1, then the value b2 does not have to be computed. Below we present the code of these functions.
function mulUpXpToNp(int256 a, int256 b) internal pure returns (int256) {
int256 b1 = b / 1e19;
int256 b2 = b % 1e19;
int256 prod1 = a * b1;
if (!(a == 0 || prod1 / a == b1))
BalancerErrors._require(false, Errors.MUL_OVERFLOW);
int256 prod2 = a * b2;
if (!(a == 0 || prod2 / a == b2))
BalancerErrors._require(false, Errors.MUL_OVERFLOW);
return prod1 <= 0 && prod2 <= 0 ? (prod1 + prod2 / 1e19) / 1e19 : (prod1 + prod2 / 1e19 - 1) / 1e19 + 1;
}
function mulDownXpToNp(int256 a, int256 b) internal pure returns (int256) {
int256 b1 = b / 1e19;
int256 b2 = b % 1e19;
int256 prod1 = a * b1;
if (!(a == 0 || prod1 / a == b1))
_require(false, Errors.MUL_OVERFLOW);
int256 prod2 = a * b2;
if (!(a == 0 || prod2 / a == b2))
_require(false, Errors.MUL_OVERFLOW);
return prod1 >= 0 && prod2 >= 0 ? (prod1 + prod2 / 1e19) / 1e19 : (prod1 + prod2 / 1e19 + 1) / 1e19 - 1;
}Recommendation
Consider moving the b2 computation to be performed after the first require(...) statement for gas saving in case an overflow happens when computing the variable b1.
Resolution
Fixed at commit 4d9399c68117991bd6e76059ccdc6fc6f55d293b.
| File | Fix commit | Type | Status |
libraries/SignedFixedPoint.sol | 4d9399c | Best Practices | Fixed |
The division functions SignedFixedPoint.divDownMag(...), SignedFixedPoint.divUpMag(...), SignedFixedPoint.divUpMagU(...), and SignedFixedPoint.divXp(...) are using unnecessary branches. This causes these functions to be more expensive than necessary. For instance, the function SignedFixedPoint.divUpMag(...) has an else branch after the statement if (a == 0), which is not required. Also, the return statement is inside the else branch. The function SignedFixedPoint.divDownMag(...) is represented below.
function divDownMag(int256 a, int256 b) internal pure returns (int256) {
if (b == 0)
_require(false, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
int256 aInflated = a * ONE;
if (aInflated / a != ONE)
_require(false, Errors.DIV_INTERNAL);
return aInflated / b;
}
}Recommendation
Consider removing all unnecessary conditional branches.
Resolution
Fixed at commit 4d9399c68117991bd6e76059ccdc6fc6f55d293b.
divUpMag(...) and divUpMagU(...)| File | Fix commit | Type | Status |
libraries/SignedFixedPoint.sol | 4d9399c | Best Practices | Fixed |
The functions SignedFixedPoint.divUpMag(...) and SignedFixedPoint.divUpMagU(...) could be refactored. The line if (a == 0) return 0 could be moved over the line if (b < 0). That order would save gas if a==0, since the function would return and variables wouldn’t be reassigned. The functions are reproduced below.
function divUpMagU(int256 a, int256 b) internal pure returns (int256) {
if (b == 0)
BalancerErrors._require(false, Errors.ZERO_DIVISION);
if (b < 0) {
b = -b;
a = -a;
}
if (a == 0) {
return 0;
} else {
if (a > 0) return ((a * ONE - 1) / b) + 1;
else return ((a * ONE + 1) / b) - 1;
}
}
function divUpMag(int256 a, int256 b) internal pure returns (int256) {
if (b == 0)
BalancerErrors._require(false, Errors.ZERO_DIVISION);
if (b < 0) {
b = -b;
a = -a;
}
if (a == 0) {
return 0;
} else {
int256 aInflated = a * ONE;
if (aInflated / a != ONE)
BalancerErrors._require(false, Errors.DIV_INTERNAL);
if (aInflated > 0) return ((aInflated - 1) / b) + 1;
else return ((aInflated + 1) / b) - 1;
}
}Recommendation
Consider moving the line if (a == 0) return 0 over the if (b < 0 ) to save gas in case of a==0.
Resolution
Fixed at commit 4d9399c68117991bd6e76059ccdc6fc6f55d293b.
| File | Fix commit | Type | Status |
libraries/SignedFixedPoint.sol | b153816 | Best Practices | Fixed |
The functions SignedFixedPoint.mulUpMag(...) and SignedFixedPoint.mulUpMagU(...) are checking if product is higher or lower than 0. The last else statement where product is equal to 0 is unnecessary. Replacing the last else statement with the default return 0; statement saves gas (around 44 gas units), since the branch is removed.
function mulUpMag(int256 a, int256 b) internal pure returns (int256) {
int256 product = a * b;
if (!(a == 0 || product / a == b))
BalancerErrors._require(false, Errors.MUL_OVERFLOW);
if (product > 0) return ((product - 1) / ONE) + 1;
else if (product < 0) return ((product + 1) / ONE) - 1;
else return 0;
}Recommendation
Review the function and consider removing unnecessary conditional branches.
Resolution
Unnecessary branch removed. Fixed at commit b153816de39cb2cb0a254547be1a757e0bf18c47.
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:
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.
The documentation for this audit is composed of:
In general, the contracts in the scope of this audit have a good amount of inline comments, but the documentation can be improved by adding more technical documents, such as diagrams of interaction, functional/nonfunctional requirements, and use cases. The README.md can present more details about the application. The mathematical model is well presented in the confidential papers provided for the audit. The audited files do not comply with the NatSpec standard. The NatSpec documentation considers the combination of the tags @dev, @param, @notice and @return.
Exceptionally, we noticed insufficient comments in the following functions:
function GyroCEMMMath.calcOutGivenIn(...)
function GyroCEMMMath.calcInGivenOut(...)
function SignedFixedPoint.divUpmag(...)
function SignedFixedPoint.sub(...)GyroCEMMMath.calcOutGivenIn(...) and GyroCEMMMath.calcInGivenOut(...) are core to the application;SignedFixedPoint.divUpMag(...) does not present comments explaining the way in which upward rounding is achieved in the division;SignedFixedPoint.sub(...) has an incorrect inline comment, possibly copied from the function SignedFixedPoint.add(...).- // Fixed Point addition is the same as regular checked addition
+ // Fixed Point subtraction is the same as regular checked subtractionWe also noticed two spelling errors in the file cemm/GyroCEMMMath.sol.
- * Enforces anti-overflow limits on balances and the computed invaraint in the process. */
+ * Enforces anti-overflow limits on balances and the computed invariant in the process. */
- * See calculation in Section 2.1.2. Calculation is ordered here for precision, but erorr in r is magnified by lambda
+ * See calculation in Section 2.1.2. Calculation is ordered here for precision, but error in r is magnified by lambdaWe recommend the following improvements be made to the documentation of this project:
NatSpec standard to describe each function (what it does, inputs, outputs);GyroCEMMMath.calcInGivenOut(...) and calcOutGivenIn(...).The tests are executed using the command ’brownie test’. Below we present the tests output, where we can notice the recurrent error message ’fixture QueryProcessor not found’. In summary 163 tests passed, 39 were skipped, there is 1 warning, and 12 errors in 4,480 seconds.
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.
The Leading Engineers of Blockchain Infrastructure