Atlendis
Credit Lines

Atlendis is a credit protocol where each borrower has a dedicated pool and lenders choose their own interest rate. We reviewed about 3,300 lines of Solidity behind its revolving credit lines.
report id
0085
category
DeFi & Yield
language
Solidity
final report
May 16, 2023
lines of code
3300
Content

Download audit report

1

Executive Summary

This document presents the security review conducted by Nethermind on the Atlendis revolving credit line implementation. Atlendis is a capital-efficient credit protocol where borrowers have dedicated liquidity pools to which lenders can provide assets at different interest rates. Each liquidity pool consists of a number of ticks, each representing a different interest rate for the lender. When lenders deposit, they create a position represented by an ERC721 token assigned to a tick of their choosing. During a borrow, the liquidity belonging to the lowest interest rate ticks is used first until the borrowed amount is fulfilled. Atlendis employs Know-Your-Customer (KYC) for both lenders and borrowers.

The audited code consists of 3,300 lines of Solidity with well-written NatSpec documentation for each function. The Atlendis team provided extensive documentation to assist during the audit. The audit was performed using (a) manual analysis of the codebase, (b) automated analysis tools, (c) simulation of the smart contracts, and (d) creation of test cases.

Audit assessment
Audit TypeSecurity Review
Initial ReportMay 12, 2023
Response from ClientMay 13, 2023
Final ReportMay 16, 2023
MethodsManual Review, Automated Analysis
RepositoryAtlendis
Commit Hash (Initial Audit)3bb71ee64c
DocumentationWhitepaper, Borrow/Lend process diagrams
Documentation AssessmentHigh
Test Suite AssessmentHigh
Total findings
17
Fixed
14
Acknowledged
3
Mitigated
0
Unresolved
0

Findings by severity

  • Critical0
  • High1
  • Medium4
  • Low3
  • Informational8
  • Best Practices1

2

Audited Files

#ContractLoCCommentsRatioBlankTotal
1FactoryRegistry.sol683754.4%19124
2products/RevolvingCreditLines/RevolvingCreditLine.sol533566.0%14102
3products/RevolvingCreditLines/RCLFactory.sol992828.3%21148
4products/RevolvingCreditLines/RCLRewardsManager.sol502550.0%1085
5products/RevolvingCreditLines/libraries/AccrualsHelpers.sol373594.6%779
6products/RevolvingCreditLines/libraries/LenderLogic.sol65629645.1%681020
7products/RevolvingCreditLines/libraries/Errors.sol34514.7%342
8products/RevolvingCreditLines/libraries/BorrowerLogic.sol31715649.2%36509
9products/RevolvingCreditLines/libraries/DataTypes.sol7479.5%1091
10products/RevolvingCreditLines/libraries/PositionHelpers.sol29615050.7%35481
11products/RevolvingCreditLines/libraries/RCLValidation.sol2129138.1%1060
12products/RevolvingCreditLines/libraries/RevolvingCreditLineDeployer.sol15640.0%223
13products/RevolvingCreditLines/modules/RCLGovernance.sol1105650.9%33199
14products/RevolvingCreditLines/modules/RCLState.sol1095045.9%21180
15products/RevolvingCreditLines/modules/RCLBorrowers.sol853136.5%23139
16products/RevolvingCreditLines/modules/RCLLenders.sol2447731.6%56377
17products/RevolvingCreditLines/modules/interfaces/IRCLBorrowers.sol936400.0%651
18products/RevolvingCreditLines/modules/interfaces/IRCLGovernance.sol33118357.6%25176
19products/RevolvingCreditLines/modules/interfaces/IRCLState.sol1827150.0%449
20products/RevolvingCreditLines/modules/interfaces/IRCLLenders.sol33103312.1%14150
21products/RevolvingCreditLines/interfaces/IRCLRewardsManager.sol729414.3%440
22products/RevolvingCreditLines/interfaces/IRevolvingCreditLine.sol2327117.4%555
23libraries/PoolTimelockLogic.sol402152.5%667
24libraries/FixedPointMathLib.sol785367.9%17148
25libraries/TimeValue.sol1415107.1%332
26libraries/FundsTransfer.sol352777.1%567
27common/fees/PoolTokenFeesController.sol1299472.9%38261
28common/fees/IFeesController.sol28117417.9%21166
29common/roles-manager/Managed.sol221986.4%748
30common/roles-manager/StandardRolesManager.sol534279.2%16111
31common/roles-manager/interfaces/IRolesManager.sol832400.0%545
32common/roles-manager/interfaces/IManaged.sol1029290.0%746
33common/roles-manager/interfaces/IStandardRolesManager.sol720285.7%431
34common/custodian/CustodianTimelockLogic.sol362158.3%562
35common/custodian/PoolCustodian.sol17910659.2%72357
36common/custodian/IPoolCustodian.sol47171363.8%37255
37common/custodian/CustodianStorage.sol191263.2%536
38common/custodian/adapters/IAdapter.sol933366.7%648
39common/custodian/adapters/AaveV2V3Adapter.sol533362.3%1298
40common/custodian/adapters/NeutralAdapter.sol302790.0%865
41common/custodian/adapters/extensions/IAaveLendingPool.sol1528186.7%346
42interfaces/IFactoryRegistry.sol3467197.1%11112
43interfaces/IPool.sol3260187.5%14106
44interfaces/ITimelock.sol1240333.3%961
45interfaces/IPositionDescriptor.sol411275.0%116
46interfaces/IProductFactory.sol1528186.7%447
Total3300246974.8%7426511

