Skip to content
Business logic Audit finding Intermediate

Interest can be significantly lower if addInterest isn’t called frequently enough

The interest calculation multiplies the rate by the full elapsed time in one step, so if addInterest is called infrequently the effective interest is lower than if it were called often. Lenders may receive less interest than expected.

0xA5DF Follow

Originally disclosed on Code4rena

Submitted by 0xA5DF, also found by sseefried

addInterest() always multiplies the interest rate by the time delta, and then multiplies the total borrow amount by the results (newTotalBorrowAmount = interestRate * timeDelta * totalBorrowAmount). This can lead to different interest amounts, depending on how frequently it’s called.

This will mostly affect custom pairs with stable interest rates (e.g. using linear rate with same min/max/vertex interest) which don’t have much activity (e.g. whitelisted borrowers and lenders with long term loan).

The higher the interest rate, the higher the difference will be, for example:

  • 15% annual rate would turn into 13.9% if called only once a year (compared to once a day)
  • 30% will turn into 26.2%
  • 50% will turn to 40%
  • 100% to ~70%
  • 200% to 110%

Impact

Lenders might end up gaining less interest than expected.

Proof of Concept

The following test shows a case of 50% annual rate, comparing calling it once in 3 days and only once after a year, the difference would be about 4.5% of the final debt.

At src/test/e2e/BorrowPairTest.t.sol I’ve modified _fuzzySetupBorrowToken() to this and then ran source .env && forge test --fork-url $MAINNET_URL --fork-block-number $DEFAULT_FORK_BLOCK -m testFuzzyMaxLTVBorrowToken -vvv. And I’ve also modified src/test/e2e/BasePairTest.sol a bit so that each pair can have a different name for salt (see diff below).

 function _fuzzySetupBorrowToken(
        uint256 _minInterest,
        uint256 _vertexInterest,
        uint256 _maxInterest,
        uint256 _vertexUtilization,
        uint256 _maxLTV,
        uint256 _liquidationFee,
        uint256 _priceTop,
        uint256 _priceDiv
    ) public {
        asset = IERC20(FIL_ERC20);
        collateral = IERC20(MKR_ERC20);
        oracleMultiply = AggregatorV3Interface(CHAINLINK_MKR_ETH);
        oracleMultiply.setPrice(_priceTop, 1e8, vm);
        oracleDivide = AggregatorV3Interface(CHAINLINK_FIL_ETH);
        oracleDivide.setPrice(_priceDiv, 1e8, vm);
        uint256 _oracleNormalization = 1e18;
        (
            address _rateContract,
            bytes memory _rateInitData
        ) = fuzzyRateCalculator(
                2,
                12864358183, // ~ 50% annual rate - setting this is as min/max/vertex rate
                12864358183,
                12864358183,
                _vertexUtilization
            );
        startHoax(COMPTROLLER_ADDRESS);
        setWhitelistTrue();
        vm.stopPrank();

        address[] memory _borrowerWhitelist = _maxLTV >= LTV_PRECISION
            ? users
            : new address[](0);
        address[] memory _lenderWhitelist = _maxLTV >= LTV_PRECISION
            ? users
            : new address[](0);

        uint256 borrowerDebtWrong;
        {
            // wrong calculation, when addInterest isn't called before maturity date (30 days)
            deployFraxlendCustom(
                _oracleNormalization,
                _rateContract,
                _rateInitData,
                _maxLTV,
                _liquidationFee,
                0,
                1000 * DEFAULT_INT,
                _borrowerWhitelist,
                _lenderWhitelist
            );
            pair.updateExchangeRate();
            _borrowTest(_maxLTV, 15e20, 15e23);
            vm.roll(block.number + 1);

            for(uint256 i =0; i < 100; i++){
                vm.warp(block.timestamp + 3 days);
                vm.roll(block.number + 1);
            }
            pair.addInterest();

            address borrower = users[2];
            uint256 borrowerShares = pair.userBorrowShares(borrower);
            borrowerDebtWrong = pair.toBorrowAmount(borrowerShares, false);
        }
        deploySaltName = "asdf2";
        uint256 borrowerDebtRight;
        {
            // relatively correct calculation, when addInterest is called close to maturity date
            deployFraxlendCustom(
                _oracleNormalization,
                _rateContract,
                _rateInitData,
                _maxLTV,
                _liquidationFee,
                0,
                1000 * DEFAULT_INT,
                _borrowerWhitelist,
                _lenderWhitelist
            );
            pair.updateExchangeRate();
            _borrowTest(_maxLTV, 15e20, 15e23);

            for(uint256 i =0; i < 100; i++){
                vm.warp(block.timestamp + 3 days);
                pair.addInterest();
                vm.roll(block.number + 1);

            }
            pair.addInterest();

            address borrower = users[2];
            uint256 borrowerShares = pair.userBorrowShares(borrower);
            borrowerDebtRight = pair.toBorrowAmount(borrowerShares, false);
        }

        // compare final debt between both scenarios
        assertEq(borrowerDebtRight, borrowerDebtWrong);
    }
