Download audit report
This document presents the security review performed by Nethermind of the Dyve protocol. Dyve is an NFT lending platform that allows ERC721 and ERC1155 compatible tokens to be lent out for value speculation (shorting) or access to NFT utility. Borrowers pay a fee and lock an amount of collateral specified by the lender into the contract, which remains until the borrower returns an NFT from the same collection or fails to return an NFT within the lender’s specified time frame. At this point, the lender can claim the borrower’s collateral. Orders are signed and submitted off-chain and are fulfilled on-chain.
The audited code consists of 399 lines of Solidity with code coverage of 99.06%. This audit was supported by documentation accessible from the Dyve Notion Page, which explains order types, business logic, and a technical overview. The audit was performed using a combination of the following: a) Manual analysis of the codebase; b) Automated analysis tools; and, c) Custom tests.
The other nine points of attention are classified as informational or best practices.
| Audit assessment | |
| Audit Type | Security Review |
| Initial Report | Jan. 27, 2023 |
| Response from Client | Mar. 8, 2023 |
| Final Report | Mar. 15, 2023 |
| Methods | Manual Review, Automated Analysis |
| Repository | github.com/Dyve-co/Contracts |
| Commit Hash (Initial Audit) | a0f7d06e1b |
| Commit Hash (Reaudit) | 49ed8ae1b8 |
| Documentation | Notion page |
| Documentation Assessment | Medium |
| Test Suite Assessment | High |
Findings by severity
| # | Contract | LoC | Comments | Ratio | Blank | Total |
| 1 | contracts/Dyve.sol | 352 | 98 | 27.8% | 68 | 518 |
| 2 | contracts/libraries/OrderTypes.sol | 47 | 6 | 12.8% | 6 | 59 |
| Total | 399 | 104 | 28.6% | 74 | 577 |
| # | Finding | Severity | Update |
| 1 | Reservoir-flagged NFTs can be offered by a lender | High | Fixed |
| 2 | Third party oracle dependency | Medium | Fixed |
| 3 | Reservoir oracle message replay attack | Low | Acknowledged |
| 4 | Protocol can receive no fees due to integer division | Low | Acknowledged |
| 5 | premiumCollection and premiumTokenId are not part of the signed order | Low | Acknowledged |
| 6 | Lender can borrow from themselves | Info | Acknowledged |
| 7 | Missing input validation for order duration | Info | Fixed |
| 8 | Non-existent orders have a status of BORROWED | Info | Fixed |
| 9 | Hardcoded values for the Interface ID | Best Practices | Fixed |
| 10 | Mapping entry can be saved to memory | Best Practices | Fixed |
| 11 | The nonReentrant modifier should be added to all order management functions | Best Practices | Fixed |
| 12 | Use of arbitrary number | Best Practices | Fixed |
| 13 | _transferERC20 and _transferETH may transfer with no amount | Best Practices | Fixed |
| 14 | Code does not match the specification | Best Practices | Fixed |
The Dyve protocol allows for NFT lending, where either a lender can offer an NFT or a borrower can request an NFT at a specified collateral and fee price. These orders are created and signed off-chain. Orders are fulfilled on-chain, where the signed order is passed as an argument. When an order is fulfilled, the collateral and fees are paid by the borrower, and the borrower will receive the lender’s NFT. The borrower is expected to return an NFT from the same collection within some specified timeframe, at which point their collateral would be returned. If a borrower does not return an NFT, the lender can claim the borrower’s collateral. When a borrower returns an NFTs to the protocol, a Reservoir API is used to prevent returning any stolen NFTs. Fig. 2 below describes the borrow and lend flow for the Dyve protocol.
The prepared security review is based on the following assumptions:
ERC721 or ERC1155 specification.ERC20 tokens do not have behaviors that can readjust balances, such as fee-on-transfer or rebasing tokens.During the audit, Nethermind developed fuzz tests for the Dyve contract to ensure correct behavior across many different interactions. Fuzz testing for Solidity smart contracts involves providing random or unexpected inputs to a smart contract to find vulnerabilities or bugs in its code. This technique can help detect unhandled exceptions, security flaws, and unexpected behaviors.
4.2.1 Contract changes to support fuzz testing
To reduce the test complexity and development time, some small changes were made to the Dyve contract. The changes are listed below:
closePosition function no longer checks if the NFT is flagged._validateOrder function no longer ensures the signature is valid.4.2.2 Functions and properties tested
The following is a list of functions that were tested. Each function contains a list of properties that were checked.
1. closePosition
fullfilOrder function should fail if the lent NFT did not belong to the lenderfullfilOrder function should fail if the lender does not have enough amount of ERC-1155 tokensfullfilOrder function should fail if the borrower does not have enough amount of ERC-20 tokens to payfullfilOrder function should fail if the borrower does not have enough ETH to payfullfilOrder function should fail if the order has already expiredfullfilOrder function should fail if the order’s fee or order’s collateral is set to zerofullfilOrder function should fail if order’s nonce is invalidamountamountmsg.sender’s balance (the funds are taken from it) should have decreased by the collateral + fee amountfee amountcollateral amountfee amountfee + collateral amountcollateral amountfulfillOrder should succeed if the order is valid and the users involved own the correct tokens2. closePosition
closePosition should fail if the Order was already closedclosePosition should fail if the Order has already expiredcollateralcollateral of the ordercollateralcollateral of the orderclosePosition should succeed if the order has not expired or has not been closed3. claimCollateral
claimCollateral should fail if the Order was already closedclaimCollateral should fail if the Order has not expired yetcollateralcollateralclaimCollateral should succeed if the order is open and expired already4. cancelMultipleMakerOrders
cancelMultipleMakerOrders should revert if the list of nonces is emptycancelMultipleMakerOrders should revert if the caller tries to cancel an order with a nonce lower than the minimum nonce set for the callercancelMultipleMakerOrders should succeed if the caller tries to cancel at least one valid nonce5. cancelAllOrdersForSender
cancelAllOrdersForSender should revert if called with a nonce lower or equal to the minimum nonce valid for the callercancelAllOrdersForSender should revert if called with a nonce greater or equal to the minimum nonce valid for the caller plus 500000cancelAllOrdersForSender should succeed if the nonce used is in the correct range4.2.3 Fuzz testing summary
These properties shown above were tested through 50,000 runs. All tests passed with no errors or unusual behavior. The test suite and environment has been delivered as a z˙ip file along with the 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/Dyve.sol | 49ed8ae | High | Fixed |
When closing a position, a borrower must ensure that Reservoir does not flag the NFT being returned. This check ensures that stolen NFTs cannot be used to close the position. Although the borrower has their NFT checked on return, the same check is not done for a lender when fulfilling the position. If a lender gets their flagged NFT order fulfilled by a borrower, the lender can now guarantee that they will either receive a non-flagged NFT of the same collection or the order collateral (effectively laundering the stolen NFT). Furthermore, Reservoir will flag an NFT that does not support the ERC721 standard. An example of an NFT that does not support the ERC721 standard is Cryptopunks. A lender could take advantage of this property on some NFT collections to create an order that cannot be closed by the borrower, guaranteeing that the lender will get the order collateral. This would mean that even if a borrower successfully shorted an NFT and wanted to close the position to secure profits, they would lose their collateral.
Recommendation
Consider adding a Reservoir NFT flag check when fulfilling an order.
Resolution
Fixed in commit 49ed8ae1b8a03a63783213cf15f1c20b07481e86 .
| File | Fix commit | Type | Status |
contracts/Dyve.sol | 49ed8ae | Medium | Fixed |
The Dyve protocol makes use of the Reservoir API to determine whether an NFT was stolen before accepting it when closing a position. In the function closePosition, the message argument (which comes from the API) must match the RESERVOIR_ORACLE_ADDRESS. This is shown below:
if (!ReservoirOracle._verifyMessage(messageId, maxMessageAge, message)) {
revert ReservoirOracle.InvalidMessage();
}It is impossible to change the RESERVOIR_ORACLE_ADDRESS once it has been set. Suppose the API is discontinued or experiences downtime. In that case, it will be impossible to close orders as there will be no way to generate a valid message that can pass the message verification in closePosition. This would effectively act as a DOS against normally closing a position, leading to the borrower always losing their collateral.
Recommendation
Consider adding a function that allows the RESERVOIR_ORACLE_ADDRESS variable to be changed. This way, if the API has issues, it will still be possible to change the oracle address so orders can still be closed.
Resolution
Fixed in commit 49ed8ae1b8a03a63783213cf15f1c20b07481e86 .
Reservoir oracle message replay attack| File | Fix commit | Type | Status |
contracts/Dyve.sol | — | Low | Acknowledged |
When a user closes a position with closePosition they must provide an argument message, which contains information indicating whether an NFT is flagged. There is a time window of 5 minutes from when the message was created when it is considered valid. It is possible for a position to be closed, then the same NFT immediately be put up for lending again. A second borrower could occur, and the borrower could potentially return the NFT using the previous message even if the NFT had been flagged during the second borrower’s possession. This could allow a borrower to return an NFT flagged back to the lender.
Recommendation
Consider having a unique message between orders.
| File | Fix commit | Type | Status |
contracts/Dyve.sol | — | Low | Acknowledged |
The functions _transferETH(...) and _transferERC20(...) determine a protocolFee, which is the number of tokens that should be sent to the protocolFeeRecipient address. In both functions, protocolFee is calculated as follows:
uint256 protocolFee = (fee * protocolFeeManager.determineProtocolFeeRate(premiumCollection, premiumTokenId, to)) /,! 10000; The left-hand side of the integer division can be a number smaller than 10000. In this case, the integer division would result in the protocolFee being zero. An example would be 9999 / 10000 == 0. The potentially lost fee is insignificant for Ether transfers and other 18 decimal ERC20 tokens. However, for some tokens with a smaller number of decimals, the fee loss may be higher. An example of such a token is WBTC (8 decimals) or GUSD (2 decimals). A lender aiming to take advantage of this to avoid protocol fees would have to set their fee to a value that multiplies with their fee rate so that it remains under 10000. This constraint forces the lender to charge very little for fees and isn’t economically viable to take advantage of.
Recommendation
This finding is only concerned with fee loss for high-value, low decimal ERC20 tokens. For the vast majority of tokens, this will not be an issue as the potential losses are virtually non-existent, and there is no incentive for a lender to act in this way. When whitelisting a currency for use within the protocol, consider the value per token and decimal amount.
Resolution
We agree and will consider this for future token whitelisting.
premiumCollection and premiumTokenId are not part of the signed order| File | Fix commit | Type | Status |
libraries/OrderTypes.sol | — | Low | Acknowledged |
When fulfilling an order, the fields premiumCollection and premiumTokenId from the struct OrderTypes.Order are used to calculate the portion of order fees that the Dyve protocol should take. Since these fields are not included in the order signature, the borrower is free to change these fields to any value. This can allow a malicious borrower to make a lender give a larger fee cut to the Dyve protocol by tampering with the order’s premium collection and token fields. Note that the order types ERC721_TO_ERC20 and ERC1155_TO_ERC20 are not affected by this as the lender is the one fulfilling the order, and they would not act in a way that negatively impacts their fees. The code snippet below shows the function used for computing the hash of an order. Notice that premiumCollection and premiumTokenId are not used to compute the hash.
// keccak256("Order(uint256 orderType,address signer,address collection,uint256 tokenId,uint256 amount,uint256,! duration,uint256 collateral,uint256 fee,address currency,uint256 nonce,uint256 endTime)")
bytes32 internal constant ORDER_HASH = 0xaad599fc66ff6b968ccb16010214cc3102e0a7e009000f61cab3f208682c3088;
...
function hash(Order memory order) internal pure returns (bytes32) {
return keccak256(
abi.encode(
ORDER_HASH,
order.orderType,
order.signer,
order.collection,
order.tokenId,
order.amount,
order.duration,
order.collateral,
order.fee,
order.currency,
order.nonce,
order.endTime
)
);
}Recommendation
Ensure that the premiumCollection and premiumTokenId fields are signed when fulfilling an order to prevent fee tampering.
Resolution
The recommended solution by Nethermind is not implemented because it would cause a new issue, reducing the flexibility for a lender to get reduced fees if they own multiple premium NFTs. As borrowers are not incentivized to adjust directed platform fees, we do not anticipate any material redirects. As a control, Dyve can review any instances retrospectively and redirect necessary funds to the lenders as needed.
Update from Nethermind Security
The issue introduced by the recommendation refers to a scenario where the lender transfers the token used as a premium token. The decision of whether the lender receives the premium feature or not would be made by the lender. Therefore, we consider the recommendation a valid solution. However, by not introducing this change, the Dyve team aims for more freedom of action for its lenders. They rely on the lack of clear incentives for borrowers not to direct fees to the lenders.
| File | Fix commit | Type | Status |
contracts/Dyve.sol | — | Info | Acknowledged |
A lender can borrow from their order. This can lead to unexpected behavior as it is possible for a user to create and then interact with an order within the same transaction. Functions that rely on block.timestamp may assume that some time has passed between function calls which may not be the case.
Recommendation
A lender borrowing from their order is not an expected user action and may lead to unexpected behavior within the protocol. Consider adding a check to prevent a lender and borrower from being at the same address.
| File | Fix commit | Type | Status |
contracts/Dyve.sol | 49ed8ae | Info | Fixed |
A lender can create a valid order where the duration is zero. Although it does not make sense for a borrower to fulfill this order, as mentioned in a previous finding, a lender can borrow from their order allowing for positions to be opened and then collateral claimed within the same transaction, which may lead to unexpected behavior.
Recommendation
Consider adding a check to ensure that OrderTypes.Order.duration cannot be zero when fulfilling an order.
Resolution
Fixed in commit 49ed8ae1b8a03a63783213cf15f1c20b07481e86 .
BORROWED| File | Fix commit | Type | Status |
contracts/Dyve.sol | 49ed8ae | Info | Fixed |
Every order has a status field with the type enum OrderStatus. The first value declared in an enum is equivalent to 0, the second is equivalent to 1, and so on. The first enum value in OrderStatus is BORROWED. Since the unwritten state defaults to zero, queries to a non-existent order will have a status of BORROWED. This could cause issues when interacting with other smart contracts and/or off-chain monitoring. The declaration of the OrderStatus enum is shown below:
// The NFT's listing status
enum OrderStatus {
BORROWED,
EXPIRED,
CLOSED
}Recommendation
Change the OrderStatus enum so that its first (default) value indicates a non-existent order.
Resolution
Fixed in commit 49ed8ae1b8a03a63783213cf15f1c20b07481e86 .
| File | Fix commit | Type | Status |
contracts/Dyve.sol | 49ed8ae | Best Practices | Fixed |
Writing magic values manually is always error-prone. The Dyve contract has the interfaceId values for EIP-721 and EIP-1155 manually written, as can be seen below. A typo in these values could cause integration issues to the protocol.
bytes4 public constant INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 public constant INTERFACE_ID_ERC1155 = 0xd9b67a26;Recommendation
Consider using the syntax type(Type).interfaceId instead of manually writing the values.
- bytes4 public constant INTERFACE_ID_ERC721 = 0x80ac58cd;
- bytes4 public constant INTERFACE_ID_ERC1155 = 0xd9b67a26;
+ bytes4 public constant INTERFACE_ID_ERC721 = type(IERC721).interfaceId;
+ bytes4 public constant INTERFACE_ID_ERC1155 = type(IERC1155).interfaceId;Resolution
Fixed in commit 49ed8ae1b8a03a63783213cf15f1c20b07481e86 .
| File | Fix commit | Type | Status |
contracts/Dyve.sol | 49ed8ae | Best Practices | Fixed |
In the functions closePosition and claimCollateral the order data is loaded as follows:
Order storage order = orders[orderHash];Since the mapping is loaded to a storage variable rather than a memory variable, accessing any elements inside the struct will incur a SLOAD operation, which can be expensive. The variable order can be changed to memory instead, reducing gas costs when accessing elements. It should be noted that changing the order status of a memory variable would not cause a change in storage. Also, when emitting the event using the memory variable, the order field will contain the unchanged BORROWED value, so the event emission would have to be changed as well. An example is shown below for the function claimCollateral.
function claimCollateral(bytes32 orderHash) external {
- Order storage order = orders[orderHash];
+ Order memory order = orders[orderHash];
// ...
- order.status = OrderStatus.EXPIRED;
+ orders[orderHash].status = OrderStatus.EXPIRED;
// ...
emit Claim(
order.orderHash,
order.orderType,
order.borrower,
order.lender,
order.collection,
order.tokenId,
order.amount,
order.collateral,
order.currency,
- order.status
+ OrderStatus.EXPIRED
);
}Recommendation
Change the variable order to memory to reduce storage queries to save gas.
Resolution
Fixed in commit 49ed8ae1b8a03a63783213cf15f1c20b07481e86 .
nonReentrant modifier should be added to all order management functions| File | Fix commit | Type | Status |
contracts/Dyve.sol | 49ed8ae | Best Practices | Fixed |
The function fulfillOrder(...) has the nonReentrant modifier, however the functions closePosition(...) and claimCollateral(...) do not. Under normal use cases, the user would not be expected to reenter these functions, so adding nonReentrant helps to prevent undefined behavior that could potentially lead to unexpected results.
Recommendation
Add the nonReentrant modifier to the functions closePosition(...) and claimCollateral(...).
Resolution
Fixed in commit 49ed8ae1b8a03a63783213cf15f1c20b07481e86 .
| File | Fix commit | Type | Status |
contracts/Dyve.sol | 49ed8ae | Best Practices | Fixed |
In the function cancelAllOrdersForSender(...), the number 500000 is hardcoded. It is considered a best practice to define arbitrary values as constants.
Recommendation
Consider using a constant variable instead of arbitrary numbers.
Resolution
Fixed in commit 49ed8ae1b8a03a63783213cf15f1c20b07481e86
_transferERC20 and _transferETH may transfer with no amount| File | Fix commit | Type | Status |
contracts/Dyve.sol | 49ed8ae | Best Practices | Fixed |
In the functions _transferERC20(...) and _transferETH(...) it is possible to have a protocolFee of zero if the lender owns an NFT from a "premium collection". Even if the protocolFee is zero, a transfer to protocolFeeRecipient is still attempted. In _transferEth(...) the call CALL(...) operation is still executed, costing unnecessary gas. In _transferERC20(...), on top of costing unnecessary gas, this can potentially lead to unexpected behavior as some ERC20 tokens may revert on zero transfers which would prevent an order from being fulfilled.
Recommendation
Consider checking if the fee amount to be sent to the protocol is zero, and if so, skip the transfer.
Resolution
Fixed in commit 49ed8ae1b8a03a63783213cf15f1c20b07481e86 .
| File | Fix commit | Type | Status |
contracts/Dyve.sol | 49ed8ae | Best Practices | Fixed |
In the definition of the struct Dyve.Order there is an inline documentation (shown below) stating that the Order.amount field should always be set to 1 in the case of an ERC721 order. However, there are no checks in the code to ensure this condition.
struct Order {
...
uint256 tokenId; // id of the token
uint256 amount; // amount of the token (only applicable for ERC1155, always set to 1 for ERC721)
uint256 duration; // duration of the borrow
...
}A similar situation occurs for the currency field. The documentation provided by the Dyve team describes the currency field as follows: "The type of ERC20 token to be used (zero address if native ETH is to be used)". However, this behavior does not exist in the code.
Recommendation
Ensure consistency between code and documentation.
Resolution
Fixed in commit 49ed8ae1b8a03a63783213cf15f1c20b07481e86 .
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 audited files follow the NatSpec documentation, which is the recommended way to document inline comments. There is only one function that does not have a NatSpec summary, which is hash() in OrderTypes.sol. The files have a comment ratio of 12.8% and 27.8%, respectively, which is satisfactory. Aside from the NatSpec documentation, the code contains some inline comments explaining specific workings, which are very helpful to understand the flow of the protocol and the inner workings of functions.
The README.md contains a short description of the protocol but does not contain any information to guide developers on how to install, compile and test the code. The image linked in the document appears to be a broken link, pointing to a different organization and repository. Dyve also provided external documentation to help with the audit process. The documentation covers three main sections:
All three sections contain detailed information about the system and how it is intended to work. We recommend the following improvements to be made to the current state of documentation:
README.md by adding instructions for initial setup, compiling and testing.,! with zero fees (84ms)
,! with non-zero fees (102ms)
,! premium collection maker field (84ms)
,! not own the specified token in the maker order (92ms)
The relevant output is presented below.
| 30Tests passed | 0Failed |
The complete test output is in the full 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.
The Leading Engineers of Blockchain Infrastructure