DebitaIncentives::updateFunds will exit prematurely and not update whitelisted pairs causing loss of funds to lenders and borrowers
The updateFunds function in DebitaIncentives exits early when it encounters a non-whitelisted principle-collateral pair, skipping all subsequent valid pairs. This prevents lenders and borrowers from having their incentive amounts recorded, so they cannot claim incentives they are owed.
0x37 Follow with 0xe4669da, 0xloscar01 and 16 others
Originally disclosed on Sherlock
Source: https://github.com/sherlock-audit/2024-10-debita-judging/issues/870
Found by
0x37, 0xe4669da, 0xloscar01, BengalCatBalu, DenTonylifer, ExtraCaterpillar, Honour, Pro_King, Ryonen, bbl4de, dimulski, jjk, jsmi, liquidbuddha, merlin, newspacexyz, robertodf, t.aksoy, tmotfl
Summary
The DebitaIncentives::updateFunds function iterates over the lenders array, verifying whether the principle and collateral pair for each lend offer is whitelisted. If a non-whitelisted pair is encountered, the function exits prematurely, causing it to skip the processing of all subsequent pairs, even if they are valid and whitelisted.
This causes the loss of potential funds for lenders and borrowers, as they would have been eligible to claim incentives had the function processed all valid pairs. Specifically, the lentAmountPerUserPerEpoch, totalUsedTokenPerEpoch, and borrowAmountPerEpoch mappings are not updated.
Root Cause
In DebitaIncentives.sol#L317 the return keyword is used, stopping the entire function, not just the iteration, ignoring the subsequent elements in the informationOffers array.
Internal pre-conditions
-
At least one lend offer be active with the following conditions (non-whitelisted pair lend offer):
principleandacceptedCollateralspair is not whitelisted in theDebitaIncentivescontract.lonelyLendermust be false.availableAmountis greater than0.
-
At least one lend offer be active with the following conditions (whitelisted pair lend offer):
principleandacceptedCollateralspair is whitelisted in theDebitaIncentivescontract.lonelyLendermust be false.availableAmountis greater than0.
-
At least one borrow order must be active with the following conditions:
acceptedPrinciplesmust include at least a whitelisted principle and at least a non-whitelisted principle.collateralwhen paired with the principle, it must be whitelisted.availableAmountis greater than0.
-
The terms of the borrow order must allow it to be successfully matched with both types of lend offers in a single
DebitaV3Aggregator::matchOffersV3call. -
DebitaV3Aggregatormust not be paused.
External pre-conditions
No response
Attack Path
DebitaIncentivescontract owner whitelists pair of principle and collateral callingDebitaIncentives::whitelListCollateral- A user calls
DebitaIncentives::incentivizePairto incentivize the already whitelisted principle. This function transfers the tokens given as incentives from the user to theDebitaIncentivescontract. The amount of incentives is updated:
if (lendIncentivize[i]) {
lentIncentivesPerTokenPerEpoch[principle][
hashVariables(incentivizeToken, epoch)
] += amount;
} else {
borrowedIncentivesPerTokenPerEpoch[principle][
hashVariables(incentivizeToken, epoch)
] += amount;
}
- Another user calls
DebitaV3Aggregator::matchOffersV3to match a previously created borrow order with one lend offer that has a non-whitelisted pair and another lend offer that has a whitelisted pair.
Inside matchOffersV3, the DebitaIncentives::updateFunds function is called to update the funds of the lenders and borrowers. offers array contains the principle of each accepted lend offer, and it is passed as an argument.
DebitaIncentives(s_Incentives).updateFunds(
@> offers,
borrowInfo.collateral,
lenders,
borrowInfo.owner
);
updateFunds function iterates over the array, and checks if the principle and collateral pair is whitelisted. If the pair is not whitelisted, the return keyword halts the entire function. The offer containing the non-whitelisted principle is at index 0, so the function stops before the iteration reaches the offer at index 1 that has the whitelisted principle. This stops lentAmountPerUserPerEpoch, totalUsedTokenPerEpoch and borrowAmountPerEpoch from being updated.
function updateFunds(
infoOfOffers[] memory informationOffers,
address collateral,
address[] memory lenders,
address borrower
) public onlyAggregator {
for (uint i = 0; i < lenders.length; i++) {
bool validPair = isPairWhitelisted[informationOffers[i].principle][
collateral
];
if (!validPair) {
@> return;
}
address principle = informationOffers[i].principle;
uint _currentEpoch = currentEpoch();
lentAmountPerUserPerEpoch[lenders[i]][
hashVariables(principle, _currentEpoch)
] += informationOffers[i].principleAmount;
totalUsedTokenPerEpoch[principle][
_currentEpoch
] += informationOffers[i].principleAmount;
borrowAmountPerEpoch[borrower][
hashVariables(principle, _currentEpoch)
] += informationOffers[i].principleAmount;
emit UpdatedFunds(
lenders[i],
principle,
collateral,
borrower,
_currentEpoch
);
}
}
As the mappings are not updated, the beneficiary lender or borrower can't claim the incentives:
DebitaIncentives::claimIncentives#L152-L154
uint lentAmount = lentAmountPerUserPerEpoch[msg.sender][
hashVariables(principle, epoch)
];
DebitaIncentives::claimIncentives#L164-L166
uint borrowAmount = borrowAmountPerEpoch[msg.sender][
hashVariables(principle, epoch)
];
DebitaIncentives::claimIncentives#L170-L173
require(
borrowAmount > 0 || lentAmount > 0,
"No borrowed or lent amount"
);
Impact
Permanent loss of funds for lenders and borrowers who would have been eligible to claim incentives for a given epoch.
PoC
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Test, console} from "forge-std/Test.sol";
import {stdError} from "forge-std/StdError.sol";
import {DLOImplementation} from "@contracts/DebitaLendOffer-Implementation.sol";
import {DLOFactory} from "@contracts/DebitaLendOfferFactory.sol";
import {DBOImplementation} from "@contracts/DebitaBorrowOffer-Implementation.sol";
import {DBOFactory} from "@contracts/DebitaBorrowOffer-Factory.sol";
import {DebitaV3Aggregator} from "@contracts/DebitaV3Aggregator.sol";
import {ERC20Mock} from "@openzeppelin/contracts/mocks/token/ERC20Mock.sol";
import {DebitaIncentives} from "@contracts/DebitaIncentives.sol";
import {Ownerships} from "@contracts/DebitaLoanOwnerships.sol";
import {auctionFactoryDebita} from "@contracts/auctions/AuctionFactory.sol";
import {DebitaV3Loan} from "@contracts/DebitaV3Loan.sol";
import {DynamicData} from "../interfaces/getDynamicData.sol";
contract UpdateFundsTest is Test {
DBOFactory public DBOFactoryContract;
DLOFactory public DLOFactoryContract;
Ownerships public ownershipsContract;
DebitaIncentives public incentivesContract;
DebitaV3Aggregator public DebitaV3AggregatorContract;
auctionFactoryDebita public auctionFactoryDebitaContract;
DebitaV3Loan public DebitaV3LoanContract;
ERC20Mock public AEROContract;
ERC20Mock public USDCContract;
ERC20Mock public wETHContract;
DLOImplementation public LendOrder;
DBOImplementation public BorrowOrder;
DynamicData public allDynamicData;
address USDC;
address wETH;
address AERO;
address borrower = address(0x2);
address lender1 = address(0x3);
address lender2 = address(0x4);
address feeAddress = address(this);
function setUp() public {
allDynamicData = new DynamicData();
ownershipsContract = new Ownerships();
incentivesContract = new DebitaIncentives();
DBOImplementation borrowOrderImplementation = new DBOImplementation();
DBOFactoryContract = new DBOFactory(address(borrowOrderImplementation));
DLOImplementation proxyImplementation = new DLOImplementation();
DLOFactoryContract = new DLOFactory(address(proxyImplementation));
auctionFactoryDebitaContract = new auctionFactoryDebita();
USDCContract = new ERC20Mock();
wETHContract = new ERC20Mock();
AEROContract = new ERC20Mock();
DebitaV3Loan loanInstance = new DebitaV3Loan();
DebitaV3AggregatorContract = new DebitaV3Aggregator(
address(DLOFactoryContract),
address(DBOFactoryContract),
address(incentivesContract),
address(ownershipsContract),
address(auctionFactoryDebitaContract),
address(loanInstance)
);
USDC = address(USDCContract);
wETH = address(wETHContract);
AERO = address(AEROContract);
wETHContract.mint(lender1, 5 ether);
AEROContract.mint(lender2, 5 ether);
USDCContract.mint(borrower, 10 ether);
USDCContract.mint(address(this), 100 ether);
ownershipsContract.setDebitaContract(
address(DebitaV3AggregatorContract)
);
incentivesContract.setAggregatorContract(
address(DebitaV3AggregatorContract)
);
DLOFactoryContract.setAggregatorContract(
address(DebitaV3AggregatorContract)
);
DBOFactoryContract.setAggregatorContract(
address(DebitaV3AggregatorContract)
);
auctionFactoryDebitaContract.setAggregator(
address(DebitaV3AggregatorContract)
);
}
// Given the condition in the DebitaIncentives::updateFunds function:
// function updateFunds(
// infoOfOffers[] memory informationOffers,
// address collateral,
// address[] memory lenders,
// address borrower
// ) public onlyAggregator {
// for (uint i = 0; i < lenders.length; i++) {
// bool validPair = isPairWhitelisted[informationOffers[i].principle][
// collateral
// ];
// if (!validPair) {
// return; // <------ Stops the entire function, not just the iteration
// }
// This test demonstrates that the DebitaIncentives::updateFunds function
// terminates prematurely when processing the `informationOffers` array
// if any element contains a non-whitelisted pair of principle and collateral.
// As a result, all subsequent elements in the array are ignored, even if they
// are valid and whitelisted.
// Example scenario with an array of 4 elements:
// - Index 0: Whitelisted pair
// - Index 1: Non-whitelisted pair
// - Index 2: Whitelisted pair
// - Index 3: Whitelisted pair
// The function processes the first element, but terminates upon encountering
// the non-whitelisted pair at index 1, skipping the valid pairs at indexes 2 and 3.
// In the test, the following scenario is replicated:
// - Index 0: Non-whitelisted pair
// - Index 1: Whitelisted pair
// Because the first element (Index 0) contains a non-whitelisted pair,
// the function terminates and skips the valid whitelisted pair at Index 1.
// Steps:
// 1. Whitelist a pair of principle and collateral. (AERO, USDC)
// 2. Incentivize the whitelisted pair.
// 3. Create two lending offers:
// - One with a non-whitelisted pair. (wETH, USDC)
// - One with the whitelisted pair. (AERO, USDC)
// 4. Create a borrow order in which the accepted principles are wETH and AERO and the collateral is USDC.
// 5. Call `matchOffersV3` to match the borrow order with the lending offers.
// 6. Observe that no updates occur in the DebitaIncentives contract because the function exits prematurely upon encountering the non-whitelisted pair.
// This behavior highlights an issue: valid pairs that occur after a non-whitelisted pair
// in the array are not processed due to the premature return.
function testUpdateFunds() public {
bool[] memory oraclesActivated = allDynamicData.getDynamicBoolArray(2);
uint[] memory ltvs = allDynamicData.getDynamicUintArray(2);
uint[] memory ratio = allDynamicData.getDynamicUintArray(2);
uint[] memory ratioLenders = allDynamicData.getDynamicUintArray(1);
uint[] memory ltvsLenders = allDynamicData.getDynamicUintArray(1);
bool[] memory oraclesActivatedLenders = allDynamicData
.getDynamicBoolArray(1);
address[] memory acceptedPrinciples = allDynamicData
.getDynamicAddressArray(2);
address[] memory acceptedCollaterals = allDynamicData
.getDynamicAddressArray(1);
address[] memory oraclesCollateral = allDynamicData
.getDynamicAddressArray(1);
address[] memory oraclesPrinciples = allDynamicData
.getDynamicAddressArray(2);
address[] memory incentivizedPrinciples = allDynamicData
.getDynamicAddressArray(1);
address[] memory incentiveTokens = allDynamicData
.getDynamicAddressArray(1);
bool[] memory lendIncentivize = allDynamicData.getDynamicBoolArray(1);
uint[] memory incentiveAmounts = allDynamicData.getDynamicUintArray(1);
uint[] memory incentiveEpochs = allDynamicData.getDynamicUintArray(1);
ratioLenders[0] = 1e18;
ratio[0] = 1e18;
ratio[1] = 1e18;
acceptedPrinciples[0] = wETH;
acceptedPrinciples[1] = AERO;
acceptedCollaterals[0] = USDC;
oraclesActivated[0] = false;
oraclesActivated[1] = false;
incentivizedPrinciples[0] = AERO;
incentiveTokens[0] = USDC;
lendIncentivize[0] = true;
incentiveAmounts[0] = 100 ether;
incentiveEpochs[0] = 2;
// 1. Whitelist a pair of principle and collateral (AERO, USDC)
incentivesContract.whitelListCollateral({
_principle: AERO,
_collateral: USDC,
whitelist: true
});
// Check if pair is whitelisted
assertEq(
incentivesContract.isPairWhitelisted(AERO, USDC),
true,
"Pair should be whitelisted"
);
// Check that wETH USDC pair is not whitelisted
assertEq(
incentivesContract.isPairWhitelisted(wETH, USDC),
false,
"Pair should not be whitelisted"
);
// 2. Incentivize the whitelisted pair
USDCContract.approve(address(incentivesContract), 100 ether);
incentivesContract.incentivizePair({
principles: incentivizedPrinciples,
incentiveToken: incentiveTokens,
lendIncentivize: lendIncentivize,
amounts: incentiveAmounts,
epochs: incentiveEpochs
});
// Check state changes
{
assertEq(incentivesContract.principlesIncentivizedPerEpoch(2), 1);
assertEq(incentivesContract.hasBeenIndexed(2, AERO), true);
assertEq(incentivesContract.epochIndexToPrinciple(2, 0), AERO);
assertEq(incentivesContract.hasBeenIndexedBribe(2, USDC), true);
//keccak256(principle address, index)
bytes32 hash = incentivesContract.hashVariables(AERO, 0);
assertEq(
incentivesContract.SpecificBribePerPrincipleOnEpoch(2, hash),
USDC
);
//keccack256(bribe token, epoch)
bytes32 hashLend2 = incentivesContract.hashVariables(USDC, 2);
assertEq(
incentivesContract.lentIncentivesPerTokenPerEpoch(
AERO,
hashLend2
),
100 ether
);
assertEq(
USDCContract.balanceOf(address(incentivesContract)),
100 ether
);
}
// 3. Create a lend offer with non-whitelisted pair (wETH, USDC)
vm.startPrank(lender1);
wETHContract.approve(address(DLOFactoryContract), 5e18);
address lendOffer1 = DLOFactoryContract.createLendOrder({
_perpetual: false,
_oraclesActivated: oraclesActivatedLenders,
_lonelyLender: false,
_LTVs: ltvsLenders,
_apr: 1000,
_maxDuration: 8640000,
_minDuration: 86400,
_acceptedCollaterals: acceptedCollaterals,
_principle: wETH,
_oracles_Collateral: oraclesCollateral,
_ratio: ratioLenders,
_oracleID_Principle: address(0x0),
_startedLendingAmount: 5e18
});
// Create a lend offer with whitelisted pair (AERO, USDC)
vm.startPrank(lender2);
AEROContract.approve(address(DLOFactoryContract), 5e18);
address lendOffer2 = DLOFactoryContract.createLendOrder({
_perpetual: false,
_oraclesActivated: oraclesActivatedLenders,
_lonelyLender: false,
_LTVs: ltvsLenders,
_apr: 1000,
_maxDuration: 8640000,
_minDuration: 86400,
_acceptedCollaterals: acceptedCollaterals,
_principle: AERO,
_oracles_Collateral: oraclesCollateral,
_ratio: ratioLenders,
_oracleID_Principle: address(0x0),
_startedLendingAmount: 5e18
});
// 4. Create a borrow offer with accepted principles wETH and AERO and collateral USDC
vm.startPrank(borrower);
USDCContract.approve(address(DBOFactoryContract), 10e18);
address borrowOrderAddress = DBOFactoryContract.createBorrowOrder({
_oraclesActivated: oraclesActivated,
_LTVs: ltvs,
_maxInterestRate: 1400,
_duration: 864000,
_acceptedPrinciples: acceptedPrinciples,
_collateral: USDC,
_isNFT: false,
_receiptID: 0,
_oracleIDS_Principles: oraclesPrinciples,
_ratio: ratio,
_oracleID_Collateral: address(0x0),
_collateralAmount: 10e18
});
vm.stopPrank();
// 5. Call mathOffersV3 to match the borrow order with the lending offers
address[] memory lendOrders = new address[](2);
uint[] memory lendAmounts = allDynamicData.getDynamicUintArray(2);
uint[] memory percentagesOfRatio = allDynamicData.getDynamicUintArray(
2
);
uint[] memory indexForPrinciple_BorrowOrder = allDynamicData
.getDynamicUintArray(2);
uint[] memory indexForCollateral_LendOrder = allDynamicData
.getDynamicUintArray(2);
uint[] memory indexPrinciple_LendOrder = allDynamicData
.getDynamicUintArray(2);
indexForPrinciple_BorrowOrder[0] = 0;
indexForPrinciple_BorrowOrder[1] = 1;
indexForCollateral_LendOrder[0] = 0;
indexForCollateral_LendOrder[1] = 0;
indexPrinciple_LendOrder[0] = 0;
indexPrinciple_LendOrder[1] = 1;
lendOrders[0] = lendOffer1;
lendOrders[1] = lendOffer2;
percentagesOfRatio[0] = 10000;
percentagesOfRatio[1] = 10000;
lendAmounts[0] = 5e18;
lendAmounts[1] = 5e18;
// Advance time to the next epoch (2)
vm.warp(incentivesContract.epochDuration() + block.timestamp);
assertEq(incentivesContract.currentEpoch(), 2);
address deployedLoan = DebitaV3AggregatorContract.matchOffersV3({
lendOrders: lendOrders,
lendAmountPerOrder: lendAmounts,
porcentageOfRatioPerLendOrder: percentagesOfRatio,
borrowOrder: borrowOrderAddress,
principles: acceptedPrinciples,
indexForPrinciple_BorrowOrder: indexForPrinciple_BorrowOrder,
indexForCollateral_LendOrder: indexForCollateral_LendOrder,
indexPrinciple_LendOrder: indexPrinciple_LendOrder
});
// 6. Check that the lend offer with the whitelisted pair has not been updated
{
bytes32 hashPrincipleEpoch = incentivesContract.hashVariables(
AERO,
2
);
uint256 lentAmountPerUserPerEpoch = incentivesContract
.lentAmountPerUserPerEpoch(lender2, hashPrincipleEpoch);
console.log(
"lentAmountPerUserPerEpoch: ",
lentAmountPerUserPerEpoch
);
uint256 totalUsedTokenPerEpoch = incentivesContract
.totalUsedTokenPerEpoch(AERO, 2);
console.log("totalUsedTokenPerEpoch: ", totalUsedTokenPerEpoch);
uint256 borrowAmountPerEpoch = incentivesContract
.borrowAmountPerEpoch(borrower, hashPrincipleEpoch);
console.log("borrowAmountPerEpoch: ", borrowAmountPerEpoch);
// Advance time to the next epoch (3)
vm.warp(incentivesContract.epochDuration() + block.timestamp);
assertEq(incentivesContract.currentEpoch(), 3);
address[] memory principles = new address[](1);
principles[0] = AERO;
address[][] memory tokensIncentives = new address[][](1);
tokensIncentives[0] = new address[](1);
tokensIncentives[0][0] = USDC;
// Lender2 can't claim the incentives because the funds were not updated
vm.startPrank(lender2);
if (lentAmountPerUserPerEpoch == 0) {
vm.expectRevert("No borrowed or lent amount");
incentivesContract.claimIncentives({
principles: principles,
tokensIncentives: tokensIncentives,
epoch: 2
});
}
// else statement will only execute AFTER mitigation (changing DebitaIncentives::updateFunds `if (!validPair) return;` to `if (!validPair) continue;`)
else {
incentivesContract.claimIncentives({
principles: principles,
tokensIncentives: tokensIncentives,
epoch: 2
});
assertEq(USDCContract.balanceOf(lender2), 100 ether); // After mitigation, lender2 can claim the incentives. Before mitigation, lender2 loses his incentives
}
}
}
}
Logs
lentAmountPerUserPerEpoch: 0
totalUsedTokenPerEpoch: 0
borrowAmountPerEpoch: 0
Steps to reproduce:
-
Create a file
UpdateFundsTest.t.solinsideDebita-V3-Contracts/test/local/and paste the PoC code. -
Run the test in the terminal with the following command:
forge test --mt testUpdateFunds -vv
Mitigation
Change the return keyword in DebitaIncentives::addFunds
function updateFunds(
infoOfOffers[] memory informationOffers,
address collateral,
address[] memory lenders,
address borrower
) public onlyAggregator {
for (uint i = 0; i < lenders.length; i++) {
bool validPair = isPairWhitelisted[informationOffers[i].principle][
collateral
];
if (!validPair) {
- return;
+ continue;
}
address principle = informationOffers[i].principle;
uint _currentEpoch = currentEpoch();
lentAmountPerUserPerEpoch[lenders[i]][
hashVariables(principle, _currentEpoch)
] += informationOffers[i].principleAmount;
totalUsedTokenPerEpoch[principle][
_currentEpoch
] += informationOffers[i].principleAmount;
borrowAmountPerEpoch[borrower][
hashVariables(principle, _currentEpoch)
] += informationOffers[i].principleAmount;
emit UpdatedFunds(
lenders[i],
principle,
collateral,
borrower,
_currentEpoch
);
}
}
After applying the change, running the test case provided in the PoC will output the following logs:
lentAmountPerUserPerEpoch: 5000000000000000000
totalUsedTokenPerEpoch: 5000000000000000000
borrowAmountPerEpoch: 5000000000000000000
Discussion
sherlock-admin2
The protocol team fixed this issue in the following PRs/commits: https://github.com/DebitaFinance/Debita-V3-Contracts/commit/f185f42fcdbeca0bb9005767c1302c8daf24e940
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
How it worked
Root cause
The function uses a return statement inside a loop, which exits the entire function rather than skipping only the invalid iteration.
Impact
Lenders and borrowers permanently lose incentive funds they would have been eligible to claim for that epoch.
What the attacker needed
At least one non-whitelisted lend offer active; At least one whitelisted lend offer active; Borrow order accepts both principles; Aggregator not paused
The fix
The return statement should be changed to continue so that only the invalid pair is skipped and subsequent valid pairs are processed.
How it was found
- The contract owner whitelists a principle and collateral pair.
- A user incentivizes the whitelisted pair by transferring incentive tokens to the contract.
- Two lend offers are created: one with a non-whitelisted pair and one with the whitelisted pair.
- A borrow order is created that accepts both principles and uses the collateral.
- matchOffersV3 is called to match the borrow order with both lend offers.
- The whitelisted pair's incentive amounts remain zero, so the lender cannot claim incentives.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
A smart contract function that records who is owed rewards stops completely when it sees one invalid entry, instead of just skipping that entry. Because it stops, later valid entries are never recorded, so those users cannot claim their rewards.
What is Business logic?
The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.