Skip to content
Verified contractPartialMIT

CreditModule

Address0x2994e619aee98e379ce6eb92ce6339fac3f9ecdb
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.38

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.38+commit.1835d247
Language
solidity
Optimization
Yes, 200 runs
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,405,274
Creation transaction
0xb1e8a59d93…a6fea8e3cb

44 files

The source code is large: one file is shown at a time. Choose a file in the list.

project/contracts/modules/CreditModule.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.38;

import "../interfaces/IMultiPool.sol";
import "../interfaces/IMultiPoolEvents.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import "../MultiPool.sol";

/// @title MultiPool credit-side logic
library CreditModule {
    using SafeERC20 for IERC20;
    using EnumerableSet for EnumerableSet.UintSet;

    /// @notice Reverts unless called through an initialized `MultiPool` (via `delegatecall`) — see
    ///         `Layout.initialized`. Guards every public function below against being invoked
    ///         directly at this library's own deployed address.
    function _requireInitialized() private view {
        require(_getStorage().initialized, IMultiPoolEvents.NotInitialized());
    }

    /// @notice See the matching function in `IMultiPool` for full behavior docs.
    function updateCreditAccInterestPerToken(IERC20 token) public returns (uint256 accCreditInterestPerToken) {
        _requireInitialized();
        TokenData storage tokenData = _getStorage().tokens[address(token)];
        uint32 secondsForAccrue = uint32(block.timestamp - tokenData.lastUpdateTime);
        if (secondsForAccrue == 0) return tokenData.accCreditInterestPerToken;
        tokenData.lastUpdateTime = uint32(block.timestamp);
        accCreditInterestPerToken = tokenData.accCreditInterestPerToken;
        if (tokenData.totalBorrowed > 0) {
            uint256 delta = Math.mulDiv(tokenData.creditApr * PRECISION, secondsForAccrue, 10000 * 365 days);
            accCreditInterestPerToken += delta;
            tokenData.accCreditInterestPerToken = accCreditInterestPerToken;
            tokenData.totalCreditInterestAccrued = SafeCast.toUint96(uint256(tokenData.totalCreditInterestAccrued) + Math.mulDiv(tokenData.totalBorrowed, delta, PRECISION));
            tokenData.totalActiveTime += secondsForAccrue;
        }
    }

    /// @notice See the matching function in `IMultiPool` for full behavior docs.
    function borrow(IERC20 token, uint128 amount, uint32 creditId, address receiver) public {
        _requireInitialized();
        require(receiver != address(0), IMultiPoolEvents.ZeroAddress());
        require(amount > 0, IMultiPoolEvents.ZeroAmount());
        TokenData storage tokenData = _getStorage().tokens[address(token)];
        require(tokenData.creditApr > 0, IMultiPoolEvents.ZeroAPR());
        uint256 accCreditInterestPerToken = updateCreditAccInterestPerToken(token);
        require(tokenData.totalDeposited >= tokenData.totalBorrowed, IMultiPoolEvents.InsufficientLiquidity());
        require(amount <= tokenData.totalDeposited - tokenData.totalBorrowed, IMultiPoolEvents.InsufficientLiquidity());

        if (creditId == 0) {
            creditId = ++tokenData.creditId;
            tokenData.userCreditLines[msg.sender].add(creditId);
        } else {
            require(tokenData.userCreditLines[msg.sender].contains(creditId), IMultiPoolEvents.NotUsersCreditId(creditId));
        }

        CreditLine storage line = tokenData.creditLines[msg.sender][creditId];
        uint128 oldPrincipalBalance = line.principalBalance;
        if (oldPrincipalBalance > 0) {
            uint256 pendingInterest = Math.mulDiv(oldPrincipalBalance, accCreditInterestPerToken, PRECISION) - line.interestDebt;
            if (pendingInterest > 0) {
                uint128 newAccruedInterest = line.accruedInterest + SafeCast.toUint128(pendingInterest);
                line.accruedInterest = newAccruedInterest;
                emit IMultiPoolEvents.AccruedCreditInterest(token, msg.sender, creditId, pendingInterest, newAccruedInterest);
            }
        }

        tokenData.totalBorrowed += amount;
        uint128 newPrincipalBalance = oldPrincipalBalance + amount;
        line.principalBalance = newPrincipalBalance;
        line.interestDebt = SafeCast.toUint128(Math.mulDiv(newPrincipalBalance, accCreditInterestPerToken, PRECISION));

        SafeERC20.safeTransferFrom(token, _getStorage().creditVault, receiver, amount);
        if (receiver != msg.sender) {
            emit IMultiPoolEvents.BorrowTo(token, msg.sender, creditId, amount, newPrincipalBalance, receiver);
        } else {
            emit IMultiPoolEvents.Borrow(token, msg.sender, creditId, amount, newPrincipalBalance);
        }
    }

    /// @notice See the matching function in `IMultiPool` for full behavior docs.
    function repay(IERC20 token, uint128 amount, uint32 creditId) public {
        _requireInitialized();
        TokenData storage tokenData = _getStorage().tokens[address(token)];
        require(tokenData.userCreditLines[msg.sender].contains(creditId), IMultiPoolEvents.NotUsersCreditId(creditId));
        uint256 accCreditInterestPerToken = updateCreditAccInterestPerToken(token);

        CreditLine storage line = tokenData.creditLines[msg.sender][creditId];
        uint256 pendingInterest = Math.mulDiv(line.principalBalance, accCreditInterestPerToken, PRECISION) - line.interestDebt;
        uint128 remainingAccruedInterest = line.accruedInterest + SafeCast.toUint128(pendingInterest);
        if (pendingInterest > 0) emit IMultiPoolEvents.AccruedCreditInterest(token, msg.sender, creditId, pendingInterest, remainingAccruedInterest);
        uint128 remainingPrincipalBalance = line.principalBalance;

        bool interestOnly = amount == 0;
        if (interestOnly) {
            require(remainingAccruedInterest > 0, IMultiPoolEvents.NoCreditInterest());
        } else {
            require(remainingPrincipalBalance > 0, IMultiPoolEvents.NoPrincipalDebt());
        }

        if (remainingAccruedInterest > 0) {
            uint128 interestToRepay = interestOnly || amount > remainingAccruedInterest ? remainingAccruedInterest : amount;

            remainingAccruedInterest -= interestToRepay;
            line.accruedInterest = remainingAccruedInterest;
            if (!interestOnly) amount -= uint128(interestToRepay);
            tokenData.totalCreditInterestPaid = SafeCast.toUint96(uint256(tokenData.totalCreditInterestPaid) + interestToRepay);

            SafeERC20.safeTransferFrom(token, msg.sender, _getStorage().creditVault, interestToRepay);
            emit IMultiPoolEvents.CreditInterestPaid(token, msg.sender, creditId, interestToRepay);
        }

        if (!interestOnly && amount > 0) {
            uint128 repayAmount = amount > remainingPrincipalBalance ? remainingPrincipalBalance : amount;
            remainingPrincipalBalance -= repayAmount;
            line.principalBalance = remainingPrincipalBalance;
            tokenData.totalBorrowed -= repayAmount;

            SafeERC20.safeTransferFrom(token, msg.sender, _getStorage().creditVault, repayAmount);
            emit IMultiPoolEvents.Repay(token, msg.sender, creditId, repayAmount, remainingPrincipalBalance);
        }

        line.interestDebt = SafeCast.toUint128(Math.mulDiv(remainingPrincipalBalance, accCreditInterestPerToken, PRECISION));
    }

    /// @notice See the matching function in `IMultiPool` for full behavior docs.
    function closeCreditLine(IERC20 token, uint32 creditId) public {
        _requireInitialized();
        TokenData storage tokenData = _getStorage().tokens[address(token)];
        require(tokenData.userCreditLines[msg.sender].contains(creditId), IMultiPoolEvents.NotUsersCreditId(creditId));

        CreditLine storage line = tokenData.creditLines[msg.sender][creditId];
        require(line.principalBalance == 0 && line.accruedInterest == 0, IMultiPoolEvents.CreditLineNotSettled(creditId));

        tokenData.userCreditLines[msg.sender].remove(creditId);
        delete tokenData.creditLines[msg.sender][creditId];
        emit IMultiPoolEvents.CreditLineClosed(token, msg.sender, creditId);
    }

    // ── Read-side aggregation (moved from the former ViewLib) ───────────────────────────────

    /// @notice Aggregates a user's open credit lines for `tokenData`, projecting the
    ///         credit-interest accumulator to `block.timestamp`.
    function aggregateCredits(TokenData storage tokenData, address user) public view returns (
        uint128 totalPrincipalBalance,
        uint256 totalPendingInterest,
        UserCreditInfo[] memory creditsInfo
    ) {
        _requireInitialized();
        uint256 accCreditInterestPerToken = tokenData.accCreditInterestPerToken;
        if (block.timestamp > tokenData.lastUpdateTime && tokenData.totalBorrowed > 0) {
            uint256 secondsForAccrue = block.timestamp - tokenData.lastUpdateTime;
            accCreditInterestPerToken += Math.mulDiv(tokenData.creditApr * PRECISION, secondsForAccrue, 10000 * 365 days);
        }
        uint256[] memory creditIds = tokenData.userCreditLines[user].values();
        creditsInfo = new UserCreditInfo[](creditIds.length);
        for (uint256 i = 0; i < creditIds.length; i++) {
            uint32 creditId = uint32(creditIds[i]);
            CreditLine memory line = tokenData.creditLines[user][creditId];
            uint256 pendingInterest = line.accruedInterest + Math.mulDiv(line.principalBalance, accCreditInterestPerToken, PRECISION) - line.interestDebt;
            totalPrincipalBalance += line.principalBalance;
            totalPendingInterest += pendingInterest;
            creditsInfo[i] = UserCreditInfo({
                creditId: creditId,
                pendingInterest: pendingInterest,
                creditLine: line
            });
        }
        return (totalPrincipalBalance, totalPendingInterest, creditsInfo);
    }

    /// @notice Returns a read-only snapshot of a user's credit-side position for `tokenData`.
    function getUserCreditInfo(TokenData storage tokenData, address user) public view returns (CreditUserInfo memory userInfo) {
        _requireInitialized();
        (uint128 totalPrincipalBalance, uint256 pendingInterest, UserCreditInfo[] memory creditsInfo) = aggregateCredits(tokenData, user);
        userInfo = CreditUserInfo({
            principalBalance: totalPrincipalBalance,
            pendingCreditInterest: pendingInterest,
            isBorrower: tokenData.borrowers[user],
            creditsInfo: creditsInfo
        });
    }

    /// @notice Returns `tokenData`'s credit interest on its aggregated borrow positions, summed
    ///         across every borrower, past and present, projected to `block.timestamp`. See
    ///         `IMultiPool.totalCreditInterest`.
    function totalCreditInterest(TokenData storage tokenData) public view returns (uint256 accruedInterest, uint256 paidInterest) {
        _requireInitialized();
        uint256 totalAccrued = tokenData.totalCreditInterestAccrued;
        if (block.timestamp > tokenData.lastUpdateTime && tokenData.totalBorrowed > 0) {
            uint256 secondsForAccrue = block.timestamp - tokenData.lastUpdateTime;
            uint256 delta = Math.mulDiv(tokenData.creditApr * PRECISION, secondsForAccrue, 10000 * 365 days);
            totalAccrued += Math.mulDiv(tokenData.totalBorrowed, delta, PRECISION);
        }
        accruedInterest = totalAccrued;
        paidInterest = tokenData.totalCreditInterestPaid;
    }

    /// @notice Returns a full snapshot of `tokenData`'s aggregated credit market combined with
    ///         `user`'s credit position.
    function getCreditInfo(TokenData storage tokenData, IERC20 token, address user, bool paused) public view returns (CreditInfo memory creditInfo) {
        _requireInitialized();
        creditInfo = CreditInfo({
            token: token,
            creditApr: tokenData.creditApr,
            totalDeposited: tokenData.totalDeposited,
            totalBorrowed: tokenData.totalBorrowed,
            paused: paused,
            userInfo: getUserCreditInfo(tokenData, user),
            avgApr: calcAvgApr(tokenData)
        });
    }

    /// @notice Time-weighted average `creditApr` over the seconds the token had outstanding
    ///         borrows, projected to `block.timestamp`. Averages the rate over time, not over principal.
    function calcAvgApr(TokenData storage tokenData) internal view returns (uint16 avgApr) {
        uint256 accCreditInterestPerToken = tokenData.accCreditInterestPerToken;
        uint256 totalActiveTime = tokenData.totalActiveTime;
        if (block.timestamp > tokenData.lastUpdateTime && tokenData.totalBorrowed > 0) {
            uint256 secondsForAccrue = block.timestamp - tokenData.lastUpdateTime;
            accCreditInterestPerToken += Math.mulDiv(tokenData.creditApr * PRECISION, secondsForAccrue, 10000 * 365 days);
            totalActiveTime += secondsForAccrue;
        }
        if (totalActiveTime == 0) return 0;
        return SafeCast.toUint16(Math.mulDiv(accCreditInterestPerToken, 365 days * 10000, totalActiveTime * PRECISION, Math.Rounding.Ceil));
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "none"
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "remappings": [
    "npm/@openzeppelin/[email protected]/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/",
    "project/:@openzeppelin/contracts-upgradeable/=npm/@openzeppelin/[email protected]/",
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.