编译器
0.8.10+commit.fc410830
文件 1 的 45:Address.sol
pragma solidity ^0.8.1;
library Address {
function isContract(address account) internal view returns (bool) {
return account.code.length > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
文件 2 的 45:AddressUpgradeable.sol
pragma solidity ^0.8.1;
library AddressUpgradeable {
function isContract(address account) internal view returns (bool) {
return account.code.length > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
文件 3 的 45:AddressesProvider.sol
pragma solidity >=0.8.0;
import { SafeOwnableUpgradeable } from "../ionic/SafeOwnableUpgradeable.sol";
contract AddressesProvider is SafeOwnableUpgradeable {
mapping(string => address) private _addresses;
mapping(address => Contract) public plugins;
mapping(address => Contract) public flywheelRewards;
mapping(address => RedemptionStrategy) public redemptionStrategiesConfig;
mapping(address => FundingStrategy) public fundingStrategiesConfig;
JarvisPool[] public jarvisPoolsConfig;
CurveSwapPool[] public curveSwapPoolsConfig;
mapping(address => mapping(address => address)) public balancerPoolForTokens;
function initialize(address owner) public initializer {
__SafeOwnable_init(owner);
}
struct Contract {
address addr;
string contractInterface;
}
struct RedemptionStrategy {
address addr;
string contractInterface;
address outputToken;
}
struct FundingStrategy {
address addr;
string contractInterface;
address inputToken;
}
struct JarvisPool {
address syntheticToken;
address collateralToken;
address liquidityPool;
uint256 expirationTime;
}
struct CurveSwapPool {
address poolAddress;
address[] coins;
}
function setFlywheelRewards(
address rewardToken,
address flywheelRewardsModule,
string calldata contractInterface
) public onlyOwner {
flywheelRewards[rewardToken] = Contract(flywheelRewardsModule, contractInterface);
}
function setPlugin(
address asset,
address plugin,
string calldata contractInterface
) public onlyOwner {
plugins[asset] = Contract(plugin, contractInterface);
}
function setRedemptionStrategy(
address asset,
address strategy,
string calldata contractInterface,
address outputToken
) public onlyOwner {
redemptionStrategiesConfig[asset] = RedemptionStrategy(strategy, contractInterface, outputToken);
}
function getRedemptionStrategy(address asset) public view returns (RedemptionStrategy memory) {
return redemptionStrategiesConfig[asset];
}
function setFundingStrategy(
address asset,
address strategy,
string calldata contractInterface,
address inputToken
) public onlyOwner {
fundingStrategiesConfig[asset] = FundingStrategy(strategy, contractInterface, inputToken);
}
function getFundingStrategy(address asset) public view returns (FundingStrategy memory) {
return fundingStrategiesConfig[asset];
}
function setJarvisPool(
address syntheticToken,
address collateralToken,
address liquidityPool,
uint256 expirationTime
) public onlyOwner {
jarvisPoolsConfig.push(JarvisPool(syntheticToken, collateralToken, liquidityPool, expirationTime));
}
function setCurveSwapPool(address poolAddress, address[] calldata coins) public onlyOwner {
curveSwapPoolsConfig.push(CurveSwapPool(poolAddress, coins));
}
function setAddress(string calldata id, address newAddress) external onlyOwner {
_addresses[id] = newAddress;
}
function getAddress(string calldata id) public view returns (address) {
return _addresses[id];
}
function getCurveSwapPools() public view returns (CurveSwapPool[] memory) {
return curveSwapPoolsConfig;
}
function getJarvisPools() public view returns (JarvisPool[] memory) {
return jarvisPoolsConfig;
}
function setBalancerPoolForTokens(
address inputToken,
address outputToken,
address pool
) external onlyOwner {
balancerPoolForTokens[inputToken][outputToken] = pool;
}
function getBalancerPoolForTokens(address inputToken, address outputToken) external view returns (address) {
return balancerPoolForTokens[inputToken][outputToken];
}
}
文件 4 的 45:Auth.sol
pragma solidity >=0.8.0;
abstract contract Auth {
event OwnerUpdated(address indexed user, address indexed newOwner);
event AuthorityUpdated(address indexed user, Authority indexed newAuthority);
address public owner;
Authority public authority;
constructor(address _owner, Authority _authority) {
owner = _owner;
authority = _authority;
emit OwnerUpdated(msg.sender, _owner);
emit AuthorityUpdated(msg.sender, _authority);
}
modifier requiresAuth() virtual {
require(isAuthorized(msg.sender, msg.sig), "UNAUTHORIZED");
_;
}
function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) {
Authority auth = authority;
return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner;
}
function setAuthority(Authority newAuthority) public virtual {
require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig));
authority = newAuthority;
emit AuthorityUpdated(msg.sender, newAuthority);
}
function setOwner(address newOwner) public virtual requiresAuth {
owner = newOwner;
emit OwnerUpdated(msg.sender, newOwner);
}
}
interface Authority {
function canCall(
address user,
address target,
bytes4 functionSig
) external view returns (bool);
}
文件 5 的 45:AuthoritiesRegistry.sol
pragma solidity >=0.8.0;
import { PoolRolesAuthority } from "../ionic/PoolRolesAuthority.sol";
import { SafeOwnableUpgradeable } from "../ionic/SafeOwnableUpgradeable.sol";
import { IonicComptroller } from "../compound/ComptrollerInterface.sol";
import { TransparentUpgradeableProxy } from "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";
contract AuthoritiesRegistry is SafeOwnableUpgradeable {
mapping(address => PoolRolesAuthority) public poolsAuthorities;
PoolRolesAuthority public poolAuthLogic;
address public leveredPositionsFactory;
bool public noAuthRequired;
function initialize(address _leveredPositionsFactory) public initializer {
__SafeOwnable_init(msg.sender);
leveredPositionsFactory = _leveredPositionsFactory;
poolAuthLogic = new PoolRolesAuthority();
}
function reinitialize(address _leveredPositionsFactory) public onlyOwnerOrAdmin {
leveredPositionsFactory = _leveredPositionsFactory;
poolAuthLogic = new PoolRolesAuthority();
noAuthRequired = block.chainid == 245022934;
}
function createPoolAuthority(address pool) public onlyOwner returns (PoolRolesAuthority auth) {
require(address(poolsAuthorities[pool]) == address(0), "already created");
TransparentUpgradeableProxy proxy = new TransparentUpgradeableProxy(address(poolAuthLogic), _getProxyAdmin(), "");
auth = PoolRolesAuthority(address(proxy));
auth.initialize(address(this));
poolsAuthorities[pool] = auth;
auth.openPoolSupplierCapabilities(IonicComptroller(pool));
auth.setUserRole(address(this), auth.REGISTRY_ROLE(), true);
reconfigureAuthority(pool);
}
function reconfigureAuthority(address poolAddress) public {
IonicComptroller pool = IonicComptroller(poolAddress);
PoolRolesAuthority auth = poolsAuthorities[address(pool)];
if (msg.sender != poolAddress || address(auth) != address(0)) {
require(address(auth) != address(0), "no such authority");
require(msg.sender == owner() || msg.sender == poolAddress, "not owner or pool");
auth.configureRegistryCapabilities();
auth.configurePoolSupplierCapabilities(pool);
auth.configurePoolBorrowerCapabilities(pool);
auth.configureOpenPoolLiquidatorCapabilities(pool);
auth.configureLeveredPositionCapabilities(pool);
if (auth.owner() != owner()) {
auth.setOwner(owner());
}
}
}
function canCall(
address pool,
address user,
address target,
bytes4 functionSig
) external view returns (bool) {
PoolRolesAuthority authorityForPool = poolsAuthorities[pool];
if (address(authorityForPool) == address(0)) {
return noAuthRequired;
} else {
return authorityForPool.canCall(user, target, functionSig);
}
}
function setUserRole(
address pool,
address user,
uint8 role,
bool enabled
) external {
PoolRolesAuthority poolAuth = poolsAuthorities[pool];
require(address(poolAuth) != address(0), "auth does not exist");
require(msg.sender == owner() || msg.sender == leveredPositionsFactory, "not owner or factory");
require(msg.sender != leveredPositionsFactory || role == poolAuth.LEVERED_POSITION_ROLE(), "only lev pos role");
poolAuth.setUserRole(user, role, enabled);
}
}
文件 6 的 45:BasePriceOracle.sol
pragma solidity >=0.8.0;
import "../compound/CTokenInterfaces.sol";
interface BasePriceOracle {
function price(address underlying) external view returns (uint256);
function getUnderlyingPrice(ICErc20 cToken) external view returns (uint256);
}
文件 7 的 45:CTokenInterfaces.sol
pragma solidity >=0.8.0;
import { IonicComptroller } from "./ComptrollerInterface.sol";
import { InterestRateModel } from "./InterestRateModel.sol";
import { ComptrollerV3Storage } from "./ComptrollerStorage.sol";
import { AddressesProvider } from "../ionic/AddressesProvider.sol";
abstract contract CTokenAdminStorage {
address payable public ionicAdmin;
}
abstract contract CErc20Storage is CTokenAdminStorage {
bool internal _notEntered;
string public name;
string public symbol;
uint8 public decimals;
uint256 internal constant borrowRateMaxMantissa = 0.0005e16;
uint256 internal constant reserveFactorPlusFeesMaxMantissa = 1e18;
IonicComptroller public comptroller;
InterestRateModel public interestRateModel;
uint256 internal initialExchangeRateMantissa;
uint256 public adminFeeMantissa;
uint256 public ionicFeeMantissa;
uint256 public reserveFactorMantissa;
uint256 public accrualBlockNumber;
uint256 public borrowIndex;
uint256 public totalBorrows;
uint256 public totalReserves;
uint256 public totalAdminFees;
uint256 public totalIonicFees;
uint256 public totalSupply;
mapping(address => uint256) internal accountTokens;
mapping(address => mapping(address => uint256)) internal transferAllowances;
struct BorrowSnapshot {
uint256 principal;
uint256 interestIndex;
}
mapping(address => BorrowSnapshot) internal accountBorrows;
uint256 public constant protocolSeizeShareMantissa = 2.8e16;
uint256 public constant feeSeizeShareMantissa = 1e17;
address public underlying;
AddressesProvider public ap;
}
abstract contract CTokenBaseEvents {
event Transfer(address indexed from, address indexed to, uint256 amount);
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa);
event NewAdminFee(uint256 oldAdminFeeMantissa, uint256 newAdminFeeMantissa);
event NewIonicFee(uint256 oldIonicFeeMantissa, uint256 newIonicFeeMantissa);
event Approval(address indexed owner, address indexed spender, uint256 amount);
event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows);
}
abstract contract CTokenFirstExtensionEvents is CTokenBaseEvents {
event Flash(address receiver, uint256 amount);
}
abstract contract CTokenSecondExtensionEvents is CTokenBaseEvents {
event Mint(address minter, uint256 mintAmount, uint256 mintTokens);
event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens);
event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows);
event RepayBorrow(address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows);
event LiquidateBorrow(
address liquidator,
address borrower,
uint256 repayAmount,
address cTokenCollateral,
uint256 seizeTokens
);
event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves);
event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves);
}
interface CTokenFirstExtensionInterface {
function transfer(address dst, uint256 amount) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 amount
) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256);
function _setAdminFee(uint256 newAdminFeeMantissa) external returns (uint256);
function _setInterestRateModel(InterestRateModel newInterestRateModel) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function borrowRatePerBlock() external view returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
function exchangeRateCurrent() external view returns (uint256);
function accrueInterest() external returns (uint256);
function totalBorrowsCurrent() external view returns (uint256);
function borrowBalanceCurrent(address account) external view returns (uint256);
function getTotalUnderlyingSupplied() external view returns (uint256);
function balanceOfUnderlying(address owner) external view returns (uint256);
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
function flash(uint256 amount, bytes calldata data) external;
function supplyRatePerBlockAfterDeposit(uint256 mintAmount) external view returns (uint256);
function supplyRatePerBlockAfterWithdraw(uint256 withdrawAmount) external view returns (uint256);
function borrowRatePerBlockAfterBorrow(uint256 borrowAmount) external view returns (uint256);
function registerInSFS() external returns (uint256);
}
interface CTokenSecondExtensionInterface {
function mint(uint256 mintAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function repayBorrow(uint256 repayAmount) external returns (uint256);
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);
function liquidateBorrow(
address borrower,
uint256 repayAmount,
address cTokenCollateral
) external returns (uint256);
function getCash() external view returns (uint256);
function seize(
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256);
function _withdrawAdminFees(uint256 withdrawAmount) external returns (uint256);
function _withdrawIonicFees(uint256 withdrawAmount) external returns (uint256);
function selfTransferOut(address to, uint256 amount) external;
function selfTransferIn(address from, uint256 amount) external returns (uint256);
}
interface CDelegatorInterface {
function implementation() external view returns (address);
function _setImplementationSafe(address implementation_, bytes calldata becomeImplementationData) external;
function _upgrade() external;
}
interface CDelegateInterface {
function _becomeImplementation(bytes calldata data) external;
function delegateType() external pure returns (uint8);
function contractType() external pure returns (string memory);
}
abstract contract CErc20AdminBase is CErc20Storage {
function hasAdminRights() internal view returns (bool) {
ComptrollerV3Storage comptrollerStorage = ComptrollerV3Storage(address(comptroller));
return
(msg.sender == comptrollerStorage.admin() && comptrollerStorage.adminHasRights()) ||
(msg.sender == address(ionicAdmin) && comptrollerStorage.ionicAdminHasRights());
}
}
abstract contract CErc20FirstExtensionBase is
CErc20AdminBase,
CTokenFirstExtensionEvents,
CTokenFirstExtensionInterface
{}
abstract contract CTokenSecondExtensionBase is
CErc20AdminBase,
CTokenSecondExtensionEvents,
CTokenSecondExtensionInterface,
CDelegateInterface
{}
abstract contract CErc20DelegatorBase is CErc20AdminBase, CTokenSecondExtensionEvents, CDelegatorInterface {}
interface CErc20StorageInterface {
function admin() external view returns (address);
function adminHasRights() external view returns (bool);
function ionicAdmin() external view returns (address);
function ionicAdminHasRights() external view returns (bool);
function comptroller() external view returns (IonicComptroller);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function adminFeeMantissa() external view returns (uint256);
function ionicFeeMantissa() external view returns (uint256);
function reserveFactorMantissa() external view returns (uint256);
function protocolSeizeShareMantissa() external view returns (uint256);
function feeSeizeShareMantissa() external view returns (uint256);
function totalReserves() external view returns (uint256);
function totalAdminFees() external view returns (uint256);
function totalIonicFees() external view returns (uint256);
function totalBorrows() external view returns (uint256);
function accrualBlockNumber() external view returns (uint256);
function underlying() external view returns (address);
function borrowIndex() external view returns (uint256);
function interestRateModel() external view returns (address);
}
interface CErc20PluginStorageInterface is CErc20StorageInterface {
function plugin() external view returns (address);
}
interface CErc20PluginRewardsInterface is CErc20PluginStorageInterface {
function approve(address, address) external;
}
interface ICErc20 is
CErc20StorageInterface,
CTokenSecondExtensionInterface,
CTokenFirstExtensionInterface,
CDelegatorInterface,
CDelegateInterface
{}
interface ICErc20Plugin is CErc20PluginStorageInterface, ICErc20 {
function _updatePlugin(address _plugin) external;
}
interface ICErc20PluginRewards is CErc20PluginRewardsInterface, ICErc20 {}
文件 8 的 45:CarefulMath.sol
pragma solidity >=0.8.0;
contract CarefulMath {
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint256 c;
unchecked {
c = a * b;
}
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {
uint256 c;
unchecked {
c = a + b;
}
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
function addThenSubUInt(
uint256 a,
uint256 b,
uint256 c
) internal pure returns (MathError, uint256) {
(MathError err0, uint256 sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
文件 9 的 45:Comptroller.sol
pragma solidity >=0.8.0;
import { ICErc20 } from "./CTokenInterfaces.sol";
import { ComptrollerErrorReporter } from "./ErrorReporter.sol";
import { Exponential } from "./Exponential.sol";
import { BasePriceOracle } from "../oracles/BasePriceOracle.sol";
import { Unitroller } from "./Unitroller.sol";
import { IFeeDistributor } from "./IFeeDistributor.sol";
import { IIonicFlywheel } from "../ionic/strategies/flywheel/IIonicFlywheel.sol";
import { DiamondExtension, DiamondBase, LibDiamond } from "../ionic/DiamondExtension.sol";
import { ComptrollerExtensionInterface, ComptrollerBase, ComptrollerInterface } from "./ComptrollerInterface.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
contract Comptroller is ComptrollerBase, ComptrollerInterface, ComptrollerErrorReporter, Exponential, DiamondExtension {
using EnumerableSet for EnumerableSet.AddressSet;
event MarketListed(ICErc20 cToken);
event MarketEntered(ICErc20 cToken, address account);
event MarketExited(ICErc20 cToken, address account);
event NewCloseFactor(uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa);
event NewCollateralFactor(ICErc20 cToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa);
event NewLiquidationIncentive(uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa);
event NewPriceOracle(BasePriceOracle oldPriceOracle, BasePriceOracle newPriceOracle);
event WhitelistEnforcementChanged(bool enforce);
event AddedRewardsDistributor(address rewardsDistributor);
uint256 internal constant closeFactorMinMantissa = 0.05e18;
uint256 internal constant closeFactorMaxMantissa = 0.9e18;
uint256 internal constant collateralFactorMaxMantissa = 0.9e18;
uint256 internal constant liquidationIncentiveMinMantissa = 1.0e18;
uint256 internal constant liquidationIncentiveMaxMantissa = 1.5e18;
modifier isAuthorized() {
require(IFeeDistributor(ionicAdmin).canCall(address(this), msg.sender, address(this), msg.sig), "not authorized");
_;
}
function effectiveSupplyCaps(
address cToken
) public view override(ComptrollerBase, ComptrollerInterface) returns (uint256 supplyCap) {
return ComptrollerBase.effectiveSupplyCaps(cToken);
}
function effectiveBorrowCaps(
address cToken
) public view override(ComptrollerBase, ComptrollerInterface) returns (uint256 borrowCap) {
return ComptrollerBase.effectiveBorrowCaps(cToken);
}
function getAssetsIn(address account) external view returns (ICErc20[] memory) {
ICErc20[] memory assetsIn = accountAssets[account];
return assetsIn;
}
function checkMembership(address account, ICErc20 cToken) external view returns (bool) {
return markets[address(cToken)].accountMembership[account];
}
function enterMarkets(address[] memory cTokens) public override isAuthorized returns (uint256[] memory) {
uint256 len = cTokens.length;
uint256[] memory results = new uint256[](len);
for (uint256 i = 0; i < len; i++) {
ICErc20 cToken = ICErc20(cTokens[i]);
results[i] = uint256(addToMarketInternal(cToken, msg.sender));
}
return results;
}
function addToMarketInternal(ICErc20 cToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(cToken)];
if (!marketToJoin.isListed) {
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower] == true) {
return Error.NO_ERROR;
}
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(cToken);
if (!borrowers[borrower]) {
allBorrowers.push(borrower);
borrowers[borrower] = true;
borrowerIndexes[borrower] = allBorrowers.length - 1;
}
emit MarketEntered(cToken, borrower);
return Error.NO_ERROR;
}
function exitMarket(address cTokenAddress) external override isAuthorized returns (uint256) {
require(markets[cTokenAddress].isListed, "!Comptroller:exitMarket");
ICErc20 cToken = ICErc20(cTokenAddress);
(uint256 oErr, uint256 tokensHeld, uint256 amountOwed, ) = cToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "!exitMarket");
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
uint256 allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[cTokenAddress];
if (!marketToExit.accountMembership[msg.sender]) {
return uint256(Error.NO_ERROR);
}
delete marketToExit.accountMembership[msg.sender];
ICErc20[] memory userAssetList = accountAssets[msg.sender];
uint256 len = userAssetList.length;
uint256 assetIndex = len;
for (uint256 i = 0; i < len; i++) {
if (userAssetList[i] == ICErc20(cTokenAddress)) {
assetIndex = i;
break;
}
}
assert(assetIndex < len);
ICErc20[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.pop();
if (storedList.length == 0) {
allBorrowers[borrowerIndexes[msg.sender]] = allBorrowers[allBorrowers.length - 1];
allBorrowers.pop();
borrowerIndexes[allBorrowers[borrowerIndexes[msg.sender]]] = borrowerIndexes[msg.sender];
borrowerIndexes[msg.sender] = 0;
borrowers[msg.sender] = false;
}
emit MarketExited(ICErc20(cTokenAddress), msg.sender);
return uint256(Error.NO_ERROR);
}
function mintAllowed(address cTokenAddress, address minter, uint256 mintAmount) external override returns (uint256) {
require(!mintGuardianPaused[cTokenAddress], "!mint:paused");
if (!markets[cTokenAddress].isListed) {
return uint256(Error.MARKET_NOT_LISTED);
}
if (enforceWhitelist && !whitelist[minter]) {
return uint256(Error.SUPPLIER_NOT_WHITELISTED);
}
uint256 supplyCap = effectiveSupplyCaps(cTokenAddress);
if (supplyCap != 0 && !supplyCapWhitelist[cTokenAddress].contains(minter)) {
uint256 totalUnderlyingSupply = ICErc20(cTokenAddress).getTotalUnderlyingSupplied();
uint256 whitelistedSuppliersSupply = asComptrollerExtension().getWhitelistedSuppliersSupply(cTokenAddress);
uint256 nonWhitelistedTotalSupply;
if (whitelistedSuppliersSupply >= totalUnderlyingSupply) nonWhitelistedTotalSupply = 0;
else nonWhitelistedTotalSupply = totalUnderlyingSupply - whitelistedSuppliersSupply;
require(nonWhitelistedTotalSupply + mintAmount < supplyCap, "!supply cap");
}
flywheelPreSupplierAction(cTokenAddress, minter);
return uint256(Error.NO_ERROR);
}
function redeemAllowed(address cToken, address redeemer, uint256 redeemTokens) external override returns (uint256) {
uint256 allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens);
if (allowed != uint256(Error.NO_ERROR)) {
return allowed;
}
flywheelPreSupplierAction(cToken, redeemer);
return uint256(Error.NO_ERROR);
}
function redeemAllowedInternal(
address cToken,
address redeemer,
uint256 redeemTokens
) internal view returns (uint256) {
if (!markets[cToken].isListed) {
return uint256(Error.MARKET_NOT_LISTED);
}
if (!markets[cToken].accountMembership[redeemer]) {
return uint256(Error.NO_ERROR);
}
(Error err, , , uint256 shortfall) = getHypotheticalAccountLiquidityInternal(
redeemer,
ICErc20(cToken),
redeemTokens,
0,
0
);
if (err != Error.NO_ERROR) {
return uint256(err);
}
if (shortfall > 0) {
return uint256(Error.INSUFFICIENT_LIQUIDITY);
}
return uint256(Error.NO_ERROR);
}
function mintVerify(address cToken, address minter, uint256 actualMintAmount, uint256 mintTokens) external {
suppliers[minter] = true;
}
function redeemVerify(
address cToken,
address redeemer,
uint256 redeemAmount,
uint256 redeemTokens
) external override {
require(markets[msg.sender].isListed, "!market");
if (redeemTokens == 0 && redeemAmount > 0) {
revert("!zero");
}
}
function getMaxRedeemOrBorrow(
address account,
ICErc20 cTokenModify,
bool isBorrow
) external view override returns (uint256) {
address cToken = address(cTokenModify);
uint256 balanceOfUnderlying = cTokenModify.balanceOfUnderlying(account);
(Error err, , uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal(
account,
isBorrow ? cTokenModify : ICErc20(address(0)),
0,
0,
0
);
require(err == Error.NO_ERROR, "!liquidity");
if (shortfall > 0) return 0;
uint256 maxBorrowOrRedeemAmount;
if (!isBorrow && !markets[cToken].accountMembership[account]) {
maxBorrowOrRedeemAmount = balanceOfUnderlying;
} else {
maxBorrowOrRedeemAmount = _getMaxRedeemOrBorrow(liquidity, cTokenModify, isBorrow);
if (!isBorrow && balanceOfUnderlying < maxBorrowOrRedeemAmount) maxBorrowOrRedeemAmount = balanceOfUnderlying;
}
uint256 cTokenLiquidity = cTokenModify.getCash();
return maxBorrowOrRedeemAmount <= cTokenLiquidity ? maxBorrowOrRedeemAmount : cTokenLiquidity;
}
function _getMaxRedeemOrBorrow(
uint256 liquidity,
ICErc20 cTokenModify,
bool isBorrow
) internal view returns (uint256) {
if (liquidity == 0) return 0;
uint256 conversionFactor = oracle.getUnderlyingPrice(cTokenModify);
require(conversionFactor > 0, "!oracle");
if (!isBorrow) {
uint256 collateralFactorMantissa = markets[address(cTokenModify)].collateralFactorMantissa;
conversionFactor = (collateralFactorMantissa * conversionFactor) / 1e18;
}
return (liquidity * 1e18) / conversionFactor;
}
function borrowAllowed(address cToken, address borrower, uint256 borrowAmount) external override returns (uint256) {
require(!borrowGuardianPaused[cToken], "!borrow:paused");
if (!markets[cToken].isListed) {
return uint256(Error.MARKET_NOT_LISTED);
}
if (!markets[cToken].accountMembership[borrower]) {
require(msg.sender == cToken, "!ctoken");
Error err = addToMarketInternal(ICErc20(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint256(err);
}
assert(markets[cToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(ICErc20(cToken)) == 0) {
return uint256(Error.PRICE_ERROR);
}
if (enforceWhitelist && !whitelist[borrower]) {
return uint256(Error.SUPPLIER_NOT_WHITELISTED);
}
uint256 borrowCap = effectiveBorrowCaps(cToken);
if (borrowCap != 0 && !borrowCapWhitelist[cToken].contains(borrower)) {
uint256 totalBorrows = ICErc20(cToken).totalBorrowsCurrent();
uint256 whitelistedBorrowersBorrows = asComptrollerExtension().getWhitelistedBorrowersBorrows(cToken);
uint256 nonWhitelistedTotalBorrows;
if (whitelistedBorrowersBorrows >= totalBorrows) nonWhitelistedTotalBorrows = 0;
else nonWhitelistedTotalBorrows = totalBorrows - whitelistedBorrowersBorrows;
require(nonWhitelistedTotalBorrows + borrowAmount < borrowCap, "!borrow:cap");
}
flywheelPreBorrowerAction(cToken, borrower);
(uint256 err, , , uint256 shortfall) = this.getHypotheticalAccountLiquidity(borrower, cToken, 0, borrowAmount, 0);
if (err != uint256(Error.NO_ERROR)) {
return err;
}
if (shortfall > 0) {
return uint256(Error.INSUFFICIENT_LIQUIDITY);
}
return uint256(Error.NO_ERROR);
}
function borrowWithinLimits(address cToken, uint256 accountBorrowsNew) external view override returns (uint256) {
uint256 minBorrowEth = IFeeDistributor(ionicAdmin).minBorrowEth();
if (minBorrowEth > 0) {
uint256 oraclePriceMantissa = oracle.getUnderlyingPrice(ICErc20(cToken));
if (oraclePriceMantissa == 0) return uint256(Error.PRICE_ERROR);
(MathError mathErr, uint256 borrowBalanceEth) = mulScalarTruncate(
Exp({ mantissa: oraclePriceMantissa }),
accountBorrowsNew
);
if (mathErr != MathError.NO_ERROR) return uint256(Error.MATH_ERROR);
if (borrowBalanceEth < minBorrowEth) return uint256(Error.BORROW_BELOW_MIN);
}
return uint256(Error.NO_ERROR);
}
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint256 repayAmount
) external override returns (uint256) {
if (!markets[cToken].isListed) {
return uint256(Error.MARKET_NOT_LISTED);
}
flywheelPreBorrowerAction(cToken, borrower);
return uint256(Error.NO_ERROR);
}
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount
) external override returns (uint256) {
if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) {
return uint256(Error.MARKET_NOT_LISTED);
}
uint256 borrowBalance = ICErc20(cTokenBorrowed).borrowBalanceCurrent(borrower);
if (isDeprecated(ICErc20(cTokenBorrowed))) {
require(borrowBalance >= repayAmount, "!borrow>repay");
} else {
(Error err, , , uint256 shortfall) = getHypotheticalAccountLiquidityInternal(
borrower,
ICErc20(address(0)),
0,
0,
0
);
if (err != Error.NO_ERROR) {
return uint256(err);
}
if (shortfall == 0) {
return uint256(Error.INSUFFICIENT_SHORTFALL);
}
uint256 maxClose = mul_ScalarTruncate(Exp({ mantissa: closeFactorMantissa }), borrowBalance);
if (repayAmount > maxClose) {
return uint256(Error.TOO_MUCH_REPAY);
}
}
return uint256(Error.NO_ERROR);
}
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external override returns (uint256) {
require(!seizeGuardianPaused, "!seize:paused");
if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) {
return uint256(Error.MARKET_NOT_LISTED);
}
if (ICErc20(cTokenCollateral).comptroller() != ICErc20(cTokenBorrowed).comptroller()) {
return uint256(Error.COMPTROLLER_MISMATCH);
}
flywheelPreTransferAction(cTokenCollateral, borrower, liquidator);
return uint256(Error.NO_ERROR);
}
function transferAllowed(
address cToken,
address src,
address dst,
uint256 transferTokens
) external override returns (uint256) {
require(!transferGuardianPaused, "!transfer:paused");
uint256 allowed = redeemAllowedInternal(cToken, src, transferTokens);
if (allowed != uint256(Error.NO_ERROR)) {
return allowed;
}
flywheelPreTransferAction(cToken, src, dst);
return uint256(Error.NO_ERROR);
}
function flywheelPreSupplierAction(address cToken, address supplier) internal {
for (uint256 i = 0; i < rewardsDistributors.length; i++)
IIonicFlywheel(rewardsDistributors[i]).flywheelPreSupplierAction(cToken, supplier);
}
function flywheelPreBorrowerAction(address cToken, address borrower) internal {
for (uint256 i = 0; i < rewardsDistributors.length; i++)
IIonicFlywheel(rewardsDistributors[i]).flywheelPreBorrowerAction(cToken, borrower);
}
function flywheelPreTransferAction(address cToken, address src, address dst) internal {
for (uint256 i = 0; i < rewardsDistributors.length; i++)
IIonicFlywheel(rewardsDistributors[i]).flywheelPreTransferAction(cToken, src, dst);
}
struct AccountLiquidityLocalVars {
ICErc20 asset;
uint256 sumCollateral;
uint256 sumBorrowPlusEffects;
uint256 cTokenBalance;
uint256 borrowBalance;
uint256 exchangeRateMantissa;
uint256 oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
uint256 borrowCapForCollateral;
uint256 borrowedAssetPrice;
uint256 assetAsCollateralValueCap;
}
function getAccountLiquidity(address account) public view override returns (uint256, uint256, uint256, uint256) {
(
Error err,
uint256 collateralValue,
uint256 liquidity,
uint256 shortfall
) = getHypotheticalAccountLiquidityInternal(account, ICErc20(address(0)), 0, 0, 0);
return (uint256(err), collateralValue, liquidity, shortfall);
}
function getHypotheticalAccountLiquidity(
address account,
address cTokenModify,
uint256 redeemTokens,
uint256 borrowAmount,
uint256 repayAmount
) public view returns (uint256, uint256, uint256, uint256) {
(
Error err,
uint256 collateralValue,
uint256 liquidity,
uint256 shortfall
) = getHypotheticalAccountLiquidityInternal(
account,
ICErc20(cTokenModify),
redeemTokens,
borrowAmount,
repayAmount
);
return (uint256(err), collateralValue, liquidity, shortfall);
}
function getHypotheticalAccountLiquidityInternal(
address account,
ICErc20 cTokenModify,
uint256 redeemTokens,
uint256 borrowAmount,
uint256 repayAmount
) internal view returns (Error, uint256, uint256, uint256) {
AccountLiquidityLocalVars memory vars;
if (address(cTokenModify) != address(0)) {
vars.borrowedAssetPrice = oracle.getUnderlyingPrice(cTokenModify);
}
for (uint256 i = 0; i < accountAssets[account].length; i++) {
vars.asset = accountAssets[account][i];
{
uint256 oErr;
(oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = vars.asset.getAccountSnapshot(
account
);
if (oErr != 0) {
return (Error.SNAPSHOT_ERROR, 0, 0, 0);
}
}
{
vars.collateralFactor = Exp({ mantissa: markets[address(vars.asset)].collateralFactorMantissa });
vars.exchangeRate = Exp({ mantissa: vars.exchangeRateMantissa });
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(vars.asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0, 0);
}
vars.oraclePrice = Exp({ mantissa: vars.oraclePriceMantissa });
vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice);
}
{
vars.assetAsCollateralValueCap = asComptrollerExtension().getAssetAsCollateralValueCap(
vars.asset,
cTokenModify,
redeemTokens > 0,
account
);
uint256 assetCollateralValue = mul_ScalarTruncate(vars.tokensToDenom, vars.cTokenBalance);
if (assetCollateralValue > vars.assetAsCollateralValueCap)
assetCollateralValue = vars.assetAsCollateralValueCap;
vars.sumCollateral += assetCollateralValue;
}
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(
vars.oraclePrice,
vars.borrowBalance,
vars.sumBorrowPlusEffects
);
if (vars.asset == cTokenModify) {
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(
vars.tokensToDenom,
redeemTokens,
vars.sumBorrowPlusEffects
);
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(
vars.oraclePrice,
borrowAmount,
vars.sumBorrowPlusEffects
);
uint256 repayEffect = mul_ScalarTruncate(vars.oraclePrice, repayAmount);
if (repayEffect >= vars.sumBorrowPlusEffects) {
vars.sumBorrowPlusEffects = 0;
} else {
vars.sumBorrowPlusEffects -= repayEffect;
}
}
}
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, vars.sumCollateral, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint256 actualRepayAmount
) external view override returns (uint256, uint256) {
uint256 priceBorrowedMantissa = oracle.getUnderlyingPrice(ICErc20(cTokenBorrowed));
uint256 priceCollateralMantissa = oracle.getUnderlyingPrice(ICErc20(cTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint256(Error.PRICE_ERROR), 0);
}
ICErc20 collateralCToken = ICErc20(cTokenCollateral);
uint256 exchangeRateMantissa = collateralCToken.exchangeRateCurrent();
uint256 seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
uint256 protocolSeizeShareMantissa = collateralCToken.protocolSeizeShareMantissa();
uint256 feeSeizeShareMantissa = collateralCToken.feeSeizeShareMantissa();
Exp memory totalPenaltyMantissa = add_(
add_(Exp({ mantissa: liquidationIncentiveMantissa }), Exp({ mantissa: protocolSeizeShareMantissa })),
Exp({ mantissa: feeSeizeShareMantissa })
);
numerator = mul_(totalPenaltyMantissa, Exp({ mantissa: priceBorrowedMantissa }));
denominator = mul_(Exp({ mantissa: priceCollateralMantissa }), Exp({ mantissa: exchangeRateMantissa }));
ratio = div_(numerator, denominator);
seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount);
return (uint256(Error.NO_ERROR), seizeTokens);
}
function _addRewardsDistributor(address distributor) external returns (uint256) {
require(hasAdminRights(), "!admin");
require(IIonicFlywheel(distributor).isRewardsDistributor(), "!isRewardsDistributor");
for (uint256 i = 0; i < rewardsDistributors.length; i++) require(distributor != rewardsDistributors[i], "!added");
rewardsDistributors.push(distributor);
emit AddedRewardsDistributor(distributor);
return uint256(Error.NO_ERROR);
}
function _setWhitelistEnforcement(bool enforce) external returns (uint256) {
if (!hasAdminRights()) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_WHITELIST_ENFORCEMENT_OWNER_CHECK);
}
if (enforceWhitelist == enforce) {
return uint256(Error.NO_ERROR);
}
enforceWhitelist = enforce;
emit WhitelistEnforcementChanged(enforce);
return uint256(Error.NO_ERROR);
}
function _setWhitelistStatuses(address[] calldata suppliers, bool[] calldata statuses) external returns (uint256) {
if (!hasAdminRights()) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_WHITELIST_STATUS_OWNER_CHECK);
}
for (uint256 i = 0; i < suppliers.length; i++) {
address supplier = suppliers[i];
if (statuses[i]) {
if (!whitelist[supplier]) {
whitelist[supplier] = true;
whitelistArray.push(supplier);
whitelistIndexes[supplier] = whitelistArray.length - 1;
}
} else {
if (whitelist[supplier]) {
whitelistArray[whitelistIndexes[supplier]] = whitelistArray[whitelistArray.length - 1];
whitelistArray.pop();
whitelistIndexes[whitelistArray[whitelistIndexes[supplier]]] = whitelistIndexes[supplier];
whitelistIndexes[supplier] = 0;
whitelist[supplier] = false;
}
}
}
return uint256(Error.NO_ERROR);
}
function _setPriceOracle(BasePriceOracle newOracle) public returns (uint256) {
if (!hasAdminRights()) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
BasePriceOracle oldOracle = oracle;
oracle = newOracle;
emit NewPriceOracle(oldOracle, newOracle);
return uint256(Error.NO_ERROR);
}
function _setCloseFactor(uint256 newCloseFactorMantissa) external returns (uint256) {
if (!hasAdminRights()) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK);
}
Exp memory newCloseFactorExp = Exp({ mantissa: newCloseFactorMantissa });
Exp memory lowLimit = Exp({ mantissa: closeFactorMinMantissa });
if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
Exp memory highLimit = Exp({ mantissa: closeFactorMaxMantissa });
if (lessThanExp(highLimit, newCloseFactorExp)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
uint256 oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint256(Error.NO_ERROR);
}
function _setCollateralFactor(ICErc20 cToken, uint256 newCollateralFactorMantissa) public returns (uint256) {
if (!hasAdminRights()) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
Market storage market = markets[address(cToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({ mantissa: newCollateralFactorMantissa });
Exp memory highLimit = Exp({ mantissa: collateralFactorMaxMantissa });
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
uint256 oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint256(Error.NO_ERROR);
}
function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external returns (uint256) {
if (!hasAdminRights()) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
Exp memory newLiquidationIncentive = Exp({ mantissa: newLiquidationIncentiveMantissa });
Exp memory minLiquidationIncentive = Exp({ mantissa: liquidationIncentiveMinMantissa });
if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
Exp memory maxLiquidationIncentive = Exp({ mantissa: liquidationIncentiveMaxMantissa });
if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
uint256 oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint256(Error.NO_ERROR);
}
function _supportMarket(ICErc20 cToken) internal returns (uint256) {
if (!hasAdminRights()) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(cToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
require(address(cToken.comptroller()) == address(this), "!comptroller");
address underlying = ICErc20(address(cToken)).underlying();
if (address(cTokensByUnderlying[underlying]) != address(0)) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
Market storage market = markets[address(cToken)];
market.isListed = true;
market.collateralFactorMantissa = 0;
allMarkets.push(cToken);
cTokensByUnderlying[underlying] = cToken;
emit MarketListed(cToken);
return uint256(Error.NO_ERROR);
}
function _deployMarket(
uint8 delegateType,
bytes calldata constructorData,
bytes calldata becomeImplData,
uint256 collateralFactorMantissa
) external returns (uint256) {
if (!hasAdminRights()) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
bool oldIonicAdminHasRights = ionicAdminHasRights;
ionicAdminHasRights = true;
ICErc20 cToken = ICErc20(IFeeDistributor(ionicAdmin).deployCErc20(delegateType, constructorData, becomeImplData));
ionicAdminHasRights = oldIonicAdminHasRights;
uint256 err = _supportMarket(cToken);
IFeeDistributor(ionicAdmin).authoritiesRegistry().reconfigureAuthority(address(this));
return err == uint256(Error.NO_ERROR) ? _setCollateralFactor(cToken, collateralFactorMantissa) : err;
}
function _becomeImplementation() external {
require(msg.sender == address(this), "!self call");
if (!_notEnteredInitialized) {
_notEntered = true;
_notEnteredInitialized = true;
}
}
function isDeprecated(ICErc20 cToken) public view returns (bool) {
return
markets[address(cToken)].collateralFactorMantissa == 0 &&
borrowGuardianPaused[address(cToken)] == true &&
add_(add_(cToken.reserveFactorMantissa(), cToken.adminFeeMantissa()), cToken.ionicFeeMantissa()) == 1e18;
}
function asComptrollerExtension() internal view returns (ComptrollerExtensionInterface) {
return ComptrollerExtensionInterface(address(this));
}
function _getExtensionFunctions() external pure virtual override returns (bytes4[] memory functionSelectors) {
uint8 fnsCount = 32;
functionSelectors = new bytes4[](fnsCount);
functionSelectors[--fnsCount] = this.isDeprecated.selector;
functionSelectors[--fnsCount] = this._deployMarket.selector;
functionSelectors[--fnsCount] = this.getAssetsIn.selector;
functionSelectors[--fnsCount] = this.checkMembership.selector;
functionSelectors[--fnsCount] = this._setPriceOracle.selector;
functionSelectors[--fnsCount] = this._setCloseFactor.selector;
functionSelectors[--fnsCount] = this._setCollateralFactor.selector;
functionSelectors[--fnsCount] = this._setLiquidationIncentive.selector;
functionSelectors[--fnsCount] = this._setWhitelistEnforcement.selector;
functionSelectors[--fnsCount] = this._setWhitelistStatuses.selector;
functionSelectors[--fnsCount] = this._addRewardsDistributor.selector;
functionSelectors[--fnsCount] = this.getHypotheticalAccountLiquidity.selector;
functionSelectors[--fnsCount] = this.getMaxRedeemOrBorrow.selector;
functionSelectors[--fnsCount] = this.enterMarkets.selector;
functionSelectors[--fnsCount] = this.exitMarket.selector;
functionSelectors[--fnsCount] = this.mintAllowed.selector;
functionSelectors[--fnsCount] = this.redeemAllowed.selector;
functionSelectors[--fnsCount] = this.redeemVerify.selector;
functionSelectors[--fnsCount] = this.borrowAllowed.selector;
functionSelectors[--fnsCount] = this.borrowWithinLimits.selector;
functionSelectors[--fnsCount] = this.repayBorrowAllowed.selector;
functionSelectors[--fnsCount] = this.liquidateBorrowAllowed.selector;
functionSelectors[--fnsCount] = this.seizeAllowed.selector;
functionSelectors[--fnsCount] = this.transferAllowed.selector;
functionSelectors[--fnsCount] = this.mintVerify.selector;
functionSelectors[--fnsCount] = this.getAccountLiquidity.selector;
functionSelectors[--fnsCount] = this.liquidateCalculateSeizeTokens.selector;
functionSelectors[--fnsCount] = this._beforeNonReentrant.selector;
functionSelectors[--fnsCount] = this._afterNonReentrant.selector;
functionSelectors[--fnsCount] = this._becomeImplementation.selector;
functionSelectors[--fnsCount] = this.effectiveSupplyCaps.selector;
functionSelectors[--fnsCount] = this.effectiveBorrowCaps.selector;
require(fnsCount == 0, "use the correct array length");
}
function _beforeNonReentrant() external override {
require(markets[msg.sender].isListed, "!Comptroller:_beforeNonReentrant");
require(_notEntered, "!reentered");
_notEntered = false;
}
function _afterNonReentrant() external override {
require(markets[msg.sender].isListed, "!Comptroller:_afterNonReentrant");
_notEntered = true;
}
}
文件 10 的 45:ComptrollerInterface.sol
pragma solidity >=0.8.0;
import { BasePriceOracle } from "../oracles/BasePriceOracle.sol";
import { ICErc20 } from "./CTokenInterfaces.sol";
import { DiamondExtension } from "../ionic/DiamondExtension.sol";
import { ComptrollerV4Storage } from "../compound/ComptrollerStorage.sol";
import { PrudentiaLib } from "../adrastia/PrudentiaLib.sol";
import { IHistoricalRates } from "adrastia-periphery/rates/IHistoricalRates.sol";
interface ComptrollerInterface {
function isDeprecated(ICErc20 cToken) external view returns (bool);
function _becomeImplementation() external;
function _deployMarket(
uint8 delegateType,
bytes memory constructorData,
bytes calldata becomeImplData,
uint256 collateralFactorMantissa
) external returns (uint256);
function getAssetsIn(address account) external view returns (ICErc20[] memory);
function checkMembership(address account, ICErc20 cToken) external view returns (bool);
function _setPriceOracle(BasePriceOracle newOracle) external returns (uint256);
function _setCloseFactor(uint256 newCloseFactorMantissa) external returns (uint256);
function _setCollateralFactor(ICErc20 market, uint256 newCollateralFactorMantissa) external returns (uint256);
function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external returns (uint256);
function _setWhitelistEnforcement(bool enforce) external returns (uint256);
function _setWhitelistStatuses(address[] calldata _suppliers, bool[] calldata statuses) external returns (uint256);
function _addRewardsDistributor(address distributor) external returns (uint256);
function getHypotheticalAccountLiquidity(
address account,
address cTokenModify,
uint256 redeemTokens,
uint256 borrowAmount,
uint256 repayAmount
) external view returns (uint256, uint256, uint256, uint256);
function getMaxRedeemOrBorrow(address account, ICErc20 cToken, bool isBorrow) external view returns (uint256);
function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory);
function exitMarket(address cToken) external returns (uint256);
function mintAllowed(address cToken, address minter, uint256 mintAmount) external returns (uint256);
function redeemAllowed(address cToken, address redeemer, uint256 redeemTokens) external returns (uint256);
function redeemVerify(address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens) external;
function borrowAllowed(address cToken, address borrower, uint256 borrowAmount) external returns (uint256);
function borrowWithinLimits(address cToken, uint256 accountBorrowsNew) external view returns (uint256);
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint256 repayAmount
) external returns (uint256);
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount
) external returns (uint256);
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256);
function transferAllowed(address cToken, address src, address dst, uint256 transferTokens) external returns (uint256);
function mintVerify(address cToken, address minter, uint256 actualMintAmount, uint256 mintTokens) external;
function getAccountLiquidity(
address account
) external view returns (uint256 error, uint256 collateralValue, uint256 liquidity, uint256 shortfall);
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint256 repayAmount
) external view returns (uint256, uint256);
function _beforeNonReentrant() external;
function _afterNonReentrant() external;
function effectiveSupplyCaps(address cToken) external view returns (uint256 supplyCap);
function effectiveBorrowCaps(address cToken) external view returns (uint256 borrowCap);
}
interface ComptrollerStorageInterface {
function admin() external view returns (address);
function adminHasRights() external view returns (bool);
function ionicAdmin() external view returns (address);
function ionicAdminHasRights() external view returns (bool);
function pendingAdmin() external view returns (address);
function oracle() external view returns (BasePriceOracle);
function pauseGuardian() external view returns (address);
function closeFactorMantissa() external view returns (uint256);
function liquidationIncentiveMantissa() external view returns (uint256);
function isUserOfPool(address user) external view returns (bool);
function whitelist(address account) external view returns (bool);
function enforceWhitelist() external view returns (bool);
function borrowCapForCollateral(address borrowed, address collateral) external view returns (uint256);
function borrowingAgainstCollateralBlacklist(address borrowed, address collateral) external view returns (bool);
function suppliers(address account) external view returns (bool);
function cTokensByUnderlying(address) external view returns (address);
function supplyCaps(address cToken) external view returns (uint256);
function borrowCaps(address cToken) external view returns (uint256);
function markets(address cToken) external view returns (bool, uint256);
function accountAssets(address, uint256) external view returns (address);
function borrowGuardianPaused(address cToken) external view returns (bool);
function mintGuardianPaused(address cToken) external view returns (bool);
function rewardsDistributors(uint256) external view returns (address);
}
interface SFSRegister {
function register(address _recipient) external returns (uint256 tokenId);
}
interface ComptrollerExtensionInterface {
function getWhitelistedSuppliersSupply(address cToken) external view returns (uint256 supplied);
function getWhitelistedBorrowersBorrows(address cToken) external view returns (uint256 borrowed);
function getAllMarkets() external view returns (ICErc20[] memory);
function getAllBorrowers() external view returns (address[] memory);
function getAllBorrowersCount() external view returns (uint256);
function getPaginatedBorrowers(
uint256 page,
uint256 pageSize
) external view returns (uint256 _totalPages, address[] memory _pageOfBorrowers);
function getRewardsDistributors() external view returns (address[] memory);
function getAccruingFlywheels() external view returns (address[] memory);
function _supplyCapWhitelist(address cToken, address account, bool whitelisted) external;
function _setBorrowCapForCollateral(address cTokenBorrow, address cTokenCollateral, uint256 borrowCap) external;
function _setBorrowCapForCollateralWhitelist(
address cTokenBorrow,
address cTokenCollateral,
address account,
bool whitelisted
) external;
function isBorrowCapForCollateralWhitelisted(
address cTokenBorrow,
address cTokenCollateral,
address account
) external view returns (bool);
function _blacklistBorrowingAgainstCollateral(
address cTokenBorrow,
address cTokenCollateral,
bool blacklisted
) external;
function _blacklistBorrowingAgainstCollateralWhitelist(
address cTokenBorrow,
address cTokenCollateral,
address account,
bool whitelisted
) external;
function isBlacklistBorrowingAgainstCollateralWhitelisted(
address cTokenBorrow,
address cTokenCollateral,
address account
) external view returns (bool);
function isSupplyCapWhitelisted(address cToken, address account) external view returns (bool);
function _borrowCapWhitelist(address cToken, address account, bool whitelisted) external;
function isBorrowCapWhitelisted(address cToken, address account) external view returns (bool);
function _removeFlywheel(address flywheelAddress) external returns (bool);
function getWhitelist() external view returns (address[] memory);
function addNonAccruingFlywheel(address flywheelAddress) external returns (bool);
function _setMarketSupplyCaps(ICErc20[] calldata cTokens, uint256[] calldata newSupplyCaps) external;
function _setMarketBorrowCaps(ICErc20[] calldata cTokens, uint256[] calldata newBorrowCaps) external;
function _setBorrowCapGuardian(address newBorrowCapGuardian) external;
function _setPauseGuardian(address newPauseGuardian) external returns (uint256);
function _setMintPaused(ICErc20 cToken, bool state) external returns (bool);
function _setBorrowPaused(ICErc20 cToken, bool state) external returns (bool);
function _setTransferPaused(bool state) external returns (bool);
function _setSeizePaused(bool state) external returns (bool);
function _unsupportMarket(ICErc20 cToken) external returns (uint256);
function getAssetAsCollateralValueCap(
ICErc20 collateral,
ICErc20 cTokenModify,
bool redeeming,
address account
) external view returns (uint256);
function registerInSFS() external returns (uint256);
}
interface ComptrollerPrudentiaCapsExtInterface {
function getBorrowCapConfig() external view returns (PrudentiaLib.PrudentiaConfig memory);
function getSupplyCapConfig() external view returns (PrudentiaLib.PrudentiaConfig memory);
function _setSupplyCapConfig(PrudentiaLib.PrudentiaConfig calldata newConfig) external;
function _setBorrowCapConfig(PrudentiaLib.PrudentiaConfig calldata newConfig) external;
}
interface UnitrollerInterface {
function comptrollerImplementation() external view returns (address);
function _upgrade() external;
function _acceptAdmin() external returns (uint256);
function _setPendingAdmin(address newPendingAdmin) external returns (uint256);
function _toggleAdminRights(bool hasRights) external returns (uint256);
}
interface IComptrollerExtension is ComptrollerExtensionInterface, ComptrollerStorageInterface {}
interface IonicComptroller is
ComptrollerInterface,
ComptrollerExtensionInterface,
UnitrollerInterface,
ComptrollerStorageInterface
{
}
abstract contract ComptrollerBase is ComptrollerV4Storage {
bool public constant isComptroller = true;
function effectiveSupplyCaps(address cToken) public view virtual returns (uint256 supplyCap) {
PrudentiaLib.PrudentiaConfig memory capConfig = supplyCapConfig;
if (capConfig.controller != address(0)) {
address underlyingToken = ICErc20(cToken).underlying();
supplyCap = IHistoricalRates(capConfig.controller).getRateAt(underlyingToken, capConfig.offset).current;
int256 scaleByDecimals = 18;
(bool success, bytes memory data) = underlyingToken.staticcall(abi.encodeWithSignature("decimals()"));
if (success && data.length == 32) {
scaleByDecimals = int256(uint256(abi.decode(data, (uint8))));
}
scaleByDecimals += capConfig.decimalShift;
if (scaleByDecimals >= 0) {
supplyCap *= 10 ** uint256(scaleByDecimals);
} else {
supplyCap /= 10 ** uint256(-scaleByDecimals);
}
} else {
supplyCap = supplyCaps[cToken];
}
}
function effectiveBorrowCaps(address cToken) public view virtual returns (uint256 borrowCap) {
PrudentiaLib.PrudentiaConfig memory capConfig = borrowCapConfig;
if (capConfig.controller != address(0)) {
address underlyingToken = ICErc20(cToken).underlying();
borrowCap = IHistoricalRates(capConfig.controller).getRateAt(underlyingToken, capConfig.offset).current;
int256 scaleByDecimals = 18;
(bool success, bytes memory data) = underlyingToken.staticcall(abi.encodeWithSignature("decimals()"));
if (success && data.length == 32) {
scaleByDecimals = int256(uint256(abi.decode(data, (uint8))));
}
scaleByDecimals += capConfig.decimalShift;
if (scaleByDecimals >= 0) {
borrowCap *= 10 ** uint256(scaleByDecimals);
} else {
borrowCap /= 10 ** uint256(-scaleByDecimals);
}
} else {
borrowCap = borrowCaps[cToken];
}
}
}
文件 11 的 45:ComptrollerStorage.sol
pragma solidity >=0.8.0;
import "./IFeeDistributor.sol";
import "../oracles/BasePriceOracle.sol";
import { ICErc20 } from "./CTokenInterfaces.sol";
import { PrudentiaLib } from "../adrastia/PrudentiaLib.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
contract UnitrollerAdminStorage {
address payable public ionicAdmin;
address public admin;
address public pendingAdmin;
bool public ionicAdminHasRights = true;
bool public adminHasRights = true;
function hasAdminRights() internal view returns (bool) {
return (msg.sender == admin && adminHasRights) || (msg.sender == address(ionicAdmin) && ionicAdminHasRights);
}
}
contract ComptrollerV1Storage is UnitrollerAdminStorage {
BasePriceOracle public oracle;
uint256 public closeFactorMantissa;
uint256 public liquidationIncentiveMantissa;
uint256 internal maxAssets;
mapping(address => ICErc20[]) public accountAssets;
}
contract ComptrollerV2Storage is ComptrollerV1Storage {
struct Market {
bool isListed;
uint256 collateralFactorMantissa;
mapping(address => bool) accountMembership;
}
mapping(address => Market) public markets;
ICErc20[] public allMarkets;
mapping(address => bool) internal borrowers;
address[] public allBorrowers;
mapping(address => uint256) internal borrowerIndexes;
mapping(address => bool) public suppliers;
mapping(address => ICErc20) public cTokensByUnderlying;
bool public enforceWhitelist;
mapping(address => bool) public whitelist;
address[] public whitelistArray;
mapping(address => uint256) internal whitelistIndexes;
address public pauseGuardian;
bool public _mintGuardianPaused;
bool public _borrowGuardianPaused;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public mintGuardianPaused;
mapping(address => bool) public borrowGuardianPaused;
}
contract ComptrollerV3Storage is ComptrollerV2Storage {
address public borrowCapGuardian;
mapping(address => uint256) public borrowCaps;
mapping(address => uint256) public supplyCaps;
address[] public rewardsDistributors;
bool internal _notEntered;
bool internal _notEnteredInitialized;
address[] public nonAccruingRewardsDistributors;
mapping(address => mapping(address => uint256)) public borrowCapForCollateral;
mapping(address => mapping(address => bool)) public borrowingAgainstCollateralBlacklist;
mapping(address => mapping(address => EnumerableSet.AddressSet)) internal borrowCapForCollateralWhitelist;
mapping(address => mapping(address => EnumerableSet.AddressSet))
internal borrowingAgainstCollateralBlacklistWhitelist;
mapping(address => EnumerableSet.AddressSet) internal supplyCapWhitelist;
mapping(address => EnumerableSet.AddressSet) internal borrowCapWhitelist;
}
contract ComptrollerV4Storage is ComptrollerV3Storage {
PrudentiaLib.PrudentiaConfig internal borrowCapConfig;
PrudentiaLib.PrudentiaConfig internal supplyCapConfig;
}
文件 12 的 45:ContextUpgradeable.sol
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
文件 13 的 45:Create2Upgradeable.sol
pragma solidity ^0.8.0;
library Create2Upgradeable {
function deploy(
uint256 amount,
bytes32 salt,
bytes memory bytecode
) internal returns (address addr) {
require(address(this).balance >= amount, "Create2: insufficient balance");
require(bytecode.length != 0, "Create2: bytecode length is zero");
assembly {
addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
}
require(addr != address(0), "Create2: Failed on deploy");
}
function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
return computeAddress(salt, bytecodeHash, address(this));
}
function computeAddress(
bytes32 salt,
bytes32 bytecodeHash,
address deployer
) internal pure returns (address addr) {
assembly {
let ptr := mload(0x40)
mstore(add(ptr, 0x40), bytecodeHash)
mstore(add(ptr, 0x20), salt)
mstore(ptr, deployer)
let start := add(ptr, 0x0b)
mstore8(start, 0xff)
addr := keccak256(start, 85)
}
}
}
文件 14 的 45:DiamondExtension.sol
pragma solidity >=0.8.0;
abstract contract DiamondExtension {
function _getExtensionFunctions() external pure virtual returns (bytes4[] memory);
}
error FunctionNotFound(bytes4 _functionSelector);
error ExtensionNotFound(bytes4 _functionSelector);
error FunctionAlreadyAdded(bytes4 _functionSelector, address _currentImpl);
abstract contract DiamondBase {
function _registerExtension(DiamondExtension extensionToAdd, DiamondExtension extensionToReplace) external virtual;
function _listExtensions() public view returns (address[] memory) {
return LibDiamond.listExtensions();
}
fallback() external {
address extension = LibDiamond.getExtensionForFunction(msg.sig);
if (extension == address(0)) revert FunctionNotFound(msg.sig);
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), extension, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
}
library LibDiamond {
bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.extensions.diamond.storage");
struct Function {
address extension;
bytes4 selector;
}
struct LogicStorage {
Function[] functions;
address[] extensions;
}
function getExtensionForFunction(bytes4 msgSig) internal view returns (address) {
return getExtensionForSelector(msgSig, diamondStorage());
}
function diamondStorage() internal pure returns (LogicStorage storage ds) {
bytes32 position = DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
}
function listExtensions() internal view returns (address[] memory) {
return diamondStorage().extensions;
}
function registerExtension(DiamondExtension extensionToAdd, DiamondExtension extensionToReplace) internal {
if (address(extensionToReplace) != address(0)) {
removeExtension(extensionToReplace);
}
addExtension(extensionToAdd);
}
function removeExtension(DiamondExtension extension) internal {
LogicStorage storage ds = diamondStorage();
removeExtensionFunctions(extension);
for (uint8 i = 0; i < ds.extensions.length; i++) {
if (ds.extensions[i] == address(extension)) {
ds.extensions[i] = ds.extensions[ds.extensions.length - 1];
ds.extensions.pop();
}
}
}
function addExtension(DiamondExtension extension) internal {
LogicStorage storage ds = diamondStorage();
for (uint8 i = 0; i < ds.extensions.length; i++) {
require(ds.extensions[i] != address(extension), "extension already added");
}
addExtensionFunctions(extension);
ds.extensions.push(address(extension));
}
function removeExtensionFunctions(DiamondExtension extension) internal {
bytes4[] memory fnsToRemove = extension._getExtensionFunctions();
LogicStorage storage ds = diamondStorage();
for (uint16 i = 0; i < fnsToRemove.length; i++) {
bytes4 selectorToRemove = fnsToRemove[i];
assert(address(extension) == getExtensionForSelector(selectorToRemove, ds));
uint16 indexToKeep = getIndexForSelector(selectorToRemove, ds);
ds.functions[indexToKeep] = ds.functions[ds.functions.length - 1];
ds.functions.pop();
}
}
function addExtensionFunctions(DiamondExtension extension) internal {
bytes4[] memory fnsToAdd = extension._getExtensionFunctions();
LogicStorage storage ds = diamondStorage();
uint16 functionsCount = uint16(ds.functions.length);
for (uint256 functionsIndex = 0; functionsIndex < fnsToAdd.length; functionsIndex++) {
bytes4 selector = fnsToAdd[functionsIndex];
address oldImplementation = getExtensionForSelector(selector, ds);
if (oldImplementation != address(0)) revert FunctionAlreadyAdded(selector, oldImplementation);
ds.functions.push(Function(address(extension), selector));
functionsCount++;
}
}
function getExtensionForSelector(bytes4 selector, LogicStorage storage ds) internal view returns (address) {
uint256 fnsLen = ds.functions.length;
for (uint256 i = 0; i < fnsLen; i++) {
if (ds.functions[i].selector == selector) return ds.functions[i].extension;
}
return address(0);
}
function getIndexForSelector(bytes4 selector, LogicStorage storage ds) internal view returns (uint16) {
uint16 fnsLen = uint16(ds.functions.length);
for (uint16 i = 0; i < fnsLen; i++) {
if (ds.functions[i].selector == selector) return i;
}
return type(uint16).max;
}
}
文件 15 的 45:ERC1967Proxy.sol
pragma solidity ^0.8.0;
import "../Proxy.sol";
import "./ERC1967Upgrade.sol";
contract ERC1967Proxy is Proxy, ERC1967Upgrade {
constructor(address _logic, bytes memory _data) payable {
_upgradeToAndCall(_logic, _data, false);
}
function _implementation() internal view virtual override returns (address impl) {
return ERC1967Upgrade._getImplementation();
}
}
文件 16 的 45:ERC1967Upgrade.sol
pragma solidity ^0.8.2;
import "../beacon/IBeacon.sol";
import "../../interfaces/draft-IERC1822.sol";
import "../../utils/Address.sol";
import "../../utils/StorageSlot.sol";
abstract contract ERC1967Upgrade {
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
event Upgraded(address indexed implementation);
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
function _upgradeToAndCallUUPS(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
event AdminChanged(address previousAdmin, address newAdmin);
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
event BeaconUpgraded(address indexed beacon);
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
function _setBeacon(address newBeacon) private {
require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
文件 17 的 45:ERC20.sol
pragma solidity >=0.8.0;
abstract contract ERC20 {
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
string public name;
string public symbol;
uint8 public immutable decimals;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
uint256 internal immutable INITIAL_CHAIN_ID;
bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
function approve(address spender, uint256 amount) public virtual returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) public virtual returns (bool) {
balanceOf[msg.sender] -= amount;
unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool) {
uint256 allowed = allowance[from][msg.sender];
if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
return true;
}
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
unchecked {
address recoveredAddress = ecrecover(
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
),
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
),
v,
r,
s
);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
function computeDomainSeparator() internal view virtual returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
function _mint(address to, uint256 amount) internal virtual {
totalSupply += amount;
unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal virtual {
balanceOf[from] -= amount;
unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
}
文件 18 的 45:EnumerableSet.sol
pragma solidity ^0.8.0;
library EnumerableSet {
struct Set {
bytes32[] _values;
mapping(bytes32 => uint256) _indexes;
}
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _remove(Set storage set, bytes32 value) private returns (bool) {
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set._values[lastIndex];
set._values[toDeleteIndex] = lastValue;
set._indexes[lastValue] = valueIndex;
}
set._values.pop();
delete set._indexes[value];
return true;
} else {
return false;
}
}
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
struct Bytes32Set {
Set _inner;
}
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
assembly {
result := store
}
return result;
}
struct AddressSet {
Set _inner;
}
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
struct UintSet {
Set _inner;
}
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
文件 19 的 45:ErrorReporter.sol
pragma solidity >=0.8.0;
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
COMPTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY,
SUPPLIER_NOT_WHITELISTED,
BORROW_BELOW_MIN,
SUPPLY_ABOVE_MAX,
NONZERO_TOTAL_SUPPLY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
ADD_REWARDS_DISTRIBUTOR_OWNER_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
TOGGLE_ADMIN_RIGHTS_OWNER_CHECK,
TOGGLE_AUTO_IMPLEMENTATIONS_ENABLED_OWNER_CHECK,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_CONTRACT_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SET_WHITELIST_ENFORCEMENT_OWNER_CHECK,
SET_WHITELIST_STATUS_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK,
UNSUPPORT_MARKET_OWNER_CHECK,
UNSUPPORT_MARKET_DOES_NOT_EXIST,
UNSUPPORT_MARKET_IN_USE
}
event Failure(uint256 error, uint256 info, uint256 detail);
function fail(Error err, FailureInfo info) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), 0);
return uint256(err);
}
function failOpaque(
Error err,
FailureInfo info,
uint256 opaqueError
) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), opaqueError);
return uint256(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
COMPTROLLER_REJECTION,
COMPTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED,
UTILIZATION_ABOVE_MAX
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_IONIC_FEES_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_ADMIN_FEES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_COMPTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_COMPTROLLER_REJECTION,
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
NEW_UTILIZATION_RATE_ABOVE_MAX,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
WITHDRAW_IONIC_FEES_ACCRUE_INTEREST_FAILED,
WITHDRAW_IONIC_FEES_CASH_NOT_AVAILABLE,
WITHDRAW_IONIC_FEES_FRESH_CHECK,
WITHDRAW_IONIC_FEES_VALIDATION,
WITHDRAW_ADMIN_FEES_ACCRUE_INTEREST_FAILED,
WITHDRAW_ADMIN_FEES_CASH_NOT_AVAILABLE,
WITHDRAW_ADMIN_FEES_FRESH_CHECK,
WITHDRAW_ADMIN_FEES_VALIDATION,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COMPTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
TOGGLE_ADMIN_RIGHTS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_ADMIN_FEE_ACCRUE_INTEREST_FAILED,
SET_ADMIN_FEE_ADMIN_CHECK,
SET_ADMIN_FEE_FRESH_CHECK,
SET_ADMIN_FEE_BOUNDS_CHECK,
SET_IONIC_FEE_ACCRUE_INTEREST_FAILED,
SET_IONIC_FEE_FRESH_CHECK,
SET_IONIC_FEE_BOUNDS_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_COMPTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
event Failure(uint256 error, uint256 info, uint256 detail);
function fail(Error err, FailureInfo info) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), 0);
return uint256(err);
}
function failOpaque(
Error err,
FailureInfo info,
uint256 opaqueError
) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), opaqueError);
return err == Error.COMPTROLLER_REJECTION ? 1000 + opaqueError : uint256(err);
}
}
文件 20 的 45:Exponential.sol
pragma solidity >=0.8.0;
import "./CarefulMath.sol";
import "./ExponentialNoError.sol";
contract Exponential is CarefulMath, ExponentialNoError {
function getExp(uint256 num, uint256 denom) internal pure returns (MathError, Exp memory) {
(MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({ mantissa: 0 }));
}
(MathError err1, uint256 rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({ mantissa: 0 }));
}
return (MathError.NO_ERROR, Exp({ mantissa: rational }));
}
function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {
(MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({ mantissa: result }));
}
function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {
(MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({ mantissa: result }));
}
function mulScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) {
(MathError err0, uint256 scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({ mantissa: 0 }));
}
return (MathError.NO_ERROR, Exp({ mantissa: scaledMantissa }));
}
function mulScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (MathError, uint256) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
function divScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) {
(MathError err0, uint256 descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({ mantissa: 0 }));
}
return (MathError.NO_ERROR, Exp({ mantissa: descaledMantissa }));
}
function divScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) {
(MathError err0, uint256 numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({ mantissa: 0 }));
}
return getExp(numerator, divisor.mantissa);
}
function divScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {
(MathError err0, uint256 doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({ mantissa: 0 }));
}
(MathError err1, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({ mantissa: 0 }));
}
(MathError err2, uint256 product) = divUInt(doubleScaledProductWithHalfScale, expScale);
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({ mantissa: product }));
}
function mulExp(uint256 a, uint256 b) internal pure returns (MathError, Exp memory) {
return mulExp(Exp({ mantissa: a }), Exp({ mantissa: b }));
}
function mulExp3(
Exp memory a,
Exp memory b,
Exp memory c
) internal pure returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
}
文件 21 的 45:ExponentialNoError.sol
pragma solidity >=0.8.0;
contract ExponentialNoError {
uint256 constant expScale = 1e18;
uint256 constant doubleScale = 1e36;
uint256 constant halfExpScale = expScale / 2;
uint256 constant mantissaOne = expScale;
struct Exp {
uint256 mantissa;
}
struct Double {
uint256 mantissa;
}
function truncate(Exp memory exp) internal pure returns (uint256) {
return exp.mantissa / expScale;
}
function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
function mul_ScalarTruncateAddUInt(
Exp memory a,
uint256 scalar,
uint256 addend
) internal pure returns (uint256) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) {
return left.mantissa < right.mantissa;
}
function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) {
return left.mantissa <= right.mantissa;
}
function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) {
return left.mantissa > right.mantissa;
}
function isZeroExp(Exp memory value) internal pure returns (bool) {
return value.mantissa == 0;
}
function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({ mantissa: add_(a.mantissa, b.mantissa) });
}
function add_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({ mantissa: add_(a.mantissa, b.mantissa) });
}
function add_(uint256 a, uint256 b) internal pure returns (uint256) {
return add_(a, b, "addition overflow");
}
function add_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({ mantissa: sub_(a.mantissa, b.mantissa) });
}
function sub_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({ mantissa: sub_(a.mantissa, b.mantissa) });
}
function sub_(uint256 a, uint256 b) internal pure returns (uint256) {
return sub_(a, b, "subtraction underflow");
}
function sub_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({ mantissa: mul_(a.mantissa, b.mantissa) / expScale });
}
function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) {
return Exp({ mantissa: mul_(a.mantissa, b) });
}
function mul_(uint256 a, Exp memory b) internal pure returns (uint256) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({ mantissa: mul_(a.mantissa, b.mantissa) / doubleScale });
}
function mul_(Double memory a, uint256 b) internal pure returns (Double memory) {
return Double({ mantissa: mul_(a.mantissa, b) });
}
function mul_(uint256 a, Double memory b) internal pure returns (uint256) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint256 a, uint256 b) internal pure returns (uint256) {
return mul_(a, b, "multiplication overflow");
}
function mul_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({ mantissa: div_(mul_(a.mantissa, expScale), b.mantissa) });
}
function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) {
return Exp({ mantissa: div_(a.mantissa, b) });
}
function div_(uint256 a, Exp memory b) internal pure returns (uint256) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({ mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa) });
}
function div_(Double memory a, uint256 b) internal pure returns (Double memory) {
return Double({ mantissa: div_(a.mantissa, b) });
}
function div_(uint256 a, Double memory b) internal pure returns (uint256) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint256 a, uint256 b) internal pure returns (uint256) {
return div_(a, b, "divide by zero");
}
function div_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint256 a, uint256 b) internal pure returns (Double memory) {
return Double({ mantissa: div_(mul_(a, doubleScale), b) });
}
}
文件 22 的 45:IBeacon.sol
pragma solidity ^0.8.0;
interface IBeacon {
function implementation() external view returns (address);
}
文件 23 的 45:IFeeDistributor.sol
pragma solidity >=0.8.0;
import "../ionic/AuthoritiesRegistry.sol";
interface IFeeDistributor {
function minBorrowEth() external view returns (uint256);
function maxUtilizationRate() external view returns (uint256);
function interestFeeRate() external view returns (uint256);
function latestComptrollerImplementation(address oldImplementation) external view returns (address);
function latestCErc20Delegate(uint8 delegateType)
external
view
returns (address cErc20Delegate, bytes memory becomeImplementationData);
function latestPluginImplementation(address oldImplementation) external view returns (address);
function getComptrollerExtensions(address comptroller) external view returns (address[] memory);
function getCErc20DelegateExtensions(address cErc20Delegate) external view returns (address[] memory);
function deployCErc20(
uint8 delegateType,
bytes calldata constructorData,
bytes calldata becomeImplData
) external returns (address);
function canCall(
address pool,
address user,
address target,
bytes4 functionSig
) external view returns (bool);
function authoritiesRegistry() external view returns (AuthoritiesRegistry);
fallback() external payable;
receive() external payable;
}
文件 24 的 45:IFlywheelBooster.sol
pragma solidity ^0.8.10;
import {ERC20} from "solmate/tokens/ERC20.sol";
interface IFlywheelBooster {
function boostedTotalSupply(ERC20 strategy) external view returns (uint256);
function boostedBalanceOf(ERC20 strategy, address user) external view returns (uint256);
}
文件 25 的 45:IFlywheelRewards.sol
pragma solidity ^0.8.10;
import {ERC20} from "solmate/tokens/ERC20.sol";
import {IonicFlywheelCore} from "../IonicFlywheelCore.sol";
interface IFlywheelRewards {
function getAccruedRewards(ERC20 strategy, uint32 lastUpdatedTimestamp) external returns (uint256 rewards);
function flywheel() external view returns (IonicFlywheelCore);
function rewardToken() external view returns (ERC20);
}
文件 26 的 45:IHistoricalRates.sol
pragma solidity >=0.5.0 <0.9.0;
import "./RateLibrary.sol";
interface IHistoricalRates {
function getRateAt(address token, uint256 index) external view returns (RateLibrary.Rate memory);
function getRates(address token, uint256 amount) external view returns (RateLibrary.Rate[] memory);
function getRates(
address token,
uint256 amount,
uint256 offset,
uint256 increment
) external view returns (RateLibrary.Rate[] memory);
function getRatesCount(address token) external view returns (uint256);
function getRatesCapacity(address token) external view returns (uint256);
function setRatesCapacity(address token, uint256 amount) external;
}
文件 27 的 45:IIonicFlywheel.sol
pragma solidity ^0.8.10;
import { ERC20 } from "solmate/tokens/ERC20.sol";
interface IIonicFlywheel {
function isRewardsDistributor() external returns (bool);
function isFlywheel() external returns (bool);
function flywheelPreSupplierAction(address market, address supplier) external;
function flywheelPreBorrowerAction(address market, address borrower) external;
function flywheelPreTransferAction(address market, address src, address dst) external;
function compAccrued(address user) external view returns (uint256);
function addMarketForRewards(ERC20 strategy) external;
function marketState(ERC20 strategy) external view returns (uint224 index, uint32 lastUpdatedTimestamp);
}
文件 28 的 45:Initializable.sol
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
abstract contract Initializable {
uint8 private _initialized;
bool private _initializing;
event Initialized(uint8 version);
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized < type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
文件 29 的 45:InterestRateModel.sol
pragma solidity >=0.8.0;
abstract contract InterestRateModel {
bool public constant isInterestRateModel = true;
function getBorrowRate(
uint256 cash,
uint256 borrows,
uint256 reserves
) public view virtual returns (uint256);
function getSupplyRate(
uint256 cash,
uint256 borrows,
uint256 reserves,
uint256 reserveFactorMantissa
) public view virtual returns (uint256);
}
文件 30 的 45:IonicFlywheelCore.sol
pragma solidity ^0.8.10;
import { ERC20 } from "solmate/tokens/ERC20.sol";
import { SafeTransferLib } from "solmate/utils/SafeTransferLib.sol";
import { SafeCastLib } from "solmate/utils/SafeCastLib.sol";
import { IFlywheelRewards } from "./rewards/IFlywheelRewards.sol";
import { IFlywheelBooster } from "./IFlywheelBooster.sol";
import { SafeOwnableUpgradeable } from "../../../ionic/SafeOwnableUpgradeable.sol";
contract IonicFlywheelCore is SafeOwnableUpgradeable {
using SafeTransferLib for ERC20;
using SafeCastLib for uint256;
uint256 public performanceFee;
address public feeRecipient;
ERC20 public rewardToken;
ERC20[] public allStrategies;
IFlywheelRewards public flywheelRewards;
IFlywheelBooster public flywheelBooster;
mapping(address => uint256) internal _rewardsAccrued;
mapping(ERC20 => RewardsState) internal _strategyState;
mapping(ERC20 => mapping(address => uint224)) internal _userIndex;
constructor() {
_disableInitializers();
}
function initialize(
ERC20 _rewardToken,
IFlywheelRewards _flywheelRewards,
IFlywheelBooster _flywheelBooster,
address _owner
) public initializer {
__SafeOwnable_init(msg.sender);
rewardToken = _rewardToken;
flywheelRewards = _flywheelRewards;
flywheelBooster = _flywheelBooster;
_transferOwnership(_owner);
performanceFee = 10e16;
feeRecipient = _owner;
}
event AccrueRewards(ERC20 indexed strategy, address indexed user, uint256 rewardsDelta, uint256 rewardsIndex);
event ClaimRewards(address indexed user, uint256 amount);
function accrue(ERC20 strategy, address user) public returns (uint256) {
(uint224 index, uint32 ts) = strategyState(strategy);
RewardsState memory state = RewardsState(index, ts);
if (state.index == 0) return 0;
state = accrueStrategy(strategy, state);
return accrueUser(strategy, user, state);
}
function accrue(
ERC20 strategy,
address user,
address secondUser
) public returns (uint256, uint256) {
(uint224 index, uint32 ts) = strategyState(strategy);
RewardsState memory state = RewardsState(index, ts);
if (state.index == 0) return (0, 0);
state = accrueStrategy(strategy, state);
return (accrueUser(strategy, user, state), accrueUser(strategy, secondUser, state));
}
function claimRewards(address user) external {
uint256 accrued = rewardsAccrued(user);
if (accrued != 0) {
_rewardsAccrued[user] = 0;
rewardToken.safeTransferFrom(address(flywheelRewards), user, accrued);
emit ClaimRewards(user, accrued);
}
}
event AddStrategy(address indexed newStrategy);
function addStrategyForRewards(ERC20 strategy) external onlyOwner {
_addStrategyForRewards(strategy);
}
function _addStrategyForRewards(ERC20 strategy) internal {
(uint224 index, ) = strategyState(strategy);
require(index == 0, "strategy");
_strategyState[strategy] = RewardsState({
index: (10**rewardToken.decimals()).safeCastTo224(),
lastUpdatedTimestamp: block.timestamp.safeCastTo32()
});
allStrategies.push(strategy);
emit AddStrategy(address(strategy));
}
function getAllStrategies() external view returns (ERC20[] memory) {
return allStrategies;
}
event FlywheelRewardsUpdate(address indexed newFlywheelRewards);
function setFlywheelRewards(IFlywheelRewards newFlywheelRewards) external onlyOwner {
if (address(flywheelRewards) != address(0)) {
uint256 oldRewardBalance = rewardToken.balanceOf(address(flywheelRewards));
if (oldRewardBalance > 0) {
rewardToken.safeTransferFrom(address(flywheelRewards), address(newFlywheelRewards), oldRewardBalance);
}
}
flywheelRewards = newFlywheelRewards;
emit FlywheelRewardsUpdate(address(newFlywheelRewards));
}
event FlywheelBoosterUpdate(address indexed newBooster);
function setBooster(IFlywheelBooster newBooster) external onlyOwner {
flywheelBooster = newBooster;
emit FlywheelBoosterUpdate(address(newBooster));
}
event UpdatedFeeSettings(
uint256 oldPerformanceFee,
uint256 newPerformanceFee,
address oldFeeRecipient,
address newFeeRecipient
);
function updateFeeSettings(uint256 _performanceFee, address _feeRecipient) external onlyOwner {
_updateFeeSettings(_performanceFee, _feeRecipient);
}
function _updateFeeSettings(uint256 _performanceFee, address _feeRecipient) internal {
emit UpdatedFeeSettings(performanceFee, _performanceFee, feeRecipient, _feeRecipient);
if (feeRecipient != _feeRecipient) {
_rewardsAccrued[_feeRecipient] += rewardsAccrued(feeRecipient);
_rewardsAccrued[feeRecipient] = 0;
}
performanceFee = _performanceFee;
feeRecipient = _feeRecipient;
}
struct RewardsState {
uint224 index;
uint32 lastUpdatedTimestamp;
}
function accrueStrategy(ERC20 strategy, RewardsState memory state)
private
returns (RewardsState memory rewardsState)
{
uint256 strategyRewardsAccrued = flywheelRewards.getAccruedRewards(strategy, state.lastUpdatedTimestamp);
rewardsState = state;
if (strategyRewardsAccrued > 0) {
uint256 supplyTokens = address(flywheelBooster) != address(0)
? flywheelBooster.boostedTotalSupply(strategy)
: strategy.totalSupply();
uint256 accruedFees = (strategyRewardsAccrued * performanceFee) / uint224(100e16);
_rewardsAccrued[feeRecipient] += accruedFees;
strategyRewardsAccrued -= accruedFees;
uint224 deltaIndex;
if (supplyTokens != 0)
deltaIndex = ((strategyRewardsAccrued * (10**strategy.decimals())) / supplyTokens).safeCastTo224();
rewardsState = RewardsState({
index: state.index + deltaIndex,
lastUpdatedTimestamp: block.timestamp.safeCastTo32()
});
_strategyState[strategy] = rewardsState;
}
}
function accrueUser(
ERC20 strategy,
address user,
RewardsState memory state
) private returns (uint256) {
uint224 strategyIndex = state.index;
uint224 supplierIndex = userIndex(strategy, user);
_userIndex[strategy][user] = strategyIndex;
if (supplierIndex == 0) {
supplierIndex = (10**rewardToken.decimals()).safeCastTo224();
}
uint224 deltaIndex = strategyIndex - supplierIndex;
uint256 supplierTokens = address(flywheelBooster) != address(0)
? flywheelBooster.boostedBalanceOf(strategy, user)
: strategy.balanceOf(user);
uint256 supplierDelta = (deltaIndex * supplierTokens) / (10**strategy.decimals());
uint256 supplierAccrued = rewardsAccrued(user) + supplierDelta;
_rewardsAccrued[user] = supplierAccrued;
emit AccrueRewards(strategy, user, supplierDelta, strategyIndex);
return supplierAccrued;
}
function rewardsAccrued(address user) public virtual returns (uint256) {
return _rewardsAccrued[user];
}
function userIndex(ERC20 strategy, address user) public virtual returns (uint224) {
return _userIndex[strategy][user];
}
function strategyState(ERC20 strategy) public virtual returns (uint224 index, uint32 lastUpdatedTimestamp) {
return (_strategyState[strategy].index, _strategyState[strategy].lastUpdatedTimestamp);
}
}
文件 31 的 45:IonicFlywheelLensRouter.sol
pragma solidity ^0.8.10;
import { ERC20 } from "solmate/tokens/ERC20.sol";
import { IonicFlywheelCore } from "./IonicFlywheelCore.sol";
import { IonicComptroller } from "../../../compound/ComptrollerInterface.sol";
import { ICErc20 } from "../../../compound/CTokenInterfaces.sol";
import { BasePriceOracle } from "../../../oracles/BasePriceOracle.sol";
import { PoolDirectory } from "../../../PoolDirectory.sol";
interface IPriceOracle_IFLR {
function getUnderlyingPrice(ERC20 cToken) external view returns (uint256);
function price(address underlying) external view returns (uint256);
}
contract IonicFlywheelLensRouter {
PoolDirectory public fpd;
constructor(PoolDirectory _fpd) {
fpd = _fpd;
}
struct MarketRewardsInfo {
uint256 underlyingPrice;
ICErc20 market;
RewardsInfo[] rewardsInfo;
}
struct RewardsInfo {
uint256 rewardSpeedPerSecondPerToken;
uint256 rewardTokenPrice;
uint256 formattedAPR;
address flywheel;
address rewardToken;
}
function getPoolMarketRewardsInfo(IonicComptroller comptroller) external returns (MarketRewardsInfo[] memory) {
ICErc20[] memory markets = comptroller.getAllMarkets();
return _getMarketRewardsInfo(markets, comptroller);
}
function getMarketRewardsInfo(ICErc20[] memory markets) external returns (MarketRewardsInfo[] memory) {
IonicComptroller pool;
for (uint256 i = 0; i < markets.length; i++) {
ICErc20 asMarket = ICErc20(address(markets[i]));
if (address(pool) == address(0)) pool = asMarket.comptroller();
else require(asMarket.comptroller() == pool);
}
return _getMarketRewardsInfo(markets, pool);
}
function _getMarketRewardsInfo(ICErc20[] memory markets, IonicComptroller comptroller)
internal
returns (MarketRewardsInfo[] memory)
{
if (address(comptroller) == address(0) || markets.length == 0) return new MarketRewardsInfo[](0);
address[] memory flywheels = comptroller.getAccruingFlywheels();
address[] memory rewardTokens = new address[](flywheels.length);
uint256[] memory rewardTokenPrices = new uint256[](flywheels.length);
uint256[] memory rewardTokenDecimals = new uint256[](flywheels.length);
BasePriceOracle oracle = comptroller.oracle();
MarketRewardsInfo[] memory infoList = new MarketRewardsInfo[](markets.length);
for (uint256 i = 0; i < markets.length; i++) {
RewardsInfo[] memory rewardsInfo = new RewardsInfo[](flywheels.length);
ICErc20 market = ICErc20(address(markets[i]));
uint256 price = oracle.price(market.underlying());
if (i == 0) {
for (uint256 j = 0; j < flywheels.length; j++) {
ERC20 rewardToken = IonicFlywheelCore(flywheels[j]).rewardToken();
rewardTokens[j] = address(rewardToken);
rewardTokenPrices[j] = oracle.price(address(rewardToken));
rewardTokenDecimals[j] = uint256(rewardToken.decimals());
}
}
for (uint256 j = 0; j < flywheels.length; j++) {
IonicFlywheelCore flywheel = IonicFlywheelCore(flywheels[j]);
uint256 rewardSpeedPerSecondPerToken = getRewardSpeedPerSecondPerToken(
flywheel,
market,
rewardTokenDecimals[j]
);
uint256 apr = getApr(
rewardSpeedPerSecondPerToken,
rewardTokenPrices[j],
price,
market.exchangeRateCurrent(),
address(flywheel.flywheelBooster()) != address(0)
);
rewardsInfo[j] = RewardsInfo({
rewardSpeedPerSecondPerToken: rewardSpeedPerSecondPerToken,
rewardTokenPrice: rewardTokenPrices[j],
formattedAPR: apr,
flywheel: address(flywheel),
rewardToken: rewardTokens[j]
});
}
infoList[i] = MarketRewardsInfo({ market: market, rewardsInfo: rewardsInfo, underlyingPrice: price });
}
return infoList;
}
function scaleIndexDiff(uint256 indexDiff, uint256 decimals) internal pure returns (uint256) {
return decimals <= 18 ? uint256(indexDiff) * (10**(18 - decimals)) : uint256(indexDiff) / (10**(decimals - 18));
}
function getRewardSpeedPerSecondPerToken(
IonicFlywheelCore flywheel,
ICErc20 market,
uint256 decimals
) internal returns (uint256 rewardSpeedPerSecondPerToken) {
ERC20 strategy = ERC20(address(market));
(uint224 indexBefore, uint32 lastUpdatedTimestampBefore) = flywheel.strategyState(strategy);
flywheel.accrue(strategy, address(0));
(uint224 indexAfter, uint32 lastUpdatedTimestampAfter) = flywheel.strategyState(strategy);
if (lastUpdatedTimestampAfter > lastUpdatedTimestampBefore) {
rewardSpeedPerSecondPerToken =
scaleIndexDiff((indexAfter - indexBefore), decimals) /
(lastUpdatedTimestampAfter - lastUpdatedTimestampBefore);
}
}
function getApr(
uint256 rewardSpeedPerSecondPerToken,
uint256 rewardTokenPrice,
uint256 underlyingPrice,
uint256 exchangeRate,
bool isBorrow
) internal pure returns (uint256) {
if (rewardSpeedPerSecondPerToken == 0) return 0;
uint256 nativeSpeedPerSecondPerCToken = rewardSpeedPerSecondPerToken * rewardTokenPrice;
uint256 nativeSpeedPerYearPerCToken = nativeSpeedPerSecondPerCToken * 365.25 days;
uint256 assetSpeedPerYearPerCToken = nativeSpeedPerYearPerCToken / underlyingPrice;
uint256 assetSpeedPerYearPerCTokenScaled = assetSpeedPerYearPerCToken * 1e18;
uint256 apr = assetSpeedPerYearPerCTokenScaled;
if (!isBorrow) {
apr = assetSpeedPerYearPerCTokenScaled / exchangeRate;
} else {
apr = assetSpeedPerYearPerCTokenScaled / 1e18;
}
return apr;
}
function getRewardsAprForMarket(ICErc20 market) internal returns (int256 totalMarketRewardsApr) {
IonicComptroller comptroller = market.comptroller();
BasePriceOracle oracle = comptroller.oracle();
uint256 underlyingPrice = oracle.getUnderlyingPrice(market);
address[] memory flywheels = comptroller.getAccruingFlywheels();
for (uint256 j = 0; j < flywheels.length; j++) {
IonicFlywheelCore flywheel = IonicFlywheelCore(flywheels[j]);
ERC20 rewardToken = flywheel.rewardToken();
uint256 rewardSpeedPerSecondPerToken = getRewardSpeedPerSecondPerToken(
flywheel,
market,
uint256(rewardToken.decimals())
);
uint256 marketApr = getApr(
rewardSpeedPerSecondPerToken,
oracle.price(address(rewardToken)),
underlyingPrice,
market.exchangeRateCurrent(),
address(flywheel.flywheelBooster()) != address(0)
);
totalMarketRewardsApr += int256(marketApr);
}
}
function getUserNetValueDeltaForMarket(
address user,
ICErc20 market,
int256 offchainApr,
int256 blocksPerYear
) internal returns (int256) {
IonicComptroller comptroller = market.comptroller();
BasePriceOracle oracle = comptroller.oracle();
int256 netApr = getRewardsAprForMarket(market) +
getUserInterestAprForMarket(user, market, blocksPerYear) +
offchainApr;
return (netApr * int256(market.balanceOfUnderlying(user)) * int256(oracle.getUnderlyingPrice(market))) / 1e36;
}
function getUserInterestAprForMarket(
address user,
ICErc20 market,
int256 blocksPerYear
) internal returns (int256) {
uint256 borrows = market.borrowBalanceCurrent(user);
uint256 supplied = market.balanceOfUnderlying(user);
uint256 supplyRatePerBlock = market.supplyRatePerBlock();
uint256 borrowRatePerBlock = market.borrowRatePerBlock();
IonicComptroller comptroller = market.comptroller();
BasePriceOracle oracle = comptroller.oracle();
uint256 assetPrice = oracle.getUnderlyingPrice(market);
uint256 collateralValue = (supplied * assetPrice) / 1e18;
uint256 borrowsValue = (borrows * assetPrice) / 1e18;
uint256 yieldValuePerBlock = collateralValue * supplyRatePerBlock;
uint256 interestOwedValuePerBlock = borrowsValue * borrowRatePerBlock;
if (collateralValue == 0) return 0;
return ((int256(yieldValuePerBlock) - int256(interestOwedValuePerBlock)) * blocksPerYear) / int256(collateralValue);
}
struct AdjustedUserNetAprVars {
int256 userNetAssetsValue;
int256 userNetValueDelta;
BasePriceOracle oracle;
ICErc20[] markets;
IonicComptroller pool;
}
function getAdjustedUserNetApr(
address user,
int256 blocksPerYear,
address[] memory offchainRewardsAprMarkets,
int256[] memory offchainRewardsAprs
) public returns (int256) {
AdjustedUserNetAprVars memory vars;
(, PoolDirectory.Pool[] memory pools) = fpd.getActivePools();
for (uint256 i = 0; i < pools.length; i++) {
IonicComptroller pool = IonicComptroller(pools[i].comptroller);
vars.oracle = pool.oracle();
vars.markets = pool.getAllMarkets();
for (uint256 j = 0; j < vars.markets.length; j++) {
int256 offchainRewardsApr = 0;
for (uint256 k = 0; k < offchainRewardsAprMarkets.length; k++) {
if (offchainRewardsAprMarkets[k] == address(vars.markets[j])) offchainRewardsApr = offchainRewardsAprs[k];
}
vars.userNetAssetsValue +=
int256(vars.markets[j].balanceOfUnderlying(user) * vars.oracle.getUnderlyingPrice(vars.markets[j])) /
1e18;
vars.userNetValueDelta += getUserNetValueDeltaForMarket(
user,
vars.markets[j],
offchainRewardsApr,
blocksPerYear
);
}
}
if (vars.userNetAssetsValue == 0) return 0;
else return (vars.userNetValueDelta * 1e18) / vars.userNetAssetsValue;
}
function getUserNetApr(address user, int256 blocksPerYear) external returns (int256) {
address[] memory emptyAddrArray = new address[](0);
int256[] memory emptyIntArray = new int256[](0);
return getAdjustedUserNetApr(user, blocksPerYear, emptyAddrArray, emptyIntArray);
}
function getAllRewardTokens() public view returns (address[] memory uniqueRewardTokens) {
(, PoolDirectory.Pool[] memory pools) = fpd.getActivePools();
uint256 rewardTokensCounter;
for (uint256 i = 0; i < pools.length; i++) {
IonicComptroller pool = IonicComptroller(pools[i].comptroller);
address[] memory fws = pool.getRewardsDistributors();
rewardTokensCounter += fws.length;
}
address[] memory rewardTokens = new address[](rewardTokensCounter);
uint256 uniqueRewardTokensCounter = 0;
for (uint256 i = 0; i < pools.length; i++) {
IonicComptroller pool = IonicComptroller(pools[i].comptroller);
address[] memory fws = pool.getRewardsDistributors();
for (uint256 j = 0; j < fws.length; j++) {
address rwToken = address(IonicFlywheelCore(fws[j]).rewardToken());
if (rwToken == address(0)) break;
bool added;
for (uint256 k = 0; k < rewardTokens.length; k++) {
if (rwToken == rewardTokens[k]) {
added = true;
break;
}
}
if (!added) rewardTokens[uniqueRewardTokensCounter++] = rwToken;
}
}
uniqueRewardTokens = new address[](uniqueRewardTokensCounter);
for (uint256 i = 0; i < uniqueRewardTokensCounter; i++) {
uniqueRewardTokens[i] = rewardTokens[i];
}
}
function claimAllRewardTokens(address user) external returns (address[] memory, uint256[] memory) {
address[] memory rewardTokens = getAllRewardTokens();
uint256[] memory rewardsClaimedForToken = new uint256[](rewardTokens.length);
for (uint256 i = 0; i < rewardTokens.length; i++) {
rewardsClaimedForToken[i] = claimRewardsOfRewardToken(user, rewardTokens[i]);
}
return (rewardTokens, rewardsClaimedForToken);
}
function claimRewardsOfRewardToken(address user, address rewardToken) public returns (uint256 rewardsClaimed) {
uint256 balanceBefore = ERC20(rewardToken).balanceOf(user);
(, PoolDirectory.Pool[] memory pools) = fpd.getActivePools();
for (uint256 i = 0; i < pools.length; i++) {
IonicComptroller pool = IonicComptroller(pools[i].comptroller);
ERC20[] memory markets;
{
ICErc20[] memory cerc20s = pool.getAllMarkets();
markets = new ERC20[](cerc20s.length);
for (uint256 j = 0; j < cerc20s.length; j++) {
markets[j] = ERC20(address(cerc20s[j]));
}
}
address[] memory flywheelAddresses = pool.getAccruingFlywheels();
for (uint256 k = 0; k < flywheelAddresses.length; k++) {
IonicFlywheelCore flywheel = IonicFlywheelCore(flywheelAddresses[k]);
if (address(flywheel.rewardToken()) == rewardToken) {
for (uint256 m = 0; m < markets.length; m++) {
flywheel.accrue(markets[m], user);
}
flywheel.claimRewards(user);
}
}
}
uint256 balanceAfter = ERC20(rewardToken).balanceOf(user);
return balanceAfter - balanceBefore;
}
function claimRewardsForMarket(
address user,
ERC20 market,
IonicFlywheelCore[] calldata flywheels,
bool[] calldata accrue
)
external
returns (
IonicFlywheelCore[] memory,
address[] memory rewardTokens,
uint256[] memory rewards
)
{
uint256 size = flywheels.length;
rewards = new uint256[](size);
rewardTokens = new address[](size);
for (uint256 i = 0; i < size; i++) {
uint256 newRewards;
if (accrue[i]) {
newRewards = flywheels[i].accrue(market, user);
} else {
newRewards = flywheels[i].rewardsAccrued(user);
}
rewards[i] = rewards[i] >= newRewards ? rewards[i] : newRewards;
flywheels[i].claimRewards(user);
rewardTokens[i] = address(flywheels[i].rewardToken());
}
return (flywheels, rewardTokens, rewards);
}
function claimRewardsForPool(address user, IonicComptroller comptroller)
public
returns (
IonicFlywheelCore[] memory,
address[] memory,
uint256[] memory
)
{
ICErc20[] memory cerc20s = comptroller.getAllMarkets();
ERC20[] memory markets = new ERC20[](cerc20s.length);
address[] memory flywheelAddresses = comptroller.getAccruingFlywheels();
IonicFlywheelCore[] memory flywheels = new IonicFlywheelCore[](flywheelAddresses.length);
bool[] memory accrue = new bool[](flywheelAddresses.length);
for (uint256 j = 0; j < flywheelAddresses.length; j++) {
flywheels[j] = IonicFlywheelCore(flywheelAddresses[j]);
accrue[j] = true;
}
for (uint256 j = 0; j < cerc20s.length; j++) {
markets[j] = ERC20(address(cerc20s[j]));
}
return claimRewardsForMarkets(user, markets, flywheels, accrue);
}
function claimRewardsForMarkets(
address user,
ERC20[] memory markets,
IonicFlywheelCore[] memory flywheels,
bool[] memory accrue
)
public
returns (
IonicFlywheelCore[] memory,
address[] memory rewardTokens,
uint256[] memory rewards
)
{
rewards = new uint256[](flywheels.length);
rewardTokens = new address[](flywheels.length);
for (uint256 i = 0; i < flywheels.length; i++) {
for (uint256 j = 0; j < markets.length; j++) {
ERC20 market = markets[j];
uint256 newRewards;
if (accrue[i]) {
newRewards = flywheels[i].accrue(market, user);
} else {
newRewards = flywheels[i].rewardsAccrued(user);
}
rewards[i] = rewards[i] >= newRewards ? rewards[i] : newRewards;
}
flywheels[i].claimRewards(user);
rewardTokens[i] = address(flywheels[i].rewardToken());
}
return (flywheels, rewardTokens, rewards);
}
}
文件 32 的 45:OwnableUpgradeable.sol
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
modifier onlyOwner() {
_checkOwner();
_;
}
function owner() public view virtual returns (address) {
return _owner;
}
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
文件 33 的 45:PoolDirectory.sol
pragma solidity >=0.8.0;
import "openzeppelin-contracts-upgradeable/contracts/utils/Create2Upgradeable.sol";
import { IonicComptroller } from "./compound/ComptrollerInterface.sol";
import { BasePriceOracle } from "./oracles/BasePriceOracle.sol";
import { Unitroller } from "./compound/Unitroller.sol";
import "./ionic/SafeOwnableUpgradeable.sol";
import "./ionic/DiamondExtension.sol";
contract PoolDirectory is SafeOwnableUpgradeable {
function initialize(bool _enforceDeployerWhitelist, address[] memory _deployerWhitelist) public initializer {
__SafeOwnable_init(msg.sender);
enforceDeployerWhitelist = _enforceDeployerWhitelist;
for (uint256 i = 0; i < _deployerWhitelist.length; i++) deployerWhitelist[_deployerWhitelist[i]] = true;
}
struct Pool {
string name;
address creator;
address comptroller;
uint256 blockPosted;
uint256 timestampPosted;
}
Pool[] public pools;
mapping(address => uint256[]) private _poolsByAccount;
mapping(address => bool) public poolExists;
event PoolRegistered(uint256 index, Pool pool);
bool public enforceDeployerWhitelist;
mapping(address => bool) public deployerWhitelist;
function _setDeployerWhitelistEnforcement(bool enforce) external onlyOwner {
enforceDeployerWhitelist = enforce;
}
function _editDeployerWhitelist(address[] calldata deployers, bool status) external onlyOwner {
require(deployers.length > 0, "No deployers supplied.");
for (uint256 i = 0; i < deployers.length; i++) deployerWhitelist[deployers[i]] = status;
}
function _registerPool(string memory name, address comptroller) internal returns (uint256) {
require(!poolExists[comptroller], "Pool already exists in the directory.");
require(!enforceDeployerWhitelist || deployerWhitelist[msg.sender], "Sender is not on deployer whitelist.");
require(bytes(name).length <= 100, "No pool name supplied.");
Pool memory pool = Pool(name, msg.sender, comptroller, block.number, block.timestamp);
pools.push(pool);
_poolsByAccount[msg.sender].push(pools.length - 1);
poolExists[comptroller] = true;
emit PoolRegistered(pools.length - 1, pool);
return pools.length - 1;
}
function _deprecatePool(address comptroller) external onlyOwner {
for (uint256 i = 0; i < pools.length; i++) {
if (pools[i].comptroller == comptroller) {
_deprecatePool(i);
break;
}
}
}
function _deprecatePool(uint256 index) public onlyOwner {
Pool storage ionicPool = pools[index];
require(ionicPool.comptroller != address(0), "pool already deprecated");
uint256[] storage creatorPools = _poolsByAccount[ionicPool.creator];
for (uint256 i = 0; i < creatorPools.length; i++) {
if (creatorPools[i] == index) {
creatorPools[i] = creatorPools[creatorPools.length - 1];
creatorPools.pop();
break;
}
}
poolExists[ionicPool.comptroller] = true;
ionicPool.comptroller = address(0);
ionicPool.creator = address(0);
ionicPool.name = "";
ionicPool.blockPosted = 0;
ionicPool.timestampPosted = 0;
}
function deployPool(
string memory name,
address implementation,
bytes calldata constructorData,
bool enforceWhitelist,
uint256 closeFactor,
uint256 liquidationIncentive,
address priceOracle
) external returns (uint256, address) {
require(implementation != address(0), "No Comptroller implementation contract address specified.");
require(priceOracle != address(0), "No PriceOracle contract address specified.");
bytes memory unitrollerCreationCode = abi.encodePacked(type(Unitroller).creationCode, constructorData);
address proxy = Create2Upgradeable.deploy(
0,
keccak256(abi.encodePacked(msg.sender, name, ++poolsCounter)),
unitrollerCreationCode
);
IonicComptroller comptrollerProxy = IonicComptroller(proxy);
comptrollerProxy._upgrade();
require(comptrollerProxy._setCloseFactor(closeFactor) == 0, "Failed to set pool close factor.");
require(
comptrollerProxy._setLiquidationIncentive(liquidationIncentive) == 0,
"Failed to set pool liquidation incentive."
);
require(comptrollerProxy._setPriceOracle(BasePriceOracle(priceOracle)) == 0, "Failed to set pool price oracle.");
if (enforceWhitelist)
require(comptrollerProxy._setWhitelistEnforcement(true) == 0, "Failed to enforce supplier/borrower whitelist.");
require(comptrollerProxy._setPendingAdmin(msg.sender) == 0, "Failed to set pending admin on Unitroller.");
return (_registerPool(name, proxy), proxy);
}
function getActivePools() public view returns (uint256[] memory, Pool[] memory) {
uint256 count = 0;
for (uint256 i = 0; i < pools.length; i++) {
if (pools[i].comptroller != address(0)) count++;
}
Pool[] memory activePools = new Pool[](count);
uint256[] memory poolIds = new uint256[](count);
uint256 index = 0;
for (uint256 i = 0; i < pools.length; i++) {
if (pools[i].comptroller != address(0)) {
poolIds[index] = i;
activePools[index] = pools[i];
index++;
}
}
return (poolIds, activePools);
}
function getAllPools() public view returns (Pool[] memory) {
uint256 count = 0;
for (uint256 i = 0; i < pools.length; i++) {
if (pools[i].comptroller != address(0)) count++;
}
Pool[] memory result = new Pool[](count);
uint256 index = 0;
for (uint256 i = 0; i < pools.length; i++) {
if (pools[i].comptroller != address(0)) {
result[index++] = pools[i];
}
}
return result;
}
function getPublicPools() external view returns (uint256[] memory, Pool[] memory) {
uint256 arrayLength = 0;
(, Pool[] memory activePools) = getActivePools();
for (uint256 i = 0; i < activePools.length; i++) {
try IonicComptroller(activePools[i].comptroller).enforceWhitelist() returns (bool enforceWhitelist) {
if (enforceWhitelist) continue;
} catch {}
arrayLength++;
}
uint256[] memory indexes = new uint256[](arrayLength);
Pool[] memory publicPools = new Pool[](arrayLength);
uint256 index = 0;
for (uint256 i = 0; i < activePools.length; i++) {
try IonicComptroller(activePools[i].comptroller).enforceWhitelist() returns (bool enforceWhitelist) {
if (enforceWhitelist) continue;
} catch {}
indexes[index] = i;
publicPools[index] = activePools[i];
index++;
}
return (indexes, publicPools);
}
function getPoolsOfUser(address user) external view returns (uint256[] memory, Pool[] memory) {
uint256 arrayLength = 0;
(, Pool[] memory activePools) = getActivePools();
for (uint256 i = 0; i < activePools.length; i++) {
try IonicComptroller(activePools[i].comptroller).isUserOfPool(user) returns (bool isUsing) {
if (!isUsing) continue;
} catch {}
arrayLength++;
}
uint256[] memory indexes = new uint256[](arrayLength);
Pool[] memory poolsOfUser = new Pool[](arrayLength);
uint256 index = 0;
for (uint256 i = 0; i < activePools.length; i++) {
try IonicComptroller(activePools[i].comptroller).isUserOfPool(user) returns (bool isUsing) {
if (!isUsing) continue;
} catch {}
indexes[index] = i;
poolsOfUser[index] = activePools[i];
index++;
}
return (indexes, poolsOfUser);
}
function getPoolsByAccount(address account) external view returns (uint256[] memory, Pool[] memory) {
uint256[] memory indexes = new uint256[](_poolsByAccount[account].length);
Pool[] memory accountPools = new Pool[](_poolsByAccount[account].length);
(, Pool[] memory activePools) = getActivePools();
for (uint256 i = 0; i < _poolsByAccount[account].length; i++) {
indexes[i] = _poolsByAccount[account][i];
accountPools[i] = activePools[_poolsByAccount[account][i]];
}
return (indexes, accountPools);
}
function setPoolName(uint256 index, string calldata name) external {
IonicComptroller _comptroller = IonicComptroller(pools[index].comptroller);
require(
(msg.sender == _comptroller.admin() && _comptroller.adminHasRights()) || msg.sender == owner(),
"!permission"
);
pools[index].name = name;
}
mapping(address => bool) public adminWhitelist;
uint256 public poolsCounter;
event AdminWhitelistUpdated(address[] admins, bool status);
function _editAdminWhitelist(address[] calldata admins, bool status) external onlyOwner {
require(admins.length > 0, "No admins supplied.");
for (uint256 i = 0; i < admins.length; i++) adminWhitelist[admins[i]] = status;
emit AdminWhitelistUpdated(admins, status);
}
function getPublicPoolsByVerification(bool whitelistedAdmin) external view returns (uint256[] memory, Pool[] memory) {
uint256 arrayLength = 0;
(, Pool[] memory activePools) = getActivePools();
for (uint256 i = 0; i < activePools.length; i++) {
IonicComptroller comptroller = IonicComptroller(activePools[i].comptroller);
try comptroller.admin() returns (address admin) {
if (whitelistedAdmin != adminWhitelist[admin]) continue;
} catch {}
arrayLength++;
}
uint256[] memory indexes = new uint256[](arrayLength);
Pool[] memory publicPools = new Pool[](arrayLength);
uint256 index = 0;
for (uint256 i = 0; i < activePools.length; i++) {
IonicComptroller comptroller = IonicComptroller(activePools[i].comptroller);
try comptroller.admin() returns (address admin) {
if (whitelistedAdmin != adminWhitelist[admin]) continue;
} catch {}
indexes[index] = i;
publicPools[index] = activePools[i];
index++;
}
return (indexes, publicPools);
}
function getVerifiedPoolsOfWhitelistedAccount(address account)
external
view
returns (uint256[] memory, Pool[] memory)
{
uint256 arrayLength = 0;
(, Pool[] memory activePools) = getActivePools();
for (uint256 i = 0; i < activePools.length; i++) {
IonicComptroller comptroller = IonicComptroller(activePools[i].comptroller);
try comptroller.enforceWhitelist() returns (bool enforceWhitelist) {
if (!enforceWhitelist || !comptroller.whitelist(account)) continue;
} catch {}
arrayLength++;
}
uint256[] memory indexes = new uint256[](arrayLength);
Pool[] memory accountWhitelistedPools = new Pool[](arrayLength);
uint256 index = 0;
for (uint256 i = 0; i < activePools.length; i++) {
IonicComptroller comptroller = IonicComptroller(activePools[i].comptroller);
try comptroller.enforceWhitelist() returns (bool enforceWhitelist) {
if (!enforceWhitelist || !comptroller.whitelist(account)) continue;
} catch {}
indexes[index] = i;
accountWhitelistedPools[index] = activePools[i];
index++;
}
return (indexes, accountWhitelistedPools);
}
}
文件 34 的 45:PoolRolesAuthority.sol
pragma solidity >=0.8.0;
import { IonicComptroller, ComptrollerInterface } from "../compound/ComptrollerInterface.sol";
import { ICErc20, CTokenSecondExtensionInterface, CTokenFirstExtensionInterface } from "../compound/CTokenInterfaces.sol";
import { RolesAuthority, Authority } from "solmate/auth/authorities/RolesAuthority.sol";
import "openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol";
contract PoolRolesAuthority is RolesAuthority, Initializable {
constructor() RolesAuthority(address(0), Authority(address(0))) {
_disableInitializers();
}
function initialize(address _owner) public initializer {
owner = _owner;
authority = this;
}
uint8 public constant REGISTRY_ROLE = 0;
uint8 public constant SUPPLIER_ROLE = 1;
uint8 public constant BORROWER_ROLE = 2;
uint8 public constant LIQUIDATOR_ROLE = 3;
uint8 public constant LEVERED_POSITION_ROLE = 4;
function configureRegistryCapabilities() external requiresAuth {
setRoleCapability(REGISTRY_ROLE, address(this), PoolRolesAuthority.configureRegistryCapabilities.selector, true);
setRoleCapability(
REGISTRY_ROLE,
address(this),
PoolRolesAuthority.configurePoolSupplierCapabilities.selector,
true
);
setRoleCapability(
REGISTRY_ROLE,
address(this),
PoolRolesAuthority.configurePoolBorrowerCapabilities.selector,
true
);
setRoleCapability(
REGISTRY_ROLE,
address(this),
PoolRolesAuthority.configureClosedPoolLiquidatorCapabilities.selector,
true
);
setRoleCapability(
REGISTRY_ROLE,
address(this),
PoolRolesAuthority.configureOpenPoolLiquidatorCapabilities.selector,
true
);
setRoleCapability(
REGISTRY_ROLE,
address(this),
PoolRolesAuthority.configureLeveredPositionCapabilities.selector,
true
);
setRoleCapability(REGISTRY_ROLE, address(this), RolesAuthority.setUserRole.selector, true);
}
function openPoolSupplierCapabilities(IonicComptroller pool) external requiresAuth {
_setPublicPoolSupplierCapabilities(pool, true);
}
function closePoolSupplierCapabilities(IonicComptroller pool) external requiresAuth {
_setPublicPoolSupplierCapabilities(pool, false);
}
function _setPublicPoolSupplierCapabilities(IonicComptroller pool, bool setPublic) internal {
setPublicCapability(address(pool), pool.enterMarkets.selector, setPublic);
setPublicCapability(address(pool), pool.exitMarket.selector, setPublic);
ICErc20[] memory allMarkets = pool.getAllMarkets();
for (uint256 i = 0; i < allMarkets.length; i++) {
bytes4[] memory selectors = getSupplierMarketSelectors();
for (uint256 j = 0; j < selectors.length; j++) {
setPublicCapability(address(allMarkets[i]), selectors[j], setPublic);
}
}
}
function configurePoolSupplierCapabilities(IonicComptroller pool) external requiresAuth {
_configurePoolSupplierCapabilities(pool, SUPPLIER_ROLE);
}
function getSupplierMarketSelectors() internal pure returns (bytes4[] memory selectors) {
uint8 fnsCount = 6;
selectors = new bytes4[](fnsCount);
selectors[--fnsCount] = CTokenSecondExtensionInterface.mint.selector;
selectors[--fnsCount] = CTokenSecondExtensionInterface.redeem.selector;
selectors[--fnsCount] = CTokenSecondExtensionInterface.redeemUnderlying.selector;
selectors[--fnsCount] = CTokenFirstExtensionInterface.transfer.selector;
selectors[--fnsCount] = CTokenFirstExtensionInterface.transferFrom.selector;
selectors[--fnsCount] = CTokenFirstExtensionInterface.approve.selector;
require(fnsCount == 0, "use the correct array length");
return selectors;
}
function _configurePoolSupplierCapabilities(IonicComptroller pool, uint8 role) internal {
setRoleCapability(role, address(pool), pool.enterMarkets.selector, true);
setRoleCapability(role, address(pool), pool.exitMarket.selector, true);
ICErc20[] memory allMarkets = pool.getAllMarkets();
for (uint256 i = 0; i < allMarkets.length; i++) {
bytes4[] memory selectors = getSupplierMarketSelectors();
for (uint256 j = 0; j < selectors.length; j++) {
setRoleCapability(role, address(allMarkets[i]), selectors[j], true);
}
}
}
function openPoolBorrowerCapabilities(IonicComptroller pool) external requiresAuth {
_setPublicPoolBorrowerCapabilities(pool, true);
}
function closePoolBorrowerCapabilities(IonicComptroller pool) external requiresAuth {
_setPublicPoolBorrowerCapabilities(pool, false);
}
function _setPublicPoolBorrowerCapabilities(IonicComptroller pool, bool setPublic) internal {
ICErc20[] memory allMarkets = pool.getAllMarkets();
for (uint256 i = 0; i < allMarkets.length; i++) {
setPublicCapability(address(allMarkets[i]), allMarkets[i].borrow.selector, setPublic);
setPublicCapability(address(allMarkets[i]), allMarkets[i].repayBorrow.selector, setPublic);
setPublicCapability(address(allMarkets[i]), allMarkets[i].repayBorrowBehalf.selector, setPublic);
setPublicCapability(address(allMarkets[i]), allMarkets[i].flash.selector, setPublic);
}
}
function configurePoolBorrowerCapabilities(IonicComptroller pool) external requiresAuth {
_configurePoolSupplierCapabilities(pool, BORROWER_ROLE);
ICErc20[] memory allMarkets = pool.getAllMarkets();
for (uint256 i = 0; i < allMarkets.length; i++) {
setRoleCapability(BORROWER_ROLE, address(allMarkets[i]), allMarkets[i].borrow.selector, true);
setRoleCapability(BORROWER_ROLE, address(allMarkets[i]), allMarkets[i].repayBorrow.selector, true);
setRoleCapability(BORROWER_ROLE, address(allMarkets[i]), allMarkets[i].repayBorrowBehalf.selector, true);
setRoleCapability(BORROWER_ROLE, address(allMarkets[i]), allMarkets[i].flash.selector, true);
}
}
function configureClosedPoolLiquidatorCapabilities(IonicComptroller pool) external requiresAuth {
ICErc20[] memory allMarkets = pool.getAllMarkets();
for (uint256 i = 0; i < allMarkets.length; i++) {
setPublicCapability(address(allMarkets[i]), allMarkets[i].liquidateBorrow.selector, false);
setRoleCapability(LIQUIDATOR_ROLE, address(allMarkets[i]), allMarkets[i].liquidateBorrow.selector, true);
setRoleCapability(LIQUIDATOR_ROLE, address(allMarkets[i]), allMarkets[i].redeem.selector, true);
}
}
function configureOpenPoolLiquidatorCapabilities(IonicComptroller pool) external requiresAuth {
ICErc20[] memory allMarkets = pool.getAllMarkets();
for (uint256 i = 0; i < allMarkets.length; i++) {
setPublicCapability(address(allMarkets[i]), allMarkets[i].liquidateBorrow.selector, true);
setPublicCapability(address(allMarkets[i]), allMarkets[i].redeem.selector, true);
}
}
function configureLeveredPositionCapabilities(IonicComptroller pool) external requiresAuth {
setRoleCapability(LEVERED_POSITION_ROLE, address(pool), pool.enterMarkets.selector, true);
setRoleCapability(LEVERED_POSITION_ROLE, address(pool), pool.exitMarket.selector, true);
ICErc20[] memory allMarkets = pool.getAllMarkets();
for (uint256 i = 0; i < allMarkets.length; i++) {
setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].mint.selector, true);
setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].redeem.selector, true);
setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].redeemUnderlying.selector, true);
setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].borrow.selector, true);
setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].repayBorrow.selector, true);
setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].flash.selector, true);
}
}
}
文件 35 的 45:Proxy.sol
pragma solidity ^0.8.0;
abstract contract Proxy {
function _delegate(address implementation) internal virtual {
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
function _implementation() internal view virtual returns (address);
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
fallback() external payable virtual {
_fallback();
}
receive() external payable virtual {
_fallback();
}
function _beforeFallback() internal virtual {}
}
文件 36 的 45:PrudentiaLib.sol
pragma solidity >=0.8.0;
library PrudentiaLib {
struct PrudentiaConfig {
address controller;
uint8 offset;
int8 decimalShift;
}
}
文件 37 的 45:RateLibrary.sol
pragma solidity >=0.5.0 <0.9.0;
pragma experimental ABIEncoderV2;
library RateLibrary {
struct Rate {
uint64 target;
uint64 current;
uint32 timestamp;
}
}
文件 38 的 45:RolesAuthority.sol
pragma solidity >=0.8.0;
import {Auth, Authority} from "../Auth.sol";
contract RolesAuthority is Auth, Authority {
event UserRoleUpdated(address indexed user, uint8 indexed role, bool enabled);
event PublicCapabilityUpdated(address indexed target, bytes4 indexed functionSig, bool enabled);
event RoleCapabilityUpdated(uint8 indexed role, address indexed target, bytes4 indexed functionSig, bool enabled);
constructor(address _owner, Authority _authority) Auth(_owner, _authority) {}
mapping(address => bytes32) public getUserRoles;
mapping(address => mapping(bytes4 => bool)) public isCapabilityPublic;
mapping(address => mapping(bytes4 => bytes32)) public getRolesWithCapability;
function doesUserHaveRole(address user, uint8 role) public view virtual returns (bool) {
return (uint256(getUserRoles[user]) >> role) & 1 != 0;
}
function doesRoleHaveCapability(
uint8 role,
address target,
bytes4 functionSig
) public view virtual returns (bool) {
return (uint256(getRolesWithCapability[target][functionSig]) >> role) & 1 != 0;
}
function canCall(
address user,
address target,
bytes4 functionSig
) public view virtual override returns (bool) {
return
isCapabilityPublic[target][functionSig] ||
bytes32(0) != getUserRoles[user] & getRolesWithCapability[target][functionSig];
}
function setPublicCapability(
address target,
bytes4 functionSig,
bool enabled
) public virtual requiresAuth {
isCapabilityPublic[target][functionSig] = enabled;
emit PublicCapabilityUpdated(target, functionSig, enabled);
}
function setRoleCapability(
uint8 role,
address target,
bytes4 functionSig,
bool enabled
) public virtual requiresAuth {
if (enabled) {
getRolesWithCapability[target][functionSig] |= bytes32(1 << role);
} else {
getRolesWithCapability[target][functionSig] &= ~bytes32(1 << role);
}
emit RoleCapabilityUpdated(role, target, functionSig, enabled);
}
function setUserRole(
address user,
uint8 role,
bool enabled
) public virtual requiresAuth {
if (enabled) {
getUserRoles[user] |= bytes32(1 << role);
} else {
getUserRoles[user] &= ~bytes32(1 << role);
}
emit UserRoleUpdated(user, role, enabled);
}
}
文件 39 的 45:SafeCastLib.sol
pragma solidity >=0.8.0;
library SafeCastLib {
function safeCastTo248(uint256 x) internal pure returns (uint248 y) {
require(x < 1 << 248);
y = uint248(x);
}
function safeCastTo224(uint256 x) internal pure returns (uint224 y) {
require(x < 1 << 224);
y = uint224(x);
}
function safeCastTo192(uint256 x) internal pure returns (uint192 y) {
require(x < 1 << 192);
y = uint192(x);
}
function safeCastTo160(uint256 x) internal pure returns (uint160 y) {
require(x < 1 << 160);
y = uint160(x);
}
function safeCastTo128(uint256 x) internal pure returns (uint128 y) {
require(x < 1 << 128);
y = uint128(x);
}
function safeCastTo96(uint256 x) internal pure returns (uint96 y) {
require(x < 1 << 96);
y = uint96(x);
}
function safeCastTo64(uint256 x) internal pure returns (uint64 y) {
require(x < 1 << 64);
y = uint64(x);
}
function safeCastTo32(uint256 x) internal pure returns (uint32 y) {
require(x < 1 << 32);
y = uint32(x);
}
function safeCastTo24(uint256 x) internal pure returns (uint24 y) {
require(x < 1 << 24);
y = uint24(x);
}
function safeCastTo16(uint256 x) internal pure returns (uint16 y) {
require(x < 1 << 16);
y = uint16(x);
}
function safeCastTo8(uint256 x) internal pure returns (uint8 y) {
require(x < 1 << 8);
y = uint8(x);
}
}
文件 40 的 45:SafeOwnableUpgradeable.sol
pragma solidity >=0.8.0;
import "openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol";
abstract contract SafeOwnableUpgradeable is OwnableUpgradeable {
address public pendingOwner;
function __SafeOwnable_init(address owner_) internal onlyInitializing {
__Ownable_init();
_transferOwnership(owner_);
}
struct AddressSlot {
address value;
}
modifier onlyOwnerOrAdmin() {
bool isOwner = owner() == _msgSender();
if (!isOwner) {
address admin = _getProxyAdmin();
bool isAdmin = admin == _msgSender();
require(isAdmin, "Ownable: caller is neither the owner nor the admin");
}
_;
}
event NewPendingOwner(address oldPendingOwner, address newPendingOwner);
event NewOwner(address oldOwner, address newOwner);
function _setPendingOwner(address newPendingOwner) public onlyOwner {
address oldPendingOwner = pendingOwner;
pendingOwner = newPendingOwner;
emit NewPendingOwner(oldPendingOwner, newPendingOwner);
}
function _acceptOwner() public {
require(msg.sender == pendingOwner, "not the pending owner");
address oldOwner = owner();
address oldPendingOwner = pendingOwner;
_transferOwnership(pendingOwner);
pendingOwner = address(0);
emit NewOwner(oldOwner, pendingOwner);
emit NewPendingOwner(oldPendingOwner, pendingOwner);
}
function renounceOwnership() public override onlyOwner {
revert("not used anymore");
}
function transferOwnership(address newOwner) public override onlyOwner {
emit NewPendingOwner(pendingOwner, newOwner);
pendingOwner = newOwner;
}
function _getProxyAdmin() internal view returns (address admin) {
bytes32 _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
AddressSlot storage adminSlot;
assembly {
adminSlot.slot := _ADMIN_SLOT
}
admin = adminSlot.value;
}
}
文件 41 的 45:SafeTransferLib.sol
pragma solidity >=0.8.0;
import {ERC20} from "../tokens/ERC20.sol";
library SafeTransferLib {
function safeTransferETH(address to, uint256 amount) internal {
bool success;
assembly {
success := call(gas(), to, amount, 0, 0, 0, 0)
}
require(success, "ETH_TRANSFER_FAILED");
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 amount
) internal {
bool success;
assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), from)
mstore(add(freeMemoryPointer, 36), to)
mstore(add(freeMemoryPointer, 68), amount)
success := and(
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
)
}
require(success, "TRANSFER_FROM_FAILED");
}
function safeTransfer(
ERC20 token,
address to,
uint256 amount
) internal {
bool success;
assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), to)
mstore(add(freeMemoryPointer, 36), amount)
success := and(
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
require(success, "TRANSFER_FAILED");
}
function safeApprove(
ERC20 token,
address to,
uint256 amount
) internal {
bool success;
assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), to)
mstore(add(freeMemoryPointer, 36), amount)
success := and(
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
require(success, "APPROVE_FAILED");
}
}
文件 42 的 45:StorageSlot.sol
pragma solidity ^0.8.0;
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
文件 43 的 45:TransparentUpgradeableProxy.sol
pragma solidity ^0.8.0;
import "../ERC1967/ERC1967Proxy.sol";
contract TransparentUpgradeableProxy is ERC1967Proxy {
constructor(
address _logic,
address admin_,
bytes memory _data
) payable ERC1967Proxy(_logic, _data) {
_changeAdmin(admin_);
}
modifier ifAdmin() {
if (msg.sender == _getAdmin()) {
_;
} else {
_fallback();
}
}
function admin() external ifAdmin returns (address admin_) {
admin_ = _getAdmin();
}
function implementation() external ifAdmin returns (address implementation_) {
implementation_ = _implementation();
}
function changeAdmin(address newAdmin) external virtual ifAdmin {
_changeAdmin(newAdmin);
}
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeToAndCall(newImplementation, bytes(""), false);
}
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
_upgradeToAndCall(newImplementation, data, true);
}
function _admin() internal view virtual returns (address) {
return _getAdmin();
}
function _beforeFallback() internal virtual override {
require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
super._beforeFallback();
}
}
文件 44 的 45:Unitroller.sol
pragma solidity >=0.8.0;
import "./ErrorReporter.sol";
import "./ComptrollerStorage.sol";
import "./Comptroller.sol";
import { DiamondExtension, DiamondBase, LibDiamond } from "../ionic/DiamondExtension.sol";
contract Unitroller is ComptrollerV3Storage, ComptrollerErrorReporter, DiamondBase {
event AdminRightsToggled(bool hasRights);
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
event NewAdmin(address oldAdmin, address newAdmin);
constructor(address payable _ionicAdmin) {
admin = msg.sender;
ionicAdmin = _ionicAdmin;
}
function _toggleAdminRights(bool hasRights) external returns (uint256) {
if (!hasAdminRights()) {
return fail(Error.UNAUTHORIZED, FailureInfo.TOGGLE_ADMIN_RIGHTS_OWNER_CHECK);
}
if (adminHasRights == hasRights) return uint256(Error.NO_ERROR);
adminHasRights = hasRights;
emit AdminRightsToggled(hasRights);
return uint256(Error.NO_ERROR);
}
function _setPendingAdmin(address newPendingAdmin) public returns (uint256) {
if (!hasAdminRights()) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
address oldPendingAdmin = pendingAdmin;
pendingAdmin = newPendingAdmin;
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint256(Error.NO_ERROR);
}
function _acceptAdmin() public returns (uint256) {
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
admin = pendingAdmin;
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint256(Error.NO_ERROR);
}
function comptrollerImplementation() public view returns (address) {
return LibDiamond.getExtensionForFunction(bytes4(keccak256(bytes("_deployMarket(uint8,bytes,bytes,uint256)"))));
}
function _upgrade() external {
require(msg.sender == address(this) || hasAdminRights(), "!self || !admin");
address currentImplementation = comptrollerImplementation();
address latestComptrollerImplementation = IFeeDistributor(ionicAdmin).latestComptrollerImplementation(
currentImplementation
);
_updateExtensions(latestComptrollerImplementation);
if (currentImplementation != latestComptrollerImplementation) {
_functionCall(address(this), abi.encodeWithSignature("_becomeImplementation()"), "!become impl");
}
}
function _functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.call(data);
if (!success) {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
return returndata;
}
function _updateExtensions(address currentComptroller) internal {
address[] memory latestExtensions = IFeeDistributor(ionicAdmin).getComptrollerExtensions(currentComptroller);
address[] memory currentExtensions = LibDiamond.listExtensions();
for (uint256 i = 0; i < currentExtensions.length; i++) {
LibDiamond.removeExtension(DiamondExtension(currentExtensions[i]));
}
for (uint256 i = 0; i < latestExtensions.length; i++) {
LibDiamond.addExtension(DiamondExtension(latestExtensions[i]));
}
}
function _registerExtension(DiamondExtension extensionToAdd, DiamondExtension extensionToReplace) external override {
require(hasAdminRights(), "!unauthorized");
LibDiamond.registerExtension(extensionToAdd, extensionToReplace);
}
}
文件 45 的 45:draft-IERC1822.sol
pragma solidity ^0.8.0;
interface IERC1822Proxiable {
function proxiableUUID() external view returns (bytes32);
}
{
"compilationTarget": {
"contracts/ionic/strategies/flywheel/IonicFlywheelLensRouter.sol": "IonicFlywheelLensRouter"
},
"evmVersion": "london",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs",
"useLiteralContent": true
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": []
}
[{"inputs":[{"internalType":"contract PoolDirectory","name":"_fpd","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"claimAllRewardTokens","outputs":[{"internalType":"address[]","name":"","type":"address[]"},{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"contract ERC20","name":"market","type":"address"},{"internalType":"contract IonicFlywheelCore[]","name":"flywheels","type":"address[]"},{"internalType":"bool[]","name":"accrue","type":"bool[]"}],"name":"claimRewardsForMarket","outputs":[{"internalType":"contract IonicFlywheelCore[]","name":"","type":"address[]"},{"internalType":"address[]","name":"rewardTokens","type":"address[]"},{"internalType":"uint256[]","name":"rewards","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"contract ERC20[]","name":"markets","type":"address[]"},{"internalType":"contract IonicFlywheelCore[]","name":"flywheels","type":"address[]"},{"internalType":"bool[]","name":"accrue","type":"bool[]"}],"name":"claimRewardsForMarkets","outputs":[{"internalType":"contract IonicFlywheelCore[]","name":"","type":"address[]"},{"internalType":"address[]","name":"rewardTokens","type":"address[]"},{"internalType":"uint256[]","name":"rewards","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"contract IonicComptroller","name":"comptroller","type":"address"}],"name":"claimRewardsForPool","outputs":[{"internalType":"contract IonicFlywheelCore[]","name":"","type":"address[]"},{"internalType":"address[]","name":"","type":"address[]"},{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"rewardToken","type":"address"}],"name":"claimRewardsOfRewardToken","outputs":[{"internalType":"uint256","name":"rewardsClaimed","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"fpd","outputs":[{"internalType":"contract PoolDirectory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"int256","name":"blocksPerYear","type":"int256"},{"internalType":"address[]","name":"offchainRewardsAprMarkets","type":"address[]"},{"internalType":"int256[]","name":"offchainRewardsAprs","type":"int256[]"}],"name":"getAdjustedUserNetApr","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getAllRewardTokens","outputs":[{"internalType":"address[]","name":"uniqueRewardTokens","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract ICErc20[]","name":"markets","type":"address[]"}],"name":"getMarketRewardsInfo","outputs":[{"components":[{"internalType":"uint256","name":"underlyingPrice","type":"uint256"},{"internalType":"contract ICErc20","name":"market","type":"address"},{"components":[{"internalType":"uint256","name":"rewardSpeedPerSecondPerToken","type":"uint256"},{"internalType":"uint256","name":"rewardTokenPrice","type":"uint256"},{"internalType":"uint256","name":"formattedAPR","type":"uint256"},{"internalType":"address","name":"flywheel","type":"address"},{"internalType":"address","name":"rewardToken","type":"address"}],"internalType":"struct IonicFlywheelLensRouter.RewardsInfo[]","name":"rewardsInfo","type":"tuple[]"}],"internalType":"struct IonicFlywheelLensRouter.MarketRewardsInfo[]","name":"","type":"tuple[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IonicComptroller","name":"comptroller","type":"address"}],"name":"getPoolMarketRewardsInfo","outputs":[{"components":[{"internalType":"uint256","name":"underlyingPrice","type":"uint256"},{"internalType":"contract ICErc20","name":"market","type":"address"},{"components":[{"internalType":"uint256","name":"rewardSpeedPerSecondPerToken","type":"uint256"},{"internalType":"uint256","name":"rewardTokenPrice","type":"uint256"},{"internalType":"uint256","name":"formattedAPR","type":"uint256"},{"internalType":"address","name":"flywheel","type":"address"},{"internalType":"address","name":"rewardToken","type":"address"}],"internalType":"struct IonicFlywheelLensRouter.RewardsInfo[]","name":"rewardsInfo","type":"tuple[]"}],"internalType":"struct IonicFlywheelLensRouter.MarketRewardsInfo[]","name":"","type":"tuple[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"int256","name":"blocksPerYear","type":"int256"}],"name":"getUserNetApr","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"nonpayable","type":"function"}]