4

System Overview

The audit is based on seven contracts:

Fig. 2 presents the interaction diagram of contracts.

The RevolvingCreditLine contract implements all the logic of the revolving credit line system. It is also the entry point of interaction, allowing lenders and borrowers to participate in lending and borrowing activities within the protocol. The contract will enable lenders to deposit funds into a pool, specifying the amount and the interest rate they desire for their funds. Borrowers can use these funds to borrow loans. The contract matches lenders’ positions with borrowers based on the specified interest rates. Lenders can change the interest rate of their positions and withdraw their funds when not borrowed. On the other hand, Borrowers can borrow funds from the order book by matching positions with lenders at prevailing interest rates. They can borrow multiple times if the maximum borrowable amount is not reached and there are available funds. Borrowers are also responsible for repaying their loans to start a new loan cycle.

The RCLFactory contract is responsible for deploying Revolving Credit Line (RCL) contracts. The main purpose of the RCLFactory contract is to streamline the creation and initialization of a RevolvingCreditLine pool, ensuring consistency and standardized functionality.

The FactoryRegistry contract serves as a registry for product factories within the protocol. Its main purpose is to manage and utilize these product factories to deploy instances of products and register them within the system. The StandardRolesManager contract handles all role management within a pool. Its main purpose is to define and manage the permissions and roles of different participants in each pool. It is specifically designed to define and manage the following roles:

  • Lender: This role is assigned to participants authorized to provide liquidity to pools for borrowers. They can engage in actions such as depositing funds, changing interest rates, or withdrawing their positions.
  • Borrower: This role is assigned to participants who are authorized to borrow. Borrowers have their own liquidity pools and can borrow from funds provided by lenders. They can engage in actions such as borrowing, repaying, and rolling loans over.
  • Operator: By default, positions within the pool are not transferable unless an operator initiates the transfer. The operator role transfers positions between different addresses or accounts, enabling flexibility in managing ownership and control over positions.

The PoolCustodian contract handles the custody of funds. It is a dedicated storage and management mechanism for the funds associated with a specific pool. Lenders can deposit their tokens into the custodian contract, and those funds can either remain in the contract itself or be further deposited into a third-party yield provider like Aave or Compound to generate additional yield.

The Adapter contract is a connector or interface between a PoolCustodian and a specific yield provider. Its primary purpose is to implement the necessary logic to facilitate actions such as depositing, withdrawing, and computing rewards associated with the yield provider. The derived contracts of Adapter include NeutralAdapter and AaveV2V3Adapter.

The PoolTokenFeesController contract is specifically designed to handle and manage fees associated with pool tokens within each pool. Its main purpose is to control and regulate the collection and distribution of fees incurred during various actions, such as borrowing, interest, withdrawal, and exit fees.

5

Risk Rating Methodology

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

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

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

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

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

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

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

Impact / LikelihoodLowMediumHigh
HighMediumHighCritical
MediumLowMediumHigh
LowInfo / Best PracticesLowMedium
UndeterminedUndeterminedUndeterminedUndetermined

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

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

6

Issues

6.1 Attackers can front-run causing borrowers to borrow or lenders to exit at a high rate

FileFix commitTypeStatus
RCLLenders.sol—HighAcknowledged

The RevolvingLineCredit contract allows lenders to deposit funds at a specific rate, and borrowers can borrow them from the lowest to the highest rate. However, malicious lenders can change the rate at any time before their positions are borrowed, forcing the borrower to borrow at a higher rate by front-running the borrowing transaction. This issue also exists if lenders want to exit their position because when a borrowed position exits, it has to loop through every tick and remove funds, similar to the deposit process.

Attack Scenario

