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.solmain13.04 KB
- npm/@openzeppelin/[email protected]/access/AccessControlUpgradeable.sol8.28 KB
- npm/@openzeppelin/[email protected]/proxy/utils/Initializable.sol144 B
- npm/@openzeppelin/[email protected]/proxy/utils/UUPSUpgradeable.sol148 B
- npm/@openzeppelin/[email protected]/utils/ContextUpgradeable.sol1.22 KB
- npm/@openzeppelin/[email protected]/utils/PausableUpgradeable.sol3.68 KB
- npm/@openzeppelin/[email protected]/utils/introspection/ERC165Upgradeable.sol1.17 KB
- npm/@openzeppelin/[email protected]/access/IAccessControl.sol3.34 KB
- npm/@openzeppelin/[email protected]/interfaces/IERC1363.sol4.45 KB
- npm/@openzeppelin/[email protected]/interfaces/IERC165.sol193 B
- npm/@openzeppelin/[email protected]/interfaces/IERC1967.sol637 B
- npm/@openzeppelin/[email protected]/interfaces/IERC20.sol182 B
- npm/@openzeppelin/[email protected]/interfaces/IERC5267.sol740 B
- npm/@openzeppelin/[email protected]/interfaces/draft-IERC1822.sol882 B
- npm/@openzeppelin/[email protected]/proxy/ERC1967/ERC1967Utils.sol6.26 KB
- npm/@openzeppelin/[email protected]/proxy/beacon/IBeacon.sol473 B
- npm/@openzeppelin/[email protected]/proxy/utils/Initializable.sol9.28 KB
- npm/@openzeppelin/[email protected]/proxy/utils/UUPSUpgradeable.sol6.32 KB
- npm/@openzeppelin/[email protected]/token/ERC20/IERC20.sol2.78 KB
- npm/@openzeppelin/[email protected]/token/ERC20/utils/SafeERC20.sol13.31 KB
- npm/@openzeppelin/[email protected]/utils/Address.sol6.8 KB
- npm/@openzeppelin/[email protected]/utils/Arrays.sol35.17 KB
- npm/@openzeppelin/[email protected]/utils/Bytes.sol14.74 KB
- npm/@openzeppelin/[email protected]/utils/Comparators.sol443 B
- npm/@openzeppelin/[email protected]/utils/Errors.sol896 B
- npm/@openzeppelin/[email protected]/utils/LowLevelCall.sol5.55 KB
- npm/@openzeppelin/[email protected]/utils/Panic.sol1.97 KB
- npm/@openzeppelin/[email protected]/utils/ReentrancyGuardTransient.sol2.85 KB
- npm/@openzeppelin/[email protected]/utils/SlotDerivation.sol5.32 KB
- npm/@openzeppelin/[email protected]/utils/StorageSlot.sol4.18 KB
- npm/@openzeppelin/[email protected]/utils/Strings.sol21.54 KB
- npm/@openzeppelin/[email protected]/utils/TransientSlot.sol5.08 KB
- npm/@openzeppelin/[email protected]/utils/cryptography/ECDSA.sol12.15 KB
- npm/@openzeppelin/[email protected]/utils/cryptography/MessageHashUtils.sol8.63 KB
- npm/@openzeppelin/[email protected]/utils/introspection/IERC165.sol871 B
- npm/@openzeppelin/[email protected]/utils/math/Math.sol32.66 KB
- npm/@openzeppelin/[email protected]/utils/math/SafeCast.sol34.94 KB
- npm/@openzeppelin/[email protected]/utils/math/SignedMath.sol2.61 KB
- npm/@openzeppelin/[email protected]/utils/structs/EnumerableSet.sol33.3 KB
- project/contracts/MultiPool.sol31.65 KB
- project/contracts/interfaces/IMultiPool.sol55.71 KB
- project/contracts/interfaces/IMultiPoolEvents.sol13.52 KB
- project/contracts/modules/DepositModule.sol29.59 KB
- project/contracts/utils/EIP712Upgradeable.sol6.07 KB
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.