Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 17 additions & 8 deletions src/adapters/MidnightAdapter.sol
Original file line number Diff line number Diff line change
Expand Up @@ -507,9 +507,14 @@ contract MidnightAdapter is IMidnightAdapterStaticTyping {
(inProgressBuyMarketId, inProgressBuyBoughtNetCredit) = (bytes32(0), 0);

if (newNetCredit > 0) {
uint256 amortizedValue =
(newNetCredit - boughtNetCredit).mulDivUp(WAD, WAD + _marketData.netRate * ttm) + buyerAssets;
_marketData.netRate = (newNetCredit - amortizedValue).mulDivDown(WAD, amortizedValue * ttm).toUint72();
// netRate = (newNetCredit - amortizedValue) / (amortizedValue * ttm), with
// amortizedValue the carried net credit's discounted value plus buyerAssets.
// Both terms are multiplied by discount to round only once.
uint256 discount = WAD + _marketData.netRate * ttm;
uint256 amortizedValueTimesDiscount = (newNetCredit - boughtNetCredit) * WAD + buyerAssets * discount;
_marketData.netRate = (newNetCredit * discount - amortizedValueTimesDiscount)
.mulDivDown(WAD, amortizedValueTimesDiscount * ttm)
.toUint72();
}

if (newNetCredit > 0 && oldNetCredit == 0) {
Expand Down Expand Up @@ -591,12 +596,16 @@ contract MidnightAdapter is IMidnightAdapterStaticTyping {
} else {
uint256 ttm = market.maturity.zeroFloorSub(block.timestamp);
require(sellerAssets >= soldNetCredit.mulDivUp(WAD, WAD + maxNetSellRate * ttm), NetSellRateTooHigh());
uint256 shortfall = soldNetCredit.mulDivUp(WAD, WAD + _marketData.netRate * ttm).zeroFloorSub(sellerAssets);
if (shortfall > 0) {
// Same as in onBuy, with amortizedValue the remaining net credit's discounted value plus the shortfall (the
// sold net credit's discounted value minus sellerAssets).
uint256 discount = WAD + _marketData.netRate * ttm;
if (soldNetCredit * WAD > sellerAssets * discount) {
require(!noSalesWithShortfall, SalesWithShortfallDisabled());
uint256 amortizedValue = newNetCredit.mulDivUp(WAD, WAD + _marketData.netRate * ttm) + shortfall;
require(amortizedValue <= newNetCredit, ShortfallTooHigh());
_marketData.netRate = (newNetCredit - amortizedValue).mulDivDown(WAD, amortizedValue * ttm).toUint72();
uint256 amortizedValueTimesDiscount = (newNetCredit + soldNetCredit) * WAD - sellerAssets * discount;
require(amortizedValueTimesDiscount <= newNetCredit * discount, ShortfallTooHigh());
_marketData.netRate = (newNetCredit * discount - amortizedValueTimesDiscount)
.mulDivDown(WAD, amortizedValueTimesDiscount * ttm)
.toUint72();
}
}

Expand Down
28 changes: 22 additions & 6 deletions test/MidnightAdapterTest.sol

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading