From cb0b425646e5e9e25b3da4ff3b58cb6f790df16a Mon Sep 17 00:00:00 2001 From: "John McClure (pickleback)" Date: Thu, 19 Dec 2024 02:04:33 -0600 Subject: [PATCH] revert when attempting to close more bonds than the position has in the Portfolio library --- contracts/libraries/EverlongPortfolio.sol | 11 ++++++++++- test/everlong/units/Portfolio.t.sol | 11 +++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/contracts/libraries/EverlongPortfolio.sol b/contracts/libraries/EverlongPortfolio.sol index c29f564..9186073 100644 --- a/contracts/libraries/EverlongPortfolio.sol +++ b/contracts/libraries/EverlongPortfolio.sol @@ -26,6 +26,10 @@ library EverlongPortfolioLibrary { /// @notice Thrown on attempting to add a position to a full queue. error QueueFull(); + /// @notice Thrown when attempting to decrease a position by more than it + /// has. + error InsufficientBonds(); + /// @dev The state of the portfolio which contains a double-ended queue /// of {IEverlongStrategy.EverlongPosition} along with the portfolio's average /// maturity, vault share price, and total bond count. @@ -211,8 +215,13 @@ library EverlongPortfolioLibrary { // Ensure there are items in the queue. if (frontIndex == self._end) revert QueueEmpty(); + // Revert if trying to decrease by an amount greater than what is + // present. + if (_amount > self._q[frontIndex].bondAmount) { + revert InsufficientBonds(); + } // Remove the position if _amount equals the position's bondAmount. - if (_amount >= self._q[frontIndex].bondAmount) { + else if (_amount == self._q[frontIndex].bondAmount) { value = _removePosition(self); } // Reduce the position's bondAmount by `_amount`. diff --git a/test/everlong/units/Portfolio.t.sol b/test/everlong/units/Portfolio.t.sol index 63d2031..def4d31 100644 --- a/test/everlong/units/Portfolio.t.sol +++ b/test/everlong/units/Portfolio.t.sol @@ -121,4 +121,15 @@ contract TestPortfolio is EverlongTest { "position count should be 0 after opening and closing a long for the full bond amount" ); } + + /// @dev Validates that `InsufficientBonds` error is thrown when trying + /// to decrease a position by more than its `bondAmount`. + function test_handleClosePosition_insufficient_bonds_failure() external { + // Create a position with a single bond in it. + portfolio.handleOpenPosition(1, 1); + + // Attempt to close 2 bonds from the position. This should revert. + vm.expectRevert(EverlongPortfolioLibrary.InsufficientBonds.selector); + portfolio.handleClosePosition(2); + } }