Skip to content
Business logic Audit finding Intermediate

User’s attempt to deposit & withdraw reverts due to the calculation style inside _calculateShares()

t0x1c Follow with DanielArmstrong

Originally disclosed on Code4rena

Submitted by t0x1c, also found by DanielArmstrong

Scenario 1:

The following flow of events (one among many) causes a revert:

  1. Alice calls depositExactAmountETH() to deposit 1 ether. This executes successfully, as expected.
  2. Bob calls depositExactAmountETH() to deposit 1.5 ether (or 0.5 ether or 1 ether or 2 ether or any other value). This reverts unexpectedly.

In case Bob was attempting to make this deposit to rescue his soon-to-become or already bad debt and to avoid liquidation, this revert will delay his attempt which could well be enough for him to be liquidated by any liquidator, causing loss of funds for Bob. Here’s a concrete example with numbers:

  1. Bob calls depositExactAmountETH() to deposit 1 ether. This executes successfully, as expected.
  2. Bob calls borrowExactAmountETH() to borrow 0.7 ether. This executes successfully, as expected.
  3. Bob can see that price is soon going to spiral downward and cause a bad debt. He plans to deposit some additional collateral to safeguard himself. He calls depositExactAmountETH() again to deposit 0.5 ether. This reverts unexpectedly.
  4. Prices go down and he is liquidated.

Scenario 2:

A similar revert occurs when the following flow of events occur:

  1. Alice calls depositExactAmountETH() to deposit 10 ether. This executes successfully, as expected.
  2. Bob calls withdrawExactAmountETH() to withdraw 10 ether (or 10 ether - 1 or 10 ether - 1000 or 9.5 ether or 9.1 ether). This reverts unexpectedly.

Bob is not able to withdraw his entire deposit. If he leaves behind 1 ether and withdraws only 9 ether, then he does not face a revert.

In both of the above cases, eventually the revert is caused by the validation failure on L234-L237 due to the check inside _validateParameter():

  File: contracts/WiseLending.sol

  210:              function _compareSharePrices(
  211:                  address _poolToken,
  212:                  uint256 _lendSharePriceBefore,
  213:                  uint256 _borrowSharePriceBefore
  214:              )
  215:                  private
  216:                  view
  217:              {
  218:                  (
  219:                      uint256 lendSharePriceAfter,
  220:                      uint256 borrowSharePriceAfter
  221:                  ) = _getSharePrice(
  222:                      _poolToken
  223:                  );
  224:
  225:                  uint256 currentSharePriceMax = _getCurrentSharePriceMax(
  226:                      _poolToken
  227:                  );
  228:
  229:                  _validateParameter(
  230:                      _lendSharePriceBefore,
  231:                      lendSharePriceAfter
  232:                  );
  233:
  234: @--->            _validateParameter(
  235: @--->                lendSharePriceAfter,
  236: @--->                currentSharePriceMax
  237:                  );
  238:
  239:                  _validateParameter(
  240:                      _borrowSharePriceBefore,
  241:                      currentSharePriceMax
  242:                  );
  243:
  244:                  _validateParameter(
  245:                      borrowSharePriceAfter,
  246:                      _borrowSharePriceBefore
  247:                  );
  248:              }

Root Cause

  1. _compareSharePrices() is called by _syncPoolAfterCodeExecution() which is executed due to the syncPool modifier attached to depositExactAmountETH().

  2. Before _syncPoolAfterCodeExecution() in the above step is executed, the following internal calls are made by depositExactAmountETH():

    • The _handleDeposit() function is called on L407 which in-turn calls calculateLendingShares() on L115.
    • The calculateLendingShares() function now calls _calculateShares() on L26.
    • _calculateShares() decreases the calculated shares by 1 which is represented by the variable lendingPoolData[_poolToken].totalDepositShares inside _getSharePrice().
    • The _getSharePrice() functions uses this lendingPoolData[_poolToken].totalDepositShares variable in the denominator on L185-187 and in many cases, returns an increased value (in this case it evaluates to 1000000000000000001) which is captured in the variable lendSharePriceAfter inside _compareSharePrices().
  3. Circling back to our first step, this causes the validation to fail on L234-L237 inside _compareSharePrices() since the lendSharePriceAfter is now greater than currentSharePriceMax i.e. 1000000000000000001 > 1000000000000000000. Hence, the transaction reverts.

