Download audit report
This document presents the security review performed by Nethermind on the Arcadia Finance contracts. Arcadia Finance is an opensource lending and borrowing protocol allowing users to access decentralized exchanges with borrowed funds. The audit focuses on two of their products: Arcadia Vaults and Arcadia Lending.
Arcadia Vaults are the core of Arcadia Finance’s product suite and are responsible for locking, pricing, and managing collateral. They are user-controlled vaults enabling the on-chain pricing of any combination of different types of assets in one single base currency. These vaults are non-custodial and function as decentralized and composable margin accounts, allowing individuals, DAOs, and other protocols to deposit and manage various assets as collateral. They also provide access to on-chain native leverage without requiring the creation of folded positions (repeatedly borrowing and depositing as much as possible) in lending protocols.
Arcadia Lending is the first financial product developed on top of the Arcadia Vaults. It is a non-custodial peer-to-contract lending protocol that allows users to borrow against a combination of assets. With Arcadia Vaults and Arcadia Lending, borrowers have the opportunity to borrow against their entire portfolio with just one position. Additionally, Arcadia Lending improves lenders’ experience by offering multiple options to provide liquidity depending on their risk appetite.
The audited code consists of 2,329 lines of Solidity. Of these lines, 1600 correspond to Arcadia Vault with code coverage of 92.75%. The other 729 corresponds to Arcadia Lending with code coverage of 100%. Overall, the audited code is of high quality and shows a strong understanding of Solidity’s best practices. The team provided documentation presenting the main use cases and protocol mechanisms. This documentation was supported by multiple walkthroughs of the code and continuous communication with the team. The audit was performed using (a) manual analysis of the codebase, (b) automated analysis tools, and (c) simulation of the smart contracts.
Some of the most relevant issues are related to the lack of checks when interacting with other trusted entities.
| Audit assessment | |
| Audit Type | Security Review |
| Initial Report | Feb. 27, 2023 |
| Response from Client | Mar. 1, 2023 |
| Final Report | Mar. 2, 2023 |
| Methods | Manual Review, Automated Analysis |
| Repository | Vaults, Lending Protocol |
| Commit Hash (Initial Audit - Vault) | 7baf91c039 |
| Commit Hash (Initial Audit - Lending) | 88a3bd12f0 |
| Commit Hash (Reaudit - Vault) | 0c2dc7b65e |
| Commit Hash (Reaudit - Lending) | 476620fab3 |
| Documentation | README.md - Vaults, README.md - Lending, Protocol docs |
| Documentation Assessment | High |
| Test Suite Assessment | High |
Findings by severity
| # | Contract | LoC | Comments | Ratio | Blank | Total |
| 1 | src/InterestRateModule.sol | 32 | 27 | 84.4% | 6 | 65 |
| 2 | src/TrustedCreditor.sol | 13 | 32 | 246.2% | 6 | 51 |
| 3 | src/Tranche.sol | 133 | 95 | 71.4% | 45 | 273 |
| 4 | src/DebtToken.sol | 54 | 79 | 146.3% | 23 | 156 |
| 5 | src/LendingPool.sol | 376 | 334 | 88.8% | 102 | 812 |
| 6 | src/libraries/DataTypes.sol | 9 | 6 | 66.7% | 1 | 16 |
| 7 | src/interfaces/IFactory.sol | 5 | 16 | 320.0% | 2 | 23 |
| 8 | src/interfaces/IVault.sol | 6 | 21 | 350.0% | 3 | 30 |
| 9 | src/interfaces/ITranche.sol | 5 | 12 | 240.0% | 2 | 19 |
| 10 | src/interfaces/ILendingPool.sol | 8 | 26 | 325.0% | 5 | 39 |
| 11 | src/interfaces/ILiquidator.sol | 4 | 12 | 300.0% | 1 | 17 |
| 12 | src/security/Guardian.sol | 84 | 85 | 101.2% | 18 | 187 |
| Total | 729 | 745 | 102.2% | 214 | 1688 |
The audit consists of two phases: a) Arcadia Vaults and b) Arcadia Lending. The Arcadia Vaults are the core of Arcadia Finance and are responsible for locking, pricing, managing, and liquidating collateral. The scope of this part consists of 30 contracts. Arcadia Lending is a protocol where users can borrow against a combination of assets. The scope of the lending part embraces 12 contracts.
Arcadia VaultsFig.2 presents the core contracts in Arcadia Vaults and their dependencies. In summary, Proxy, Factory, Vault, MainRegistry, Liquidator, and OracleHub are the contracts that implement key features provided by Arcadia Vaults. LendingPool is part of Arcadia Lending.
Proxy and FactoryThe Factory extends the abstract contracts FactoryGuardian and ERC721. Arcadia Vaults themselves are according to the ERC-721 standard and can thus be represented as a single asset. A vault is user-controlled and it is deployed through the proxy factory by the user calling the function createVault(...). Then, the user becomes the single owner of the deployed vault. The Factory manages all vaults with their respective version information. This contract has the following public functions. For simplicity reasons, we do not list functions in the contract ERC721 since it is a well-known open standard for unique tokens. We also omitted functions implemented in Owned.
− createVault(...)
− upgradeVaultVersion(...)
− safeTransferFrom(...)
− transferFrom(...)
− setNewVaultInfo(...)
− blockVaultVersion(...)
− liquidate(...)
− setBaseURI(...)
− changeGuardian(...)
− pause(...)
− unpause(...)In addition to these functions, the contract provides 6 (six) getters which are not described here.
VaultA deployed vault is linked to a specific vault logic contract that includes features from which the vault owner can benefit, such as flash withdrawals and active collateral management. This vault logic is upgradeable, but the vault owner can decide if or when they want to upgrade to the new version. Users can deposit assets (ERC20, ERC721, ERC1155, ...) in their respective vaults. The vault denominates all the pooled assets into one baseCurrency (one unit of account, e.g., USD or ETH). Users can use the single-denominated value of all their assets to take margin (take credit line, financing for leverage...). This contract has the following public functions:
− initialize(...)
− upgradeVault(...)
− upgradeHook(...)
− transferOwnership(...)
− setBaseCurrency(...)
− openTrustedMarginAccount(...)
− closeTrustedMarginAccount(...)
− liquidateVault(...)
− setAssetManager(...)
− vaultManagementAction(...)
− deposit(...)
− withdraw(...)
− skim(...)In addition to these functions, the contract also provides 10 (ten) getters which are not described here.
MainRegistryThe MainRegistry is a core part of the protocol. It contains all the information related to valid base currencies and their respective pricing modules, and it is the entity able to calculate the value stored in a Vault. End-users should not directly interact with the contract MainRegistry, only Vaults, Pricing Modules, or the contract owner. The public functions implemented in the contract are listed below:
− setAllowedAction(...)
− addBaseCurrency(...)
− addPricingModule(...)
− addAsset(...)
− batchProcessWithdraw(...)
− batchProcessDeposit(...)Moreover, this contract also provides 6 (six) getters which are not described here.
LiquidatorThe Liquidator holds the execution logic and storage of all information about liquidating Arcadia Vaults. For example, a Creditor can start an auction to liquidate the collateral of a vault, and any user (the bidder) can buy a vault and end the auction. This contract implements a dutch auction in which the price constantly decreases and the first bidder to buy the vault, immediately ends the auction. The public functions implemented in this contract are listed below:
− setWeights(...)
− setAuctionCurveParameters(...)
− setStartPriceMultiplier(...)
− setMinimumPriceMultiplier(...)
− startAuction(...)
− buyVault(...)
− endAuction(...)In addition to these functions presented above, this contract also provides 3 (three) getters which are not described here.
OracleHubThe contract OracleHub is responsible for storing the addresses and other necessary information of the Price Oracles and returns asset rates. Only MainRegistry, sub-registries, or the contract owner should directly interact with the Oracle Hub. The public functions implemented in this contract are listed below:
− addOracle(...)
− decommissionOracle(...)In addition to these functions presented above, this contract also provides 2 (two) getters which are not described here.
Arcadia LendingFig.3 presents the essential Arcadia Lending contracts and their main dependencies. In summary, Arcadia Lending is built on top of the Arcadia Vaults. The contracts Vault, Factory, and Liquidator are Arcadia Vaults’ contracts that the Lending interacts with. The core contracts in the Lending protocol are Tranche and LendingPool.
TrancheThe contract Tranche extends the Owned and ERC4626 contracts. The ERC-4626 standard is used to represent the interest-bearing positions of liquidity providers. Tranche allows for the lending of a specified ERC20 token, managed by a lending pool. This contract provides only the get function totalAssets(...). The public functions implemented in this contract are listed below:
− lock(...)
− unLock(...)
− setAuctionInProgress(...)
− deposit(...)
− mint(...)
− withdraw(...)
− redeem(...)
− totalAssetsAndSync(...)
− convertToSharesAndSync(...)
− convertToAssetsAndSync(...)
− previewDepositAndSync(...)
− previewMintAndSync(...)
− previewWithdrawAndSync(...)
− previewRedeemAndSync(...)LendingPoolThe contract LendingPool extends the contracts DebtToken, TrustedCreditor, Guardian, and InterestRateModel. The ERC-4626 standard is used to represent the open debt of borrowers (DebtToken). The abstract contract TrustedCreditor implements the minimum functionality to interact with Arcadia Vaults (we omitted this association in Fig.2 for simplicity reasons). The abstract contract Guardian provides a mechanism that allows authorized accounts to trigger an emergency stop. Finally, the contract InterestRateModel consists of functions to set the configuration parameters and calculate the interest rate.
LendingPool implements the main logic to provide liquidity and take or repay loans for a certain asset. This contract does the accounting of the debtTokens (ERC4626) and also provides liquidity against positions backed by Arcadia Vaults as collateral. The public functions implemented in this contract are listed below:
− addTranche(...)
− setInterestWeight(...)
− setLiquidationWeight(...)
− setMaxInitiatorFee(...)
− setTreasuryInterestWeight(...)
− setTreasuryLiquidationWeight(...)
− setTreasury(...)
− setOriginationFee(...)
− setBorrowCap(...)
− setSupplyCap(...)
− depositInLendingPool(...)
− donateToTranche(...)
− withdrawFromLendingPool(...)
− approveBeneficiary(...)
− borrow(...)
− repay(...)
− doActionWithLeverage(...)
− liquidityOfAndSync(...)
− setInterestConfig(...)
− liquidateVault(...)
− settleLiquidation(...)
− setVaultVersion(...)In addition to these functions presented above, this contract also provides 5 (five) getters which are not described here.
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 |
LendingPool.solVault.sol | PR #69 | Critical | Fixed |
The lending pool function doActionWithLeverage(...) allows users to borrow assets and execute some arbitrary actions through a vault, using the vault’s collateral. A condition that must be met after this action is that the vault should be in a healthy state. The doActionWithLeverage(...) function can be called by the vault owner, or by an approved beneficiary with some allowance. This allowance check relies on the Solidity 0.8 overflow feature to prevent spending more allowance than a caller has. When the amount is zero, this check will pass as no underflow occurs. The allowance check is shown below:
//Check allowances to take debt
if (vaultOwner != msg.sender) {
uint256 allowed = creditAllowance[vault][msg.sender];
if (allowed != type(uint256).max) {
creditAllowance[vault][msg.sender] = allowed - amountBorrowedWithFee;
}
}Following the allowance check, the vault debt will be updated and the borrowed assets will be transferred, but only if the amountBorrowedWithFee is not equal to zero. When this function is called with an amount of zero, the amountBorrowedWithFee will also be zero, so none of the debt updates or asset transfers will occur. This check is shown below:
if (amountBorrowedWithFee != 0) {
//Mint debt tokens to the vault, debt must be minted Before the actions in the vault are performed.
_deposit(amountBorrowedWithFee, vault);
//Send Borrowed funds to the actionHandler
asset.safeTransfer(actionHandler, amountBorrowed);
realisedLiquidityOf[treasury] += amountBorrowedWithFee - amountBorrowed;
emit Borrow(vault, referrer, amountBorrowedWithFee);
}This means that any caller who passes an amount of zero will pass all checks and state updates, but the target vault’s vaultManagementAction(...) function will still execute with the actionHandler and actionData of the caller’s choosing. An attacker could use this behavior to execute arbitrary calls on behalf of any vault with its trusted creditor set to a lending pool, as long as after the arbitrary call the vault is still considered healthy. A possible action an attacker could do is transfer all unused collateral to their own address.
Recommendation
Ensure that amount cannot be zero in doActionWithLeverage(...).
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-lending/pull/69 . The proposed fix would disallow users to send a transaction that takes 0 additional debt. Although users should in that case directly call the vault, it should remain a valid transaction. The implemented resolution is to enforce that anyone calling the doActionWithLeverage who is not the owner of the vault, has an infinite creditAllowance for that vault. We thus assume that a user that sets an ’infinite approval for allowance’ for a third party also trusts that third party with the funds in their vault (as the third party could lock the entire vault either way by taking additional debt in the name of the vault).
baseCurrency may differ from the one set by the TrustedCreditor| File | Fix commit | Type | Status |
Vault.solLendingPool.sol | PR #235 | Critical | Fixed |
When a vault opens a new margin account, it sets its base currency to the one selected by the TrustedCreditor. However, until the vault has any used margin, the owner can change the base currency of the vault. The function that allows this change is shown in the code snippet below.
function setBaseCurrency(address baseCurrency_) external onlyOwner {
require(getUsedMargin() == 0, "V_SBC: Non-zero open position");
_setBaseCurrency(baseCurrency_);
}This difference between currencies could cause multiple issues. Two different scenarios where this issue could affect the protocol are described below.
Scenario 1: A user can borrow more assets than their collateral. When a user borrows assets, a check is done to ensure that the vault used as collateral is in a healthy state after accruing the new debt. To check if a vault is healthy at a specific time, the vault’s collateral value is compared with the vault’s used margin. This check can be found multiple times throughout the code and can be seen in the code snippet below.
...
uint256 usedMargin = getUsedMargin();
if (usedMargin > 0) {
uint256 collValue = getCollateralValue();
require(collValue >= usedMargin, "V_VMA: coll. value too low");
}
...The getCollateralValue() and getUsedMargin() functions can be seen in the snippet of code below.
function getCollateralValue() public view returns (uint256 collateralValue) {
// @audit - This function returns the assets in the vault
(...) = generateAssetData();
// @audit - This function will return the collateral value of all the assets in the vault
collateralValue =
IMainRegistry(registry).getCollateralValue(...);
}
function getUsedMargin() public view returns (uint256 usedMargin) {
if (!isTrustedCreditorSet) return 0;
//getOpenPosition() is a view function, cannot modify state.
usedMargin = ITrustedCreditor(trustedCreditor).getOpenPosition(address(this));
}As can be seen from the code, the result of the getCollateralValue() function will be denominated in the vault’s base currency. The result of the function getUsedMargin() depends on the TrustedCreditor. In the current implementation, the LendingPool contracts occupy this role. The LendingPool will return the debt accrued to the vault, and it will be denominated in the underlying token of the LendingPool. As mentioned before, these currencies may be different, causing the health check for the vault to return an incorrect value. For example, if the user has 1 ETH as collateral, it would have a nominal value of 1e18. If the underlying asset of the LendingPool is USDC, which has 6 decimals, the user could potentially borrow millions of USDC with just 1 ETH as collateral.
Scenario 2: Assets can be locked in the LendingPool. When liquidating a vault, the price of it is paid in its base currency. This payment is then transferred to the LendingPool, where it is added to the realized liquidity. However, if the base currency of the vault is different from the underlying asset of the LiquidityPool, the LiquidityPool cannot transfer or use these assets.
Recommendation
Allow to change the baseCurrency of the Vault only if there is no open margin account
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-vaults/pull/235 .
| File | Fix commit | Type | Status |
LendingPool.sol | PR #234 PR #66 | Critical | Fixed |
A vault can interact with a lending pool even if it does not match its trusted creditor. When borrowing assets using borrow(...) or doActionWithLeverage(...), debt tokens are minted to the borrowing vault. Vaults are allowed to borrow optimistically, where a health check through the function isVaultHealthy(...) is done after the debt has been given. The vault function isVaultHealthy(...) only checks the debt tokens of its current trusted creditor. In the case where you borrow from a lending pool different from your trusted creditor, your vault’s used margin will not change. This allows a user to borrow unlimited assets from any pool without becoming undercollateralized.
Recommendation
When borrowing from a vault, ensure that the vault’s trusted creditor is equal to the lending pool address.
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-vaults/pull/234 , and https://github.com/arcadia-finance/arcadia- lending/pull/66 .
A vault has two privileged roles: Beneficiary and Asset Manager. The beneficiary role can borrow on behalf of the vault, and the asset manager role can execute arbitrary calls using the vault’s funds. Upon ownership change such as through liquidations or selling vaults, the vault owner is updated, however, the privileged roles are not reset. Since previous privileged roles were not cleared, the new owner may have their assets transferred or borrowed by addresses trusted by the previous owner, but not the new owner. This behavior can be combined with a liquidation event to steal more funds than were originally in the vault. When a liquidation event starts, the debt tokens belonging to the liquidated vault are set to zero as shown below in LendingPool:
function liquidateVault(address vault) external whenLiquidationNotPaused processInterests {
...
//Remove debt from Vault (burn DebtTokens)
_withdraw(openDebt, vault, vault);
}During liquidation, the owner is also removed from the vault. Since the collateral is still in the vault but the debt has been set to zero, the privileged roles can use the assets again. This allows for two scenarios depending on the role:
borrow(...) and doActionWithLeverage(...) while the auction is still in progress. These funds can be borrowed without the intention to return, allowing the original owner to keep their borrowed funds, and then borrow using their collateral once again;vaultManagementAction(...) to execute an arbitrary call to transfer the collateral tokens. Since the debt has been reset, the under-collateralization check will pass and the tokens will be transferred. This allows the original owner to keep their borrowed funds, and then recover their collateral as well.Recommendation
Ensure that the privileged roles are cleared during liquidation or when ownership is transferred.
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-vaults/pull/237 , and https://github.com/arcadia-finance/arcadia- lending/pull/67 .
openDebt during Vault liquidation| File | Fix commit | Type | Status |
LendingPool.sol | PR #68 | Medium | Fixed |
To initiate a liquidation for a vault, the function liquidateVault(...) in the LendingPool contract must be called. This function performs the following actions:
openDebt for the vault;The openDebt value is a crucial component of the liquidation process. It is used to calculate the liquidation price and to determine if bad debt exists after liquidation. The following line of code is used to calculate the openDebt for a vault.
uint256 openDebt = balanceOf[vault];However, the balance in the LendingPool refers to the DebtTokens owned by the vault, not the outstanding debt for that vault. Using DebtTokens instead of the actual debt would cause the openDebt used for the liquidation process to be smaller than the actual debt accrued by the vault. This has multiple consequences, such as:
Recommendation
Instead of setting openDebt equals to balanceOf[vault], consider setting it to maxWithdraw(vault), as shown below.
- uint256 openDebt = balanceOf[vault];
+ uint256 openDebt = maxWithdraw(vault);Resolution
Fixed in https://github.com/arcadia-finance/arcadia-lending/pull/68 What essentially would happen here is a partial liquidation: only part of the openDebt is withdrawn (the realized portion), and only for this part of the openDebt, the auction price is calculated. In practice, this would be only a very limited difference, being the accrued interests. Although this was unintended behavior, this wouldn’t lead to user or protocol loss of funds. The interests that have been added to the realized liquidity would remain as open debt on the vault.
Imagine the scenario:
Now the vault gets liquidated, and it gets auctioned for 10. Now, the vault buyer receives a vault, but it still has 1 debt. There is no loss of funds and no errors in accounting, although we do agree that this was an unforeseen scenario.
WETH tokenWhen depositing or withdrawing tokens to a vault, the user passes an array assetTypes as an argument to specify which type of asset its associated address in the assetAddresses array is. The asset type will determine which internal deposit or withdrawal function to use. However, there are no checks to ensure that an address matches the type passed by the user. During a deposit, it is possible for a user to pass an ERC20 token address, but set the asset type to indicate that it’s an ERC721 token. This would lead to _depositERC721(...) being called, which would attempt to call safeTransferFrom(...) on the ERC20 token which does not exist. For most tokens, this would revert and no damage to the protocol can be done. The function is shown below:
function _depositERC721(address from, address ERC721Address, uint256 id) internal {
IERC721(ERC721Address).safeTransferFrom(from, address(this), id);
erc721Stored.push(ERC721Address);
erc721TokenIds.push(id);
}For the token WETH a different behavior will occur. WETH implements a fallback function that takes the msg.value and increments the caller’s balance. In the case of the safeTransferFrom call above, this would be a zero value call so no balance change would occur, but the call would still succeed rather than reverting. The fallback function is shown below:
function() public payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
Deposit(msg.sender, msg.value);
}An attacker can pass WETH for a deposit or withdrawal stating that it is an ERC721 token, and use the fallback behavior of WETH to successfully call deposit(...) and withdraw(...) without transferring any balance. In both functions, the following call to update the pricing module exposure will still occur, as shown below:
// When depositing
IMainRegistry(registry).batchProcessDeposit(assetAddresses, assetIds, assetAmounts);
// When withdrawing
IMainRegistry(registry).batchProcessWithdrawal(assetAddresses, assetIds, assetAmounts);This allows an attacker to arbitrarily manipulate the exposure of the WETH pricing module. The exposure can be set to zero, in which case any further withdrawals by other users will lead to reverting as they attempt to subtract their withdrawal amount from zero. This would lead to users’ funds being permanently locked. The exposure can also be increased to the max exposure, preventing any further deposits from other users and acting as a deposit DOS. The exposure can also be set to any value in between, allowing for subtle changes in exposure that result in higher or lower levels of risk than expected.
Recommendation
Check that asset types are correct for each asset.
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-vaults/pull/240 . The team has assessed the High classification and deems this to be too high. Although this could temporarily block users’ funds, it can be relatively easily mitigated by bundling a flash bots transaction where the exposure is increased together with a withdrawal call. Alternatively, users could upgrade to a new vault version where the batch process is skipped and where debt can only be repaid, and as such allow users to withdraw assets. This would not lead to any user (borrower or LP) nor protocol losses.
Update from Nethermind Security
After the discussion with the client, we agreed to downgrade the severity to Medium.
| File | Fix commit | Type | Status |
Factory.sol | PR #242 | Medium | Fixed |
Users deploy their vaults through the function createVault(...) which uses the CREATE2 opcode to deploy the vault to a deterministic address. The salt used for deployment is controlled by the caller through the argument salt. It is possible for a user’s vault deployment transaction to be front-run by an attacker, where the attacker’s transaction uses the same salt argument. This would lead to the attacker’s transaction executing first, making them the owner of the new contract. When the user’s transaction executes the vault deployment will fail as the attacker’s vault is already deployed at that address. This can be used for DOS vault deployment against any user or allow a targeted DOS against a specific address (for example, a particular ENS domain address).
Recommendation
Consider mixing the user-provided salt argument with msg.sender to ensure that deployed vault addresses will still be deterministic per caller, but two different callers with the same salt will not get the same vault address.
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-vaults/pull/242 . Note that we used tx.origin instead of msg.sender, as such even vaults deployed via a third contract cannot be front-runned.
minPriceMultiplier is not scaled to 20 decimals in _calcPriceOfVault(...)| File | Fix commit | Type | Status |
Liquidator.sol | PR #238 | Medium | Fixed |
The minPriceMultiplier is a two-decimal value used to calculate the vault pricing during an auction. For example, a minimum price multiplier of 30 would represent 30%. This value is used by _calcPriceOfVault(...) to determine the pricing of a vault based on the current time and cut-off time. When the cut-off time has not been reached, the following formula is used:
price = openDebt * (LogExpMath.pow(base, timePassed) * (startPriceMultiplier - minPriceMultiplier) + minPriceMultiplier) / 1e20;
// NOTE: timepassed = (block.timestamp - startTime) * 1e18The final minPriceMultiplier which is only two decimals is added to an 18-decimal value. When the division by 1e20 occurs, the added minPriceMultiplier is insignificant and the integer division will disregard the value completely. This causes the sum minPriceMultiplier to effectively play no part in the final price calculation. This impacts the vault auction price by causing it to be lower than expected, which is demonstrated below.
Scenario: Consider the following values set in the Liquidator contract:
startPriceMultiplier = 110 // 2 decimals
minPriceMultiplier = 50 // 2 decimals
cutoffTime = 14400
base = 1e18 // 18 decimalsLet’s assume that 6000 seconds have passed, so approximately 42% of the time before cutoffTime:
timepassed = 6000 * 1e18 = 6000000000000000000000 // 18 decimals
openDebt = 10000We would expect the resulting price to simply be openDebt * startPriceMultiplier because the base is 1e18 and the cutoffTime has not been exceeded. However, we actually calculate the price to be:
price = openDebt * (LogExpMath.pow(base, timePassed) * (startPriceMultiplier - minPriceMultiplier) + minPriceMultiplier) / 1e20;
price = 10000 * (LogExpMath.pow(1e18, 6000000000000000000000) * (110 - 50) + 50) / 1e20;
price = 10000 * (1e18 * (60) + 50) / 1e20;
price = 10000 * (6e19 + 50) / 1e20;
price = (6e23 + 500000) / 1e20;
price = 6000;Since the base is 1e18 in our scenario, we do not expect the price to decrease regardless of the time elapsed. The calculated price should always be openDebt * startPriceMultiplier = 11000 in our example. However, the price that we calculated was 6000, which is incorrect. If we run the same calculation but adjust the sum minPriceMultiplier to be 20 decimals we will receive the proper vault price:
price = openDebt * (LogExpMath.pow(base, timePassed) * (startPriceMultiplier - minPriceMultiplier) + (minPriceMultiplier * 1e18)) / 1e20;
price = 10000 * (LogExpMath.pow(1e18, 6000000000000000000000) * (110 - 50) + 5e19) / 1e20;
price = 10000 * (1e18 * (60) + 5e19) / 1e20;
price = 10000 * (6e19 + 5e19) / 1e20;
price = (6e23 + 5e23) / 1e20;
price = 11e23 / 1e20;
price = 11000;We can observe that when minPriceMultiplier is not brought up to 20 decimals, the purchase price of the vault in an auction is lower than expected.
Recommendation
Ensure that the sum for minPriceMultiplier is scaled to 18 decimals.
- price = openDebt
- * (LogExpMath.pow(base, timePassed) * (startPriceMultiplier - minPriceMultiplier) + minPriceMultiplier)
- / 1e20;
+ price = openDebt
+ * (LogExpMath.pow(base, timePassed) * (startPriceMultiplier - minPriceMultiplier) + uint256(minPriceMultiplier)*1e18)
+ / 1e20;Resolution
Fixed in https://github.com/arcadia-finance/arcadia-vaults/pull/238 . The team has assessed the High classification and argues that this classification is too high. A first -and valid- implementation of Arcadia’s auction curves was to let auction prices go to zero altogether.
Although the minPriceMultiplier’s decimals are not correct in this implementation, the auction price curve would still pass all price levels and would thus still be able to be sold to atomic liquidators at the market- or similar price. Besides that, we possess multiple other degrees of freedom by using other auction curve parameters to create a similar curve as the curve that was expected when minPriceMultiplier had the foreseen decimals. This issue is relatively easily mitigated and we do not see this issue causing protocol-wide (or any) loss. We thus propose a Low or Medium classification.
Update from Nethermind Security
After the discussion with the client, we agreed to downgrade the severity to Medium.
| File | Fix commit | Type | Status |
OracleHub.sol | PR #257 | Low | Fixed |
New assets are added to the main registry by pricing modules with the function addAsset(...). Assets’ additional data are also stored in mapping assetToInformation in the pricing module. Before that, the array oracles is checked with a call to OraclesHub.checkOracleSequence(...). However, the function does not check if the array oracles is not empty, which allows it to add assets without oracles. The oracles are also not checked if they are active, so assets may be added with inactive oracles.
New assets are added to the main registry through a pricing module contract with the function addAsset(...). When adding an asset the caller must provide a sequence of oracles, which are validated in OracleHub.checkOracleSequence(...). However, there are no checks to ensure the following conditions: a) the provided array of oracles must not be empty; b) all of the provided oracles must be active.
Recommendation
Check-in OraclesHub.checkOracleSequence(...) if the array oracles is not empty, and if the provided oracles are active.
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-vaults/pull/257 .
| File | Fix commit | Type | Status |
StandardERC20PricingModule.sol | PR #257 | Low | Fixed |
The function addAsset(...) will add a new asset to the MainRegistry. As part of the asset information, this function receives a sequence of oracles to price the asset in USD. This sequence of oracles is checked in the function checkOracleSequence(...) from the OracleHub contract. The check is shown in the code snippet below.
function addAsset(...)
external
onlyOwner
{
require(!inPricingModule[asset], "PM20_AA: already added");
IOraclesHub(oracleHub).checkOracleSequence(oracles);
inPricingModule[asset] = true;
assetsInPricingModule.push(asset);
uint256 assetUnit = 10 ** IERC20(asset).decimals();
require(assetUnit <= 1e18, "PM20_AA: Maximal 18 decimals");
assetToInformation[asset].assetUnit = uint64(assetUnit);
assetToInformation[asset].oracles = oracles;
_setRiskVariablesForAsset(asset, riskVars);
exposure[asset].maxExposure = maxExposure;
IMainRegistry(mainRegistry).addAsset(asset);
}The checkOracleSequence(...) function ensures that the provided oracle sequence meets the following requirements:
OracleHub;baseAsset of each oracle must be equal to the quoteAsset of the next oracle;However, there is no check ensuring that the quoteAsset of the first oracle is the same as the asset being added. If the first oracle of the sequence has an incorrect quoteAsset, the returned price could be wrong.
Recommendation
Consider adding a check to ensure that the quoteAsset from the first oracle is the same as the asset being added, otherwise revert.
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-vaults/pull/257 .
| File | Fix commit | Type | Status |
Liquidator.sol | PR #259 | Low | Fixed |
The owner of the Liquidator contract has access to the function setMinimumPriceMultiplier(...) which allows the minPriceMultiplier to be set to a value within the range of 0 to 90. When a vault is on auction, the price is found using _calcPriceOfVault(...) which uses minPriceMultiplier as part of the price calculation.
If the Liquidator owner address becomes compromised (private key breach or multi-sig issue), since setMinimumPliceMultiplier(...) can be called at any time by the owner, it is possible for the owner to abuse the minPriceMultiplier by setting it to a very low value, purchasing the vault, and then returning the value back to normal.
As described below in _calcPriceOfVault(...), while timePassed is not greater than cutoffTime, the vault price continuously decreases. If minPriceMultiplier is set during an active auction, the prices can decrease faster than expected.
function _calcPriceOfVault(uint256 startTime, uint256 openDebt) internal view returns (uint256 price) {
uint256 timePassed;
unchecked {
timePassed = block.timestamp - startTime;
if (timePassed > cutoffTime) {
price = openDebt * minPriceMultiplier / 1e2;
} else {
timePassed = timePassed * 1e18;
price = openDebt
* (LogExpMath.pow(base, timePassed) * (startPriceMultiplier - minPriceMultiplier) + minPriceMultiplier)
/ 1e20;
}
}
}Recommendation
Consider setting some lower limit to the minPriceMultiplier in setMinimumPriceMultiplier(...) or prevent minPriceMultiplier from being changed while an auction is live.
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-vaults/pull/259 . The implemented solution stores all auction curve data per auction, and as such the owner has no influence on the price curve of any ongoing auction. We do like to mention that this finding implies the private keys of n of the n-out-of-m multisign signers of the liquidator contract are compromised.
| File | Fix commit | Type | Status |
MainRegistry.solOracleHub | PR #244 PR #258 | Low | Mitigated |
The function getListOfValuesPerAsset(...) may use ChainLink oracles to compute some of the asset’s values. However, the values returned by these oracles are not checked to be up to date. Relevant parts of the function are reproduced in the snippet of code below.
function getListOfValuesPerAsset(...) public view returns (RiskModule.AssetValueAndRiskVariables[] memory) {
...
if (rateBaseCurrencyToUsd == 0) {
//Get the BaseCurrency-USD rate
// @audit - This does not ensure that the data is not stale
(, rateBaseCurrencyToUsd,,,) = IChainLinkData(
baseCurrencyToInformation[baseCurrency].baseCurrencyToUsdOracle
).latestRoundData();
...Using a stale value could affect the returned values.
Recommendation
Consider checking if the fetched data was updated recently enough.
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-vaults/pull/244 . I used a similar pattern to also allow the owner of the ERC20PricingModule to update price oracles for an asset, but only if one of the oracles was decommissioned first: https://github.com/arcadia-finance/arcadia-vaults/pull/258 .
| File | Fix commit | Type | Status |
DebtToken.sol | PR #70 PR #245 | Low | Fixed |
When users borrow funds from the LendingPool, an amount of DebtToken is minted for the user based on the current rate between the underlying asset and share. However, when calculating the number of shares, the current implementation rounds up for deposits and rounds down for withdrawals. This rounding issue can be exploited by attackers to steal funds from the LendingPool. For example, let’s say that Alice is the first user to borrow from the LendingPool, and she borrows amount = 1000. The state of the pool would be:
realisedDebt = 1000
balanceOf[Alice] = 1000
totalSupply = 1000Sometime after that, Bob borrows amount = 95 from the LendingPool. Because some time had passed, there is an unrealized debt of 100, so the current state of the pool is:
realisedDebt = 1000
unrealisedDebt = 100
=> totalAssets() = 1100The amount of DebtToken received by Bob is computed in the following way:
shares = mulDivDown(assets, totalSupply, totalAssets)
= roundDown((95 * 1000) / 1100)
= roundDown(86.3) = 86After borrowing, the LendingPool is in the following state:
totalAsset() = realisedDebt + unrealisedDebt + 86 = 1186
balanceOf[Alice] = 1000, balanceOf[Bob] = 86
totalSupply = 1086If in the same block, Bob tries to repay amount = 93, the amount of DebtTokens that will be burned is computed in the following way:
shares = mulDivUp(assets, totalSupply, totalAsset)
= roundUp((93 * 1086) / 1186)
= roundUp(85.15)
= 86
balanceOf[Bob] = 0So, he will have repaid less than he borrowed, even though all his Debt Tokens were burnt.
Recommendation
To prevent this issue, we recommend rounding up in function _deposit(...) and rounding down in function _withdraw(...) when calculating shares.
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-lending/pull/70 , and https://github.com/arcadia-finance/arcadiavaults/pull/245 .
settleLiquidation(...)| File | Fix commit | Type | Status |
LendingPool.sol | — | Low | Acknowledged |
Arcadia Lending has been designed such that liquidity providers are able to choose distinct risk tranches that align with their respective risk profiles. In the event of any defaults, the most junior tranche will experience a reduction in their underlying tokens. Additionally, if the most junior tranche is entirely wiped out, the next most junior tranche will assume responsibility, and so on. However, the current implementation only locks the most junior tranche during liquidation auctions. This could potentially allow liquidity providers from other tranches to withdraw their funds as soon as the auction price went down and had potential effects on their own tranche.
Recommendation
Consider locking all tranches during the liquidation auction.
Resolution
This is a design choice. Default events should already occur very exceptionally, a complete wipe-out of the junior tranche is an unhappy flow of an unhappy flow and should never occur in practice. We do not want to block the LPs in more senior tranches to avoid certain from frontrunning in a scenario that in theory should never occur.
vaultManagementAction(...)Each vault has an asset limit to ensure that users cannot deposit too many assets. This check exists in the function deposit(...) and is shown below:
function deposit(...) external onlyOwner {
uint256 assetAddressesLength = assetAddresses.length;
require(
assetAddressesLength == assetIds.length && assetAddressesLength == assetAmounts.length
&& assetAddressesLength == assetTypes.length,
"V_D: Length mismatch"
);
_deposit(assetAddresses, assetIds, assetAmounts, assetTypes, msg.sender);
require(erc20Stored.length + erc721Stored.length + erc1155Stored.length <= ASSET_LIMIT, "V_D: Too many assets");
}However, this asset limit can be bypassed through the function vaultManagementAction(...), as it makes a call directly to _deposit(...) without checking if the asset limit has been reached.
Recommendation
Ensure that the asset limit is checked both during calls to deposit(...) and vaultManagementAction(...).
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-vaults/pull/239 .
| File | Fix commit | Type | Status |
LendingPool.solVault.sol | PR #237 PR #67 PR #69 | Low | Fixed |
The role of asset manager for a vault should only be assigned to fully trusted accounts. Accounts with this role can use the function vaultManagementAction(...) to execute arbitrary calls using funds from the vault. With the condition that after executing these calls the vault stays in a healthy state. However, the function vaultManagementAction(...) can be also called through the function doActionWithLeverage(...) (located in the LendingPool contract) if the LendingPool is the current TrustedCreditor of the vault.
A user should be able to call doActionWithLeverage(...) for a vault if it is the owner of the vault, or if it has any credit given for this vault. Credit or allowance for a vault is a quantitative measure of trust, but because any amount of allowance permits the user to execute the doActionWithLeverage(...) function, giving the minimum amount of allowance to a user implies full trust over that user.
Recommendation
Only allow the owner and asset managers of a vault to execute doActionWithLeverage(...) for the vault.
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-vaults/pull/237 , https://github.com/arcadia-finance/arcadialending/pull/67 , and https://github.com/arcadia-finance/arcadia-lending/pull/69 .
When withdrawing ERC721 assets from a vault, the internal function _withdrawERC721(...) will handle the token transfer, as well as update erc721Stored and erc721TokenIds if necessary.
It is possible to transfer an ERC721 token directly to the vault contract without using the proper deposit(...) function. By skipping deposit(...), the following is not updated:
erc721TokenIds array;erc721Stored array;Once a direct ERC721 transfer is done, it is possible to withdraw the token through the proper withdraw(...) function, which decreases the token’s pricing module exposure even though it was never increased because deposit(...) was not called. There are two approaches to successfully decreasing an ERC721 pricing module exposure:
The vault has no tracked ERC721 tokens: An ERC721 token is directly transferred to the vault contract. During the withdrawal process, the tokenIdLength will be zero so the logic in the else statement will execute. Since the tokenIdLength is zero the for loop will execute zero times and the token will be transferred from the vault to the to address. The vault has one tracked ERC721 token: The vault has only one ERC721 token that has been correctly deposited. An ERC721 token of a different collection is then transferred directly to the vault. During the withdrawal process for the directly transferred token, the tokenIdLength is one, so erc721TokenIds and erc721Stored (containing only one entry) are both popped. The directly transferred token is then transferred to the to address. Note that now the properly added ERC721 token is not tracked, so approach (1) can be used to recover these tokens (which will reduce the exposure back to the correct level) or the token can be skimmed which will leave the exposure increased.
Both approaches allow the exposure of an ERC721 pricing module to be reduced, which will eventually prevent users from withdrawing due to overflow checks when the exposure tries to decrease from zero. Approach (2) allows for the exposure to be increased, which could be used to reach the max deposit and DOS any deposits by other users. This finding has a severity of undetermined as part of the exploit path involves the ERC721 pricing module which is out of scope, however, this finding is still present in the report as the cause of this issue exists in the in-scope Vault contract. The function is shown below:
function _withdrawERC721(address to, address ERC721Address, uint256 id) internal {
uint256 tokenIdLength = erc721TokenIds.length;
if (tokenIdLength == 1) {
// there was only one ERC721 stored on the contract, safe to remove both lists
erc721TokenIds.pop();
erc721Stored.pop();
} else {
for (uint256 i; i < tokenIdLength;) {
if (erc721TokenIds[i] == id && erc721Stored[i] == ERC721Address) {
erc721TokenIds[i] = erc721TokenIds[tokenIdLength - 1];
erc721TokenIds.pop();
erc721Stored[i] = erc721Stored[tokenIdLength - 1];
erc721Stored.pop();
break;
}
unchecked {
++i;
}
}
}
IERC721(ERC721Address).safeTransferFrom(address(this), to, id);
}Recommendation
Ensure that in _withdrawERC721 the token being withdrawn and its ID exists in the erc721Stored and erc721TokenIds arrays.
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-vaults/pull/241 .
latestVaultVersion| File | Fix commit | Type | Status |
Factory.sol | — | Info | Mitigated |
In the vault factory it is possible for the owner to block a particular vault version from being deployed or upgraded. However in the case that the vault version being blocked is the latest version, the state variable latestVaultVersion does not change. This affects the createVault(...) function, as an expected feature is that you can pass 0 as the vaultVersion to use the latest vault version. When a user does this, a require statement checking for a blocked version would revert when a user tries to deploy with the latest vault version, which may confuse users.
It is challenging to address this issue as simply rolling back the latest vault version will lead to the version information getting overwritten on the next vault update. If this approach is taken, the vault upgrade Merkle tree must also support the blocked latest version (for users that deployed the vault before it was blocked).
Recommendation
This issue can be addressed by changing the contracts, however, an alternative option is to be prepared to modify the website UI to designate a particular unblocked vault version as the default instead of using the latest.
Resolution
This issue will need to be addressed at the level of the website UI, not the smart contracts
liquidatorWhile closing a margin account using closeTrustedMarginAccount(...) the values such as isTrustedCreditorSet and trustedCreditor are reset, while the liquidator value is not.
function closeTrustedMarginAccount() external onlyOwner {
require(isTrustedCreditorSet, "V_CTMA: NOT SET");
//getOpenPosition() is a view function, cannot modify state.
require(ITrustedCreditor(trustedCreditor).getOpenPosition(address(this)) == 0, "V_CTMA: NON-ZERO OPEN POSITION");
isTrustedCreditorSet = false;
trustedCreditor = address(0);
}Recommendation
Consider resetting liquidator while closing a margin account.
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-vaults/pull/254 .
changeGuardian(...) does not emit the oldGuardian| File | Fix commit | Type | Status |
BaseGuardian.solGuardian.sol | PR #250 PR #71 | Info | Fixed |
The function changeGuardian(...) is used to set the guardian address. The function should emit an event with the oldGuardian and newGuardian addresses. However, the event is triggered after updating the new address, thus, overriding the current guardian.
function changeGuardian(address guardian_) external onlyOwner {
guardian = guardian_;
///////////////////////////////////////
// @audit Event is not emitting the oldGuardian
/////////////////////////////////
emit GuardianChanged(guardian, guardian_);
}Recommendation
Consider emitting the event GuardianChanged before the new guardian address is set or create a temporary variable to save the oldGuardian address.
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-vaults/pull/250 , and https://github.com/arcadia-finance/arcadia- lending/pull/71 .
baseCurrency is used| File | Fix commit | Type | Status |
MainRegistry.sol | PR #248 | Info | Fixed |
The following functions receive an argument baseCurrency which indicates which base currency the asset value should be denominated in the functions below.
- getListOfValuesPerAssets(address[],uint256[],uint256[],address)
- getCollateralValue(...)
- getLiquidationValue(...)
- getTotalValue(address[],uint256[],uint256[],address)If an invalid baseCurrency is used, the mapping assetToBaseCurrency will return the value 0, which is a valid identifier for the base currency USD. Users would expect that passing some asset as baseCurrency would return the value of the assets denoted in their chosen base currency, however, if an invalid baseCurrency is provided, these functions will silently default to USD without giving any warning to the user.
Recommendation
Consider adding a check to ensure that the received baseCurrency is valid and revert otherwise.
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-vaults/pull/248 .
| File | Fix commit | Type | Status |
MultiCall.sol | PR #255 | Info | Fixed |
The function ActionMultiCall.executeAction(...) allows the vault to make arbitrary calls while using its assets. At the end of the function, the field incoming.assetAmounts is updated for ERC20 and ERC1155 tokens, but not for ERC721 tokens. While ERC721 token transfers do not require an amount, the vault still needs the amount for this token to be set to 1. Failing to set the incoming.assetAmounts for the ERC721 token in the actionData call may result in the token being left in the action handler contract.
Recommendation
Consider setting the amount for ERC721 tokens to 1 in the ActionMultiCall.executeAction(...) function.
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-vaults/pull/255 .
| File | Fix commit | Type | Status |
Liquidator.sol | — | Info | Acknowledged |
In the Liquidator contract constructor, the state variable base is set to 1e18. This variable is used to compute the vault price in the _calcPriceOfVault(...) function. The base determines how quickly the price decreases over time. The vault price is expected to decrease over time in a dutch auction fashion. Therefore, the value returned by the LogExpMath.pow(base, timePassed) function should be strictly less than 1. However, with the current base value, the LogExpMath.pow(base, timePassed) function will always return 1, and the vault price will never decrease as long as timePassed is less than or equal to cutoffTime.
constructor(...){
...
base = 1e18;
}
function _calcPriceOfVault(uint256 startTime, uint256 openDebt) internal view returns (uint256 price) {
...
price = openDebt
* (LogExpMath.pow(base, timePassed) * (startPriceMultiplier - minPriceMultiplier) + minPriceMultiplier)
/ 1e20;
}Recommendation
It is recommended to set a decreasing curve for the price of vaults in the constructor.
Resolution
It will be set in the constructor before contracts are deployed.
The function _depositERC20(...) checks the return value from token transfer.
require(IERC20(ERC20Address).transferFrom(from, address(this), amount), "V_D20: Transfer from failed");That makes a problem for depositing tokens that do not return a success value (e.g. USDT ), and the require statement would fail even if the transfer was successful. Note that the same issue is in functions skim(...) and _withdrawERC20(...).
Recommendation
Consider using the SafeERC20 library to allow for tokens that do not return on a successful transfer. Alternatively, ensure that the whitelisted ERC20 tokens that are allowed to be used as collateral all return true on a successful transfer.
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-vaults/pull/256 .
onERC721Received(...) in factory contract| File | Fix commit | Type | Status |
Factory.sol | PR #247 | Info | Fixed |
The factory contract implements the function onERC721Receieved(...) which allows contracts to receive ERC721 tokens. Since the factory is an ERC721 token itself, it should not need to hold any token, and transferring any ERC721 token to the factory will result in a loss of funds.
Recommendation
Consider removing the function onERC721Received(...) in the factory contract.
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-vaults/pull/247 .
assetIds length may differ from amounts| File | Fix commit | Type | Status |
MainRegistry.sol | PR #251 PR #251 | Info | Fixed |
The function batchProcessWithdrawal(...) receives arrays as parameters that need to have the same length. However, there is no check for the array assetIds length.
function batchProcessWithdrawal(
address[] calldata assetAddresses,
uint256[] calldata assetIds,
uint256[] calldata amounts
) external whenWithdrawNotPaused onlyVault {
uint256 addressesLength = assetAddresses.length;
require(addressesLength == amounts.length, "MR_BPW: LENGTH_MISMATCH");
...
}Recommendation
Consider comparing the length of the array assetIds with assetAddresses or amounts arrays.
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-vaults/pull/251 . This would in practice never have been a problem since there were redundant checks on the length of arrays in the deposit() and withdraw() in Vault.sol. We have however also removed these redundant checks in commit hash ff07b19d2618f9606b17d1e69da4703ae0bd182c.
getListOfValuesPerAsset(...)| File | Fix commit | Type | Status |
MainRegistry.sol | PR #253 PR #253 | Best Practices | Fixed |
In the function getListOfValuesPerAsset(...) the rate between the baseCurrency and USD is received from the ChainLink oracle. This is only fetched once during the function call, but every time a comparison is made to check that the value has been fetched, to avoid fetching again.
function getListOfValuesPerAsset(
address[] calldata assetAddresses,
uint256[] calldata assetIds,
uint256[] calldata assetAmounts,
uint256 baseCurrency
) public view returns (RiskModule.AssetValueAndRiskVariables[] memory) {
...
if (rateBaseCurrencyToUsd == 0) {
//Get the BaseCurrency-USD rate
(, rateBaseCurrencyToUsd,,,) = IChainLinkData(
baseCurrencyToInformation[baseCurrency].baseCurrencyToUsdOracle
).latestRoundData();
}
...Recommendation
Consider fetching this value outside the loop and save it in a memory variable for use in the loop.
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-vaults/pull/253 . While doing the optimization I noticed another possible issue when both valueInUsd and valueInBaseCurrency are non-zero, see commit hash 92f0fc1003c0fa739ef4d374b00c20af60132a0f, which is also part of previous mentioned PR.
Description: Two potential optimizations in the vault contract have been identified that involve caching storage variables to save gas. In the vault contract, the length of an array can be cached outside a loop to save gas, as shown below.
- for (uint256 i; i < erc721Stored.length;)
+ uint256 erc721StoredLength = erc721Stored.length;
+ for (uint256 i; i < erc721StoredLength;)In the same contract, a temporary variable is used to reduce storage reads in the generateAssetData(...) function. Consider doing the same for the token id of ERC1155.
Recommendation
Consider caching these storage variables to reduce storage reads.
Resolution
Fixed in https://github.com/arcadia-finance/arcadia-vaults/pull/252 .
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 Arcadia team provided three documents to assist the audit process: (a) Arcadia Finance - specifies the problem, the solution, and the product; (b) Arcadia Vaults - includes information on its architecture, pricing logic, asset management, and vault logic; and (c) Arcadia Lending - embraces a diagram describing the flow of the lending application, risk models, features that are implemented (e.g., liquidations, risk tranches, interests, etc.), and how they should behave for different scenarios.
These documents covered the most common terms used in the source code, explanations for architecture decisions, and core business logic and functions flow. By reading the whole documentation suite, we could get a proper comprehension of how the contracts should operate. The provided documentation is well-written and structured. It is a complete source of resources for developers and auditors. The codebase has sufficient inline comments and meaningful naming for functions and variables, helping the audit team to understand function flow and to detect issues.
Along this investigation, we noticed some areas in the code where the implementation differs from the specification and/or inline comments.
The OracleHub contract documentation stipulates that no end-user should interact with the contract. However, checkOracleSequence and decommissionOracle functions are external and can be called without any restriction.
/**
* @title Oracle Hub
* @author Arcadia Finance
* @notice The Oracle Hub stores the addresses and other necessary information of the Price Oracles and returns rates of assets
* @dev No end-user should directly interact with the Oracle-Hub, only the Main Registry, Sub-Registries, or the contract owner.
*/
/**
* @notice Sets an oracle to inactive if it has not been updated in the last week or if its answer is below the minimum answer.
* @param oracle The address of the oracle to be checked
* @dev An inactive oracle will always return a rate of 0.
* @dev Anyone can call this function as part of an oracle failsafe mechanism.
* Next to the deposit limits, the rate of an asset can be set to 0 if the oracle is not performing as intended.
* @dev If the oracle becomes functional again (all checks pass), anyone can activate the oracle again.
*/Recommendation: Consider modifying the documentation and removing wrong statements.
_IMPLEMENTATION_SLOTThe inline documentation for the _IMPLEMENTATION_SLOT states that:
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/However, in the constructor, there is no validation of this value.
Recommendation: Consider unifying documentation with code by changing documentation or code. Below we propose code for validation of the _IMPLEMENTATION_SLOT value:
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));The relevant output is presented below.
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