@@ -492,6 +492,20 @@ contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool {
492492
493493 // --- Liquidation functions ---
494494
495+ function getMaxAmountToOffset () external view override returns (uint ) {
496+ uint totalLUSD = totalLUSDDeposits; // cache
497+ // - If the SP has total deposits >= 1e18, we leave 1e18 in it untouched.
498+ // - If it has 0 < x < 1e18 total deposits, we leave x in it.
499+ uint256 lusdToLeaveInSP = LiquityMath._min (MIN_LUSD_IN_SP, totalLUSD);
500+ uint LUSDInSPForOffsets = totalLUSD - lusdToLeaveInSP; // safe, for the line above
501+ // Let’s avoid underflow in case of a tiny offset
502+ if (LUSDInSPForOffsets.mul (DECIMAL_PRECISION) <= lastLUSDLossError_Offset) {
503+ LUSDInSPForOffsets = 0 ;
504+ }
505+
506+ return LUSDInSPForOffsets;
507+ }
508+
495509 /*
496510 * Cancels out the specified debt against the LUSD contained in the Stability Pool (as far as possible)
497511 * and transfers the Trove's ETH collateral from ActivePool to StabilityPool.
@@ -536,7 +550,19 @@ contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool {
536550 uint ETHNumerator = _collToAdd.mul (DECIMAL_PRECISION).add (lastETHError_Offset);
537551
538552 assert (_debtToOffset < _totalLUSDDeposits);
539- uint LUSDLossNumerator = _debtToOffset.mul (DECIMAL_PRECISION).sub (lastLUSDLossError_Offset);
553+ uint LUSDLossNumerator;
554+ /* Let’s avoid underflow in case of a small offset
555+ * Per getMaxAmountToOffset, if the max used, this will never happen.
556+ * If the max is not used, then offset value is at least MN_NET_DEBT,
557+ * which means that total LUSD deposits when error was produced was around 2e21 LUSD.
558+ * See: https://github.com/liquity/dev/pull/417#issuecomment-805721292
559+ * As we are doing floor + 1 in the division, it will still offset something
560+ */
561+ if (_debtToOffset.mul (DECIMAL_PRECISION) <= lastLUSDLossError_Offset) {
562+ LUSDLossNumerator = 0 ;
563+ } else {
564+ LUSDLossNumerator = _debtToOffset.mul (DECIMAL_PRECISION).sub (lastLUSDLossError_Offset);
565+ }
540566 /*
541567 * Add 1 to make error in quotient positive. We want "slightly too much" LUSD loss,
542568 * which ensures the error in any given compoundedLUSDDeposit favors the Stability Pool.
0 commit comments