1. Alice (the attacker) adds $1M at the lowest rate tick. Bob (the borrower) sees this as a great term and calls borrow(...) to borrow $1M from Alice; 2. While Bob’s transaction is in the mempool, Alice front-runs and updates the rate from the lowest rate to the highest rate; 3. When Bob’s transaction is executed, he will borrow funds at the highest rate, which is not what Bob expected or intended;

Recommendation

Consider adding protection for the borrower in the function borrow(...). For example, consider allowing the borrower to specify the maximum tick they want to borrow from in this call.

Resolution

The protocol is by the construction of a hybrid, built with both smart contracts and legal contracts. As a consequence, the users will have to comply with strict identity checks, and will explicitly not be allowed to perform such actions in the protocol. Additionally, addressing this would add more complexity to the protocol, which does not seem necessary considering the potential consequences at this time. This finding will be considered in further developments, as the Atlendis team will work on new iterations of the smart contracts.

6.2 Function exit(...) is vulnerable to ERC777 reentrancy attack

FileFix commitTypeStatus
RCLLenders.sol—MediumFixed

The RCLLenders contract contains an exit(...) function, which allows lenders to exit their position before maturity. This function calculates the number of tokens the lender will receive, updates the contract state, and sends the funds to the lender. If the lender wants to fully exit their position by withdrawing their entire borrowed amount (i.e., borrowedAmountToExit == type(uint256).max), the position is burned after the funds are transferred out.

However, this implementation does not follow the check-effect-interactions pattern and may be vulnerable to reentrancy attacks if the token is an ERC777 with a call hook on the receiver. An attacker can call exit(...) again using the call hook before the position is burned, allowing them to steal the funds. The code snippet for the exit(...) function is shown below:

//////////////////////////////////////////////////////////
// @audit Funds are transferred out here
//////////////////////////////////////////////////////////
FundsTransfer.chargedWithdraw({
token: TOKEN,
custodian: CUSTODIAN,
recipient: msg.sender,
amount: toBeWithdrawn - fees,
fees: fees
});

//////////////////////////////////////////////////////////////////////////////////
// @audit The position is burned after the funds are transferred out
//////////////////////////////////////////////////////////////////////////////////
if (borrowedAmountToExit == type(uint256).max) {
burn(positionId);
emit Exited(positionId, true, unborrowedAmount, actualBorrowedAmountToExit, toBeWithdrawn - fees, fees);
} else {
emit Exited(positionId, false, unborrowedAmount, actualBorrowedAmountToExit, toBeWithdrawn - fees, fees);
}

Recommendation

To prevent reentrancy attacks, consider following the check-effect-interactions pattern or using ReentrancyGuard.

Resolution

Updated logic to apply the check effect pattern according to the recommendation.

Update from Nethermind Security

Solved in https://github.com/Atlendis/priv-contracts-v2/pull/612.

6.3 Insufficient amount of tokens due to rounding issues in the lateRepayFees calculation

FileFix commitTypeStatus
BorrowerLogic.sol—MediumFixed

The function repay(...) will loop through every tick to calculate the late repayment fee for each tick. But in the end, the total amount of the late repayment fee is calculated using the total borrowed value instead of summing up the fee in each individual tick.

The issue is the fee calculation rounding up, so if there are n ticks, the potential amount increased is 2 × n token weis because each tick rounds up twice. While the total fee is rounded up only once, the pool might potentially lack 2 × n − 1 token weis.

function repay(
...
) public returns (uint256 fees, uint256 lateRepayFees) {
...
while (currentInterestRate <= maxRate) {
DataTypes.Tick storage tick = ticks[currentInterestRate];
if (tick.latestLoanId == currentLoan.id) {
if (block.timestamp > currentLoan.maturity) {
registerLateRepaymentAccruals(tick, block.timestamp - currentLoan.maturity, lateInterestFeesRate);
}
...
}
currentInterestRate += spacing;
}
//////////////////////////////////////////////////////////////
// @audit Rounding up once using `totalBorrowed`
// While it's rounded up twice in each tick in `registerLateRepaymentAccruals()`
//////////////////////////////////////////////////////////////
lateRepayFees = block.timestamp > currentLoan.maturity
? AccrualsHelpers.accrualsForUp(totalBorrowed, block.timestamp - currentLoan.maturity, lateInterestFeesRate)
: 0;
}