The reduction by 1 inside _calculateShares() is done by the protocol in its own favour to safeguard itself. The lendingPoolData[_poolToken].pseudoTotalPool; however, is never modified. This mismatch eventually reaches a significant divergence, and is the root cause of these reverts.

See:

  • The last comment inside the Proof of Concept-2 (Withdraw scenario) section later in the report.
  • Option1 inside the Recommended Mitigation Steps section later in the report.
  File: contracts/WiseLending.sol

  97:               modifier syncPool(
  98:                   address _poolToken
  99:               ) {
  100:                  (
  101:                      uint256 lendSharePrice,
  102:                      uint256 borrowSharePrice
  103:                  ) = _syncPoolBeforeCodeExecution(
  104:                      _poolToken
  105:                  );
  106:
  107:                  _;
  108:
  109: @--->            _syncPoolAfterCodeExecution(
  110:                      _poolToken,
  111:                      lendSharePrice,
  112:                      borrowSharePrice
  113:                  );
  114:              }
  File: contracts/WiseLending.sol

  308:              function _syncPoolAfterCodeExecution(
  309:                  address _poolToken,
  310:                  uint256 _lendSharePriceBefore,
  311:                  uint256 _borrowSharePriceBefore
  312:              )
  313:                  private
  314:              {
  315:                  _newBorrowRate(
  316:                      _poolToken
  317:                  );
  318:
  319: @--->            _compareSharePrices(
  320:                      _poolToken,
  321:                      _lendSharePriceBefore,
  322:                      _borrowSharePriceBefore
  323:                  );
  324:              }
  File: contracts/WiseLending.sol

  388:              function depositExactAmountETH(
  389:                  uint256 _nftId
  390:              )
  391:                  external
  392:                  payable
  393:                  syncPool(WETH_ADDRESS)
  394:                  returns (uint256)
  395:              {
  396: @--->            return _depositExactAmountETH(
  397:                      _nftId
  398:                  );
  399:              }
  400:
  401:              function _depositExactAmountETH(
  402:                  uint256 _nftId
  403:              )
  404:                  private
  405:                  returns (uint256)
  406:              {
  407: @--->            uint256 shareAmount = _handleDeposit(
  408:                      msg.sender,
  409:                      _nftId,
  410:                      WETH_ADDRESS,
  411:                      msg.value
  412:                  );
  413:
  414:                  _wrapETH(
  415:                      msg.value
  416:                  );
  417:
  418:                  return shareAmount;
  419:              }
  File: contracts/WiseCore.sol

  106:              function _handleDeposit(
  107:                  address _caller,
  108:                  uint256 _nftId,
  109:                  address _poolToken,
  110:                  uint256 _amount
  111:              )
  112:                  internal
  113:                  returns (uint256)
  114:              {
  115: @--->            uint256 shareAmount = calculateLendingShares(
  116:                      {
  117:                          _poolToken: _poolToken,
  118:                          _amount: _amount,
  119: @--->                    _maxSharePrice: false
  120:                      }
  121:                  );
  122:
  File: contracts/MainHelper.sol

  17:               function calculateLendingShares(
  18:                   address _poolToken,
  19:                   uint256 _amount,
  20:                   bool _maxSharePrice
  21:               )
  22:                   public
  23:                   view
  24:                   returns (uint256)
  25:               {
  26:  @--->            return _calculateShares(
  27:                       lendingPoolData[_poolToken].totalDepositShares * _amount,
  28:                       lendingPoolData[_poolToken].pseudoTotalPool,
  29:                       _maxSharePrice
  30:                   );
  31:               }
  32:
  33:               function _calculateShares(
  34:                   uint256 _product,
  35:                   uint256 _pseudo,
  36:                   bool _maxSharePrice
  37:               )
  38:                   private
  39:                   pure
  40:                   returns (uint256)
  41:               {
  42:                   return _maxSharePrice == true
  43:                       ? _product / _pseudo + 1
  44:  @--->                : _product / _pseudo - 1;
  45:               }
  File: contracts/WiseLending.sol

  210:              function _compareSharePrices(
  211:                  address _poolToken,
  212:                  uint256 _lendSharePriceBefore,
  213:                  uint256 _borrowSharePriceBefore
  214:              )
  215:                  private
  216:                  view
  217:              {
  218:                  (
  219: @--->                uint256 lendSharePriceAfter,
  220:                      uint256 borrowSharePriceAfter
  221: @--->            ) = _getSharePrice(
  222:                      _poolToken
  223:                  );
  224:
  225:                  uint256 currentSharePriceMax = _getCurrentSharePriceMax(
  226:                      _poolToken
  227:                  );
  228:
  229:                  _validateParameter(
  230:                      _lendSharePriceBefore,
  231:                      lendSharePriceAfter
  232:                  );
  233:
  234:                  _validateParameter(
  235: @--->                lendSharePriceAfter,
  236:                      currentSharePriceMax
  237:                  );
  238:
  239:                  _validateParameter(
  240:                      _borrowSharePriceBefore,
  241:                      currentSharePriceMax
  242:                  );
  243:
  244:                  _validateParameter(
  245:                      borrowSharePriceAfter,
  246:                      _borrowSharePriceBefore
  247:                  );
  248:              }
  File: contracts/WiseLending.sol

  165:              function _getSharePrice(
  166:                  address _poolToken
  167:              )
  168:                  private
  169:                  view
  170:                  returns (
  171:                      uint256,
  172:                      uint256
  173:                  )
  174:              {
  175:                  uint256 borrowSharePrice = borrowPoolData[_poolToken].pseudoTotalBorrowAmount
  176:                      * PRECISION_FACTOR_E18
  177:                      / borrowPoolData[_poolToken].totalBorrowShares;
  178:
  179:                  _validateParameter(
  180:                      MIN_BORROW_SHARE_PRICE,
  181:                      borrowSharePrice
  182:                  );
  183:
  184:                  return (
  185:                      lendingPoolData[_poolToken].pseudoTotalPool
  186:                          * PRECISION_FACTOR_E18
  187: @--->                    / lendingPoolData[_poolToken].totalDepositShares,
  188:                      borrowSharePrice
  189:                  );
  190:              }

Proof of Concept

Deposit scenario:

Add the following tests inside contracts/WisenLendingShutdown.t.sol and run via forge test --fork-url mainnet -vvvv --mt test_t0x1c_DepositsRevert to see the tests fail.

    function test_t0x1c_DepositsRevert_Simple()
        public
    {
        uint256 nftId;
        nftId = POSITION_NFTS_INSTANCE.mintPosition();
        LENDING_INSTANCE.depositExactAmountETH{value: 1 ether}(nftId); // @audit-info : If you want to make the test pass, change this to `2 ether`

        address bob = makeAddr("Bob");
        vm.deal(bob, 10 ether); // give some ETH to Bob
        vm.startPrank(bob);

        uint256 nftId_bob = POSITION_NFTS_INSTANCE.mintPosition();
        LENDING_INSTANCE.depositExactAmountETH{value: 1.5 ether}(nftId_bob); // @audit : REVERTS incorrectly (reverts for numerous values like `0.5 ether`, `1 ether`, `2 ether`, etc.)
    }

    function test_t0x1c_DepositsRevert_With_Borrow()
        public
    {
        address bob = makeAddr("Bob");
        vm.deal(bob, 10 ether); // give some ETH to Bob
        vm.startPrank(bob);

        uint256 nftId = POSITION_NFTS_INSTANCE.mintPosition();
        LENDING_INSTANCE.depositExactAmountETH{value: 1 ether}(nftId); // @audit-info : If you want to make the test pass, change this to `2 ether`

        LENDING_INSTANCE.borrowExactAmountETH(nftId, 0.7 ether);

        LENDING_INSTANCE.depositExactAmountETH{value: 0.5 ether}(nftId); // @audit : REVERTS incorrectly; Bob can't deposit additional collateral to save himself
    }

If you want to check with values which make the test pass, change the following line in both the tests and run again:

-     LENDING_INSTANCE.depositExactAmountETH{value: 1 ether}(nftId); // @audit-info : If you want to make the test pass, change this to `2 ether`
+     LENDING_INSTANCE.depositExactAmountETH{value: 2 ether}(nftId); // @audit-info : If you want to make the test pass, change this to `2 ether`

There are numerous combinations which will cause such a “revert” scenario to occur. Just to provide another example:

Four initial deposits are made in either Style1 or Style2:

    - Style1:
        - Alice makes 4 deposits of `2.5 ether` each. Total deposits made by Alice = 4 /ast 2.5 ether = 10 ether.
    - Style2:
        - Alice makes a deposit of `2.5 ether`
        - Bob makes a deposit of `2.5 ether`
        - Carol makes a deposit of `2.5 ether`
        - Dan makes a deposit of `2.5 ether`. Total deposits made by 4 users = 4 /ast 2.5 ether = 10 ether.

Now, Emily tries to make a deposit of 2.5 ether. This reverts.

Withdraw scenario:

Add the following test inside contracts/WisenLendingShutdown.t.sol and run via forge test --fork-url mainnet -vvvv --mt test_t0x1c_WithdrawRevert to see the test fail.

    function test_t0x1c_WithdrawRevert()
        public
    {
        address bob = makeAddr("Bob");
        vm.deal(bob, 100 ether); // give some ETH to Bob
        vm.startPrank(bob);

        uint256 nftId = POSITION_NFTS_INSTANCE.mintPosition();
        LENDING_INSTANCE.depositExactAmountETH{value: 10 ether}(nftId);

        LENDING_INSTANCE.withdrawExactAmountETH(nftId, 9.1 ether); // @audit : Reverts incorrectly for all values greater than `9 ether`.
    }

If you want to check with values which make the test pass, change the following line of the test case like shown below and run again:

-     LENDING_INSTANCE.withdrawExactAmountETH(nftId, 9.1 ether); // @audit : Reverts incorrectly for all values greater than `9 ether`.
+     LENDING_INSTANCE.withdrawExactAmountETH(nftId, 9 ether); // @audit : Reverts incorrectly for all values greater than `9 ether`.

This failure happened because the moment lendingPoolData[_poolToken].pseudoTotalPool and lendingPoolData[_poolToken].totalDepositShares go below 1 ether, their divergence is significant enough to result in lendSharePrice being calculated as greater than 1000000000000000000 or 1 ether:

  lendSharePrice = lendingPoolData[_poolToken].pseudoTotalPool * 1e18 / lendingPoolData[_poolToken].totalDepositShares

Which in this case, evaluates to 1000000000000000001. This brings us back to our root cause of failure. Due to the divergence, lendSharePrice of 1000000000000000001 has become greater than currentSharePriceMax of 1000000000000000000 and fails the validation on L234-L237 inside _compareSharePrices().

High likelihood, as it’s possible for a huge number of value combinations, as shown above.

If user is trying to save his collateral, this is High severity. Otherwise he can try later with modified values making it a Medium severity.

Tools Used

Foundry

Recommended Mitigation Steps

Since the reduction by 1 inside _calculateShares() is being done to round-down in favour of the protocol, removing that without a deeper analysis could prove to be risky as it may open up other attack vectors. Still, two points come to mind which can be explored:

  • Option1: Reducing lendingPoolData[_poolToken].pseudoTotalPool too would keep it in sync with lendingPoolData[_poolToken].totalDepositShares and will avoid the current issue.
  • Option2: Not reducing it by 1 seems to solve the immediate problem at hand (needs further impact analysis):
  File: contracts/MainHelper.sol

  33:               function _calculateShares(
  34:                   uint256 _product,
  35:                   uint256 _pseudo,
  36:                   bool _maxSharePrice
  37:               )
  38:                   private
  39:                   pure
  40:                   returns (uint256)
  41:               {
  42:                   return _maxSharePrice == true
  43:                       ? _product / _pseudo + 1
- 44:                       : _product / _pseudo - 1;
+ 44:                       : _product / _pseudo;
  45:               }

Assessed type

Math

vm06007 (Wise Lending) commented:

If you remove -1 then it opens other attacks, so it is not justified suggestion. To qualify this for a finding I will let @vonMangoldt give his opinion for these details.

Trust (judge) decreased severity to Medium and commented:

High quality submission. Likelihood is Low/Med, Impact is Med/High, so Medium is appropriate.

t0x1c (warden) commented:

Likelihood is Low/Med

@Trust - Could you please expand on your reasoning behind this? As I mentioned in the report, the frequency/likelihood at which this happens currently is very high which I supported by various random examples.

To strengthen my case, here are additional example flows of events which cause a revert for Bob when he tries to save his collateral by depositing additional amount. I have even added more actors so that it can mimic a real world scenario even more closely than before.

I am also supplementing Scenario 1 and Scenario 2 (below) of the table with coded PoCs (very similar to the one I already provided in my report), just in case it helps to run it and see the scenario in action. Due to these reasons, I believe the vulnerability should qualify as a High. Requesting you to re-assess.

| Action1 | Action2 | Action3 | Action4 | Action5 |

Scenario 1 | Alice deposits 2 ether | Bob deposits 2 ether | Carol deposits 1 ether | Bob borrows 1 ether | Bob deposits 0.5 ether (reverts) |

Scenario 2 | Alice deposits 2 ether | Bob deposits 3 ether | Carol deposits 2.5 ether | Bob borrows 2 ether | Bob deposits 1 ether (reverts) |

    function test_t0x1c_MultipleDepositsCombinations_Revert_With_Borrow_Scenario1()
        public
    {
        address alice = makeAddr("Alice");
        address bob = makeAddr("Bob");
        address carol = makeAddr("Carol");
        vm.deal(alice, 10 ether);
        vm.deal(bob, 10 ether);
        vm.deal(carol, 10 ether);

        console.log("Action1");
        vm.prank(alice);
        uint256 nftId = POSITION_NFTS_INSTANCE.mintPosition();
        vm.prank(alice);
        LENDING_INSTANCE.depositExactAmountETH{value: 2 ether}(nftId);

        console.log("Action2");
        vm.prank(bob);
        uint256 nftId_Bob = POSITION_NFTS_INSTANCE.mintPosition();
        vm.prank(bob);
        LENDING_INSTANCE.depositExactAmountETH{value: 2 ether}(nftId_Bob);

        console.log("Action3");
        vm.prank(carol);
        nftId = POSITION_NFTS_INSTANCE.mintPosition();
        vm.prank(carol);
        LENDING_INSTANCE.depositExactAmountETH{value: 1 ether}(nftId);

        console.log("Action4");
        vm.prank(bob);
        LENDING_INSTANCE.borrowExactAmountETH(nftId_Bob, 1 ether);

        console.log("Action5");
        vm.prank(bob);
        LENDING_INSTANCE.depositExactAmountETH{value: 0.5 ether}(nftId_Bob); // @audit : REVERTS incorrectly; Bob can't deposit additional collateral to save himself
    }

and

    function test_t0x1c_MultipleDepositsCombinations_Revert_With_Borrow_Scenario2()
        public
    {
        address alice = makeAddr("Alice");
        address bob = makeAddr("Bob");
        address carol = makeAddr("Carol");
        vm.deal(alice, 10 ether);
        vm.deal(bob, 20 ether);
        vm.deal(carol, 10 ether);

        console.log("Action1");
        vm.prank(alice);
        uint256 nftId = POSITION_NFTS_INSTANCE.mintPosition();
        vm.prank(alice);
        LENDING_INSTANCE.depositExactAmountETH{value: 2 ether}(nftId);

        console.log("Action2");
        vm.prank(bob);
        uint256 nftId_Bob = POSITION_NFTS_INSTANCE.mintPosition();
        vm.prank(bob);
        LENDING_INSTANCE.depositExactAmountETH{value: 3 ether}(nftId_Bob);

        console.log("Action3");
        vm.prank(carol);
        nftId = POSITION_NFTS_INSTANCE.mintPosition();
        vm.prank(carol);
        LENDING_INSTANCE.depositExactAmountETH{value: 2.5 ether}(nftId);

        console.log("Action4");
        vm.prank(bob);
        LENDING_INSTANCE.borrowExactAmountETH(nftId_Bob, 2 ether);

        console.log("Action5");
        vm.prank(bob);
        LENDING_INSTANCE.depositExactAmountETH{value: 1 ether}(nftId_Bob); // @audit : REVERTS incorrectly; Bob can't deposit additional collateral to save himself
    }

Trust (judge) commented:

There is a huge number of combinations which would cause a revert, but considering the vast space of uint256 that number is actually small. Eventually, the issue is called by a rounding which is off by one, and is easily fixed in a repeat transaction. High would be an overstatement.

Wise Lending commented:

Mitigated here.


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

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

What is known

A medium-severity business logic bug in Wise Lending. Code4rena made it public on 3 May 2024. Found in the 2024-02-wise-lending audit contest (finding M-17), also found by 1 other warden.

About Business logic

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

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

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.

More by t0x1c

View all

19 more disclosed reports, best first.

More from Wise Lending

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.