Verified contractExactUNLICENSED
CollateralPool
Address0x3ed10def74388b4b4455c2a79254dbcd99ffb21f
- Balance
0 ETH
- Transactions
11
- Compiler
solc 0.8.31
- Same code
3 more contracts
Details
- Compiler
- solc 0.8.31+commit.fd3a2265
- Language
- solidity
- Optimization
- No
- License
- UNLICENSED
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 24,460,555
- Creation transaction
- 0x2b811bf5f0…d59e048150
6 files
contracts/CollateralPool.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;
import "./interfaces/IMain.sol";
import "./interfaces/IOwnable.sol";
import "./interfaces/IMarketPool.sol";
import "./interfaces/IERC20x.sol";
import "./interfaces/IERC721x.sol";
/// @title CollateralPool
/// @notice This contract manages collateral deposits, withdrawals, and reward claims for LPs.
contract CollateralPool {
event CollateralDeposited(address indexed user, uint256 amount);
event CollateralWithdrawn(address indexed user, uint256 amount);
event ContractLiquidated(address indexed liquidator, address indexed user, uint256 penalty);
event RewardsClaimed(address indexed user, uint256 index, uint256 id, uint256 amount);
address private _COLLATERALTOKEN; // Base Token
uint256 private _COLLATERALTOKEN_DECIMALS;
address private _MAIN;
/// @param _collateralToken Address of the token used as collateral.
/// @param _main Address of the main contract.
constructor(address _collateralToken, uint256 _collateralTokenDecimals, address _main) {
_COLLATERALTOKEN = _collateralToken;
_COLLATERALTOKEN_DECIMALS = _collateralTokenDecimals;
_MAIN = _main;
}
////////////////////////////////////////////////////////////////// BASE FUNCTIONS //////////////////////////////////////////////////////////////////
/// @notice Returns the address of the main contract.
/// @return Address of the main contract.
function getMain() external view returns(address) {
return _MAIN;
}
/// @notice Returns the address of the collateral Token.
/// @return Address of the collateral Token.
function getCollateralToken() external view returns(address) {
return _COLLATERALTOKEN;
}
////////////////////////////////////////////////////////////////// SET UP //////////////////////////////////////////////////////////////////
struct UserInfos {
uint256 collateral;
uint256 rent;
uint256 lastUpdate;
}
mapping(address => UserInfos) private _userInfos;
////////////////////////////////////////////////////////////////// INTERNAL //////////////////////////////////////////////////////////////////
/// @notice Converts an amount from the collateral token's decimals to 18 decimals.
/// @param _amount The amount in the collateral token's decimals to convert.
/// @return The converted amount in 18 decimals.
function collateralTokenTo18(uint256 _amount) private view returns(uint256) {
return (_amount * 1e18)/10**_COLLATERALTOKEN_DECIMALS;
}
/// @notice Converts an amount from 18 decimals to the collateral token's decimals.
/// @param _amount The amount in 18 decimals to convert.
/// @return The converted amount in the collateral token's decimals.
function toCollateralTokenDecimals(uint256 _amount) private view returns(uint256) {
return (_amount * 10**_COLLATERALTOKEN_DECIMALS)/1e18;
}
////////////////////////////////////////////////////////////////// GET FUNCTIONS //////////////////////////////////////////////////////////////////
/// @notice Returns user information for a specific user.
/// @param _user The address of the user.
/// @return UserInfos structure containing collateral, rent, and last update timestamp.
function getUserInfos(address _user) external view returns(UserInfos memory) {
return _userInfos[_user];
}
/// @notice Calculates the accumulated fees for a user.
/// @param _user The address of the user.
/// @return The total fees accumulated for the user (18 decimals).
function getUserFees(address _user) external view returns(uint256) {
UserInfos memory thisUser =_userInfos[_user];
return thisUser.rent * (block.timestamp - thisUser.lastUpdate);
}
/// @notice Returns the balance of collateral for a user after deducting rent fees.
/// @param _user The address of the user.
/// @return The net balance of the user (18 decimals).
function balanceOf(address _user) public view returns(uint256) {
if (_userInfos[_user].rent * (block.timestamp - _userInfos[_user].lastUpdate) > _userInfos[_user].collateral) {
return 0;
} else {
return _userInfos[_user].collateral - _userInfos[_user].rent * (block.timestamp - _userInfos[_user].lastUpdate);
}
}
/// @notice Calculates the rewards for a liquidity provider after deducting fees.
/// @param _index The market index.
/// @param _id The ID of the user's position in the market.
/// @return The net rewards after fees (18 decimals).
function getRewardsForLp(uint256 _index, uint256 _id) external view returns(uint256) {
// Get infos
uint256 rewards = IMarketPool(IMain(_MAIN).getIdToMarket(_index)).getRewards(_id);
uint256 fees = IMain(_MAIN).getFees();
uint256 feeAmount;
if (fees > 0) {
feeAmount = (rewards * IMain(_MAIN).getFees()) / 1e18;
} else {
feeAmount = 0;
}
return rewards - feeAmount;
}
/// @notice Determines if a user can open a contract based on their collateral and rent.
/// @param _user The address of the user.
/// @param _rent The rent amount for the new contract.
/// @return True if the user has sufficient collateral, otherwise false.
function canOpenContract(address _user, uint256 _rent) external view returns(bool) {
uint256 minCollateral = IMain(_MAIN).getMinCollateral();
// User Infos
uint256 userNewRent = _userInfos[_user].rent + _rent;
uint256 userBalance = balanceOf(_user);
uint256 balanceNeeded = userNewRent * minCollateral;
// Returns
if (userBalance > balanceNeeded) {
return true;
} else {
return false;
}
}
/// @notice Checks if a user needs to be liquidated.
/// @param _user The address of the user.
/// @return True if liquidation is required, otherwise false.
function needLiquidation(address _user) external view returns(bool) {
uint256 liqThresh = IMain(_MAIN).getLiquidationThreshold();
// User Infos
uint256 userRent = _userInfos[_user].rent;
uint256 userBalance = balanceOf(_user);
uint256 balanceNeeded = userRent * liqThresh;
// Returns
if (balanceNeeded > userBalance) {
return true;
} else {
return false;
}
}
////////////////////////////////////////////////////////////////// USERS FUNCTIONS //////////////////////////////////////////////////////////////////
/// @notice Allows a user to deposit collateral into their account.
/// @param _amount The amount of collateral to deposit.
function depositCollateral(uint256 _amount) external {
// Transaction
uint256 balBefore = IERC20x(_COLLATERALTOKEN).balanceOf(address(this));
IERC20x(_COLLATERALTOKEN).transferFrom(msg.sender, address(this), _amount);
uint256 balAfter = IERC20x(_COLLATERALTOKEN).balanceOf(address(this));
require(balAfter - balBefore == _amount, "Sent != Received");
_userInfos[msg.sender].collateral += collateralTokenTo18(_amount);
// Emit event for collateral deposit
emit CollateralDeposited(msg.sender, _amount);
}
/// @notice Allows a user to withdraw collateral if they have sufficient balance.
/// @param _amount The amount of collateral to withdraw.
function withdrawCollateral(uint256 _amount) external {
uint256 amount = collateralTokenTo18(_amount);
// Get infos
uint256 minCollateral = IMain(_MAIN).getMinCollateral();
uint256 userRent = _userInfos[msg.sender].rent;
// Allowed to withdraw ?
require(balanceOf(msg.sender) - amount >= userRent * minCollateral, "Not enough collateral");
// Transfer and update user's infos
IERC20x(_COLLATERALTOKEN).transfer(msg.sender, _amount);
_userInfos[msg.sender].collateral -= amount;
// Emit event for collateral withdrawal
emit CollateralWithdrawn(msg.sender, _amount);
}
/// @notice Claims rewards for an LP position and transfers them to the position owner.
/// @dev Verifies that the caller is authorized (position owner / tx.origin owner / or the MarketPool as configured).
/// Fetches rewards from MarketPool using an O(1) accumulator-based claim (`MarketPool.claimRewards`),
/// applies protocol fees if configured, then transfers net rewards to the LP owner and fees to protocol owner.
/// @param _index The market index in Main used to resolve the MarketPool address.
/// @param _id The LP position NFT id.
/// @return claimedRewards The net rewards transferred to the LP owner (collateral token decimals).
function claimRewards(uint256 _index, uint256 _id) external returns(uint256) {
// Allowed to claim ?
address idOwner = IERC721x(IMarketPool(IMain(_MAIN).getIdToMarket(_index)).getERC721_LP()).ownerOf(_id);
require(msg.sender == idOwner || tx.origin == idOwner || msg.sender == IMain(_MAIN).getIdToMarket(_index), "You are not allowed");
// Get infos
uint256 rewards = IMarketPool(IMain(_MAIN).getIdToMarket(_index)).claimRewards(_id);
uint256 fees = IMain(_MAIN).getFees();
uint256 feeAmount;
if (fees > 0) {
feeAmount = (rewards * IMain(_MAIN).getFees()) / 1e18;
} else {
feeAmount = 0;
}
// Transfer
IERC20x(_COLLATERALTOKEN).transfer(idOwner, toCollateralTokenDecimals(rewards - feeAmount));
IERC20x(_COLLATERALTOKEN).transfer(IOwnable(_MAIN).owner(),toCollateralTokenDecimals(feeAmount));
// Emit event for reward claimed
emit RewardsClaimed(idOwner, _index, _id, toCollateralTokenDecimals(rewards - feeAmount));
return toCollateralTokenDecimals(rewards - feeAmount);
}
/// @notice Liquidates a user’s contract if the account is below the liquidation threshold.
/// @dev Applies the liquidation penalty to the user’s collateral and updates internal state before performing
/// external interactions (CEI). Then calls MarketPool to settle/burn the contract and transfers the penalty
/// to the liquidator.
/// @param _index The market index in Main used to resolve the MarketPool address.
/// @param _id The contract NFT id to liquidate.
/// @return penalty The penalty amount awarded to the liquidator (18 decimals).
function liquidateContract(uint256 _index, uint256 _id) external returns(uint256) {
// Get infos
address user = IERC721x(IMarketPool(IMain(_MAIN).getIdToMarket(_index)).getERC721_Contract()).ownerOf(_id);
uint256 liqThresh = IMain(_MAIN).getLiquidationThreshold();
uint256 liqPen = IMain(_MAIN).getLiquidationPenalty();
// Need liquidation ?
require(balanceOf(user) < _userInfos[user].rent * liqThresh, "No liquidation needed");
// Calcul penalty
uint256 penalty = (balanceOf(user) * liqPen) / 1e18;
// State Update
_userInfos[user].collateral -= penalty;
// Close Contract
IMarketPool(IMain(_MAIN).getIdToMarket(_index)).liquidateContract(_id, msg.sender);
// Send rewards to liquidator
IERC20x(_COLLATERALTOKEN).transfer(msg.sender, toCollateralTokenDecimals(penalty));
// Emit event for contract liquidation
emit ContractLiquidated(msg.sender, user, toCollateralTokenDecimals(penalty));
return penalty;
}
////////////////////////////////////////////////////////////////// VITALS //////////////////////////////////////////////////////////////////
/**
* @notice Updates the user's collateral and rent information in the contract.
* @dev This function can only be called by Market Pools. It adjusts the user's
* collateral based on the time elapsed since the last update and either
* adds or subtracts rent depending on the `_isAdding` flag.
* @param _user The address of the user whose information is being updated.
* @param _isAdding Boolean flag indicating whether to add (`true`) or subtract (`false`) the specified `_rent`.
* @param _rent The amount of rent to add or subtract from the user's total rent.
* @param _lastUpdate The timestamp of the last update to synchronize the user's rent calculation.
* @notice Reverts if called by an address other than a registered Market Pool.
*/
function updateUserInfos(address _user, bool _isAdding, uint256 _rent, uint256 _lastUpdate) external {
// Only for Market Pools
uint256 marketId = IMain(_MAIN).getMarketId(msg.sender);
require(IMain(_MAIN).getIdToMarket(marketId) == msg.sender, "Only for Market Pools");
// Update user infos
_userInfos[_user].collateral = balanceOf(_user);
if (_isAdding) {
_userInfos[_user].rent += _rent;
} else {
_userInfos[_user].rent -= _rent;
}
_userInfos[_user].lastUpdate = _lastUpdate;
}
}
contracts/interfaces/IERC20x.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
interface IERC20x {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
function decimals() external view returns (uint8);
function mint(address _receiver, uint256 _amount) external;
function burn(address _account, uint256 _amount) external;
}contracts/interfaces/IERC721x.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
interface IERC721x {
function totalSupply() external view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
function tokenByIndex(uint256 index) external view returns (uint256);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
function safeTransferFrom(address from, address to, uint256 tokenId) external;
function transferFrom(address from, address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
function setApprovalForAll(address operator, bool approved) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function isApprovedForAll(address owner, address operator) external view returns (bool);
function getOwners() external view returns (address[] memory);
function getAllTokenIds() external view returns (uint256[] memory);
function mint(address _to, uint256 _id) external;
function burn(uint256 tokenId) external;
}contracts/interfaces/IMain.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;
interface IMain {
struct marketInfos {
address addr;
address tokenA;
address tokenB;
address priceFeed;
uint256 intervalLength;
uint256 range;
uint256 maxPriceStaleness;
uint256 yield;
}
function getCollateralToken() external view returns(address);
function getCollateralTokenDecimals() external view returns(uint256);
function getCollateralPool() external view returns(address);
function getLiquidationThreshold() external view returns(uint256);
function getLiquidationPenalty() external view returns(uint256);
function getMinCollateral() external view returns(uint256);
function getFees() external view returns(uint256);
function getMarketCount() external view returns(uint256);
function getMarketId(address _market) external view returns(uint256);
function getIdToMarket(uint256 _index) external view returns(address);
function getIdToMarketInfos(uint256 _index) external view returns(marketInfos memory);
}contracts/interfaces/IMarketPool.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;
interface IMarketPool {
struct StrikeInfos {
uint256 callLP;
uint256 callLU;
uint256 callLR;
uint256 putLP;
uint256 putLU;
uint256 putLR;
uint256 accCallPerShare;
uint256 accPutPerShare;
uint256 lastUpdate;
}
struct LpInfos {
bool isCall;
uint256 strike;
uint256 amount;
uint256 start;
uint256 rewardDebt;
}
struct ContractInfos {
bool isCall;
uint256 strike;
uint256 amount;
uint256 rent;
uint256 start;
}
function getERC721_Contract() external view returns(address);
function getERC721_LP() external view returns(address);
function getContractInfos(uint256 _id) external view returns(ContractInfos memory);
function getLpInfos(uint256 _id) external view returns(LpInfos memory);
function getStrikeInfos(uint256 _strike) external view returns(StrikeInfos memory);
function getRewards(uint256 _id) external view returns(uint256);
function claimRewards(uint256 _id) external returns(uint256 rewards);
function openContract(bool _isCall, uint256 _strikeIndex, uint256 _amount) external;
function closeContract(uint256 _id) external;
function liquidateContract(uint256 _id, address _liquidator) external;
function setPriceFeed(address _priceFeed, uint256 _decimal) external;
function setIntervalLength(uint256 _length) external;
function setRange(uint256 _range) external;
function setMaxPriceStaleness(uint256 _maxPriceStaleness) external;
function getTokenA() external view returns(address);
function getTokenB() external view returns(address);
function getPriceFeed() external view returns(address);
function getIntervals() external view returns(uint256[] memory);
function getIntervalLength() external view returns(uint256);
function getRange() external view returns(uint256);
function getMaxPriceStaleness() external view returns(uint256);
function getYield() external view returns(uint256);
function getPrice() external view returns(uint256);
function withdraw(uint256 _id) external returns(uint256, uint256, uint256);
function deposit(bool _isCall, uint256 _strikeIndex, uint256 _amount) external returns(uint256);
}contracts/interfaces/IOwnable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
interface IOwnable {
function owner() external view returns(address);
}Compiler settingsShow
{
"optimizer": {
"runs": 200,
"enabled": false
},
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.