function registerLateRepaymentAccruals(
...
) public {
if (tick.baseEpochsAmounts.borrowed != 0) {
tick.yieldFactor += AccrualsHelpers.calculateYieldFactorIncrease(tick, timeDelta, rate);
}
if (tick.newEpochsAmounts.borrowed != 0) {
uint256 newEpochsAccruals = AccrualsHelpers.accrualsForUp(tick.newEpochsAmounts.borrowed, timeDelta, rate);
tick.newEpochsAmounts.toBeAdjusted += newEpochsAccruals;
}
if (tick.detachedAmounts.borrowed != 0) {
uint256 detachedAccruals = AccrualsHelpers.accrualsForUp(tick.detachedAmounts.borrowed, timeDelta, rate);
tick.detachedAmounts.toBeAdjusted += detachedAccruals;
}
}

Recommendation

Consider calculating the total late repayment fees by summing up the late repayment fee in each tick.

Resolution

Updated logic to compute fees only a single time and use the result of the calculation twice, as opposed to computing the value in place for each use. Fixed the rounding according to the finding as a result.

Update from Nethermind Security

Solved in https://github.com/Atlendis/priv-contracts-v2/pull/588.

6.4 Wrong formula to calculate actualRate in the function registerExitFees(...)

FileFix commitTypeStatus
PoolTokenFeesController.sol—MediumFixed

Within the PoolTokenFeesController contract, the function registerExitFees(...) calculates the amount of fees users must pay based on the amount and timeUntilMaturity. The exit fee increases as the loan approaches maturity to discourage users from exiting right before maturity. However, the formula for cases in which loanAdvancement > EXIT_FEES_INFLECTION_THRESHOLD is currently implemented incorrectly in the codebase. This results in users having to pay more fees than expected.

if (loanAdvancement > EXIT_FEES_INFLECTION_THRESHOLD) {
/////////////////////////////////////////////////////
// @audit It should be divided by `1 - EXIT_FEES_INFLECTION_THRESHOLD`
// instead of `EXIT_FEES_INFLECTION_THRESHOLD`
/////////////////////////////////////////////////////
actualRate =
EXIT_FEES_INFLEXION_RATE -
(EXIT_FEES_INFLEXION_RATE - EXIT_FEES_MIN_RATE)
.mul(loanAdvancement - EXIT_FEES_INFLECTION_THRESHOLD)
.div(EXIT_FEES_INFLECTION_THRESHOLD);
} else {
actualRate =
EXIT_FEES_MAX_RATE -
(EXIT_FEES_MAX_RATE - EXIT_FEES_INFLEXION_RATE).mul(loanAdvancement).div(
EXIT_FEES_INFLECTION_THRESHOLD
);
}

Recommendation

Consider changing the denominator of the formula to ONE - EXIT_FEES_INFLECTION_THRESHOLD instead of EXIT_FEES_INFLECTION_THRESHOLD.

Resolution

Updated logic to fix the issue, as well as clarify the terms and their use. For example, a 90% loan advancement now means that the loan is 90% done, while it meant that it was 10% done before.

Update from Nethermind Security

Solved in https://github.com/Atlendis/priv-contracts-v2/pull/599.

6.5 Incorrect minDepositAmount input validation in validateDeployment

FileFix commitTypeStatus
RCLValidation.sol—MediumFixed

When deploying a contract inheriting from RCLState, a variety of parameters are packed and provided as bytes in the parametersConfig argument. This argument is then passed to the function RCLValidation.validateDeployment(...) to validate some of the packed values. One of these validated parameters is minDepositAmount, which is checked to ensure that the minimum deposit amount cannot be zero. The function is shown below:

function validateDeployment(bytes memory parametersConfig) public pure {
if (parametersConfig.length != 256) revert INVALID_PRODUCT_PARAMS();

(, uint256 minRate, uint256 maxRate, uint256 rateSpacing, , uint256 minDepositAmount, ) = abi.decode(
parametersConfig,
(uint256, uint256, uint256, uint256, uint256, uint256, uint256)
);

if (minRate >= maxRate) revert INVALID_RATE_BOUNDARIES();
if (rateSpacing == 0) revert INVALID_ZERO_RATE_SPACING();
if ((maxRate - minRate) % rateSpacing != 0) revert INVALID_RATE_PARAMETERS();
if (minDepositAmount == 0) revert INVALID_ZERO_MIN_DEPOSIT_AMOUNT();
}

The minDepositAmount argument is loaded from the 6th packed uint256, and validation is completed on that value. However, in the RCLState constructor, after validation, the minDepositAmount is set from the 8th packed uint256 instead. The 6th packed uint256 contains the value for LOAN_DURATION. As a result, the input validation for the minimum deposit amount is done on the loan duration, and the minimum deposit amount has no input validation at all, allowing a minDepositAmount of zero. A snippet from the RCLState constructor is shown below:

constructor(
...
) Managed(rolesManager) {
RCLValidation.validateDeployment(parametersConfig);

...

(
maxBorrowableAmount,
MIN_RATE,
MAX_RATE,
RATE_SPACING,
REPAYMENT_PERIOD,
LOAN_DURATION, // @audit The minimum deposit amount validation is done on this value instead
LATE_REPAYMENT_FEE_RATE,
minDepositAmount // @audit `minDepositAmount` is the 8th packed uint256, not the 6th
) = abi.decode(parametersConfig, (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256));

...

}

Recommendation

Ensure the input validation and values read between RCLState.constructor and RCLValidation.validateDeployment are consistent.

Resolution

Updated validation logic to validate the right parameter at pool deployment.

Update from Nethermind Security

Solved in https://github.com/Atlendis/priv-contracts-v2/pull/587.

6.6 Centralization risks

FileFix commitTypeStatus
src/*—LowAcknowledged

Atlendis relies on governance to manage some parts of the protocol through governance-only functions. While governance usually implies a decentralized voting system, in this case, the governance address is a multi-sig contract controlled by the Atlendis team. This places a reasonable amount of trust in the Atlendis team to manage the protocol correctly and act in the user’s best interest.

While some governance-only functions employ timelock features to give users time to react to potential protocol changes, many functions allow for instant protocol parameter changes. It is possible for governance to cause some significant damage to the protocol and its users. Some of the centralization risks are:

  • Removing lender role once a deposit has been made;
  • Initiating a rollover period and removing the borrower role from the corresponding borrower;
  • Initiating the non-standard repayment procedure unnecessarily;
  • Initiating the rescue procedure unnecessarily;

Recommendation

Consider adding a timelock feature to governance-only functions, which can change important protocol parameters, actions, or roles.

Resolution

By construction, the Atlendis protocol is a hybrid between smart contracts and legal contracts, and as a consequence relies heavily on governance to enforce on chain what was agreed off chain. For these reasons, governance has to maintain full control over the roles in the platform, in case users would not comply with the legal requirements at any time during a loan and roles have to be managed dynamically. However, in some cases, such as switching yield provider, non standard repayment procedure and updating rollover period, governance can leave a choice to users that do not agree with the decision to exit from the pool if they want. For these reasons, in these cases a timelock was implemented according to recommendation.

Update from Nethermind Security

Rollover delay implemented in https://github.com/Atlendis/priv-contracts-v2/pull/615

6.7 Rollover period can be used to lock lender funds temporarily

FileFix commitTypeStatus
RCLState.sol—LowFixed

To allow borrowers to "roll over" their loans, a rolloverPeriod is tracked in the contract that can be used to specify a time window where lenders cannot withdraw their funds. This is necessary to guarantee an available amount and rate for the borrower. A borrower can use this feature to temporarily prevent lender withdrawals until governance intervenes by simply not borrowing after requesting for a loan rollover. The modifier that prevents rollover withdrawals is shown below:

modifier onlyLoanNotInRolloverPeriod() {
if (rolloverPeriod > 0 && currentLoan.maturity > 0 && block.timestamp > currentLoan.maturity - rolloverPeriod)
revert RevolvingCreditLineErrors.RCL_LOAN_IN_ROLLOVER_PERIOD();
_;
}

Assuming that governance has accepted the borrower’s request for a rollover, the rolloverPeriod will be non-zero. The check to see if the current time is within the rollover period time window (block.timestamp > currentLoan.maturity - rolloverPeriod) has a lower limit but no upper limit. As long as the rolloverPeriod is non-zero and the borrower doesn’t update their current loan maturity, lenders cannot withdraw.

To address this, governance can intervene by setting the rolloverPeriod to zero. However, there still may be a reasonable wait time when lenders cannot withdraw.

Recommendation

Consider adding an upper bound check to the rollover period check, such that if a lender requests a rollover period and then decides not to rollover their loan, users will still be able to withdraw after some time rather than needing to wait for governance to unlock their funds.

Resolution

Updated logic so that the rollover period stops at maturity.

Update from Nethermind Security

Solved in PR.

6.8 Switching yield provider poses delegatecall risk

FileFix commitTypeStatus
PoolCustodian.sol—LowFixed

The function startSwitchYieldProviderProcedure is used to begin switching the yield provider. As a safeguard for users, this process is constrained by a timelock. However, when starting the switching process, a delegatecall is immediately executed using the newAdapter logic. This defeats the point of the timelock, as potentially arbitrary logic can be executed by the governance immediately rather than having to wait for the timelock. The code is shown below:

function startSwitchYieldProviderProcedure(
...
) external onlyGovernance {
if (delay < SWITCH_YP_MIN_TIMELOCK_DELAY) revert TIMELOCK_DELAY_TOO_SMALL();

if (!IAdapter(newAdapter).supportsInterface(type(IAdapter).interfaceId)) revert ADAPTER_NOT_SUPPORTED();

//////////////////////////////////////////////////////////////////////////////////////
// @audit A delegatecall to an arbitrary address is executed at the start of timelock
//////////////////////////////////////////////////////////////////////////////////////
bytes memory returnData = adapterDelegateCall(
newAdapter,
abi.encodeWithSignature('supportsToken(address)', newYieldProvider)
);
...
}

Recommendation

The delegatecall to check if the adapter is supported can be placed in the function executeTimelock(...). This will allow the check to occur after the timelock window rather than immediately.

Resolution

Moved the validation logic to the execution part of the timelock so that the arbitrary logic is executed after the timelock delay. That way, lenders that do not agree with the update can exit if they want.

Update from Nethermind Security

Solved in https://github.com/Atlendis/priv-contracts-v2/pull/604.

6.9 Granting and revoking governance role

FileFix commitTypeStatus
StandardRolesManager.sol—InfoFixed

Granting and revoking the governance role (or the DEFAULT_ADMIN_ROLE) is done using the functions batchGrantRole(...) and batchRevokeRole(...). As the governance role is crucial to the protocol’s operation, it would be better to ensure that at least one active EOA/contract has that role at all times. Errors can happen while transferring the role to a new address, Ex: instead of calling the grant function first, the call is initiated to the revoke first. Another possible scenario is while revoking multiple addresses with this role, the caller’s address is also included.

Recommendation

Consider implementing a mechanism to ensure that at least one has the governance role at any time. When proposing a new governance role, a set-then-claim approach is recommended to ensure that an incorrect address isn’t set as governance.

Resolution

Updated logic to follow the recommendation, do not allow governance to renounce to the role or revoke themselves, and implement a two-step process to grant governance role.

6.10 Setting minDepositAmount = 0 could cause the position counting to behave incorrectly

FileFix commitTypeStatus
RCLGovernance.sol—InfoFixed

In each tick of the RevolvingCreditLines, there are multiple epochs, and in each epoch, the positionsCount is stored to help reset the state of the epoch when there are no positions left. When users withdraw a position, the positionsCount is only decreased if they set the amount to type(uint256).max, which is a full withdrawal. An attacker can still withdraw the full amount without updating the positionsCount by specifying the exact value of the position as the amount. This results in the position being fully withdrawn but the positionsCount not being updated.

//////////////////////////////////////////////////////////////////////////
// @audit isFullWithdraw is true only when amount is type(uint256).max
//////////////////////////////////////////////////////////////////////////
bool isFullWithdraw = expectedWithdrawnAmount == type(uint256).max;
...
safeSubstractNewEpochsAmounts({
tick: tick,
shouldDecreasePositionCount: isFullWithdraw,
borrowedAmountToWithdraw: 0,
availableAmountToWithdraw: withdrawnAmount,
toBeAdjustedAmountToWithdraw: withdrawnAmount,
optedOutAmountToWithdraw: 0
});

However, when withdrawing, the remaining amount of the position is checked to be larger than minDepositAmount, so the issue only happens when governance sets minDepositAmount = 0.

Recommendation

Consider adding a check to ensure that minDepositAmount cannot be set to too small values.

Resolution

As a result of NM-10 and NM-11, minDepositAmount can never be set to zero.

Update from Nethermind Security

Solved in https://github.com/Atlendis/priv-contracts-v2/pull/602.

6.11 Inconsistent minDepositAmount input validation

FileFix commitTypeStatus
RCLGovernance.sol—InfoFixed

The value minDepositAmount can be set during deployment in RCLState.constructor(...) and changed by governance with RCLGovernance.setMinDepositAmount(...). The constructor has input validation for minDepositAmount, but setMinDepositAmount does not validate inputs.

Recommendation

Ensure input validation for minDepositAmount is consistent throughout the constructor and all setters. For completeness, it should be noted that there is another setter LoanGovernance.updateMinDepositAmount(...), which is out-of-scope for this audit that is also missing input validation.

Resolution

Updated logic so that minDepositAmount can never be set to zero in any case in the pool.

6.12 Shadowing local variables

FileFix commitTypeStatus
AaveV2V3Adapter.sol—InfoFixed

The function supportsToken(...) in AaveV2V3Adapter consumes an input parameter named yieldProvider, while a state variable with the same name is defined in CustodianStorage, which AaveV2V3Adapter inherits. Shadowing can lead to unexpected behavior and bugs, making it difficult to determine which variable is referred to in different parts of the code.

///////////////////////////////////
// @audit shadowing variable
///////////////////////////////////
function supportsToken(address yieldProvider) external view returns (bool) {
return IAaveLendingPool(yieldProvider).getReserveNormalizedIncome(address(token)) >= RAY;
}

Recommendation

Consider renaming the input parameter used in the function supportsToken(...) to avoid shadowing the state variable yieldProvider inherited from CustodianStorage.

Resolution

Updated the variable name according to the recommendation.

Update from Nethermind Security

Solved in https://github.com/Atlendis/priv-contracts-v2/pull/601.

6.13 The conditions in the withdraw(...) function’s if-else block can be simplified

FileFix commitTypeStatus
LenderLogic.sol—InfoFixed

In the function withdraw(...), the logic differs for when the tick is not borrowed and when a loan is ongoing, so they are separated by an if-else block. However, the condition to check currentLoan.maturity > 0 in the else branch could be removed since it is guaranteed to be larger than 0 in the if checks.

if (currentLoan.maturity == 0 || tick.latestLoanId < currentLoan.id) {
...
else {
////////////////////////////////////////////////////////////////////////
// @audit currentLoan.maturity is always > 0 in this branch
////////////////////////////////////////////////////////////////////////
if (currentLoan.maturity > 0 && tick.currentEpochId != position.epochId)
revert RevolvingCreditLineErrors.RCL_LOAN_RUNNING();
...
}

Recommendation

Consider removing the condition currentLoan.maturity > 0.

Resolution

Simplified the targeted condition in the withdraw function according to the recommendation.

Update from Nethermind Security

Solved in https://github.com/Atlendis/priv-contracts-v2/pull/613.

6.14 Usage of deprecated safeApprove

FileFix commitTypeStatus
AaveV2V3Adapter.sol
FundsTransfer.sol
—InfoFixed

The function safeApprove(...) is now deprecated, and its usage is discouraged, as mentioned in this comment.

Recommendation

As per OpenZeppelin documentation, "whenever possible, use safeIncreaseAllowance and safeDecreaseAllowance instead".

Resolution

Replaced safeApprove with safeIncreaseAllocation according to the recommendation.

Update from Nethermind Security

Solved in https://github.com/Atlendis/priv-contracts-v2/pull/603.

6.15 Zeroed EXIT_FEES_INFLECTION_THRESHOLD might lead to inaccurate exit fee calculation

FileFix commitTypeStatus
PoolTokenFeesController.sol—InfoFixed

In the function registerExitFees(...), the actualRate is calculated only if EXIT_FEES_INFLECTION_THRESHOLD is a non-zero value. If, by choice or mistake, that variable is not set during the contract creation, it will lead to the wrong calculation of fees during a position exit.

function registerExitFees(uint256 amount, uint256 timeUntilMaturity) external onlyPool returns (uint256 fees) {
uint256 loanAdvancement = (ONE * timeUntilMaturity) / LOAN_DURATION;
//////////////////////////////////////////////////////////////////////////////
// @audit The actualRate default value could be set as EXIT_FEES_MIN_RATE
// instead of zero.
//////////////////////////////////////////////////////////////////////////////
uint256 actualRate = 0;
if (EXIT_FEES_INFLECTION_THRESHOLD != 0) {
if (loanAdvancement > EXIT_FEES_INFLECTION_THRESHOLD) {
actualRate =
EXIT_FEES_INFLEXION_RATE -
(EXIT_FEES_INFLEXION_RATE - EXIT_FEES_MIN_RATE)
.mul(loanAdvancement - EXIT_FEES_INFLECTION_THRESHOLD)
.div(EXIT_FEES_INFLECTION_THRESHOLD);
} else {
actualRate =
EXIT_FEES_MAX_RATE -
(EXIT_FEES_MAX_RATE - EXIT_FEES_INFLEXION_RATE).mul(loanAdvancement).div(
EXIT_FEES_INFLECTION_THRESHOLD
);
}
}
fees = amount.mulUp(actualRate);
dueFees += fees;
totalFees += fees;

emit ExitFeesRegistered(TOKEN, fees, actualRate);
}

Recommendation

Either assign actualRate to EXIT_FEES_MIN_RATE if constant fees are levied when no inflexion threshold exists. Or, instead of the check:

if (EXIT_FEES_INFLECTION_THRESHOLD != 0) {
if (loanAdvancement > EXIT_FEES_INFLECTION_THRESHOLD) {
...
} else {
...
}
}

Consider changing it like this:

if (EXIT_FEES_INFLECTION_THRESHOLD != 0  && loanAdvancement > EXIT_FEES_INFLECTION_THRESHOLD) {
...
} else {
...
}

Resolution

Changed the logic so that a zero exit fees inflection threshold computes the exit fees as a simple slope between the inflection rate and max rate.

Update from Nethermind Security

Fixed in https://github.com/Atlendis/priv-contracts-v2/pull/599

6.16 PoolTokenFeesController deployment args must align with token decimals

FileFix commitTypeStatus
PoolTokenFeesController.sol—InfoAcknowledged

The contract PoolTokenFeesController sets the following immutable values at deployment:

uint256 public immutable WITHDRAWAL_FEES_RATE;
uint256 public immutable EXIT_FEES_INFLECTION_THRESHOLD;
uint256 public immutable EXIT_FEES_MIN_RATE;
uint256 public immutable EXIT_FEES_INFLEXION_RATE;
uint256 public immutable EXIT_FEES_MAX_RATE;
uint256 public immutable BORROWING_FEES_RATE;
uint256 public immutable INTEREST_FEES_RATE;

These values are consistently 18 decimals, as seen in the test file RCL.fees.t.sol, and are used to calculate fee pricing. When the pool’s token is 18 decimals, calculations are correct. However, calculations may need to be corrected when using a token with decimals other than 18 (Ex: USDC with six decimals). To demonstrate this, consider the following snippets from the function registerExitFees(...):

uint256 loanAdvancement = (ONE * timeUntilMaturity) / LOAN_DURATION;
actualRate =
EXIT_FEES_INFLEXION_RATE -
(EXIT_FEES_INFLEXION_RATE - EXIT_FEES_MIN_RATE)
.mul(loanAdvancement - EXIT_FEES_INFLECTION_THRESHOLD)
.div(EXIT_FEES_INFLECTION_THRESHOLD);

The value ONE is determined by the number of decimals in the token, as shown below:

ONE = 10**ERC20(TOKEN).decimals();

This leads to the variable loanAdvancement being six decimals. When this value is used to calculate the argument for the FixedPointMathLib multiply function, an overflow revert will occur since loanAdvancement is six decimals, but EXIT_FEES_INFLECTION_THRESHOLD is 18 decimals.

Recommendation

When deploying each pool, ensure that the PoolTokenFeesController constructor arguments are scaled appropriately for the token decimals.

Resolution

Noted, verified that our deployment scripts comply with the remark.

6.17 Unused library import in RCLBorrowers

FileFix commitTypeStatus
RCLBorrowers.sol—Best PracticesFixed

The contract RCLBorrowers imports the library TimeValue. However, no functionality from TimeValue is used.

Recommendation

Consider removing the unused library in RCLBorrowers.sol.

Resolution

Removed the unused import as recommended.

Update from Nethermind Security

Solved in https://github.com/Atlendis/priv-contracts-v2/pull/618.

7

Documentation Evaluation

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

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

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

8

Remarks & Test Suite

The Atlendis team has provided extensive documentation in the form of a PDF Whitepaper, and PNG images about user flow on different actions and protocol lifecycles. The whitepaper encompasses a broad overview of the protocol modules and detailed insights into users’ actions and associated fees. Additional documents about the user action flow helped understand each state change under the hood, during an action. Moreover, the team conducted a comprehensive code walkthrough and maintained open communication to address any inquiries or concerns raised by the Nethermind auditors.

8.3 Code Coverage

The relevant output is presented below. Please note that the low code coverage for src/libraries may be due to an issue with Foundry where internal libraries are not accurately tracked (See here)

Directory Line Coverage Functions

src 80.0 % 12 / 15 60.0 % 3 / 5 src/common/custodian 80.4 % 74 / 92 75.0 % 18 / 24 src/common/custodian/adapters 100.0 % 28 / 28 100.0 % 13 / 13 src/common/fees 100.0 % 41 / 41 100.0 % 11 / 11 src/common/rewards 92.2 % 83 / 90 83.3 % 20 / 24 src/common/rewards/modules 100.0 % 170 / 170 83.3 % 30 / 36 src/common/roles-manager 77.8 % 14 / 18 81.8 % 9 / 11 src/libraries 38.5 % 15 / 39 66.7 % 10 / 15 src/products/RevolvingCreditLines 93.2 % 55 / 59 90.9 % 10 / 11 src/products/RevolvingCreditLines/libraries 99.5 % 410 / 412 66.0 % 35 / 53 src/products/RevolvingCreditLines/modules 99.4 % 164 / 165 97.1 % 33 / 34

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.