Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Storage packing (version 4) #340

Closed
wants to merge 3 commits into from
Closed
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
78 changes: 40 additions & 38 deletions src/Morpho.sol
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.21;

import {Id, IMorpho, Market, Authorization, Signature} from "./interfaces/IMorpho.sol";
import {Id, IMorpho, Market, Totals, Authorization, Signature} from "./interfaces/IMorpho.sol";
import {
IMorphoLiquidateCallback,
IMorphoRepayCallback,
Expand Down Expand Up @@ -63,13 +63,9 @@ contract Morpho is IMorpho {
/// @inheritdoc IMorpho
mapping(Id => mapping(address => uint256)) public collateral;
/// @inheritdoc IMorpho
mapping(Id => uint256) public totalSupply;
mapping(Id => Totals) public totalSupply;
/// @inheritdoc IMorpho
mapping(Id => uint256) public totalSupplyShares;
/// @inheritdoc IMorpho
mapping(Id => uint256) public totalBorrow;
/// @inheritdoc IMorpho
mapping(Id => uint256) public totalBorrowShares;
mapping(Id => Totals) public totalBorrow;
/// @inheritdoc IMorpho
mapping(Id => uint256) public lastUpdate;
/// @inheritdoc IMorpho
Expand Down Expand Up @@ -177,12 +173,13 @@ contract Morpho is IMorpho {

_accrueInterest(market, id);

if (assets > 0) shares = assets.toSharesDown(totalSupply[id], totalSupplyShares[id]);
else assets = shares.toAssetsUp(totalSupply[id], totalSupplyShares[id]);
if (assets > 0) shares = assets.toSharesDown(totalSupply[id].assets, totalSupply[id].shares);
else assets = shares.toAssetsUp(totalSupply[id].assets, totalSupply[id].shares);
require(shares < 2 ** 128 && assets < 2 ** 128, "too big");

supplyShares[id][onBehalf] += shares;
totalSupplyShares[id] += shares;
totalSupply[id] += assets;
totalSupply[id].shares += uint128(shares);
totalSupply[id].assets += uint128(assets);

emit EventsLib.Supply(id, msg.sender, onBehalf, assets, shares);

Expand All @@ -207,16 +204,17 @@ contract Morpho is IMorpho {

_accrueInterest(market, id);

if (assets > 0) shares = assets.toSharesUp(totalSupply[id], totalSupplyShares[id]);
else assets = shares.toAssetsDown(totalSupply[id], totalSupplyShares[id]);
if (assets > 0) shares = assets.toSharesUp(totalSupply[id].assets, totalSupply[id].shares);
else assets = shares.toAssetsDown(totalSupply[id].assets, totalSupply[id].shares);
require(shares < 2 ** 128 && assets < 2 ** 128, "too big");

supplyShares[id][onBehalf] -= shares;
totalSupplyShares[id] -= shares;
totalSupply[id] -= assets;
totalSupply[id].shares -= uint128(shares);
totalSupply[id].assets -= uint128(assets);

emit EventsLib.Withdraw(id, msg.sender, onBehalf, receiver, assets, shares);

require(totalBorrow[id] <= totalSupply[id], ErrorsLib.INSUFFICIENT_LIQUIDITY);
require(totalBorrow[id].assets <= totalSupply[id].assets, ErrorsLib.INSUFFICIENT_LIQUIDITY);

IERC20(market.borrowableToken).safeTransfer(receiver, assets);

Expand All @@ -239,17 +237,18 @@ contract Morpho is IMorpho {

_accrueInterest(market, id);

if (assets > 0) shares = assets.toSharesUp(totalBorrow[id], totalBorrowShares[id]);
else assets = shares.toAssetsDown(totalBorrow[id], totalBorrowShares[id]);
if (assets > 0) shares = assets.toSharesUp(totalBorrow[id].assets, totalBorrow[id].shares);
else assets = shares.toAssetsDown(totalBorrow[id].assets, totalBorrow[id].shares);
require(shares < 2 ** 128 && assets < 2 ** 128, "too big");

borrowShares[id][onBehalf] += shares;
totalBorrowShares[id] += shares;
totalBorrow[id] += assets;
totalBorrow[id].shares += uint128(shares);
totalBorrow[id].assets += uint128(assets);

emit EventsLib.Borrow(id, msg.sender, onBehalf, receiver, assets, shares);

require(_isHealthy(market, id, onBehalf), ErrorsLib.INSUFFICIENT_COLLATERAL);
require(totalBorrow[id] <= totalSupply[id], ErrorsLib.INSUFFICIENT_LIQUIDITY);
require(totalBorrow[id].assets <= totalSupply[id].assets, ErrorsLib.INSUFFICIENT_LIQUIDITY);

IERC20(market.borrowableToken).safeTransfer(receiver, assets);

Expand All @@ -268,12 +267,13 @@ contract Morpho is IMorpho {

_accrueInterest(market, id);

if (assets > 0) shares = assets.toSharesDown(totalBorrow[id], totalBorrowShares[id]);
else assets = shares.toAssetsUp(totalBorrow[id], totalBorrowShares[id]);
if (assets > 0) shares = assets.toSharesDown(totalBorrow[id].assets, totalBorrow[id].shares);
else assets = shares.toAssetsUp(totalBorrow[id].assets, totalBorrow[id].shares);
require(shares < 2 ** 128 && assets < 2 ** 128, "too big");

borrowShares[id][onBehalf] -= shares;
totalBorrowShares[id] -= shares;
totalBorrow[id] -= assets;
totalBorrow[id].shares -= uint128(shares);
totalBorrow[id].assets -= uint128(assets);

emit EventsLib.Repay(id, msg.sender, onBehalf, assets, shares);

Expand Down Expand Up @@ -343,22 +343,24 @@ contract Morpho is IMorpho {

assetsRepaid =
seized.mulDivUp(collateralPrice, ORACLE_PRICE_SCALE).wDivUp(liquidationIncentiveFactor(market.lltv));
sharesRepaid = assetsRepaid.toSharesDown(totalBorrow[id], totalBorrowShares[id]);
sharesRepaid = assetsRepaid.toSharesDown(totalBorrow[id].assets, totalBorrow[id].shares);
require(sharesRepaid < 2 ** 128 && assetsRepaid < 2 ** 128, "too big");

borrowShares[id][borrower] -= sharesRepaid;
totalBorrowShares[id] -= sharesRepaid;
totalBorrow[id] -= assetsRepaid;
totalBorrow[id].shares -= uint128(sharesRepaid);
totalBorrow[id].assets -= uint128(assetsRepaid);

collateral[id][borrower] -= seized;

// Realize the bad debt if needed.
uint256 badDebtShares;
if (collateral[id][borrower] == 0) {
badDebtShares = borrowShares[id][borrower];
uint256 badDebt = badDebtShares.toAssetsUp(totalBorrow[id], totalBorrowShares[id]);
totalSupply[id] -= badDebt;
totalBorrow[id] -= badDebt;
totalBorrowShares[id] -= badDebtShares;
uint256 badDebt = badDebtShares.toAssetsUp(totalBorrow[id].assets, totalBorrow[id].shares);
require(badDebt < 2 ** 128, "too big");
totalSupply[id].assets -= uint128(badDebt);
totalBorrow[id].assets -= uint128(badDebt);
totalBorrow[id].shares -= uint128(badDebtShares);
borrowShares[id][borrower] = 0;
}

Expand Down Expand Up @@ -436,21 +438,21 @@ contract Morpho is IMorpho {

if (elapsed == 0) return;

uint256 marketTotalBorrow = totalBorrow[id];
uint256 marketTotalBorrow = totalBorrow[id].assets;

if (marketTotalBorrow != 0) {
uint256 borrowRate = IIrm(market.irm).borrowRate(market);
uint256 interest = marketTotalBorrow.wMulDown(borrowRate.wTaylorCompounded(elapsed));
totalBorrow[id] = marketTotalBorrow + interest;
totalSupply[id] += interest;
totalBorrow[id].assets += uint128(interest);
totalSupply[id].assets += uint128(interest);

uint256 feeShares;
if (fee[id] != 0) {
uint256 feeAmount = interest.wMulDown(fee[id]);
// The fee amount is subtracted from the total supply in this calculation to compensate for the fact that total supply is already updated.
feeShares = feeAmount.toSharesDown(totalSupply[id] - feeAmount, totalSupplyShares[id]);
feeShares = feeAmount.toSharesDown(totalSupply[id].assets - feeAmount, totalSupply[id].shares);
supplyShares[id][feeRecipient] += feeShares;
totalSupplyShares[id] += feeShares;
totalSupply[id].shares += uint128(feeShares);
}

emit EventsLib.AccrueInterest(id, borrowRate, interest, feeShares);
Expand Down Expand Up @@ -478,7 +480,7 @@ contract Morpho is IMorpho {
view
returns (bool)
{
uint256 borrowed = borrowShares[id][user].toAssetsUp(totalBorrow[id], totalBorrowShares[id]);
uint256 borrowed = borrowShares[id][user].toAssetsUp(totalBorrow[id].assets, totalBorrow[id].shares);
uint256 maxBorrow = collateral[id][user].mulDivDown(collateralPrice, ORACLE_PRICE_SCALE).wMulDown(market.lltv);

return maxBorrow >= borrowed;
Expand Down
15 changes: 7 additions & 8 deletions src/interfaces/IMorpho.sol
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ struct Market {
uint256 lltv;
}

struct Totals {
uint128 assets;
uint128 shares;
}

/// @notice Authorization struct.
/// @param authorizer Authorizer address.
/// @param authorized Authorized address.
Expand Down Expand Up @@ -64,17 +69,11 @@ interface IMorpho {

/// @notice The total supply of the market `id`.
/// @dev Does not contain the accrued interest since the last interaction.
function totalSupply(Id id) external view returns (uint256);

/// @notice The total supply shares of the market `id`.
function totalSupplyShares(Id id) external view returns (uint256);
function totalSupply(Id id) external view returns (uint128, uint128);

/// @notice The total borrow of the market `id`.
/// @dev Does not contain the accrued interest since the last interaction.
function totalBorrow(Id id) external view returns (uint256);

/// @notice The total borrow shares of the market `id`.
function totalBorrowShares(Id id) external view returns (uint256);
function totalBorrow(Id id) external view returns (uint128, uint128);

/// @notice The last update timestamp of the market `id` (also used to check if a market has been created).
function lastUpdate(Id id) external view returns (uint256);
Expand Down
3 changes: 1 addition & 2 deletions src/libraries/SharesMathLib.sol
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ import {MathLib} from "./MathLib.sol";
library SharesMathLib {
using MathLib for uint256;

uint256 internal constant VIRTUAL_SHARES = 1e18;

uint256 internal constant VIRTUAL_SHARES = 1e3;
uint256 internal constant VIRTUAL_ASSETS = 1;

/// @dev Calculates the value of the given assets quoted in shares, rounding down.
Expand Down
107 changes: 107 additions & 0 deletions src/libraries/periphery/MorphoInterestLib.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

import {Id, Market, IMorpho} from "../../interfaces/IMorpho.sol";
import {IIrm} from "../../interfaces/IIrm.sol";

import {MathLib} from "../MathLib.sol";
import {MorphoLib} from "./MorphoLib.sol";
import {MarketLib} from "../MarketLib.sol";
import {SharesMathLib} from "../SharesMathLib.sol";
import {MorphoStorageLib} from "./MorphoStorageLib.sol";

/// @title MorphoInterestLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Helper library exposing getters with the expected value after interest accrual.
/// @dev This library is not used in Morpho itself and is intended to be used by integrators.
/// @dev The getter to retrieve the expected total borrow shares is not exposed because interest accrual does not apply to it.
/// The value can be queried directly on Morpho using `totalBorrowShares`.
library MorphoInterestLib {
using MathLib for uint256;
using MarketLib for Market;
using MorphoLib for IMorpho;
using SharesMathLib for uint256;

function expectedAccrueInterest(IMorpho morpho, Market memory market)
internal
view
returns (uint256 totalSupplyAssets, uint256 toralBorrowAssets, uint256 totalSupplyShares)
{
Id id = market.id();

bytes32[] memory slots = new bytes32[](5);
slots[0] = MorphoStorageLib.totalSupplySlot(id);
slots[1] = MorphoStorageLib.totalBorrowSlot(id);
slots[2] = MorphoStorageLib.feeSlot(id);
slots[3] = MorphoStorageLib.lastUpdateSlot(id);

bytes32[] memory values = morpho.extsload(slots);
totalSupplyAssets = uint128(uint256(values[0]));
totalSupplyShares = uint256(values[0] >> 128);
toralBorrowAssets = uint128(uint256(values[1]));
uint256 fee = uint256(values[2]);
uint256 lastUpdate = uint256(values[3]);

uint256 elapsed = block.timestamp - lastUpdate;

if (elapsed == 0) return (totalSupplyAssets, toralBorrowAssets, totalSupplyShares);

if (toralBorrowAssets != 0) {
uint256 borrowRate = IIrm(market.irm).borrowRateView(market);
uint256 interest = toralBorrowAssets.wMulDown(borrowRate.wTaylorCompounded(elapsed));
toralBorrowAssets += interest;
totalSupplyAssets += interest;

if (fee != 0) {
uint256 feeAmount = interest.wMulDown(fee);
// The fee amount is subtracted from the total supply in this calculation to compensate for the fact that total supply is already updated.
uint256 feeShares = feeAmount.toSharesDown(totalSupplyAssets - feeAmount, totalSupplyShares);

totalSupplyShares += feeShares;
}
}
}

function expectedTotalSupply(IMorpho morpho, Market memory market) internal view returns (uint256 totalSupply) {
(totalSupply,,) = expectedAccrueInterest(morpho, market);
}

function expectedTotalBorrow(IMorpho morpho, Market memory market) internal view returns (uint256 totalBorrow) {
(, totalBorrow,) = expectedAccrueInterest(morpho, market);
}

function expectedTotalSupplyShares(IMorpho morpho, Market memory market)
internal
view
returns (uint256 totalSupplyShares)
{
(,, totalSupplyShares) = expectedAccrueInterest(morpho, market);
}

/// @dev Warning: It does not work for `feeRecipient` because their supply shares increase is not taken into account.
function expectedSupplyBalance(IMorpho morpho, Market memory market, address user)
internal
view
returns (uint256)
{
Id id = market.id();
uint256 supplyShares = morpho.supplyShares(id, user);
(uint256 totalSupply,, uint256 totalSupplyShares) = expectedAccrueInterest(morpho, market);

return supplyShares.toAssetsDown(totalSupply, totalSupplyShares);
}

function expectedBorrowBalance(IMorpho morpho, Market memory market, address user)
internal
view
returns (uint256)
{
Id id = market.id();
uint256 borrowShares = morpho.borrowShares(id, user);
uint256 totalBorrowShares = morpho.totalBorrowShares(id);
(, uint256 totalBorrow,) = expectedAccrueInterest(morpho, market);

return borrowShares.toAssetsUp(totalBorrow, totalBorrowShares);
}
}
Loading