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 2 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 {IFlashLender} from "./interfaces/IFlashLender.sol";
import {
IMorphoLiquidateCallback,
Expand Down Expand Up @@ -66,13 +66,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 @@ -180,12 +176,13 @@ contract Morpho is IMorpho {

_accrueInterests(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 @@ -210,16 +207,17 @@ contract Morpho is IMorpho {

_accrueInterests(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 @@ -242,17 +240,18 @@ contract Morpho is IMorpho {

_accrueInterests(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 @@ -271,12 +270,13 @@ contract Morpho is IMorpho {

_accrueInterests(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 @@ -346,22 +346,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 @@ -439,21 +441,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 accruedInterests = marketTotalBorrow.wMulDown(borrowRate.wTaylorCompounded(elapsed));
totalBorrow[id] = marketTotalBorrow + accruedInterests;
totalSupply[id] += accruedInterests;
totalBorrow[id].assets += uint128(accruedInterests);
totalSupply[id].assets += uint128(accruedInterests);

uint256 feeShares;
if (fee[id] != 0) {
uint256 feeAmount = accruedInterests.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.AccrueInterests(id, borrowRate, accruedInterests, feeShares);
Expand Down Expand Up @@ -481,7 +483,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 @@ -19,6 +19,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 @@ -66,17 +71,11 @@ interface IMorpho is IFlashLender {

/// @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
4 changes: 3 additions & 1 deletion src/mocks/IrmMock.sol
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ import {Id, Market, IMorpho} from "../interfaces/IMorpho.sol";

import {MathLib} from "../libraries/MathLib.sol";
import {MarketLib} from "../libraries/MarketLib.sol";
import {MorphoLib} from "../../test/forge/helpers/MorphoLib.sol";

contract IrmMock is IIrm {
using MathLib for uint256;
using MarketLib for Market;
using MorphoLib for IMorpho;

IMorpho private immutable MORPHO;

Expand All @@ -19,7 +21,7 @@ contract IrmMock is IIrm {

function borrowRate(Market memory market) external view returns (uint256) {
Id id = market.id();
uint256 utilization = MORPHO.totalBorrow(id).wDivDown(MORPHO.totalSupply(id));
uint256 utilization = MORPHO.totalBorrowAssets(id).wDivDown(MORPHO.totalSupplyAssets(id));

// Divide by the number of seconds in a year.
// This is a very simple model (to refine later) where x% utilization corresponds to x% APR.
Expand Down
2 changes: 2 additions & 0 deletions test/forge/BaseTest.sol
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import "forge-std/Test.sol";
import "forge-std/console.sol";

import {SigUtils} from "test/forge/helpers/SigUtils.sol";
import {MorphoLib} from "test/forge/helpers/MorphoLib.sol";
import "src/Morpho.sol";
import {ERC20Mock as ERC20} from "src/mocks/ERC20Mock.sol";
import {OracleMock as Oracle} from "src/mocks/OracleMock.sol";
Expand All @@ -13,6 +14,7 @@ import {IrmMock as Irm} from "src/mocks/IrmMock.sol";
contract BaseTest is Test {
using MathLib for uint256;
using MarketLib for Market;
using MorphoLib for Morpho;

uint256 internal constant HIGH_COLLATERAL_AMOUNT = 1e35;
uint256 internal constant MIN_TEST_AMOUNT = 100;
Expand Down
22 changes: 22 additions & 0 deletions test/forge/helpers/MorphoLib.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

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

library MorphoLib {
function totalSupplyAssets(IMorpho morpho, Id id) internal view returns (uint256 res) {
(res,) = morpho.totalSupply(id);
}

function totalSupplyShares(IMorpho morpho, Id id) internal view returns (uint256 res) {
(, res) = morpho.totalSupply(id);
}

function totalBorrowAssets(IMorpho morpho, Id id) internal view returns (uint256 res) {
(res,) = morpho.totalBorrow(id);
}

function totalBorrowShares(IMorpho morpho, Id id) internal view returns (uint256 res) {
(, res) = morpho.totalBorrow(id);
}
}
41 changes: 23 additions & 18 deletions test/forge/integration/TestIntegrationAccrueInterests.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import "../BaseTest.sol";

contract IntegrationAccrueInterestsTest is BaseTest {
using MathLib for uint256;
using MorphoLib for Morpho;
using SharesMathLib for uint256;

function testAccrueInterestsMarketNotCreated(Market memory marketFuzz) public {
Expand Down Expand Up @@ -35,14 +36,14 @@ contract IntegrationAccrueInterestsTest is BaseTest {
morpho.borrow(market, amountBorrowed, 0, BORROWER, BORROWER);
vm.stopPrank();

uint256 totalBorrowBeforeAccrued = morpho.totalBorrow(id);
uint256 totalSupplyBeforeAccrued = morpho.totalSupply(id);
uint256 totalBorrowBeforeAccrued = morpho.totalBorrowAssets(id);
uint256 totalSupplyBeforeAccrued = morpho.totalSupplyAssets(id);
uint256 totalSupplySharesBeforeAccrued = morpho.totalSupplyShares(id);

morpho.accrueInterests(market);

assertEq(morpho.totalBorrow(id), totalBorrowBeforeAccrued, "total borrow");
assertEq(morpho.totalSupply(id), totalSupplyBeforeAccrued, "total supply");
assertEq(morpho.totalBorrowAssets(id), totalBorrowBeforeAccrued, "total borrow");
assertEq(morpho.totalSupplyAssets(id), totalSupplyBeforeAccrued, "total supply");
assertEq(morpho.totalSupplyShares(id), totalSupplySharesBeforeAccrued, "total supply shares");
assertEq(morpho.supplyShares(id, OWNER), 0, "feeRecipient's supply shares");
}
Expand All @@ -62,14 +63,14 @@ contract IntegrationAccrueInterestsTest is BaseTest {
vm.roll(block.number + 1);
vm.warp(block.timestamp + timeElapsed);

uint256 totalBorrowBeforeAccrued = morpho.totalBorrow(id);
uint256 totalSupplyBeforeAccrued = morpho.totalSupply(id);
uint256 totalBorrowBeforeAccrued = morpho.totalBorrowAssets(id);
uint256 totalSupplyBeforeAccrued = morpho.totalSupplyAssets(id);
uint256 totalSupplySharesBeforeAccrued = morpho.totalSupplyShares(id);

morpho.accrueInterests(market);

assertEq(morpho.totalBorrow(id), totalBorrowBeforeAccrued, "total borrow");
assertEq(morpho.totalSupply(id), totalSupplyBeforeAccrued, "total supply");
assertEq(morpho.totalBorrowAssets(id), totalBorrowBeforeAccrued, "total borrow");
assertEq(morpho.totalSupplyAssets(id), totalSupplyBeforeAccrued, "total supply");
assertEq(morpho.totalSupplyShares(id), totalSupplySharesBeforeAccrued, "total supply shares");
assertEq(morpho.supplyShares(id, OWNER), 0, "feeRecipient's supply shares");
assertEq(morpho.lastUpdate(id), block.timestamp, "last update");
Expand Down Expand Up @@ -103,18 +104,18 @@ contract IntegrationAccrueInterestsTest is BaseTest {
vm.roll(block.number + 1);
vm.warp(block.timestamp + timeElapsed);

uint256 borrowRate = (morpho.totalBorrow(id).wDivDown(morpho.totalSupply(id))) / 365 days;
uint256 totalBorrowBeforeAccrued = morpho.totalBorrow(id);
uint256 totalSupplyBeforeAccrued = morpho.totalSupply(id);
uint256 borrowRate = (morpho.totalBorrowAssets(id).wDivDown(morpho.totalSupplyAssets(id))) / 365 days;
uint256 totalBorrowBeforeAccrued = morpho.totalBorrowAssets(id);
uint256 totalSupplyBeforeAccrued = morpho.totalSupplyAssets(id);
uint256 totalSupplySharesBeforeAccrued = morpho.totalSupplyShares(id);
uint256 expectedAccruedInterests = totalBorrowBeforeAccrued.wMulDown(borrowRate.wTaylorCompounded(timeElapsed));

vm.expectEmit(true, true, true, true, address(morpho));
emit EventsLib.AccrueInterests(id, borrowRate, expectedAccruedInterests, 0);
morpho.accrueInterests(market);

assertEq(morpho.totalBorrow(id), totalBorrowBeforeAccrued + expectedAccruedInterests, "total borrow");
assertEq(morpho.totalSupply(id), totalSupplyBeforeAccrued + expectedAccruedInterests, "total supply");
assertEq(morpho.totalBorrowAssets(id), totalBorrowBeforeAccrued + expectedAccruedInterests, "total borrow");
assertEq(morpho.totalSupplyAssets(id), totalSupplyBeforeAccrued + expectedAccruedInterests, "total supply");
assertEq(morpho.totalSupplyShares(id), totalSupplySharesBeforeAccrued, "total supply shares");
assertEq(morpho.supplyShares(id, OWNER), 0, "feeRecipient's supply shares");
assertEq(morpho.lastUpdate(id), block.timestamp, "last update");
Expand Down Expand Up @@ -166,9 +167,9 @@ contract IntegrationAccrueInterestsTest is BaseTest {
vm.roll(block.number + 1);
vm.warp(block.timestamp + timeElapsed);

params.borrowRate = (morpho.totalBorrow(id).wDivDown(morpho.totalSupply(id))) / 365 days;
params.totalBorrowBeforeAccrued = morpho.totalBorrow(id);
params.totalSupplyBeforeAccrued = morpho.totalSupply(id);
params.borrowRate = (morpho.totalBorrowAssets(id).wDivDown(morpho.totalSupplyAssets(id))) / 365 days;
params.totalBorrowBeforeAccrued = morpho.totalBorrowAssets(id);
params.totalSupplyBeforeAccrued = morpho.totalSupplyAssets(id);
params.totalSupplySharesBeforeAccrued = morpho.totalSupplyShares(id);
params.expectedAccruedInterests =
params.totalBorrowBeforeAccrued.wMulDown(params.borrowRate.wTaylorCompounded(timeElapsed));
Expand All @@ -183,10 +184,14 @@ contract IntegrationAccrueInterestsTest is BaseTest {
morpho.accrueInterests(market);

assertEq(
morpho.totalBorrow(id), params.totalBorrowBeforeAccrued + params.expectedAccruedInterests, "total borrow"
morpho.totalBorrowAssets(id),
params.totalBorrowBeforeAccrued + params.expectedAccruedInterests,
"total borrow"
);
assertEq(
morpho.totalSupply(id), params.totalSupplyBeforeAccrued + params.expectedAccruedInterests, "total supply"
morpho.totalSupplyAssets(id),
params.totalSupplyBeforeAccrued + params.expectedAccruedInterests,
"total supply"
);
assertEq(
morpho.totalSupplyShares(id),
Expand Down
Loading