diff --git a/src/test/e2e/BasePairTest.sol b/src/test/e2e/BasePairTest.sol
index 25114d9..27321dc 100644
--- a/src/test/e2e/BasePairTest.sol
+++ b/src/test/e2e/BasePairTest.sol
@@ -67,6 +67,8 @@ contract BasePairTest is FraxlendPairConstants, Scenarios, Test {
     PairAccounting public initial;
     PairAccounting public final_;
     PairAccounting public net;
+    string public deploySaltName = "asdf";
+

     // Users
     address[] public users = [vm.addr(1), vm.addr(2), vm.addr(3), vm.addr(4), vm.addr(5)];
@@ -284,10 +286,12 @@ contract BasePairTest is FraxlendPairConstants, Scenarios, Test {
         address[] memory _approvedLenders
     ) public {
         startHoax(COMPTROLLER_ADDRESS);
+
+
         {
             pair = FraxlendPair(
                 deployer.deployCustom(
-                    "testname",
+                    deploySaltName,
                     _encodeConfigData(_normalization, _rateContractAddress, _initRateData),
                     _maxLTV,
                     _liquidationFee,

Output:

  Error: a == b not satisfied [uint]
    Expected: 2000166246155040000000
      Actual: 2092489655740553483735

Also, here’s a JS function I’ve used to calculate the rate depending on frequency:

function calculateInterest(annualRate, frequency){
    let dailyRate = (1+annualRate) ** (1/365);
    let ratePerFrequency = (dailyRate -1) * 365 / frequency;
    let finalRate = (1+ratePerFrequency) ** frequency;
    return finalRate - 1;
}

Recommended Mitigation Steps

  • Let the users know that in some cases not calling addInterest() frequently enough can lead to lower interest rates.
  • Consider dividing the interest calculation into small period of times in case a long period has passed since last time addInterest() ran.

Something along these lines (this shouldn’t cost much more gas, as it’s mostly math operations):

            // Calculate interest accrued
            if(_deltaTime > THRESHOLD){
                uint256 iterations = min(MAX_ITERATIONS, _deltaTime / THRESHOLD);
                uint256 multiplier = 1e36;
                for(uint i=0; i < iterations; i++){
                _   multiplier =  (multiplier * _deltaTime  * _currentRateInfo.ratePerSec) / (1e18 * iterations);
                }
                _interestEarned = ( _totalBorrow.amount * multiplier) / 1e36;

            }else{
                _interestEarned = (_deltaTime * _totalBorrow.amount * _currentRateInfo.ratePerSec) / 1e18;
            }

DrakeEvans (Frax) acknowledged


The original report as published on Code4rena, by 0xA5DF. Images and videos are our own copies; raw HTML is shown as text. View it on Code4rena.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 7 min read.

Context

Fraxlend is a lending product in the Frax ecosystem that lets users deploy custom lending pairs. Each pair has its own interest rate contract, and the pair tracks debt through borrow shares. Interest is not accrued continuously on every read: it is materialised when addInterest() is called, which updates the rate information and the total borrow amount.

The finding concerns how addInterest() computes the interest that has accrued since the previous call. The report was submitted to Code4rena by 0xA5DF, with sseefried credited as an additional finder, and was acknowledged by DrakeEvans (Frax).

Setup

The researcher worked against the project's Foundry test suite, specifically the end-to-end tests under src/test/e2e/. The proof of concept modifies two files:

  • src/test/e2e/BorrowPairTest.t.sol, where _fuzzySetupBorrowToken() is rewritten to deploy a pair with a flat interest rate and to compare two accrual schedules.
  • src/test/e2e/BasePairTest.sol, where a deploySaltName field is added so that each deployed pair can use a different name for its salt, allowing two pairs to be deployed in the same test run.

The test is run against a mainnet fork, with the fork URL and block number supplied through environment variables:

Bash
source .env && forge test --fork-url $MAINNET_URL --fork-block-number $DEFAULT_FORK_BLOCK -m testFuzzyMaxLTVBorrowToken -vvv

The pair is configured with a linear rate contract whose minimum, vertex and maximum interest are all set to the same value, 12864358183, which the researcher describes as roughly a 50% annual rate. Because all three points are equal, the rate does not move with utilisation, which isolates the effect of call frequency from any change in the rate itself.

Finding it

The researcher observed that addInterest() multiplies the per-second interest rate by the elapsed time and then multiplies the total borrow amount by that result:

Text
newTotalBorrowAmount = interestRate * timeDelta * totalBorrowAmount

This is a single linear multiplication over the whole elapsed period. Compound interest, however, is not linear: applying a rate once over a long period gives a smaller result than applying the equivalent rate many times over short periods. The longer the gap between calls, the larger the shortfall. The researcher quantified the effect for a range of annual rates, comparing a single call per year against daily calls:

Annual rate Effective rate with one call per year
15% 13.9%
30% 26.2%
50% 40%
100% ~70%
200% 110%

The researcher notes that this mostly affects custom pairs with stable interest rates, for example a linear rate with identical minimum, maximum and vertex interest, and pairs that do not see much activity, such as whitelisted borrowers and lenders on a long-term loan. The higher the rate, the larger the discrepancy.

Exploitation

There is no attacker-controlled request here; the issue is demonstrated by comparing two accrual schedules on identical pairs.

Step 1: Configure a flat 50% rate and deploy the first pair

The modified _fuzzySetupBorrowToken() sets the collateral and asset tokens and the two Chainlink oracles, then builds the rate contract with the same value for minimum, vertex and maximum interest:

Solidity
        (
            address _rateContract,
            bytes memory _rateInitData
        ) = fuzzyRateCalculator(
                2,
                12864358183, // ~ 50% annual rate - setting this is as min/max/vertex rate
                12864358183,
                12864358183,
                _vertexUtilization
            );

The pair is deployed through deployFraxlendCustom with borrower and lender whitelists, and a borrow is opened with _borrowTest(_maxLTV, 15e20, 15e23).

Step 2: Advance a year in three-day jumps without calling addInterest()

The first scenario moves the chain forward 100 times by three days each, rolling the block number each time, and calls addInterest() only once at the end:

Solidity
            for(uint256 i =0; i < 100; i++){
                vm.warp(block.timestamp + 3 days);
                vm.roll(block.number + 1);
            }
            pair.addInterest();

The resulting debt is read back through the borrower's shares:

Solidity
            address borrower = users[2];
            uint256 borrowerShares = pair.userBorrowShares(borrower);
            borrowerDebtWrong = pair.toBorrowAmount(borrowerShares, false);

Step 3: Repeat with addInterest() on every jump

The second pair is deployed under a different salt name (deploySaltName = "asdf2"), the same borrow is opened, and the same 100 three-day jumps are made, but this time addInterest() is called inside the loop, with one further call after it:

Solidity
            for(uint256 i =0; i < 100; i++){
                vm.warp(block.timestamp + 3 days);
                pair.addInterest();
                vm.roll(block.number + 1);

            }
            pair.addInterest();

The debt is read the same way into borrowerDebtRight.

Step 4: Compare the two debts

The test asserts equality between the two final debts:

Solidity
        assertEq(borrowerDebtRight, borrowerDebtWrong);

It fails, showing that the two schedules produce different debt:

Text
  Error: a == b not satisfied [uint]
    Expected: 2000166246155040000000
      Actual: 2092489655740553483735

With a 50% annual rate, calling addInterest() once after a year instead of every three days leaves the final debt about 4.5% lower. The researcher also provides a small JavaScript function used to compute the effective rate for a given call frequency:

JavaScript
function calculateInterest(annualRate, frequency){
    let dailyRate = (1+annualRate) ** (1/365);
    let ratePerFrequency = (dailyRate -1) * 365 / frequency;
    let finalRate = (1+ratePerFrequency) ** frequency;
    return finalRate - 1;
}

Step 5: Allow two pairs in one test

To deploy both pairs in the same run, the base test contract is patched so the pair name used as the deployment salt is a variable rather than a fixed string:

Diff
diff --git a/src/test/e2e/BasePairTest.sol b/src/test/e2e/BasePairTest.sol
index 25114d9..27321dc 100644
--- a/src/test/e2e/BasePairTest.sol
+++ b/src/test/e2e/BasePairTest.sol
@@ -67,6 +67,8 @@ contract BasePairTest is FraxlendPairConstants, Scenarios, Test {
     PairAccounting public initial;
     PairAccounting public final_;
     PairAccounting public net;
+    string public deploySaltName = "asdf";
+

     // Users
     address[] public users = [vm.addr(1), vm.addr(2), vm.addr(3), vm.addr(4), vm.addr(5)];
@@ -284,10 +286,12 @@ contract BasePairTest is FraxlendPairConstants, Scenarios, Test {
         address[] memory _approvedLenders
     ) public {
         startHoax(COMPTROLLER_ADDRESS);
+
+
         {
             pair = FraxlendPair(
                 deployer.deployCustom(
-                    "testname",
+                    deploySaltName,
                     _encodeConfigData(_normalization, _rateContractAddress, _initRateData),
                     _maxLTV,
                     _liquidationFee,

Root cause

The interest calculation applies the per-second rate linearly over the entire elapsed time and multiplies the total borrow amount once. Because the multiplication is linear in timeDelta, the result depends on how the elapsed time is split across calls: many short intervals compound, while one long interval does not. The pair has no mechanism to break a long gap into smaller periods, so the accrual is only as accurate as the calling frequency. The report does not describe any other defence that would correct for this.

Impact

Lenders may end up gaining less interest than expected. The effect is largest for custom pairs with stable interest rates and low activity, such as whitelisted borrowers and lenders on a long-term loan, and grows with the interest rate. The researcher's example uses a 50% annual rate, where a single annual call leaves the final debt about 4.5% lower than calling every three days.

Fix

The researcher recommends two things:

  1. Let users know that in some cases not calling addInterest() frequently enough can lead to lower interest rates.
  2. Consider dividing the interest calculation into small periods when a long period has passed since the last addInterest() call.

A sketch of the second option is given, noting that it should not cost much more gas because it is mostly arithmetic:

Solidity
            // Calculate interest accrued
            if(_deltaTime > THRESHOLD){
                uint256 iterations = min(MAX_ITERATIONS, _deltaTime / THRESHOLD);
                uint256 multiplier = 1e36;
                for(uint i=0; i < iterations; i++){
                _   multiplier =  (multiplier * _deltaTime  * _currentRateInfo.ratePerSec) / (1e18 * iterations);
                }
                _interestEarned = ( _totalBorrow.amount * multiplier) / 1e36;

            }else{
                _interestEarned = (_deltaTime * _totalBorrow.amount * _currentRateInfo.ratePerSec) / 1e18;
            }

The report records that DrakeEvans (Frax) acknowledged the finding.

Variants to test

  • Deploy a pair with a flat rate (minimum, vertex and maximum all equal) and compare one long accrual against many short ones, as in the proof of concept. A positive result is a final debt that differs between the two schedules.
  • Try higher annual rates. The report's table shows the gap widening from 15% up to 200%, so a larger discrepancy at a higher rate confirms the same root cause.
  • Test pairs with low activity, such as whitelisted borrowers and lenders on a long-term loan, where addInterest() is unlikely to be called often. A positive result is a debt that drifts below the expected compounded value over the life of the loan.
  • Use the provided calculateInterest function to predict the effective rate for a given frequency and compare it with the debt the pair actually records.

Hunting notes

This kind of bug hides in accrual code that multiplies a rate by an elapsed time in a single step, especially where the elapsed time is unbounded because it depends on when someone last called an update function. During review, look for interest, fee or reward formulas of the form rate * delta * amount and ask whether the result should compound. Signals include a public addInterest()-style function that anyone can call, rate parameters that can be set to a flat value, and products that support custom or low-activity pairs. The researcher showed impact by running two pairs side by side and asserting that their final debts match; the assertion failed, giving a concrete numeric difference at a stated annual rate. That comparison, rather than a theoretical argument, is what makes the shortfall visible to a program.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 14 min read.

What happened, in plain words

Fraxlend is a lending product in the Frax ecosystem. It lets people create their own lending pairs: one side supplies an asset, the other side borrows it, and the borrower pays interest over time. Each pair can have its own interest rate setup, and the pair keeps track of how much each borrower owes using something called borrow shares.

Interest is not recalculated every time someone looks at the balance. Instead, it is written down (the report says "materialised") when a function called addInterest() runs. That function looks at how much time has passed since the last time it ran and works out the interest for that whole stretch in one go.

The finding is about how that one-go calculation behaves. The researcher, 0xA5DF, showed that if addInterest() is called rarely, the interest that ends up being earned is lower than if it is called often. The same annual rate produces different results depending on the calling schedule. sseefried is credited as an additional finder, and DrakeEvans from Frax acknowledged the finding.

A useful everyday comparison: imagine a savings account that pays 1% per month. If the bank adds the interest to your balance every month, next month's 1% is calculated on a slightly bigger amount, so the money grows a little faster. If the bank instead waits a whole year and applies 12% once at the end, you get less, because the monthly interest never had the chance to earn interest on itself. The Fraxlend calculation behaves like the second bank when addInterest() is called rarely.

The setup

The researcher did not attack a live website. Instead, the work was done inside the project's own test suite, written with a tool called Foundry. Foundry lets a developer write tests in the Solidity language (the language of Ethereum smart contracts) and run them against a copy of the real blockchain.

Two ideas are worth explaining before going further:

  • Smart contract: a small program that lives on a blockchain. Once deployed, it runs exactly as written, and anyone can call its public functions. Fraxlend's lending pairs are smart contracts.
  • Mainnet fork: a copy of the real Ethereum network's state, taken at a specific block (a numbered point in the chain's history). Tests can run against this copy, so they see real token addresses and real price feeds without touching the live network.

The proof of concept changes two test files:

  1. src/test/e2e/BorrowPairTest.t.sol, where a setup function called _fuzzySetupBorrowToken() is rewritten. The new version deploys a pair with a flat interest rate and compares two different schedules for calling addInterest().
  2. src/test/e2e/BasePairTest.sol, where a field called deploySaltName is added. This lets each deployed pair use a different name when it is created, so two pairs can exist in the same test run.

The test is started from a terminal with this command:

Bash
source .env && forge test --fork-url $MAINNET_URL --fork-block-number $DEFAULT_FORK_BLOCK -m testFuzzyMaxLTVBorrowToken -vvv

Line by line:

  • source .env loads environment variables from a file named .env. Environment variables are named values kept outside the code, commonly used for settings and secrets. Here they hold the fork URL and the block number.
  • forge test runs the Foundry test runner.
  • --fork-url $MAINNET_URL tells it which blockchain node to copy. $MAINNET_URL is the variable holding that address.
  • --fork-block-number $DEFAULT_FORK_BLOCK pins the copy to one specific block, so the test always sees the same state.
  • -m testFuzzyMaxLTVBorrowToken runs only the test with that name.
  • -vvv raises the verbosity, so the output includes more detail.

The pair is configured with a linear rate contract. A rate contract is a small contract that decides what interest rate applies. In a linear rate, the rate moves in a straight line between a minimum, a vertex (a middle point) and a maximum, depending on how much of the supplied asset is being borrowed. Here all three values are set to the same number, 12864358183, which the researcher describes as roughly a 50% annual rate. Because all three points are equal, the rate does not move at all: it stays flat. That isolates the effect of call frequency from any change in the rate itself.

Finding it

The researcher noticed that addInterest() multiplies the per-second interest rate by the elapsed time, and then multiplies the total borrowed amount by that result:

Text
newTotalBorrowAmount = interestRate * timeDelta * totalBorrowAmount

In plain words: take the rate for one second, multiply by how many seconds have passed, then multiply by how much is owed. That is a single straight-line multiplication over the whole period.

Compound interest is not a straight line. Applying a rate once over a long period gives a smaller result than applying the equivalent rate many times over short periods, because in the many-short-periods case each period's interest is added to the balance and then earns interest itself. The longer the gap between calls, the bigger the shortfall.

The researcher measured the effect for several annual rates, comparing one call per year against daily calls:

Annual rate Effective rate with one call per year
15% 13.9%
30% 26.2%
50% 40%
100% ~70%
200% 110%

The researcher notes that this mostly affects custom pairs with stable interest rates, for example a linear rate with identical minimum, maximum and vertex interest, and pairs that do not see much activity, such as whitelisted borrowers and lenders on a long-term loan. Whitelisting means only approved addresses may borrow or lend. The higher the rate, the larger the discrepancy.

Demonstrating it

There is no attacker-controlled request here. Nothing is sent to a server and no password is stolen. The issue is shown by running two identical pairs side by side and comparing what each one ends up charging.

Step 1: Configure a flat 50% rate and deploy the first pair

The modified _fuzzySetupBorrowToken() sets the collateral token, the asset token and the two Chainlink oracles. An oracle is a contract that reports a price from outside the blockchain, here used to value the collateral against the borrowed asset. It then builds the rate contract with the same value for minimum, vertex and maximum interest:

Solidity
        (
            address _rateContract,
            bytes memory _rateInitData
        ) = fuzzyRateCalculator(
                2,
                12864358183, // ~ 50% annual rate - setting this is as min/max/vertex rate
                12864358183,
                12864358183,
                _vertexUtilization
            );

Line by line:

  • The first two lines declare two variables that will receive the results: _rateContract, the address of the rate contract, and _rateInitData, the setup data used to initialise it. bytes memory means a chunk of raw data held in memory.
  • fuzzyRateCalculator(...) is a helper that builds a linear rate contract. The 2 selects the linear rate type.
  • The three 12864358183 values are the minimum, vertex and maximum interest. Setting them all equal is what makes the rate flat.
  • _vertexUtilization is the utilisation level at which the vertex sits. With all three rates equal, it does not change the outcome.

The pair is then deployed through deployFraxlendCustom, with borrower and lender whitelists (the maximum loan-to-value ratio, _maxLTV, means how much can be borrowed against the collateral). A borrow is opened with _borrowTest(_maxLTV, 15e20, 15e23).

Step 2: Advance a year in three-day jumps without calling addInterest()

The first scenario moves the chain forward 100 times, three days at a time, and calls addInterest() only once at the very end:

Solidity
            for(uint256 i =0; i < 100; i++){
                vm.warp(block.timestamp + 3 days);
                vm.roll(block.number + 1);
            }
            pair.addInterest();

Line by line:

  • for(uint256 i =0; i < 100; i++) repeats the body 100 times.
  • vm.warp(block.timestamp + 3 days) moves the test's clock forward by three days. vm is Foundry's cheat-code helper, a set of test-only commands that can bend the rules of the simulated chain.
  • vm.roll(block.number + 1) moves the block number forward by one, so each jump looks like a new block.
  • pair.addInterest() is called once, after the loop, so the whole year is settled in a single calculation.

The resulting debt is read back through the borrower's shares:

Solidity
            address borrower = users[2];
            uint256 borrowerShares = pair.userBorrowShares(borrower);
            borrowerDebtWrong = pair.toBorrowAmount(borrowerShares, false);

Line by line:

  • users[2] picks the third test user as the borrower.
  • pair.userBorrowShares(borrower) asks the pair how many borrow shares that user holds. Shares are the internal unit the pair uses to track each borrower's slice of the total debt.
  • pair.toBorrowAmount(borrowerShares, false) converts those shares into an actual amount owed. The false flag is passed through to that conversion.
  • The result is stored in borrowerDebtWrong, the debt from the rarely-called schedule.

Step 3: Repeat with addInterest() on every jump

The second pair is deployed under a different salt name (deploySaltName = "asdf2"). A salt is a value mixed into a contract's creation so that two contracts with the same code can get different addresses. The same borrow is opened, and the same 100 three-day jumps are made, but this time addInterest() is called inside the loop, with one further call after it:

Solidity
            for(uint256 i =0; i < 100; i++){
                vm.warp(block.timestamp + 3 days);
                pair.addInterest();
                vm.roll(block.number + 1);

            }
            pair.addInterest();

Line by line:

  • The loop again runs 100 times and moves the clock three days each time.
  • pair.addInterest() now runs inside the loop, so interest is settled every three days instead of once at the end.
  • vm.roll(block.number + 1) still advances the block number.
  • The extra pair.addInterest() after the loop settles any remaining time.

The debt is read the same way into borrowerDebtRight.

Step 4: Compare the two debts

The test asserts that the two final debts are equal:

Solidity
        assertEq(borrowerDebtRight, borrowerDebtWrong);

Line by line:

  • assertEq is a test check that fails if the two values differ.
  • borrowerDebtRight is the debt from the frequently-called pair.
  • borrowerDebtWrong is the debt from the rarely-called pair.

If the calculation were independent of call frequency, the two numbers would match and the test would pass. It fails, showing that the two schedules produce different debt:

Text
  Error: a == b not satisfied [uint]
    Expected: 2000166246155040000000
      Actual: 2092489655740553483735

In plain words: the test expected the two debts to be the same, but they were not. With a 50% annual rate, calling addInterest() once after a year instead of every three days leaves the final debt about 4.5% lower. The borrower pays less, so the lender receives less.

The researcher also provides a small JavaScript function used to compute the effective rate for a given call frequency:

JavaScript
function calculateInterest(annualRate, frequency){
    let dailyRate = (1+annualRate) ** (1/365);
    let ratePerFrequency = (dailyRate -1) * 365 / frequency;
    let finalRate = (1+ratePerFrequency) ** frequency;
    return finalRate - 1;
}

Line by line:

  • calculateInterest(annualRate, frequency) takes the yearly rate and how many times per year the interest is applied.
  • let dailyRate = (1+annualRate) ** (1/365); turns the annual rate into an equivalent daily rate. ** means "to the power of".
  • let ratePerFrequency = (dailyRate -1) * 365 / frequency; scales that daily rate to the chosen frequency.
  • let finalRate = (1+ratePerFrequency) ** frequency; compounds the scaled rate over the chosen number of periods.
  • return finalRate - 1; returns the resulting yearly rate as a decimal.

This is a calculator, not part of the exploit. It lets you predict what effective rate a given frequency produces, so you can compare the prediction with what the pair actually records.

Step 5: Allow two pairs in one test

To deploy both pairs in the same run, the base test contract is patched so the pair name used as the deployment salt is a variable rather than a fixed string:

Diff
diff --git a/src/test/e2e/BasePairTest.sol b/src/test/e2e/BasePairTest.sol
index 25114d9..27321dc 100644
--- a/src/test/e2e/BasePairTest.sol
+++ b/src/test/e2e/BasePairTest.sol
@@ -67,6 +67,8 @@ contract BasePairTest is FraxlendPairConstants, Scenarios, Test {
     PairAccounting public initial;
     PairAccounting public final_;
     PairAccounting public net;
+    string public deploySaltName = "asdf";
+

     // Users
     address[] public users = [vm.addr(1), vm.addr(2), vm.addr(3), vm.addr(4), vm.addr(5)];
@@ -284,10 +286,12 @@ contract BasePairTest is FraxlendPairConstants, Scenarios, Test {
         address[] memory _approvedLenders
     ) public {
         startHoax(COMPTROLLER_ADDRESS);
+
+
         {
             pair = FraxlendPair(
                 deployer.deployCustom(
-                    "testname",
+                    deploySaltName,
                     _encodeConfigData(_normalization, _rateContractAddress, _initRateData),
                     _maxLTV,
                     _liquidationFee,

Line by line:

  • The diff format shows changes to a file. Lines starting with - are removed, lines starting with + are added, and lines without either are context.
  • + string public deploySaltName = "asdf"; adds a public text field holding the salt name, defaulting to "asdf".
  • - "testname", removes the hard-coded name.
  • + deploySaltName, uses the variable instead, so a test can set it to "asdf2" before deploying the second pair.
  • The two added blank lines are cosmetic.

Root cause

The interest calculation applies the per-second rate linearly over the entire elapsed time and multiplies the total borrowed amount once. Because the multiplication is linear in timeDelta (the elapsed time), the result depends on how that time is split across calls: many short intervals compound, while one long interval does not. The pair has no mechanism to break a long gap into smaller periods, so the accrual is only as accurate as the calling frequency. The report does not describe any other defence that would correct for this.

Impact

Lenders may end up gaining less interest than expected. The effect is largest for custom pairs with stable interest rates and low activity, such as whitelisted borrowers and lenders on a long-term loan, and it grows with the interest rate. The researcher's example uses a 50% annual rate, where a single annual call leaves the final debt about 4.5% lower than calling every three days.

Fix

The researcher recommends two things:

  1. Let users know that in some cases not calling addInterest() frequently enough can lead to lower interest rates.
  2. Consider dividing the interest calculation into small periods when a long period has passed since the last addInterest() call.

A sketch of the second option is given, noting that it should not cost much more gas because it is mostly arithmetic. Gas is the fee paid for computation on a blockchain, so keeping the extra work small keeps the cost small.

Solidity
            // Calculate interest accrued
            if(_deltaTime > THRESHOLD){
                uint256 iterations = min(MAX_ITERATIONS, _deltaTime / THRESHOLD);
                uint256 multiplier = 1e36;
                for(uint i=0; i < iterations; i++){
                _   multiplier =  (multiplier * _deltaTime  * _currentRateInfo.ratePerSec) / (1e18 * iterations);
                }
                _interestEarned = ( _totalBorrow.amount * multiplier) / 1e36;

            }else{
                _interestEarned = (_deltaTime * _totalBorrow.amount * _currentRateInfo.ratePerSec) / 1e18;
            }

Line by line:

  • if(_deltaTime > THRESHOLD) checks whether the elapsed time is longer than a chosen threshold.
  • uint256 iterations = min(MAX_ITERATIONS, _deltaTime / THRESHOLD); decides how many small steps to use, capped at a maximum.
  • uint256 multiplier = 1e36; starts a running multiplier at 1 in a fixed-point format (1e36 means 1 followed by 36 zeros).
  • The for loop applies the rate step by step, dividing the elapsed time across the steps.
  • _interestEarned = ( _totalBorrow.amount * multiplier) / 1e36; turns the multiplier into the interest amount.
  • The else branch keeps the original single multiplication for short gaps, where the difference is negligible.

The report records that DrakeEvans (Frax) acknowledged the finding.

Variants to test

  • Deploy a pair with a flat rate (minimum, vertex and maximum all equal) and compare one long accrual against many short ones, as in the proof of concept. A positive result is a final debt that differs between the two schedules.
  • Try higher annual rates. The report's table shows the gap widening from 15% up to 200%, so a larger discrepancy at a higher rate confirms the same root cause.
  • Test pairs with low activity, such as whitelisted borrowers and lenders on a long-term loan, where addInterest() is unlikely to be called often. A positive result is a debt that drifts below the expected compounded value over the life of the loan.
  • Use the provided calculateInterest function to predict the effective rate for a given frequency and compare it with the debt the pair actually records.

Hunting notes

This kind of bug hides in accrual code that multiplies a rate by an elapsed time in a single step, especially where the elapsed time is unbounded because it depends on when someone last called an update function. During review, look for interest, fee or reward formulas of the form rate * delta * amount and ask whether the result should compound. Signals include a public addInterest()-style function that anyone can call, rate parameters that can be set to a flat value, and products that support custom or low-activity pairs. The researcher showed impact by running two pairs side by side and asserting that their final debts match; the assertion failed, giving a concrete numeric difference at a stated annual rate. That comparison, rather than a theoretical argument, is what makes the shortfall visible to a program.

Glossary

  • Smart contract: a program stored on a blockchain that runs exactly as written and can be called by anyone.
  • Solidity: the programming language used to write Ethereum smart contracts.
  • Foundry: a toolkit for writing and running tests for Solidity contracts.
  • Mainnet fork: a copy of the real Ethereum network's state at a chosen block, used for testing.
  • Block: a numbered batch of transactions in a blockchain's history.
  • Environment variable: a named value kept outside the code, often used for settings and secrets.
  • Lending pair: a Fraxlend contract where one side supplies an asset and the other borrows it.
  • Borrow shares: the internal unit a pair uses to track each borrower's slice of the total debt.
  • addInterest(): the function that settles accrued interest and updates the pair's records.
  • Interest rate contract: a small contract that decides what interest rate applies to a pair.
  • Linear rate: a rate that moves in a straight line between a minimum, a vertex and a maximum, based on utilisation.
  • Vertex: the middle point of a linear rate curve.
  • Utilisation: how much of the supplied asset is currently borrowed.
  • Oracle: a contract that reports a price from outside the blockchain.
  • Collateral: the asset a borrower puts up to secure a loan.
  • Loan-to-value (LTV): how much can be borrowed relative to the collateral's value.
  • Whitelist: a list of addresses allowed to do something, such as borrow or lend.
  • Salt: a value mixed into a contract's creation so two identical contracts get different addresses.
  • Cheat code (vm): a Foundry test-only command that can bend the simulated chain, for example by moving time or block numbers.
  • vm.warp: a cheat code that moves the test's clock.
  • vm.roll: a cheat code that moves the block number.
  • assertEq: a test check that fails if two values differ.
  • Compound interest: interest that is added to the balance and then earns interest itself.
  • Linear multiplication: multiplying a rate by time and amount in one step, without compounding.
  • Gas: the fee paid for computation on a blockchain.
  • Fixed-point number: a way of representing decimals using whole numbers, here scaled by 1e18 or 1e36.

More by 0xA5DF

View all

35 more disclosed reports, best first.

More from Frax Ether Liquid Staking contest

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.