Feature Tip: Add private address tag to any address under My Name Tag !
Overview
ETH Balance
0 ETH
Eth Value
$0.00More Info
Private Name Tags
ContractCreator
Latest 23 from a total of 23 transactions
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
Create P Token | 12471429 | 1347 days ago | IN | 0 ETH | 0.07097376 | ||||
Create P Token | 12307183 | 1373 days ago | IN | 0 ETH | 0.03030072 | ||||
Create P Token | 12296079 | 1375 days ago | IN | 0 ETH | 0.09465126 | ||||
Create P Token | 12276959 | 1377 days ago | IN | 0 ETH | 0.154594 | ||||
Create P Token | 12218480 | 1387 days ago | IN | 0 ETH | 0.04737044 | ||||
Create P Token | 12206979 | 1388 days ago | IN | 0 ETH | 0.10049477 | ||||
Create P Token | 12186435 | 1391 days ago | IN | 0 ETH | 0.09626265 | ||||
Create P Token | 12171044 | 1394 days ago | IN | 0 ETH | 0.06598865 | ||||
Create P Token | 12153876 | 1396 days ago | IN | 0 ETH | 0.15299715 | ||||
Create P Token | 12123680 | 1401 days ago | IN | 0 ETH | 0.08841828 | ||||
Create P Token | 12123304 | 1401 days ago | IN | 0 ETH | 0.06940761 | ||||
Create P Token | 12015043 | 1418 days ago | IN | 0 ETH | 0.00519634 | ||||
Create P Token | 12015034 | 1418 days ago | IN | 0 ETH | 0.06218849 | ||||
Create P Token | 11985001 | 1422 days ago | IN | 0 ETH | 0.05536192 | ||||
Create P Token | 11930787 | 1431 days ago | IN | 0 ETH | 0.08917081 | ||||
Create P Token | 11930784 | 1431 days ago | IN | 0 ETH | 0.06051328 | ||||
Create P Token | 11930777 | 1431 days ago | IN | 0 ETH | 0.01311948 | ||||
Create P Token | 11930770 | 1431 days ago | IN | 0 ETH | 0.00575 | ||||
Set Min Uniswap ... | 11914517 | 1433 days ago | IN | 0 ETH | 0.00507292 | ||||
Create P Token | 11814553 | 1449 days ago | IN | 0 ETH | 0.2169297 | ||||
Create P Token | 11682426 | 1469 days ago | IN | 0 ETH | 0.04835219 | ||||
Create P Token | 11577463 | 1485 days ago | IN | 0 ETH | 0.03724644 | ||||
Create P Token | 11576668 | 1485 days ago | IN | 0 ETH | 0.03665024 |
Latest 20 internal transactions
Advanced mode:
Parent Transaction Hash | Block |
From
|
To
|
|||
---|---|---|---|---|---|---|
12471429 | 1347 days ago | Contract Creation | 0 ETH | |||
12307183 | 1373 days ago | Contract Creation | 0 ETH | |||
12296079 | 1375 days ago | Contract Creation | 0 ETH | |||
12276959 | 1377 days ago | Contract Creation | 0 ETH | |||
12218480 | 1387 days ago | Contract Creation | 0 ETH | |||
12206979 | 1388 days ago | Contract Creation | 0 ETH | |||
12186435 | 1391 days ago | Contract Creation | 0 ETH | |||
12171044 | 1394 days ago | Contract Creation | 0 ETH | |||
12153876 | 1396 days ago | Contract Creation | 0 ETH | |||
12123680 | 1401 days ago | Contract Creation | 0 ETH | |||
12123304 | 1401 days ago | Contract Creation | 0 ETH | |||
12015034 | 1418 days ago | Contract Creation | 0 ETH | |||
11985001 | 1422 days ago | Contract Creation | 0 ETH | |||
11930787 | 1431 days ago | Contract Creation | 0 ETH | |||
11930784 | 1431 days ago | Contract Creation | 0 ETH | |||
11930777 | 1431 days ago | Contract Creation | 0 ETH | |||
11814553 | 1449 days ago | Contract Creation | 0 ETH | |||
11682426 | 1469 days ago | Contract Creation | 0 ETH | |||
11577463 | 1485 days ago | Contract Creation | 0 ETH | |||
11576668 | 1485 days ago | Contract Creation | 0 ETH |
Loading...
Loading
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.
Contract Source Code Verified (Exact Match)
Contract Name:
PTokenFactory
Compiler Version
v0.7.4+commit.3f05b770
Contract Source Code (Solidity Standard Json-Input format)
pragma solidity ^0.7.4; import './PErc20Delegator.sol'; import './RegistryInterface.sol'; import './EIP20Interface.sol'; import './Strings.sol'; import "./IPriceFeeds.sol"; import "./ErrorReporter.sol"; import "./SafeMath.sol"; import "./PEtherDelegator.sol"; import "./PPIEDelegator.sol"; import "./Controller.sol"; import "./UniswapPriceOracle.sol"; contract PTokenFactory is FactoryErrorReporter { using strings for *; using SafeMath for uint; UniswapPriceOracle public oracle; uint public minUniswapLiquidity; // decimals for pToken uint8 public decimals = 8; // default parameters for pToken address public controller; address public interestRateModel; uint256 public initialExchangeRateMantissa; uint256 public initialReserveFactorMantissa; /** * Fired on creation new pToken proxy * @param newPToken Address of new PToken proxy contract */ event PTokenCreated(address newPToken); RegistryInterface public registry; constructor( RegistryInterface registry_, uint minUniswapLiquidity_, address oracle_, address _controller, address _interestRateModel, uint256 _initialExchangeRateMantissa, uint256 _initialReserveFactorMantissa ) { registry = registry_; minUniswapLiquidity = minUniswapLiquidity_; oracle = UniswapPriceOracle(oracle_); controller = _controller; interestRateModel = _interestRateModel; initialExchangeRateMantissa = _initialExchangeRateMantissa; initialReserveFactorMantissa = _initialReserveFactorMantissa; } /** * Creates new pToken proxy contract and adds pToken to the controller * @param underlying_ The address of the underlying asset */ function createPToken(address underlying_) external returns (uint) { IUniswapV2Pair _pair = IUniswapV2Pair(oracle.getUniswapPair(underlying_)); if (address(_pair) == address(0)) { return fail(Error.INVALID_POOL, FailureInfo.PAIR_IS_NOT_EXIST); } if (!reserveIsEnough(underlying_)) { return fail(Error.INVALID_POOL, FailureInfo.DEFICIENCY_ETH_LIQUIDITY_IN_POOL); } (string memory name, string memory symbol) = _createPTokenNameAndSymbol(underlying_); uint factor; uint exchangeRateMantissa; uint power = EIP20Interface(underlying_).decimals(); if (decimals >= power) { factor = 10**(decimals - power); exchangeRateMantissa = initialExchangeRateMantissa.div(factor); } else { factor = 10**(power - decimals); exchangeRateMantissa = initialExchangeRateMantissa.mul(factor); } PErc20Delegator newPToken = new PErc20Delegator(underlying_, controller, interestRateModel, exchangeRateMantissa, initialReserveFactorMantissa, name, symbol, decimals, address(registry)); uint256 result = Controller(controller)._supportMarket(address(newPToken)); if (result != 0) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SUPPORT_MARKET_BAD_RESULT); } registry.addPToken(underlying_, address(newPToken)); emit PTokenCreated(address(newPToken)); oracle.update(underlying_); return uint(Error.NO_ERROR); } function createPETH(address pETHImplementation_) external returns (uint) { if (msg.sender != getAdmin()) { return fail(Error.UNAUTHORIZED, FailureInfo.CREATE_PETH_POOL); } string memory name = "DeFiPie ETH"; string memory symbol = "pETH"; PETHDelegator newPETH = new PETHDelegator(pETHImplementation_, controller, interestRateModel, initialExchangeRateMantissa, initialReserveFactorMantissa, name, symbol, decimals, address(registry)); uint256 result = Controller(controller)._supportMarket(address(newPETH)); if (result != 0) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SUPPORT_MARKET_BAD_RESULT); } registry.addPETH(address(newPETH)); emit PTokenCreated(address(newPETH)); return uint(Error.NO_ERROR); } function createPPIE(address underlying_, address pPIEImplementation_) external returns (uint) { if (msg.sender != getAdmin()) { return fail(Error.UNAUTHORIZED, FailureInfo.CREATE_PPIE_POOL); } string memory name = "DeFiPie PIE"; string memory symbol = "pPIE"; PPIEDelegator newPPIE = new PPIEDelegator(underlying_, pPIEImplementation_, controller, interestRateModel, initialExchangeRateMantissa, initialReserveFactorMantissa, name, symbol, decimals, address(registry)); uint256 result = Controller(controller)._supportMarket(address(newPPIE)); if (result != 0) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SUPPORT_MARKET_BAD_RESULT); } registry.addPPIE(address(newPPIE)); emit PTokenCreated(address(newPPIE)); oracle.update(underlying_); return uint(Error.NO_ERROR); } function reserveIsEnough(address asset) public view returns (bool) { uint reserve; IUniswapV2Pair _pair = IUniswapV2Pair(oracle.getUniswapPair(asset)); if(_pair.token0() == asset) { (, reserve, ) = _pair.getReserves(); } else { (reserve, , ) = _pair.getReserves(); } return bool(reserve >= minUniswapLiquidity); } function setMinUniswapLiquidity(uint minUniswapLiquidity_) public returns (uint) { if (msg.sender != getAdmin()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MIN_LIQUIDITY_OWNER_CHECK); } minUniswapLiquidity = minUniswapLiquidity_; return uint(Error.NO_ERROR); } function setOracle(address oracle_) public returns (uint) { if (msg.sender != getAdmin()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_ORACLE); } oracle = UniswapPriceOracle(oracle_); return uint(Error.NO_ERROR); } /** * Sets address of actual controller contract * @return uint 0 = success, otherwise a failure (see ErrorReporter.sol for details) */ function setController(address newController) external returns (uint) { if (msg.sender != getAdmin()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_CONTROLLER); } controller = newController; return(uint(Error.NO_ERROR)); } /** * Sets address of actual interestRateModel contract * @return uint 0 = success, otherwise a failure (see ErrorReporter.sol for details) */ function setInterestRateModel(address newInterestRateModel) external returns (uint) { if (msg.sender != getAdmin()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_INTEREST_RATE_MODEL); } interestRateModel = newInterestRateModel; return(uint(Error.NO_ERROR)); } /** * Sets initial exchange rate * @return uint 0 = success, otherwise a failure (see ErrorReporter.sol for details) */ function setInitialExchangeRateMantissa(uint _initialExchangeRateMantissa) external returns (uint) { if (msg.sender != getAdmin()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_EXCHANGE_RATE); } initialExchangeRateMantissa = _initialExchangeRateMantissa; return(uint(Error.NO_ERROR)); } function setInitialReserveFactorMantissa(uint _initialReserveFactorMantissa) external returns (uint) { if (msg.sender != getAdmin()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_RESERVE_FACTOR); } initialReserveFactorMantissa = _initialReserveFactorMantissa; return(uint(Error.NO_ERROR)); } function setPTokenDecimals(uint _decimals) external returns (uint) { if (msg.sender != getAdmin()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_DECIMALS); } decimals = uint8(_decimals); return(uint(Error.NO_ERROR)); } function getAdmin() public view returns(address payable) { return registry.admin(); } function _createPTokenNameAndSymbol(address underlying) internal view returns (string memory, string memory) { string memory name = ("DeFiPie ".toSlice().concat(EIP20Interface(underlying).name().toSlice())); string memory symbol = ("p".toSlice().concat(EIP20Interface(underlying).symbol().toSlice())); return (name, symbol); } }
pragma solidity ^0.7.4; /** * @title Careful Math * @author DeFiPie * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } }
pragma solidity ^0.7.4; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./PriceOracle.sol"; import "./ControllerInterface.sol"; import "./ControllerStorage.sol"; import "./PTokenInterfaces.sol"; import "./EIP20Interface.sol"; import "./Unitroller.sol"; /** * @title DeFiPie's Controller Contract * @author DeFiPie */ contract Controller is ControllerStorage, ControllerInterface, ControllerErrorReporter, Exponential { /// @notice Emitted when an admin supports a market event MarketListed(address pToken); /// @notice Emitted when an account enters a market event MarketEntered(address pToken, address account); /// @notice Emitted when an account exits a market event MarketExited(address pToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(address pToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when maxAssets is changed by admin event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(address pToken, string action, bool pauseState); /// @notice Emitted when market pieed status is changed event MarketPied(address pToken, bool isPied); /// @notice Emitted when PIE rate is changed event NewPieRate(uint oldPieRate, uint newPieRate); /// @notice Emitted when a new PIE speed is calculated for a market event PieSpeedUpdated(address indexed pToken, uint newSpeed); /// @notice Emitted when PIE is distributed to a supplier event DistributedSupplierPie(address indexed pToken, address indexed supplier, uint pieDelta, uint pieSupplyIndex); /// @notice Emitted when PIE is distributed to a borrower event DistributedBorrowerPie(address indexed pToken, address indexed borrower, uint pieDelta, uint pieBorrowIndex); /// @notice The threshold above which the flywheel transfers PIE, in wei uint public constant pieClaimThreshold = 0.001e18; /// @notice The initial PIE index for a market uint224 public constant pieInitialIndex = 1e36; // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // liquidationIncentiveMantissa must be no less than this value uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 constructor() { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (address[] memory) { address[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param pToken The pToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, address pToken) external view returns (bool) { return markets[pToken].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param pTokens The list of addresses of the pToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory pTokens) public override returns (uint[] memory) { uint len = pTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { address pToken = pTokens[i]; results[i] = uint(addToMarketInternal(pToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param pToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(address pToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[pToken]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } if (accountAssets[borrower].length >= maxAssets) { // no space, cannot join return Error.TOO_MANY_ASSETS; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(pToken); emit MarketEntered(pToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing neccessary collateral for an outstanding borrow. * @param pTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address pTokenAddress) external override returns (uint) { address pToken = pTokenAddress; /* Get sender tokensHeld and amountOwed underlying from the pToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = PTokenInterface(pToken).getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(pTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[pToken]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set pToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete pToken from the account’s list of assets */ // load into memory for faster iteration address[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == pToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 address[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.pop(); //storedList.length--; emit MarketExited(pToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param pToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address pToken, address minter, uint mintAmount) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[pToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[pToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving updatePieSupplyIndex(pToken); distributeSupplierPie(pToken, minter, false); return uint(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param pToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of pTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address pToken, address redeemer, uint redeemTokens) external override returns (uint) { uint allowed = redeemAllowedInternal(pToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updatePieSupplyIndex(pToken); distributeSupplierPie(pToken, redeemer, false); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address pToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[pToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[pToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, pToken, redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param pToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address pToken, address redeemer, uint redeemAmount, uint redeemTokens) external override { // Shh - currently unused // pToken; // redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param pToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address pToken, address borrower, uint borrowAmount) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[pToken], "borrow is paused"); if (!markets[pToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } Error err; if (!markets[pToken].accountMembership[borrower]) { // only pTokens may call borrowAllowed if borrower not in market require(msg.sender == pToken, "sender must be pToken"); // attempt to add borrower to the market err = addToMarketInternal(msg.sender, borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[pToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(pToken) == 0) { return uint(Error.PRICE_ERROR); } uint shortfall; (err, , shortfall) = getHypotheticalAccountLiquidityInternal(borrower, pToken, 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: PTokenInterface(pToken).borrowIndex()}); updatePieBorrowIndex(pToken, borrowIndex); distributeBorrowerPie(pToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param pToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address pToken, address payer, address borrower, uint repayAmount ) external override returns (uint) { // Shh - currently unused // payer; // borrower; // repayAmount; if (!markets[pToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: PTokenInterface(pToken).borrowIndex()}); updatePieBorrowIndex(pToken, borrowIndex); distributeBorrowerPie(pToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } /** * @notice Checks if the liquidation should be allowed to occur * @param pTokenBorrowed Asset which was borrowed by the borrower * @param pTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address pTokenBorrowed, address pTokenCollateral, address liquidator, address borrower, uint repayAmount ) external override returns (uint) { // Shh - currently unused liquidator; if (!markets[pTokenBorrowed].isListed || !markets[pTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = PTokenInterface(pTokenBorrowed).borrowBalanceStored(borrower); (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Checks if the seizing of assets should be allowed to occur * @param pTokenCollateral Asset which was used as collateral and will be seized * @param pTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address pTokenCollateral, address pTokenBorrowed, address liquidator, address borrower, uint seizeTokens ) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused // seizeTokens; if (!markets[pTokenCollateral].isListed || !markets[pTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (PTokenInterface(pTokenCollateral).controller() != PTokenInterface(pTokenBorrowed).controller()) { return uint(Error.CONTROLLER_MISMATCH); } // Keep the flywheel moving updatePieSupplyIndex(pTokenCollateral); distributeSupplierPie(pTokenCollateral, borrower, false); distributeSupplierPie(pTokenCollateral, liquidator, false); return uint(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param pToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of pTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed( address pToken, address src, address dst, uint transferTokens ) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(pToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updatePieSupplyIndex(pToken); distributeSupplierPie(pToken, src, false); distributeSupplierPie(pToken, dst, false); return uint(Error.NO_ERROR); } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `pTokenBalance` is the number of pTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint pTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, address(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, address(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param pTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address pTokenModify, uint redeemTokens, uint borrowAmount ) public view virtual returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, pTokenModify, redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param pTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral pToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, address pTokenModify, uint redeemTokens, uint borrowAmount ) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; MathError mErr; // For each asset the account is in address[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; // Read the balances and exchange rate from the pToken (oErr, vars.pTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = PTokenInterface(asset).getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) (mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumCollateral += tokensToDenom * pTokenBalance (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.pTokenBalance, vars.sumCollateral); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumBorrowPlusEffects += oraclePrice * borrowBalance (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // Calculate effects of interacting with pTokenModify if (asset == pTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in pToken.liquidateBorrowFresh) * @param pTokenBorrowed The address of the borrowed pToken * @param pTokenCollateral The address of the collateral pToken * @param actualRepayAmount The amount of pTokenBorrowed underlying to convert into pTokenCollateral tokens * @return (errorCode, number of pTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens( address pTokenBorrowed, address pTokenCollateral, uint actualRepayAmount ) external view override returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(pTokenBorrowed); uint priceCollateralMantissa = oracle.getUnderlyingPrice(pTokenCollateral); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = PTokenInterface(pTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; MathError mathErr; (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, ratio) = divExp(numerator, denominator); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the controller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the controller PriceOracle oldOracle = oracle; // Set controller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets a PIE address for the controller * @return uint 0=success */ function _setPieAddress(address pieAddress_) public returns (uint) { require(msg.sender == admin && pieAddress == address(0),"pie address may only be initialized once"); pieAddress = pieAddress_; return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { 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); } uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param pToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(address pToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[pToken]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } oracle.updateUnderlyingPrice(pToken); // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(pToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(pToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets maxAssets which controls how many markets can be entered * @dev Admin function to set maxAssets * @param newMaxAssets New max assets * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setMaxAssets(uint newMaxAssets) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK); } uint oldMaxAssets = maxAssets; maxAssets = newMaxAssets; emit NewMaxAssets(oldMaxAssets, newMaxAssets); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Check de-scaled min <= newLiquidationIncentive <= max 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); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param pToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(address pToken) external returns (uint) { if (msg.sender != admin && msg.sender != factory) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[pToken].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } PTokenInterface(pToken).isPToken(); // Sanity check to make sure its really a PToken _addMarketInternal(pToken); Market storage newMarket = markets[pToken]; newMarket.isListed = true; emit MarketListed(pToken); return uint(Error.NO_ERROR); } function _addMarketInternal(address pToken) internal { require(markets[pToken].isListed == false, "market already added"); allMarkets.push(pToken); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(address pToken, bool state) public returns (bool) { require(markets[pToken].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[pToken] = state; emit ActionPaused(pToken, "Mint", state); return state; } function _setBorrowPaused(address pToken, bool state) public returns (bool) { require(markets[pToken].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[pToken] = state; emit ActionPaused(pToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _setFactoryContract(address _factory) external returns (uint) { if (msg.sender != admin) { return uint(Error.UNAUTHORIZED); } factory = _factory; return uint(Error.NO_ERROR); } function _become(address payable unitroller) public { require(msg.sender == Unitroller(unitroller).admin(), "only unitroller admin can change brains"); require(Unitroller(unitroller)._acceptImplementation() == 0, "change not authorized"); } /*** Pie Distribution ***/ function refreshPieSpeeds() public { require(msg.sender == tx.origin, "only externally owned accounts may refresh speeds"); refreshPieSpeedsInternal(); } /** * @notice Recalculate and update PIE speeds for all PIE markets */ function refreshPieSpeedsInternal() internal { address[] memory allMarkets_ = allMarkets; for (uint i = 0; i < allMarkets_.length; i++) { address pToken = allMarkets_[i]; Exp memory borrowIndex = Exp({mantissa: PTokenInterface(pToken).borrowIndex()}); updatePieSupplyIndex(pToken); updatePieBorrowIndex(pToken, borrowIndex); } Exp memory totalUtility = Exp({mantissa: 0}); Exp[] memory utilities = new Exp[](allMarkets_.length); for (uint i = 0; i < allMarkets_.length; i++) { address pToken = allMarkets_[i]; if (markets[pToken].isPied) { oracle.updateUnderlyingPrice(pToken); Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(pToken)}); Exp memory interestPerBlock = mul_(Exp({mantissa: PTokenInterface(pToken).borrowRatePerBlock()}), PTokenInterface(pToken).totalBorrows()); Exp memory utility = mul_(interestPerBlock, assetPrice); utilities[i] = utility; totalUtility = add_(totalUtility, utility); } } for (uint i = 0; i < allMarkets_.length; i++) { address pToken = allMarkets[i]; uint newSpeed = totalUtility.mantissa > 0 ? mul_(pieRate, div_(utilities[i], totalUtility)) : 0; pieSpeeds[pToken] = newSpeed; emit PieSpeedUpdated(pToken, newSpeed); } } /** * @notice Accrue PIE to the market by updating the supply index * @param pToken The market whose supply index to update */ function updatePieSupplyIndex(address pToken) internal { PieMarketState storage supplyState = pieSupplyState[pToken]; uint supplySpeed = pieSpeeds[pToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = PTokenInterface(pToken).totalSupply(); uint pieAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(pieAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); pieSupplyState[pToken] = PieMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { supplyState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Accrue PIE to the market by updating the borrow index * @param pToken The market whose borrow index to update */ function updatePieBorrowIndex(address pToken, Exp memory marketBorrowIndex) internal { PieMarketState storage borrowState = pieBorrowState[pToken]; uint borrowSpeed = pieSpeeds[pToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(borrowState.block)); if (deltaBlocks > 0 && borrowSpeed > 0) { uint borrowAmount = div_(PTokenInterface(pToken).totalBorrows(), marketBorrowIndex); uint pieAccrued = mul_(deltaBlocks, borrowSpeed); Double memory ratio = borrowAmount > 0 ? fraction(pieAccrued, borrowAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: borrowState.index}), ratio); pieBorrowState[pToken] = PieMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { borrowState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Calculate PIE accrued by a supplier and possibly transfer it to them * @param pToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute PIE to */ function distributeSupplierPie(address pToken, address supplier, bool distributeAll) internal { PieMarketState storage supplyState = pieSupplyState[pToken]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: pieSupplierIndex[pToken][supplier]}); pieSupplierIndex[pToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = pieInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = PTokenInterface(pToken).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); uint supplierAccrued = add_(pieAccrued[supplier], supplierDelta); pieAccrued[supplier] = transferPie(supplier, supplierAccrued, distributeAll ? 0 : pieClaimThreshold); emit DistributedSupplierPie(pToken, supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate PIE accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param pToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute PIE to */ function distributeBorrowerPie( address pToken, address borrower, Exp memory marketBorrowIndex, bool distributeAll ) internal { PieMarketState storage borrowState = pieBorrowState[pToken]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: pieBorrowerIndex[pToken][borrower]}); pieBorrowerIndex[pToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(PTokenInterface(pToken).borrowBalanceStored(borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); uint borrowerAccrued = add_(pieAccrued[borrower], borrowerDelta); pieAccrued[borrower] = transferPie(borrower, borrowerAccrued, distributeAll ? 0 : pieClaimThreshold); emit DistributedBorrowerPie(pToken, borrower, borrowerDelta, borrowIndex.mantissa); } } /** * @notice Transfer PIE to the user, if they are above the threshold * @dev Note: If there is not enough PIE, we do not perform the transfer all. * @param user The address of the user to transfer PIE to * @param userAccrued The amount of PIE to (possibly) transfer * @return The amount of PIE which was NOT transferred to the user */ function transferPie(address user, uint userAccrued, uint threshold) internal returns (uint) { if (userAccrued >= threshold && userAccrued > 0) { address pie = getPieAddress(); uint pieRemaining = EIP20Interface(pie).balanceOf(address(this)); if (userAccrued <= pieRemaining) { EIP20Interface(pie).transfer(user, userAccrued); return 0; } } return userAccrued; } /** * @notice Claim all the pie accrued by holder in all markets * @param holder The address to claim PIE for */ function claimPie(address holder) public { claimPie(holder, allMarkets); } /** * @notice Claim all the pie accrued by holder in the specified markets * @param holder The address to claim PIE for * @param pTokens The list of markets to claim PIE in */ function claimPie(address holder, address[] memory pTokens) public { address[] memory holders = new address[](1); holders[0] = holder; claimPie(holders, pTokens, true, true); } /** * @notice Claim all pie accrued by the holders * @param holders The addresses to claim PIE for * @param pTokens The list of markets to claim PIE in * @param borrowers Whether or not to claim PIE earned by borrowing * @param suppliers Whether or not to claim PIE earned by supplying */ function claimPie(address[] memory holders, address[] memory pTokens, bool borrowers, bool suppliers) public { for (uint i = 0; i < pTokens.length; i++) { address pToken = pTokens[i]; require(markets[pToken].isListed, "market must be listed"); if (borrowers == true) { Exp memory borrowIndex = Exp({mantissa: PTokenInterface(pToken).borrowIndex()}); updatePieBorrowIndex(pToken, borrowIndex); for (uint j = 0; j < holders.length; j++) { distributeBorrowerPie(pToken, holders[j], borrowIndex, true); } } if (suppliers == true) { updatePieSupplyIndex(pToken); for (uint j = 0; j < holders.length; j++) { distributeSupplierPie(pToken, holders[j], true); } } } } /*** Pie Distribution Admin ***/ /** * @notice Set the amount of PIE distributed per block * @param pieRate_ The amount of PIE wei per block to distribute */ function _setPieRate(uint pieRate_) public { require(msg.sender == admin, "only admin can change pie rate"); uint oldRate = pieRate; pieRate = pieRate_; emit NewPieRate(oldRate, pieRate_); refreshPieSpeedsInternal(); } function _addPieMarkets(address[] memory pTokens) public { require(msg.sender == admin, "only admin can add pie market"); for (uint i = 0; i < pTokens.length; i++) { _addPieMarketInternal(pTokens[i]); } refreshPieSpeedsInternal(); } function _addPieMarketInternal(address pToken) internal { Market storage market = markets[pToken]; require(market.isListed == true, "pie market is not listed"); require(market.isPied == false, "pie market already added"); market.isPied = true; emit MarketPied(pToken, true); if (pieSupplyState[pToken].index == 0 && pieSupplyState[pToken].block == 0) { pieSupplyState[pToken] = PieMarketState({ index: pieInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } if (pieBorrowState[pToken].index == 0 && pieBorrowState[pToken].block == 0) { pieBorrowState[pToken] = PieMarketState({ index: pieInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } } /** * @notice Remove a market from pieMarkets, preventing it from earning PIE in the flywheel * @param pToken The address of the market to drop */ function _dropPieMarket(address pToken) public { require(msg.sender == admin, "only admin can drop pie market"); Market storage market = markets[pToken]; require(market.isPied == true, "market is not a pie market"); market.isPied = false; emit MarketPied(pToken, false); refreshPieSpeedsInternal(); } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (address[] memory) { return allMarkets; } function getBlockNumber() public view virtual returns (uint) { return block.number; } /** * @notice Return the address of the PIE token * @return The address of PIE */ function getPieAddress() public view virtual returns (address) { return pieAddress; } function getOracle() public view override returns (PriceOracle) { return oracle; } }
pragma solidity ^0.7.4; import "./PriceOracle.sol"; abstract contract ControllerInterface { /// @notice Indicator that this is a Controller contract (for inspection) bool public constant isController = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata pTokens) external virtual returns (uint[] memory); function exitMarket(address pToken) external virtual returns (uint); /*** Policy Hooks ***/ function mintAllowed(address pToken, address minter, uint mintAmount) external virtual returns (uint); function redeemAllowed(address pToken, address redeemer, uint redeemTokens) external virtual returns (uint); function redeemVerify(address pToken, address redeemer, uint redeemAmount, uint redeemTokens) external virtual; function borrowAllowed(address pToken, address borrower, uint borrowAmount) external virtual returns (uint); function repayBorrowAllowed( address pToken, address payer, address borrower, uint repayAmount) external virtual returns (uint); function liquidateBorrowAllowed( address pTokenBorrowed, address pTokenCollateral, address liquidator, address borrower, uint repayAmount) external virtual returns (uint); function seizeAllowed( address pTokenCollateral, address pTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external virtual returns (uint); function transferAllowed(address pToken, address src, address dst, uint transferTokens) external virtual returns (uint); /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address pTokenBorrowed, address pTokenCollateral, uint repayAmount) external view virtual returns (uint, uint); function getOracle() external view virtual returns (PriceOracle); }
pragma solidity ^0.7.4; import "./PriceOracle.sol"; contract UnitrollerAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of Unitroller */ address public controllerImplementation; /** * @notice Pending brains of Unitroller */ address public pendingControllerImplementation; } contract ControllerStorage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint public liquidationIncentiveMantissa; /** * @notice Max number of assets a single account can participate in (borrow or use as collateral) */ uint public maxAssets; /** * @notice Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => address[]) public accountAssets; /// @notice isListed Whether or not this market is listed /** * @notice collateralFactorMantissa Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ /// @notice accountMembership Per-market mapping of "accounts in this asset" /// @notice isPied Whether or not this market receives PIE struct Market { bool isListed; uint collateralFactorMantissa; mapping(address => bool) accountMembership; bool isPied; } /** * @notice Official mapping of pTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ 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; /// @notice index The market's last updated pieBorrowIndex or pieSupplyIndex /// @notice block The block number the index was last updated at struct PieMarketState { uint224 index; uint32 block; } /// @notice A list of all markets address[] public allMarkets; /// @notice The rate at which the flywheel distributes PIE, per block uint public pieRate; /// @notice Address of the PIE token address public pieAddress; // @notice Address of the factory address public factory; /// @notice The portion of pieRate that each market currently receives mapping(address => uint) public pieSpeeds; /// @notice The PIE market supply state for each market mapping(address => PieMarketState) public pieSupplyState; /// @notice The PIE market borrow state for each market mapping(address => PieMarketState) public pieBorrowState; /// @notice The PIE borrow index for each market for each supplier as of the last time they accrued PIE mapping(address => mapping(address => uint)) public pieSupplierIndex; /// @notice The PIE borrow index for each market for each borrower as of the last time they accrued PIE mapping(address => mapping(address => uint)) public pieBorrowerIndex; /// @notice The PIE accrued but not yet transferred to each user mapping(address => uint) public pieAccrued; }
pragma solidity ^0.7.4; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); }
pragma solidity ^0.7.4; contract ControllerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, CONTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, PRICE_UPDATE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, 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_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, CONTROLLER_REJECTION, CONTROLLER_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 } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ 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_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_CONTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_CONTROLLER_REJECTION, LIQUIDATE_CONTROLLER_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_CONTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_CONTROLLER_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, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_CONTROLLER_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, 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_CONTROLLER_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_CONTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_CONTROLLER_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, SET_NEW_IMPLEMENTATION } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract OracleErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, UPDATE_PRICE } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, NO_RESERVES, PERIOD_NOT_ELAPSED, SET_NEW_ADDRESSES, SET_NEW_IMPLEMENTATION, SET_PENDING_ADMIN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } } contract FactoryErrorReporter { enum Error { NO_ERROR, INVALID_POOL, MARKET_NOT_LISTED, UNAUTHORIZED } //TODO: Add more cases enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, CREATE_PETH_POOL, CREATE_PPIE_POOL, DEFICIENCY_ETH_LIQUIDITY_IN_POOL, PAIR_IS_NOT_EXIST, SET_MIN_LIQUIDITY_OWNER_CHECK, SET_NEW_CONTROLLER, SET_NEW_DECIMALS, SET_NEW_EXCHANGE_RATE, SET_NEW_IMPLEMENTATION, SET_NEW_INTEREST_RATE_MODEL, SET_NEW_ORACLE, SET_NEW_RESERVE_FACTOR, SET_PENDING_ADMIN_OWNER_CHECK, SUPPORT_MARKET_BAD_RESULT } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } } contract RegistryErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED } //TODO: Add more cases enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, SET_NEW_IMPLEMENTATION, SET_PENDING_ADMIN_OWNER_CHECK, SET_NEW_FACTORY } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } }
pragma solidity ^0.7.4; import "./CarefulMath.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author DeFiPie * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction_) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction_)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } }
pragma solidity ^0.7.4; import "./SafeMath.sol"; interface AggregatorInterface { function latestAnswer() external view returns (int256); } library UQ112x112 { uint224 constant Q112 = 2**112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } } library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } } interface IUniswapV2Pair { function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); } interface IUniswapV2Factory { function getPair(address tokenA, address tokenB) external view returns (address pair); }
pragma solidity ^0.7.4; /** * @title DeFiPie's InterestRateModel Interface * @author DeFiPie */ abstract contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view virtual returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view virtual returns (uint); }
pragma solidity ^0.7.4; import "./ProxyWithRegistry.sol"; import "./RegistryInterface.sol"; /** * @title DeFiPie's PErc20Delegator Contract * @notice PTokens which wrap an EIP-20 underlying and delegate to an implementation * @author DeFiPie */ contract PErc20Delegator is ProxyWithRegistry { /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @param controller_ The address of the Controller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param initialReserveFactorMantissa_ The initial reserve factor, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param registry_ The address of the registry contract */ constructor( address underlying_, address controller_, address interestRateModel_, uint initialExchangeRateMantissa_, uint initialReserveFactorMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address registry_ ) { // Set registry _setRegistry(registry_); // First delegate gets to initialize the delegator (i.e. storage contract) delegateTo(_pTokenImplementation(), abi.encodeWithSignature("initialize(address,address,address,address,uint256,uint256,string,string,uint8)", underlying_, registry_, controller_, interestRateModel_, initialExchangeRateMantissa_, initialReserveFactorMantissa_, name_, symbol_, decimals_)); } /** * @notice Internal method to delegate execution to another contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param callee The contract to delegatecall * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateTo(address callee, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize()) } } return returnData; } function delegateAndReturn() internal returns (bytes memory) { (bool success, ) = _pTokenImplementation().delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize()) switch success case 0 { revert(free_mem_ptr, returndatasize()) } default { return(free_mem_ptr, returndatasize()) } } } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts */ fallback() external payable { require(msg.value == 0,"PErc20Delegator:fallback: cannot send value to fallback"); // delegate all other functions to current implementation delegateAndReturn(); } receive() external payable { require(msg.value == 0,"PErc20Delegator:receive: cannot send value to receive"); } }
pragma solidity ^0.7.4; import "./ProxyWithRegistry.sol"; import "./RegistryInterface.sol"; import "./ErrorReporter.sol"; /** * @title DeFiPie's PETHDelegator Contract * @notice PETH which wrap a delegate to an implementation * @author DeFiPie */ contract PETHDelegator is ImplementationStorage, ProxyWithRegistry, TokenErrorReporter { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Construct a new money market * @param pETHImplementation_ The address of the PEthImplementation * @param controller_ The address of the Controller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param initialReserveFactorMantissa_ The initial reserve factor, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param registry_ The address of the registry contract */ constructor( address pETHImplementation_, address controller_, address interestRateModel_, uint initialExchangeRateMantissa_, uint initialReserveFactorMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address registry_ ) { // Set registry _setRegistry(registry_); _setImplementation(pETHImplementation_); // First delegate gets to initialize the delegator (i.e. storage contract) delegateTo(implementation, abi.encodeWithSignature("initialize(address,address,address,uint256,uint256,string,string,uint8)", registry_, controller_, interestRateModel_, initialExchangeRateMantissa_, initialReserveFactorMantissa_, name_, symbol_, decimals_)); } /** * @notice Internal method to delegate execution to another contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param callee The contract to delegatecall * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateTo(address callee, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize()) } } return returnData; } function delegateAndReturn() private returns (bytes memory) { (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize()) switch success case 0 { revert(free_mem_ptr, returndatasize()) } default { return(free_mem_ptr, returndatasize()) } } } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts */ fallback() external payable { // delegate all other functions to current implementation delegateAndReturn(); } receive() external payable { // delegate all other functions to current implementation delegateAndReturn(); } function setImplementation(address newImplementation) external returns(uint) { if (msg.sender != RegistryInterface(registry).admin()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_IMPLEMENTATION); } address oldImplementation = implementation; _setImplementation(newImplementation); emit NewImplementation(oldImplementation, implementation); return(uint(Error.NO_ERROR)); } }
pragma solidity ^0.7.4; import "./ProxyWithRegistry.sol"; import "./RegistryInterface.sol"; import "./ErrorReporter.sol"; /** * @title DeFiPie's PPIEDelegator Contract * @notice PPIE which wrap an EIP-20 underlying and delegate to an implementation * @author DeFiPie */ contract PPIEDelegator is ImplementationStorage, ProxyWithRegistry, TokenErrorReporter { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @param pPIEImplementation_ The address of the PPIEImplementation * @param controller_ The address of the Controller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param initialReserveFactorMantissa_ The initial reserve factor, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param registry_ The address of the registry contract */ constructor( address underlying_, address pPIEImplementation_, address controller_, address interestRateModel_, uint initialExchangeRateMantissa_, uint initialReserveFactorMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address registry_ ) { // Set registry _setRegistry(registry_); _setImplementation(pPIEImplementation_); // First delegate gets to initialize the delegator (i.e. storage contract) delegateTo(implementation, abi.encodeWithSignature("initialize(address,address,address,address,uint256,uint256,string,string,uint8)", underlying_, registry_, controller_, interestRateModel_, initialExchangeRateMantissa_, initialReserveFactorMantissa_, name_, symbol_, decimals_)); } /** * @notice Internal method to delegate execution to another contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param callee The contract to delegatecall * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateTo(address callee, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize()) } } return returnData; } function delegateAndReturn() internal returns (bytes memory) { (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize()) switch success case 0 { revert(free_mem_ptr, returndatasize()) } default { return(free_mem_ptr, returndatasize()) } } } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts */ fallback() external payable { require(msg.value == 0,"PPIEDelegator:fallback: cannot send value to fallback"); // delegate all other functions to current implementation delegateAndReturn(); } receive() external payable { require(msg.value == 0,"PPIEDelegator:receive: cannot send value to receive"); } function setImplementation(address newImplementation) external returns(uint) { if (msg.sender != RegistryInterface(registry).admin()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_IMPLEMENTATION); } address oldImplementation = implementation; _setImplementation(newImplementation); emit NewImplementation(oldImplementation, implementation); return(uint(Error.NO_ERROR)); } }
pragma solidity ^0.7.4; import "./ControllerInterface.sol"; import "./InterestRateModel.sol"; import "./ProxyWithRegistry.sol"; contract PTokenStorage is ProxyWithRegistryStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @dev Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal constant borrowRateMaxMantissa = 0.0005e16; /** * @dev Maximum fraction of interest that can be set aside for reserves */ uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Contract which oversees inter-pToken operations */ ControllerInterface public controller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @dev Initial exchange rate used when minting the first PTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @dev Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @dev Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } /** * @dev Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } abstract contract PTokenInterface is PTokenStorage { /** * @notice Indicator that this is a PToken contract (for inspection) */ bool public constant isPToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows, uint totalReserves); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address pTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when controller is changed */ event NewController(ControllerInterface oldController, ControllerInterface newController); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /*** User Interface ***/ function transfer(address dst, uint amount) external virtual returns (bool); function transferFrom(address src, address dst, uint amount) external virtual returns (bool); function approve(address spender, uint amount) external virtual returns (bool); function allowance(address owner, address spender) external view virtual returns (uint); function balanceOf(address owner) external view virtual returns (uint); function balanceOfUnderlying(address owner) external virtual returns (uint); function getAccountSnapshot(address account) external view virtual returns (uint, uint, uint, uint); function borrowRatePerBlock() external view virtual returns (uint); function supplyRatePerBlock() external view virtual returns (uint); function totalBorrowsCurrent() external virtual returns (uint); function borrowBalanceCurrent(address account) external virtual returns (uint); function borrowBalanceStored(address account) public view virtual returns (uint); function exchangeRateCurrent() public virtual returns (uint); function exchangeRateStored() public view virtual returns (uint); function getCash() external view virtual returns (uint); function accrueInterest() public virtual returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external virtual returns (uint); /*** Admin Functions ***/ function _setController(ControllerInterface newController) public virtual returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external virtual returns (uint); function _reduceReserves(uint reduceAmount) external virtual returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public virtual returns (uint); } contract PErc20Storage { /** * @notice Underlying asset for this PToken */ address public underlying; } abstract contract PErc20Interface is PErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external virtual returns (uint); function redeem(uint redeemTokens) external virtual returns (uint); function redeemUnderlying(uint redeemAmount) external virtual returns (uint); function borrow(uint borrowAmount) external virtual returns (uint); function repayBorrow(uint repayAmount) external virtual returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external virtual returns (uint); function liquidateBorrow(address borrower, uint repayAmount, PTokenInterface pTokenCollateral) external virtual returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external virtual returns (uint); } contract PPIEStorage { /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; } abstract contract PPIEInterface is PPIEStorage { /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); function delegate(address delegatee) external virtual; function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external virtual; function getCurrentVotes(address account) external view virtual returns (uint96); function getPriorVotes(address account, uint blockNumber) external view virtual returns (uint96); }
pragma solidity ^0.7.4; abstract contract PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; event PriceUpdated(address asset, uint price); /** * @notice Get the underlying price of a pToken asset * @param pToken The pToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(address pToken) external view virtual returns (uint); function updateUnderlyingPrice(address pToken) external virtual returns (uint); }
pragma solidity ^0.7.4; import "./RegistryInterface.sol"; contract ProxyWithRegistryStorage { /** * @notice Address of the registry contract */ address public registry; } abstract contract ProxyWithRegistryInterface is ProxyWithRegistryStorage { function _setRegistry(address _registry) internal virtual; function _pTokenImplementation() internal view virtual returns (address); } contract ProxyWithRegistry is ProxyWithRegistryInterface { /** * Returns actual address of the implementation contract from current registry * @return registry Address of the registry */ function _pTokenImplementation() internal view override returns (address) { return RegistryInterface(registry).pTokenImplementation(); } function _setRegistry(address _registry) internal override { registry = _registry; } } contract ImplementationStorage { address public implementation; function _setImplementation(address implementation_) internal { implementation = implementation_; } }
pragma solidity ^0.7.4; import "./PTokenInterfaces.sol"; import './RegistryStorage.sol'; import "./ErrorReporter.sol"; contract Registry is RegistryStorage, RegistryErrorReporter { address public factory; address public pTokenImplementation; mapping (address => address) public pTokens; address public pETH; address public pPIE; /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Emitted when PTokenImplementation is changed */ event NewPTokenImplementation(address oldImplementation, address newImplementation); /** * @notice Emitted when Factory address is changed */ event NewFactory(address oldFactory, address newFactory); constructor() {} function initialize(address _pTokenImplementation) public { require(pTokenImplementation == address(0), "Registry may only be initialized once"); pTokenImplementation = _pTokenImplementation; } /** * Sets address of actual pToken implementation contract * @return uint 0 = success, otherwise a failure (see ErrorReporter.sol for details) */ function setPTokenImplementation(address newImplementation) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_IMPLEMENTATION); } address oldImplementation = pTokenImplementation; pTokenImplementation = newImplementation; emit NewPTokenImplementation(oldImplementation, pTokenImplementation); return(uint(Error.NO_ERROR)); } function _setFactoryContract(address _factory) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_FACTORY); } address oldFactory = factory; factory = _factory; emit NewFactory(oldFactory, factory); return uint(Error.NO_ERROR); } function addPToken(address underlying, address pToken) public returns (uint) { require(msg.sender == admin || msg.sender == factory, "Only admin or factory can add PTokens"); PTokenInterface(pToken).isPToken(); // Sanity check to make sure its really a PToken require(pTokens[underlying] == address(0), "Token already added"); pTokens[underlying] = pToken; return uint(Error.NO_ERROR); } function addPETH(address pETH_) public returns (uint) { require(msg.sender == admin || msg.sender == factory, "Only admin or factory can add PETH"); PTokenInterface(pETH_).isPToken(); // Sanity check to make sure its really a PToken require(pETH == address(0), "ETH already added"); pETH = pETH_; return uint(Error.NO_ERROR); } function addPPIE(address pPIE_) public returns (uint) { require(msg.sender == admin || msg.sender == factory, "Only admin or factory can add PPIE"); PTokenInterface(pPIE_).isPToken(); // Sanity check to make sure its really a PToken require(pPIE == address(0), "PIE already added"); pPIE = pPIE_; return uint(Error.NO_ERROR); } }
pragma solidity ^0.7.4; interface RegistryInterface { /** * Returns admin address for cToken contracts * @return admin address */ function admin() external view returns (address payable); /** * Returns address of actual PToken implementation contract * @return Address of contract */ function pTokenImplementation() external view returns (address); function addPToken(address underlying, address pToken) external returns(uint); function addPETH(address pETH_) external returns(uint); function addPPIE(address pPIE_) external returns(uint); }
pragma solidity ^0.7.4; contract RegistryStorage { address public implementation; address public admin; address public pendingAdmin; }
pragma solidity ^0.7.4; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. * Reverts with custom message on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
/* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ pragma solidity ^0.7.4; library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint leng) private pure { // Copy word-length chunks while possible for(; leng >= 32; leng -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - leng) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string memory self) internal pure returns (slice memory) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal pure returns (uint) { uint ret; if (self == 0) return 0; if (uint(self) & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (uint(self) & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (uint(self) & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (uint(self) & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (uint(self) & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-terminated utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal pure returns (slice memory ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice memory self) internal pure returns (slice memory) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice memory self) internal pure returns (string memory) { string memory ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice memory self) internal pure returns (uint l) { // Starting at ptr-31 means the LSB will be the byte we care about uint ptr = self._ptr - 31; uint end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice memory self) internal pure returns (bool) { return self._len == 0; } /* * @dev Returns a negative number if `other` comes lexicographically after * `self`, a positive number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice memory self, slice memory other) internal pure returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; uint selfptr = self._ptr; uint otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint256 mask = uint256(-1); // 0xffff... if(shortest < 32) { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } uint256 diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice memory self, slice memory other) internal pure returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint l; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { l = 1; } else if(b < 0xE0) { l = 2; } else if(b < 0xF0) { l = 3; } else { l = 4; } // Check for truncated codepoints if (l > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += l; self._len -= l; rune._len = l; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice memory self) internal pure returns (slice memory ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice memory self) internal pure returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } uint b = word / divisor; if (b < 0x80) { ret = b; length = 1; } else if(b < 0xE0) { ret = b & 0x1F; length = 2; } else if(b < 0xF0) { ret = b & 0x0F; length = 3; } else { ret = b & 0x07; length = 4; } // Check for truncated codepoints if (length > self._len) { return 0; } for (uint i = 1; i < length; i++) { divisor = divisor / 256; b = (word / divisor) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice memory self) internal pure returns (bytes32 ret) { assembly { ret := keccak256(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } uint selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } uint selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } ptr = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr <= selfptr) return selfptr; ptr--; assembly { ptrdata := and(mload(ptr), mask) } } return ptr + needlelen; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice memory self, slice memory needle) internal pure returns (slice memory token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice memory self, slice memory needle) internal pure returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice memory self, slice memory needle) internal pure returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice memory self, slice memory other) internal pure returns (string memory) { string memory ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice memory self, slice[] memory parts) internal pure returns (string memory) { if (parts.length == 0) return ""; uint length = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) length += parts[i]._len; string memory ret = new string(length); uint retptr; assembly { retptr := add(ret, 32) } for(uint i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } }
pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./PriceOracle.sol"; import "./ErrorReporter.sol"; import "./PTokenInterfaces.sol"; import "./SafeMath.sol"; import "./IPriceFeeds.sol"; import "./UniswapPriceOracleStorage.sol"; import './Registry.sol'; import './EIP20Interface.sol'; contract UniswapPriceOracle is UniswapPriceOracleStorage, PriceOracle, OracleErrorReporter { using FixedPoint for *; using SafeMath for uint; Registry public registry; address public uniswapFactory; address public WETHUniswap; address public ETHUSDPriceFeed; struct cumulativePrice { FixedPoint.uq112x112 price0Average; FixedPoint.uq112x112 price1Average; uint price0CumulativePrevious; uint price1CumulativePrevious; uint32 blockTimestampPrevious; } mapping(address => cumulativePrice) public cumulativePrices; constructor() {} function initialize( address registry_, address uniswapFactory_, address WETHUniswap_, address ETHUSDPriceFeed_ ) public { require( registry == Registry(address(0)) && uniswapFactory == address(0) && WETHUniswap == address(0) && ETHUSDPriceFeed == address(0) , "UniswapPriceOracle may only be initialized once" ); registry = Registry(registry_); uniswapFactory = uniswapFactory_; WETHUniswap = WETHUniswap_; ETHUSDPriceFeed = ETHUSDPriceFeed_; } function update(address asset) public returns (uint) { IUniswapV2Pair pair = IUniswapV2Pair(getUniswapPair(asset)); uint112 reserve0; uint112 reserve1; uint32 blockTimestamp; (reserve0, reserve1, blockTimestamp) = pair.getReserves(); if (reserve0 == 0 || reserve1 == 0) { return fail(Error.UPDATE_PRICE, FailureInfo.NO_RESERVES); } if (!isPeriodElapsed(asset)) { return fail(Error.UPDATE_PRICE, FailureInfo.PERIOD_NOT_ELAPSED); } // check old pool or new if (isNewAssetForOracle(asset)) { // calc average price using reserves for young pools cumulativePrices[asset].price0Average = FixedPoint.uq112x112(uqdiv(encode(reserve1), reserve0)); cumulativePrices[asset].price1Average = FixedPoint.uq112x112(uqdiv(encode(reserve0), reserve1)); } else { uint32 timeElapsed = blockTimestamp - cumulativePrices[asset].blockTimestampPrevious; // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed cumulativePrices[asset].price0Average = FixedPoint.uq112x112(uint224((pair.price0CumulativeLast() - cumulativePrices[asset].price0CumulativePrevious) / timeElapsed)); cumulativePrices[asset].price1Average = FixedPoint.uq112x112(uint224((pair.price1CumulativeLast() - cumulativePrices[asset].price1CumulativePrevious) / timeElapsed)); } // update data cumulativePrices[asset].price0CumulativePrevious = pair.price0CumulativeLast(); cumulativePrices[asset].price1CumulativePrevious = pair.price1CumulativeLast(); cumulativePrices[asset].blockTimestampPrevious = blockTimestamp; emit PriceUpdated(asset, getCourseInETH(asset)); return uint(Error.NO_ERROR); } function getUniswapPair(address asset) public view returns (address) { IUniswapV2Factory factory = IUniswapV2Factory(uniswapFactory); return factory.getPair(WETHUniswap, asset); } function getUnderlyingPrice(address pToken) public view override returns (uint) { if (pToken == registry.pETH()) { return getPriceInUSD(registry.pETH()); } address asset = address(PErc20Interface(pToken).underlying()); uint price = getPriceInUSD(asset); uint decimals = EIP20Interface(asset).decimals(); return price.mul(10 ** (36 - decimals)).div(1e18); } function updateUnderlyingPrice(address pToken) public override returns (uint) { if (pToken == registry.pETH()) { return uint(Error.NO_ERROR); } address asset = address(PErc20Interface(pToken).underlying()); return update(asset); } // Get the most recent price for a asset in USD with 18 decimals of precision. function getPriceInUSD(address asset) public view virtual returns (uint) { uint ETHUSDPrice = uint(AggregatorInterface(ETHUSDPriceFeed).latestAnswer()); uint AssetETHCourse = getCourseInETH(asset); // div 1e8 is chainlink precision for ETH return ETHUSDPrice.mul(AssetETHCourse).div(1e8); } function getCourseInETH(address asset) public view returns(uint) { if (asset == registry.pETH()) { // ether always worth 1 return 1e18; } uint power = PTokenInterface(asset).decimals(); uint amountIn = 10**power; uint amountOut; address pair = getUniswapPair(asset); address token0 = IUniswapV2Pair(pair).token0(); address token1 = IUniswapV2Pair(pair).token1(); if (asset == token0) { amountOut = cumulativePrices[asset].price0Average.mul(amountIn).decode144(); } else { require(asset == token1, 'Oracle: INVALID_TOKEN'); amountOut = cumulativePrices[asset].price1Average.mul(amountIn).decode144(); } return amountOut; } function isNewAssetForOracle(address asset) public view returns (bool) { return bool(cumulativePrices[asset].blockTimestampPrevious == 0); } function isPeriodElapsed(address asset) public view returns (bool) { if (isNewAssetForOracle(asset)) { return true; } IUniswapV2Pair pair = IUniswapV2Pair(getUniswapPair(asset)); ( , , uint32 blockTimestamp) = pair.getReserves(); uint32 timeElapsed = blockTimestamp - cumulativePrices[asset].blockTimestampPrevious; return bool(timeElapsed > PERIOD); } // encode a uint112 as a UQ112x112 function encode(uint112 y) internal view returns (uint224 z) { z = uint224(y) * uint224(Q112); // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } function _setNewAddresses( address registry_, address uniswapFactory_, address WETHUniswap_, address ETHUSDPriceFeed_ ) external returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_ADDRESSES); } registry = Registry(registry_); uniswapFactory = uniswapFactory_; WETHUniswap = WETHUniswap_; ETHUSDPriceFeed = ETHUSDPriceFeed_; return uint(Error.NO_ERROR); } }
pragma solidity ^0.7.4; contract UniswapPriceOracleStorage { address public implementation; address public admin; address public pendingAdmin; uint Q112 = 2**112; uint public constant PERIOD = 10 minutes; }
pragma solidity ^0.7.4; import "./ErrorReporter.sol"; import "./ControllerStorage.sol"; /** * @title ControllerCore * @dev Storage for the controller is at this address, while execution is delegated to the `controllerImplementation`. * PTokens should reference this contract as their controller. */ contract Unitroller is UnitrollerAdminStorage, ControllerErrorReporter { /** * @notice Emitted when pendingControllerImplementation is changed */ event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); /** * @notice Emitted when pendingControllerImplementation is accepted, which means controller implementation is updated */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); constructor() { // Set admin to caller admin = msg.sender; } /*** Admin Functions ***/ function _setPendingImplementation(address newPendingImplementation) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK); } address oldPendingImplementation = pendingControllerImplementation; pendingControllerImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, pendingControllerImplementation); return uint(Error.NO_ERROR); } /** * @notice Accepts new implementation of controller. msg.sender must be pendingImplementation * @dev Admin function for new implementation to accept it's role as implementation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptImplementation() public returns (uint) { // Check caller is pendingImplementation and pendingImplementation ≠ address(0) if (msg.sender != pendingControllerImplementation || pendingControllerImplementation == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); } // Save current values for inclusion in log address oldImplementation = controllerImplementation; address oldPendingImplementation = pendingControllerImplementation; controllerImplementation = pendingControllerImplementation; pendingControllerImplementation = address(0); emit NewImplementation(oldImplementation, controllerImplementation); emit NewPendingImplementation(oldPendingImplementation, pendingControllerImplementation); return uint(Error.NO_ERROR); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address newPendingAdmin) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ fallback() payable external { // delegate all other functions to current implementation (bool success, ) = controllerImplementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize()) switch success case 0 { revert(free_mem_ptr, returndatasize()) } default { return(free_mem_ptr, returndatasize()) } } } receive() payable external { require(msg.value == 0, "unitroller should not get ether"); } }
{ "evmVersion": "istanbul", "libraries": {}, "metadata": { "bytecodeHash": "ipfs", "useLiteralContent": true }, "optimizer": { "enabled": true, "runs": 200 }, "remappings": [], "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "abi" ] } } }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
[{"inputs":[{"internalType":"contract RegistryInterface","name":"registry_","type":"address"},{"internalType":"uint256","name":"minUniswapLiquidity_","type":"uint256"},{"internalType":"address","name":"oracle_","type":"address"},{"internalType":"address","name":"_controller","type":"address"},{"internalType":"address","name":"_interestRateModel","type":"address"},{"internalType":"uint256","name":"_initialExchangeRateMantissa","type":"uint256"},{"internalType":"uint256","name":"_initialReserveFactorMantissa","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"error","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"info","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"detail","type":"uint256"}],"name":"Failure","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newPToken","type":"address"}],"name":"PTokenCreated","type":"event"},{"inputs":[],"name":"controller","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"pETHImplementation_","type":"address"}],"name":"createPETH","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"underlying_","type":"address"},{"internalType":"address","name":"pPIEImplementation_","type":"address"}],"name":"createPPIE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"underlying_","type":"address"}],"name":"createPToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getAdmin","outputs":[{"internalType":"address payable","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"initialExchangeRateMantissa","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"initialReserveFactorMantissa","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"interestRateModel","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minUniswapLiquidity","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"oracle","outputs":[{"internalType":"contract UniswapPriceOracle","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"registry","outputs":[{"internalType":"contract RegistryInterface","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"asset","type":"address"}],"name":"reserveIsEnough","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newController","type":"address"}],"name":"setController","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_initialExchangeRateMantissa","type":"uint256"}],"name":"setInitialExchangeRateMantissa","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_initialReserveFactorMantissa","type":"uint256"}],"name":"setInitialReserveFactorMantissa","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newInterestRateModel","type":"address"}],"name":"setInterestRateModel","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"minUniswapLiquidity_","type":"uint256"}],"name":"setMinUniswapLiquidity","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"oracle_","type":"address"}],"name":"setOracle","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_decimals","type":"uint256"}],"name":"setPTokenDecimals","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}]
Contract Creation Code
60806040526002805460ff1916600817905534801561001d57600080fd5b5060405161334a38038061334a833981810160405260e081101561004057600080fd5b508051602082015160408301516060840151608085015160a086015160c090960151600680546001600160a01b03199081166001600160a01b039889161790915560019590955560008054861694871694909417845560028054610100600160a81b03191661010094881694909402939093179092556003805490941694169390931790915560049290925560055561326b9081906100df90396000f3fe60806040523480156200001157600080fd5b5060043610620001485760003560e01c80637dc0d1d011620000bd578063bacbf215116200007b578063bacbf2151462000329578063c2bd6e841462000349578063d4270a431462000369578063f3fdb15a1462000392578063f77c4791146200039c5762000148565b80637dc0d1d01462000286578063812167e514620002905780638bcd4016146200029a57806392eefe9b14620002c3578063b34b4fd214620002ec5762000148565b8063675d972c116200010b578063675d972c14620002195780636e31020414620002235780636e9960c3146200022d5780637adbf97314620002535780637b103999146200027c5762000148565b806301de8bfa146200014d5780632f077ed8146200017f578063313ce56714620001b0578063491d1c7214620001d057806352e1ca2414620001f0575b600080fd5b6200016d600480360360208110156200016557600080fd5b5035620003a6565b60408051918252519081900360200190f35b6200016d600480360360408110156200019757600080fd5b506001600160a01b0381358116916020013516620003f1565b620001ba62000824565b6040805160ff9092168252519081900360200190f35b6200016d60048036036020811015620001e857600080fd5b50356200082d565b6200016d600480360360208110156200020857600080fd5b50356001600160a01b031662000877565b6200016d62000dca565b6200016d62000dd0565b6200023762000dd6565b604080516001600160a01b039092168252519081900360200190f35b6200016d600480360360208110156200026b57600080fd5b50356001600160a01b031662000e4f565b6200023762000ea3565b6200023762000eb2565b6200016d62000ec1565b6200016d60048036036020811015620002b257600080fd5b50356001600160a01b031662000ec7565b6200016d60048036036020811015620002db57600080fd5b50356001600160a01b031662000f1d565b62000315600480360360208110156200030457600080fd5b50356001600160a01b031662000f78565b604080519115158252519081900360200190f35b6200016d600480360360208110156200034157600080fd5b503562001179565b6200016d600480360360208110156200036157600080fd5b5035620011b9565b6200016d600480360360208110156200038157600080fd5b50356001600160a01b0316620011f9565b6200023762001580565b620002376200158f565b6000620003b262000dd6565b6001600160a01b0316336001600160a01b031614620003e157620003d96003600c620015a3565b9050620003ec565b600582905560005b90505b919050565b6000620003fd62000dd6565b6001600160a01b0316336001600160a01b0316146200042c576200042460036002620015a3565b90506200081e565b604080518082018252600b81526a446546695069652050494560a81b602080830191909152825180840184526004808252637050494560e01b9282019290925260025460035492546005546006549651959693956000958b958b956001600160a01b0361010082048116969381169593948c938c9360ff16921690620004b29062001a3a565b808b6001600160a01b031681526020018a6001600160a01b03168152602001896001600160a01b03168152602001886001600160a01b0316815260200187815260200186815260200180602001806020018560ff168152602001846001600160a01b03168152602001838103835287818151815260200191508051906020019080838360005b838110156200055257818101518382015260200162000538565b50505050905090810190601f168015620005805780820380516001836020036101000a031916815260200191505b50838103825286518152865160209182019188019080838360005b83811015620005b55781810151838201526020016200059b565b50505050905090810190601f168015620005e35780820380516001836020036101000a031916815260200191505b509c50505050505050505050505050604051809103906000f0801580156200060f573d6000803e3d6000fd5b5090506000600260019054906101000a90046001600160a01b03166001600160a01b031663a76b3fda836040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050602060405180830381600087803b1580156200067957600080fd5b505af11580156200068e573d6000803e3d6000fd5b505050506040513d6020811015620006a557600080fd5b505190508015620006ca57620006be6002600e620015a3565b9450505050506200081e565b60065460408051630dc3646760e01b81526001600160a01b03858116600483015291519190921691630dc364679160248083019260209291908290030181600087803b1580156200071a57600080fd5b505af11580156200072f573d6000803e3d6000fd5b505050506040513d60208110156200074657600080fd5b5050604080516001600160a01b038416815290517fe73d6985466386b96a63226d0cef48372289a6bf4b6dc700230cdd3c8b3d446e9181900360200190a160008054906101000a90046001600160a01b03166001600160a01b0316631c1b8772886040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050602060405180830381600087803b158015620007e757600080fd5b505af1158015620007fc573d6000803e3d6000fd5b505050506040513d60208110156200081357600080fd5b506000955050505050505b92915050565b60025460ff1681565b60006200083962000dd6565b6001600160a01b0316336001600160a01b0316146200086057620003d960036007620015a3565b6002805460ff191660ff84161790556000620003e9565b6000805460408051636f62edb360e11b81526001600160a01b03858116600483015291518493929092169163dec5db6691602480820192602092909190829003018186803b158015620008c957600080fd5b505afa158015620008de573d6000803e3d6000fd5b505050506040513d6020811015620008f557600080fd5b505190506001600160a01b0381166200091f576200091660016004620015a3565b915050620003ec565b6200092a8362000f78565b6200093d576200091660016003620015a3565b6060806200094b8562001613565b915091506000806000876001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b1580156200098e57600080fd5b505afa158015620009a3573d6000803e3d6000fd5b505050506040513d6020811015620009ba57600080fd5b505160025460ff9182169250168111620009f55760025460045460ff909116829003600a0a9350620009ed9084620017fd565b915062000a16565b60025460045460ff9091168203600a0a935062000a13908462001841565b91505b6002546003546005546006546040516000948d946001600160a01b036101008304811695918116948a9492938e938e9360ff909216929091169062000a5b9062001a48565b808a6001600160a01b03168152602001896001600160a01b03168152602001886001600160a01b0316815260200187815260200186815260200180602001806020018560ff168152602001846001600160a01b03168152602001838103835287818151815260200191508051906020019080838360005b8381101562000aec57818101518382015260200162000ad2565b50505050905090810190601f16801562000b1a5780820380516001836020036101000a031916815260200191505b50838103825286518152865160209182019188019080838360005b8381101562000b4f57818101518382015260200162000b35565b50505050905090810190601f16801562000b7d5780820380516001836020036101000a031916815260200191505b509b505050505050505050505050604051809103906000f08015801562000ba8573d6000803e3d6000fd5b5090506000600260019054906101000a90046001600160a01b03166001600160a01b031663a76b3fda836040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050602060405180830381600087803b15801562000c1257600080fd5b505af115801562000c27573d6000803e3d6000fd5b505050506040513d602081101562000c3e57600080fd5b50519050801562000c675762000c576002600e620015a3565b98505050505050505050620003ec565b60065460408051637b89273960e01b81526001600160a01b038d81166004830152858116602483015291519190921691637b8927399160448083019260209291908290030181600087803b15801562000cbf57600080fd5b505af115801562000cd4573d6000803e3d6000fd5b505050506040513d602081101562000ceb57600080fd5b5050604080516001600160a01b038416815290517fe73d6985466386b96a63226d0cef48372289a6bf4b6dc700230cdd3c8b3d446e9181900360200190a160008054906101000a90046001600160a01b03166001600160a01b0316631c1b87728b6040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050602060405180830381600087803b15801562000d8c57600080fd5b505af115801562000da1573d6000803e3d6000fd5b505050506040513d602081101562000db857600080fd5b5060009b9a5050505050505050505050565b60045481565b60055481565b600654604080516303e1469160e61b815290516000926001600160a01b03169163f851a440916004808301926020929190829003018186803b15801562000e1c57600080fd5b505afa15801562000e31573d6000803e3d6000fd5b505050506040513d602081101562000e4857600080fd5b5051905090565b600062000e5b62000dd6565b6001600160a01b0316336001600160a01b03161462000e8257620003d96003600b620015a3565b600080546001600160a01b0319166001600160a01b038416178155620003e9565b6006546001600160a01b031681565b6000546001600160a01b031681565b60015481565b600062000ed362000dd6565b6001600160a01b0316336001600160a01b03161462000efa57620003d96003600a620015a3565b600380546001600160a01b0319166001600160a01b0384161790556000620003e9565b600062000f2962000dd6565b6001600160a01b0316336001600160a01b03161462000f5057620003d960036006620015a3565b60028054610100600160a81b0319166101006001600160a01b038516021790556000620003e9565b6000805460408051636f62edb360e11b81526001600160a01b038581166004830152915184938493169163dec5db66916024808301926020929190829003018186803b15801562000fc857600080fd5b505afa15801562000fdd573d6000803e3d6000fd5b505050506040513d602081101562000ff457600080fd5b505160408051630dfe168160e01b815290519192506001600160a01b038087169290841691630dfe1681916004808301926020929190829003018186803b1580156200103f57600080fd5b505afa15801562001054573d6000803e3d6000fd5b505050506040513d60208110156200106b57600080fd5b50516001600160a01b03161415620010f957806001600160a01b0316630902f1ac6040518163ffffffff1660e01b815260040160606040518083038186803b158015620010b757600080fd5b505afa158015620010cc573d6000803e3d6000fd5b505050506040513d6060811015620010e357600080fd5b50602001516001600160701b031691506200116d565b806001600160a01b0316630902f1ac6040518163ffffffff1660e01b815260040160606040518083038186803b1580156200113357600080fd5b505afa15801562001148573d6000803e3d6000fd5b505050506040513d60608110156200115f57600080fd5b50516001600160701b031691505b50600154111592915050565b60006200118562000dd6565b6001600160a01b0316336001600160a01b031614620011ac57620003d960036005620015a3565b60018290556000620003e9565b6000620011c562000dd6565b6001600160a01b0316336001600160a01b031614620011ec57620003d960036008620015a3565b60048290556000620003e9565b60006200120562000dd6565b6001600160a01b0316336001600160a01b0316146200122c57620003d960036001620015a3565b604080518082018252600b81526a088ca8cd2a0d2ca408aa8960ab1b602080830191909152825180840184526004808252630e08aa8960e31b9282019290925260025460035492546005546006549651959693956000958a956001600160a01b0361010087048116969281169594938b938b9360ff909116921690620012b29062001a56565b808a6001600160a01b03168152602001896001600160a01b03168152602001886001600160a01b0316815260200187815260200186815260200180602001806020018560ff168152602001846001600160a01b03168152602001838103835287818151815260200191508051906020019080838360005b838110156200134357818101518382015260200162001329565b50505050905090810190601f168015620013715780820380516001836020036101000a031916815260200191505b50838103825286518152865160209182019188019080838360005b83811015620013a65781810151838201526020016200138c565b50505050905090810190601f168015620013d45780820380516001836020036101000a031916815260200191505b509b505050505050505050505050604051809103906000f080158015620013ff573d6000803e3d6000fd5b5090506000600260019054906101000a90046001600160a01b03166001600160a01b031663a76b3fda836040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050602060405180830381600087803b1580156200146957600080fd5b505af11580156200147e573d6000803e3d6000fd5b505050506040513d60208110156200149557600080fd5b505190508015620014ba57620014ae6002600e620015a3565b945050505050620003ec565b6006546040805163bfe3897f60e01b81526001600160a01b0385811660048301529151919092169163bfe3897f9160248083019260209291908290030181600087803b1580156200150a57600080fd5b505af11580156200151f573d6000803e3d6000fd5b505050506040513d60208110156200153657600080fd5b5050604080516001600160a01b038416815290517fe73d6985466386b96a63226d0cef48372289a6bf4b6dc700230cdd3c8b3d446e9181900360200190a160009695505050505050565b6003546001600160a01b031681565b60025461010090046001600160a01b031681565b60007f45b96fe442630264581b197e84bbada861235052c5a1aadfff9ea4e40a969aa0836003811115620015d357fe5b83600e811115620015e057fe5b604080519283526020830191909152600082820152519081900360600190a18260038111156200160c57fe5b9392505050565b60608060606200178762001755856001600160a01b03166306fdde036040518163ffffffff1660e01b815260040160006040518083038186803b1580156200165a57600080fd5b505afa1580156200166f573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405260208110156200169957600080fd5b8101908080516040519392919084640100000000821115620016ba57600080fd5b908301906020820185811115620016d057600080fd5b8251640100000000811182820188101715620016eb57600080fd5b82525081516020918201929091019080838360005b838110156200171a57818101518382015260200162001700565b50505050905090810190601f168015620017485780820380516001836020036101000a031916815260200191505b506040525050506200189f565b620017806040518060400160405280600881526020016702232a334a834b2960c51b8152506200189f565b90620018c6565b90506060620017f1620017cd866001600160a01b03166395d89b416040518163ffffffff1660e01b815260040160006040518083038186803b1580156200165a57600080fd5b62001780604051806040016040528060018152602001600760fc1b8152506200189f565b91935090915050915091565b60006200160c83836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525062001953565b60008262001852575060006200081e565b828202828482816200186057fe5b04146200160c5760405162461bcd60e51b8152600401808060200182810382526021815260200180620032156021913960400191505060405180910390fd5b620018a962001a64565b506040805180820190915281518152602082810190820152919050565b8051825160609182910167ffffffffffffffff81118015620018e757600080fd5b506040519080825280601f01601f19166020018201604052801562001913576020820181803683370190505b5090506000602082019050620019338186602001518760000151620019fa565b8451602085015185516200194b9284019190620019fa565b509392505050565b60008183620019e35760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015620019a75781810151838201526020016200198d565b50505050905090810190601f168015620019d55780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b506000838581620019f057fe5b0495945050505050565b5b6020811062001a1c578151835260209283019290910190601f1901620019fb565b905182516020929092036101000a6000190180199091169116179052565b6108998062001a7f83390190565b610758806200231883390190565b6107a58062002a7083390190565b60405180604001604052806000815260200160008152509056fe608060405234801561001057600080fd5b50604051610899380380610899833981810160405261014081101561003457600080fd5b815160208301516040808501516060860151608087015160a088015160c0890180519551979996989497939692959194830192918464010000000082111561007b57600080fd5b90830190602082018581111561009057600080fd5b82516401000000008111828201881017156100aa57600080fd5b82525081516020918201929091019080838360005b838110156100d75781810151838201526020016100bf565b50505050905090810190601f1680156101045780820380516001836020036101000a031916815260200191505b506040526020018051604051939291908464010000000082111561012757600080fd5b90830190602082018581111561013c57600080fd5b825164010000000081118282018810171561015657600080fd5b82525081516020918201929091019080838360005b8381101561018357818101518382015260200161016b565b50505050905090810190601f1680156101b05780820380516001836020036101000a031916815260200191505b506040908152602082015191015190925090506101cc8161036a565b6101d58961038c565b61035a60008054906101000a90046001600160a01b03168b838b8b8b8b8b8b8b604051602401808a6001600160a01b03168152602001896001600160a01b03168152602001886001600160a01b03168152602001876001600160a01b0316815260200186815260200185815260200180602001806020018460ff168152602001838103835286818151815260200191508051906020019080838360005b8381101561028a578181015183820152602001610272565b50505050905090810190601f1680156102b75780820380516001836020036101000a031916815260200191505b50838103825285518152855160209182019187019080838360005b838110156102ea5781810151838201526020016102d2565b50505050905090810190601f1680156103175780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529190526020810180516001600160e01b0390811663776fce3960e11b17909152909c506103ae169a5050505050505050505050565b5050505050505050505050610470565b600180546001600160a01b0319166001600160a01b0392909216919091179055565b600080546001600160a01b0319166001600160a01b0392909216919091179055565b606060006060846001600160a01b0316846040518082805190602001908083835b602083106103ee5780518252601f1990920191602091820191016103cf565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461044e576040519150601f19603f3d011682016040523d82523d6000602084013e610453565b606091505b50915091506000821415610468573d60208201fd5b949350505050565b61041a8061047f6000396000f3fe6080604052600436106100385760003560e01c80635c60da1b146100c45780637b103999146100f5578063d784d4261461010a5761007c565b3661007c57341561007a5760405162461bcd60e51b81526004018080602001828103825260338152602001806103b26033913960400191505060405180910390fd5b005b34156100b95760405162461bcd60e51b815260040180806020018281038252603581526020018061037d6035913960400191505060405180910390fd5b6100c161014f565b50005b3480156100d057600080fd5b506100d96101d4565b604080516001600160a01b039092168252519081900360200190f35b34801561010157600080fd5b506100d96101e3565b34801561011657600080fd5b5061013d6004803603602081101561012d57600080fd5b50356001600160a01b03166101f2565b60408051918252519081900360200190f35b60008054604051606092916001600160a01b031690829036908083838082843760405192019450600093509091505080830381855af49150503d80600081146101b4576040519150601f19603f3d011682016040523d82523d6000602084013e6101b9565b606091505b505090506040513d6000823e8180156101d0573d82f35b3d82fd5b6000546001600160a01b031681565b6001546001600160a01b031681565b600154604080516303e1469160e61b815290516000926001600160a01b03169163f851a440916004808301926020929190829003018186803b15801561023757600080fd5b505afa15801561024b573d6000803e3d6000fd5b505050506040513d602081101561026157600080fd5b50516001600160a01b031633146102855761027e600160516102ed565b90506102e8565b6000546001600160a01b031661029a8361035a565b600054604080516001600160a01b038085168252909216602083015280517fd604de94d45953f9138079ec1b82d533cb2160c906d1076d1f7ed54befbca97a9281900390910190a160009150505b919050565b60007f45b96fe442630264581b197e84bbada861235052c5a1aadfff9ea4e40a969aa083601081111561031c57fe5b83605181111561032857fe5b604080519283526020830191909152600082820152519081900360600190a182601081111561035357fe5b9392505050565b600080546001600160a01b0319166001600160a01b039290921691909117905556fe5050494544656c656761746f723a66616c6c6261636b3a2063616e6e6f742073656e642076616c756520746f2066616c6c6261636b5050494544656c656761746f723a726563656976653a2063616e6e6f742073656e642076616c756520746f2072656365697665a2646970667358221220bb35f3e3f15832c93e6a4fcd6a3c5318c416fe57c3152477dc70a255f0b32fb864736f6c63430007040033608060405234801561001057600080fd5b50604051610758380380610758833981810160405261012081101561003457600080fd5b815160208301516040808501516060860151608087015160a08801805194519698959793969295919492938201928464010000000082111561007557600080fd5b90830190602082018581111561008a57600080fd5b82516401000000008111828201881017156100a457600080fd5b82525081516020918201929091019080838360005b838110156100d15781810151838201526020016100b9565b50505050905090810190601f1680156100fe5780820380516001836020036101000a031916815260200191505b506040526020018051604051939291908464010000000082111561012157600080fd5b90830190602082018581111561013657600080fd5b825164010000000081118282018810171561015057600080fd5b82525081516020918201929091019080838360005b8381101561017d578181015183820152602001610165565b50505050905090810190601f1680156101aa5780820380516001836020036101000a031916815260200191505b506040908152602082015191015190925090506101c68161034e565b61033f6101d1610370565b8a838b8b8b8b8b8b8b604051602401808a6001600160a01b03168152602001896001600160a01b03168152602001886001600160a01b03168152602001876001600160a01b0316815260200186815260200185815260200180602001806020018460ff168152602001838103835286818151815260200191508051906020019080838360005b8381101561026f578181015183820152602001610257565b50505050905090810190601f16801561029c5780820380516001836020036101000a031916815260200191505b50838103825285518152855160209182019187019080838360005b838110156102cf5781810151838201526020016102b7565b50505050905090810190601f1680156102fc5780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529190526020810180516001600160e01b0390811663776fce3960e11b17909152909c506103f0169a5050505050505050505050565b505050505050505050506104b2565b600080546001600160a01b0319166001600160a01b0392909216919091179055565b60008060009054906101000a90046001600160a01b03166001600160a01b03166382466ff66040518163ffffffff1660e01b815260040160206040518083038186803b1580156103bf57600080fd5b505afa1580156103d3573d6000803e3d6000fd5b505050506040513d60208110156103e957600080fd5b5051905090565b606060006060846001600160a01b0316846040518082805190602001908083835b602083106104305780518252601f199092019160209182019101610411565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d8060008114610490576040519150601f19603f3d011682016040523d82523d6000602084013e610495565b606091505b509150915060008214156104aa573d60208201fd5b949350505050565b610297806104c16000396000f3fe6080604052600436106100225760003560e01c80637b103999146100ae57610066565b366100665734156100645760405162461bcd60e51b81526004018080602001828103825260358152602001806101f66035913960400191505060405180910390fd5b005b34156100a35760405162461bcd60e51b815260040180806020018281038252603781526020018061022b6037913960400191505060405180910390fd5b6100ab6100df565b50005b3480156100ba57600080fd5b506100c3610166565b604080516001600160a01b039092168252519081900360200190f35b606060006100eb610175565b6001600160a01b03166000366040518083838082843760405192019450600093509091505080830381855af49150503d8060008114610146576040519150601f19603f3d011682016040523d82523d6000602084013e61014b565b606091505b505090506040513d6000823e818015610162573d82f35b3d82fd5b6000546001600160a01b031681565b60008060009054906101000a90046001600160a01b03166001600160a01b03166382466ff66040518163ffffffff1660e01b815260040160206040518083038186803b1580156101c457600080fd5b505afa1580156101d8573d6000803e3d6000fd5b505050506040513d60208110156101ee57600080fd5b505190509056fe50457263323044656c656761746f723a726563656976653a2063616e6e6f742073656e642076616c756520746f207265636569766550457263323044656c656761746f723a66616c6c6261636b3a2063616e6e6f742073656e642076616c756520746f2066616c6c6261636ba2646970667358221220895e093bd7e3c322cfda8f1d0aaf34fb1f387204430b227dbc049e9102e27a3164736f6c63430007040033608060405234801561001057600080fd5b506040516107a53803806107a5833981810160405261012081101561003457600080fd5b815160208301516040808501516060860151608087015160a08801805194519698959793969295919492938201928464010000000082111561007557600080fd5b90830190602082018581111561008a57600080fd5b82516401000000008111828201881017156100a457600080fd5b82525081516020918201929091019080838360005b838110156100d15781810151838201526020016100b9565b50505050905090810190601f1680156100fe5780820380516001836020036101000a031916815260200191505b506040526020018051604051939291908464010000000082111561012157600080fd5b90830190602082018581111561013657600080fd5b825164010000000081118282018810171561015057600080fd5b82525081516020918201929091019080838360005b8381101561017d578181015183820152602001610165565b50505050905090810190601f1680156101aa5780820380516001836020036101000a031916815260200191505b506040908152602082015191015190925090506101c681610352565b6101cf89610374565b61034360008054906101000a90046001600160a01b0316828a8a8a8a8a8a8a60405160240180896001600160a01b03168152602001886001600160a01b03168152602001876001600160a01b0316815260200186815260200185815260200180602001806020018460ff168152602001838103835286818151815260200191508051906020019080838360005b8381101561027457818101518382015260200161025c565b50505050905090810190601f1680156102a15780820380516001836020036101000a031916815260200191505b50838103825285518152855160209182019187019080838360005b838110156102d45781810151838201526020016102bc565b50505050905090810190601f1680156103015780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529190526020810180516001600160e01b03908116639ea21c3d60e01b17909152909b50610396169950505050505050505050565b50505050505050505050610458565b600180546001600160a01b0319166001600160a01b0392909216919091179055565b600080546001600160a01b0319166001600160a01b0392909216919091179055565b606060006060846001600160a01b0316846040518082805190602001908083835b602083106103d65780518252601f1990920191602091820191016103b7565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d8060008114610436576040519150601f19603f3d011682016040523d82523d6000602084013e61043b565b606091505b50915091506000821415610450573d60208201fd5b949350505050565b61033e806104676000396000f3fe6080604052600436106100385760003560e01c80635c60da1b146100505780637b10399914610081578063d784d4261461009657610048565b36610048576100456100db565b50005b6100456100db565b34801561005c57600080fd5b50610065610160565b604080516001600160a01b039092168252519081900360200190f35b34801561008d57600080fd5b5061006561016f565b3480156100a257600080fd5b506100c9600480360360208110156100b957600080fd5b50356001600160a01b031661017e565b60408051918252519081900360200190f35b60008054604051606092916001600160a01b031690829036908083838082843760405192019450600093509091505080830381855af49150503d8060008114610140576040519150601f19603f3d011682016040523d82523d6000602084013e610145565b606091505b505090506040513d6000823e81801561015c573d82f35b3d82fd5b6000546001600160a01b031681565b6001546001600160a01b031681565b600154604080516303e1469160e61b815290516000926001600160a01b03169163f851a440916004808301926020929190829003018186803b1580156101c357600080fd5b505afa1580156101d7573d6000803e3d6000fd5b505050506040513d60208110156101ed57600080fd5b50516001600160a01b031633146102115761020a60016051610279565b9050610274565b6000546001600160a01b0316610226836102e6565b600054604080516001600160a01b038085168252909216602083015280517fd604de94d45953f9138079ec1b82d533cb2160c906d1076d1f7ed54befbca97a9281900390910190a160009150505b919050565b60007f45b96fe442630264581b197e84bbada861235052c5a1aadfff9ea4e40a969aa08360108111156102a857fe5b8360518111156102b457fe5b604080519283526020830191909152600082820152519081900360600190a18260108111156102df57fe5b9392505050565b600080546001600160a01b0319166001600160a01b039290921691909117905556fea2646970667358221220c699eeeab1e09afe10d1ac82b01d19752e6fc62f5ad5697451d9e73c06510de964736f6c63430007040033536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77a264697066735822122003dbceee381e28efb3c6bb42d0c0e0a4614cd73ac4c7009f9002ce811f0ce71b64736f6c634300070400330000000000000000000000001135270bbb0627e769a7a2e24f2b2c7f14b3d83a00000000000000000000000000000000000000000000000410d586a20a4c000000000000000000000000000085f6ab4e889bbdd760b61183d3544e77f228d77c00000000000000000000000036de5bbc618a04c9b471208ef52ee2b1f536e92d000000000000000000000000d47d39a66bb4912d127fbfc1b90884fcb354613700000000000000000000000000000000000000000000000000470de4df820000000000000000000000000000000000000000000000000000016345785d8a0000
Deployed Bytecode
0x60806040523480156200001157600080fd5b5060043610620001485760003560e01c80637dc0d1d011620000bd578063bacbf215116200007b578063bacbf2151462000329578063c2bd6e841462000349578063d4270a431462000369578063f3fdb15a1462000392578063f77c4791146200039c5762000148565b80637dc0d1d01462000286578063812167e514620002905780638bcd4016146200029a57806392eefe9b14620002c3578063b34b4fd214620002ec5762000148565b8063675d972c116200010b578063675d972c14620002195780636e31020414620002235780636e9960c3146200022d5780637adbf97314620002535780637b103999146200027c5762000148565b806301de8bfa146200014d5780632f077ed8146200017f578063313ce56714620001b0578063491d1c7214620001d057806352e1ca2414620001f0575b600080fd5b6200016d600480360360208110156200016557600080fd5b5035620003a6565b60408051918252519081900360200190f35b6200016d600480360360408110156200019757600080fd5b506001600160a01b0381358116916020013516620003f1565b620001ba62000824565b6040805160ff9092168252519081900360200190f35b6200016d60048036036020811015620001e857600080fd5b50356200082d565b6200016d600480360360208110156200020857600080fd5b50356001600160a01b031662000877565b6200016d62000dca565b6200016d62000dd0565b6200023762000dd6565b604080516001600160a01b039092168252519081900360200190f35b6200016d600480360360208110156200026b57600080fd5b50356001600160a01b031662000e4f565b6200023762000ea3565b6200023762000eb2565b6200016d62000ec1565b6200016d60048036036020811015620002b257600080fd5b50356001600160a01b031662000ec7565b6200016d60048036036020811015620002db57600080fd5b50356001600160a01b031662000f1d565b62000315600480360360208110156200030457600080fd5b50356001600160a01b031662000f78565b604080519115158252519081900360200190f35b6200016d600480360360208110156200034157600080fd5b503562001179565b6200016d600480360360208110156200036157600080fd5b5035620011b9565b6200016d600480360360208110156200038157600080fd5b50356001600160a01b0316620011f9565b6200023762001580565b620002376200158f565b6000620003b262000dd6565b6001600160a01b0316336001600160a01b031614620003e157620003d96003600c620015a3565b9050620003ec565b600582905560005b90505b919050565b6000620003fd62000dd6565b6001600160a01b0316336001600160a01b0316146200042c576200042460036002620015a3565b90506200081e565b604080518082018252600b81526a446546695069652050494560a81b602080830191909152825180840184526004808252637050494560e01b9282019290925260025460035492546005546006549651959693956000958b958b956001600160a01b0361010082048116969381169593948c938c9360ff16921690620004b29062001a3a565b808b6001600160a01b031681526020018a6001600160a01b03168152602001896001600160a01b03168152602001886001600160a01b0316815260200187815260200186815260200180602001806020018560ff168152602001846001600160a01b03168152602001838103835287818151815260200191508051906020019080838360005b838110156200055257818101518382015260200162000538565b50505050905090810190601f168015620005805780820380516001836020036101000a031916815260200191505b50838103825286518152865160209182019188019080838360005b83811015620005b55781810151838201526020016200059b565b50505050905090810190601f168015620005e35780820380516001836020036101000a031916815260200191505b509c50505050505050505050505050604051809103906000f0801580156200060f573d6000803e3d6000fd5b5090506000600260019054906101000a90046001600160a01b03166001600160a01b031663a76b3fda836040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050602060405180830381600087803b1580156200067957600080fd5b505af11580156200068e573d6000803e3d6000fd5b505050506040513d6020811015620006a557600080fd5b505190508015620006ca57620006be6002600e620015a3565b9450505050506200081e565b60065460408051630dc3646760e01b81526001600160a01b03858116600483015291519190921691630dc364679160248083019260209291908290030181600087803b1580156200071a57600080fd5b505af11580156200072f573d6000803e3d6000fd5b505050506040513d60208110156200074657600080fd5b5050604080516001600160a01b038416815290517fe73d6985466386b96a63226d0cef48372289a6bf4b6dc700230cdd3c8b3d446e9181900360200190a160008054906101000a90046001600160a01b03166001600160a01b0316631c1b8772886040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050602060405180830381600087803b158015620007e757600080fd5b505af1158015620007fc573d6000803e3d6000fd5b505050506040513d60208110156200081357600080fd5b506000955050505050505b92915050565b60025460ff1681565b60006200083962000dd6565b6001600160a01b0316336001600160a01b0316146200086057620003d960036007620015a3565b6002805460ff191660ff84161790556000620003e9565b6000805460408051636f62edb360e11b81526001600160a01b03858116600483015291518493929092169163dec5db6691602480820192602092909190829003018186803b158015620008c957600080fd5b505afa158015620008de573d6000803e3d6000fd5b505050506040513d6020811015620008f557600080fd5b505190506001600160a01b0381166200091f576200091660016004620015a3565b915050620003ec565b6200092a8362000f78565b6200093d576200091660016003620015a3565b6060806200094b8562001613565b915091506000806000876001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b1580156200098e57600080fd5b505afa158015620009a3573d6000803e3d6000fd5b505050506040513d6020811015620009ba57600080fd5b505160025460ff9182169250168111620009f55760025460045460ff909116829003600a0a9350620009ed9084620017fd565b915062000a16565b60025460045460ff9091168203600a0a935062000a13908462001841565b91505b6002546003546005546006546040516000948d946001600160a01b036101008304811695918116948a9492938e938e9360ff909216929091169062000a5b9062001a48565b808a6001600160a01b03168152602001896001600160a01b03168152602001886001600160a01b0316815260200187815260200186815260200180602001806020018560ff168152602001846001600160a01b03168152602001838103835287818151815260200191508051906020019080838360005b8381101562000aec57818101518382015260200162000ad2565b50505050905090810190601f16801562000b1a5780820380516001836020036101000a031916815260200191505b50838103825286518152865160209182019188019080838360005b8381101562000b4f57818101518382015260200162000b35565b50505050905090810190601f16801562000b7d5780820380516001836020036101000a031916815260200191505b509b505050505050505050505050604051809103906000f08015801562000ba8573d6000803e3d6000fd5b5090506000600260019054906101000a90046001600160a01b03166001600160a01b031663a76b3fda836040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050602060405180830381600087803b15801562000c1257600080fd5b505af115801562000c27573d6000803e3d6000fd5b505050506040513d602081101562000c3e57600080fd5b50519050801562000c675762000c576002600e620015a3565b98505050505050505050620003ec565b60065460408051637b89273960e01b81526001600160a01b038d81166004830152858116602483015291519190921691637b8927399160448083019260209291908290030181600087803b15801562000cbf57600080fd5b505af115801562000cd4573d6000803e3d6000fd5b505050506040513d602081101562000ceb57600080fd5b5050604080516001600160a01b038416815290517fe73d6985466386b96a63226d0cef48372289a6bf4b6dc700230cdd3c8b3d446e9181900360200190a160008054906101000a90046001600160a01b03166001600160a01b0316631c1b87728b6040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050602060405180830381600087803b15801562000d8c57600080fd5b505af115801562000da1573d6000803e3d6000fd5b505050506040513d602081101562000db857600080fd5b5060009b9a5050505050505050505050565b60045481565b60055481565b600654604080516303e1469160e61b815290516000926001600160a01b03169163f851a440916004808301926020929190829003018186803b15801562000e1c57600080fd5b505afa15801562000e31573d6000803e3d6000fd5b505050506040513d602081101562000e4857600080fd5b5051905090565b600062000e5b62000dd6565b6001600160a01b0316336001600160a01b03161462000e8257620003d96003600b620015a3565b600080546001600160a01b0319166001600160a01b038416178155620003e9565b6006546001600160a01b031681565b6000546001600160a01b031681565b60015481565b600062000ed362000dd6565b6001600160a01b0316336001600160a01b03161462000efa57620003d96003600a620015a3565b600380546001600160a01b0319166001600160a01b0384161790556000620003e9565b600062000f2962000dd6565b6001600160a01b0316336001600160a01b03161462000f5057620003d960036006620015a3565b60028054610100600160a81b0319166101006001600160a01b038516021790556000620003e9565b6000805460408051636f62edb360e11b81526001600160a01b038581166004830152915184938493169163dec5db66916024808301926020929190829003018186803b15801562000fc857600080fd5b505afa15801562000fdd573d6000803e3d6000fd5b505050506040513d602081101562000ff457600080fd5b505160408051630dfe168160e01b815290519192506001600160a01b038087169290841691630dfe1681916004808301926020929190829003018186803b1580156200103f57600080fd5b505afa15801562001054573d6000803e3d6000fd5b505050506040513d60208110156200106b57600080fd5b50516001600160a01b03161415620010f957806001600160a01b0316630902f1ac6040518163ffffffff1660e01b815260040160606040518083038186803b158015620010b757600080fd5b505afa158015620010cc573d6000803e3d6000fd5b505050506040513d6060811015620010e357600080fd5b50602001516001600160701b031691506200116d565b806001600160a01b0316630902f1ac6040518163ffffffff1660e01b815260040160606040518083038186803b1580156200113357600080fd5b505afa15801562001148573d6000803e3d6000fd5b505050506040513d60608110156200115f57600080fd5b50516001600160701b031691505b50600154111592915050565b60006200118562000dd6565b6001600160a01b0316336001600160a01b031614620011ac57620003d960036005620015a3565b60018290556000620003e9565b6000620011c562000dd6565b6001600160a01b0316336001600160a01b031614620011ec57620003d960036008620015a3565b60048290556000620003e9565b60006200120562000dd6565b6001600160a01b0316336001600160a01b0316146200122c57620003d960036001620015a3565b604080518082018252600b81526a088ca8cd2a0d2ca408aa8960ab1b602080830191909152825180840184526004808252630e08aa8960e31b9282019290925260025460035492546005546006549651959693956000958a956001600160a01b0361010087048116969281169594938b938b9360ff909116921690620012b29062001a56565b808a6001600160a01b03168152602001896001600160a01b03168152602001886001600160a01b0316815260200187815260200186815260200180602001806020018560ff168152602001846001600160a01b03168152602001838103835287818151815260200191508051906020019080838360005b838110156200134357818101518382015260200162001329565b50505050905090810190601f168015620013715780820380516001836020036101000a031916815260200191505b50838103825286518152865160209182019188019080838360005b83811015620013a65781810151838201526020016200138c565b50505050905090810190601f168015620013d45780820380516001836020036101000a031916815260200191505b509b505050505050505050505050604051809103906000f080158015620013ff573d6000803e3d6000fd5b5090506000600260019054906101000a90046001600160a01b03166001600160a01b031663a76b3fda836040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050602060405180830381600087803b1580156200146957600080fd5b505af11580156200147e573d6000803e3d6000fd5b505050506040513d60208110156200149557600080fd5b505190508015620014ba57620014ae6002600e620015a3565b945050505050620003ec565b6006546040805163bfe3897f60e01b81526001600160a01b0385811660048301529151919092169163bfe3897f9160248083019260209291908290030181600087803b1580156200150a57600080fd5b505af11580156200151f573d6000803e3d6000fd5b505050506040513d60208110156200153657600080fd5b5050604080516001600160a01b038416815290517fe73d6985466386b96a63226d0cef48372289a6bf4b6dc700230cdd3c8b3d446e9181900360200190a160009695505050505050565b6003546001600160a01b031681565b60025461010090046001600160a01b031681565b60007f45b96fe442630264581b197e84bbada861235052c5a1aadfff9ea4e40a969aa0836003811115620015d357fe5b83600e811115620015e057fe5b604080519283526020830191909152600082820152519081900360600190a18260038111156200160c57fe5b9392505050565b60608060606200178762001755856001600160a01b03166306fdde036040518163ffffffff1660e01b815260040160006040518083038186803b1580156200165a57600080fd5b505afa1580156200166f573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405260208110156200169957600080fd5b8101908080516040519392919084640100000000821115620016ba57600080fd5b908301906020820185811115620016d057600080fd5b8251640100000000811182820188101715620016eb57600080fd5b82525081516020918201929091019080838360005b838110156200171a57818101518382015260200162001700565b50505050905090810190601f168015620017485780820380516001836020036101000a031916815260200191505b506040525050506200189f565b620017806040518060400160405280600881526020016702232a334a834b2960c51b8152506200189f565b90620018c6565b90506060620017f1620017cd866001600160a01b03166395d89b416040518163ffffffff1660e01b815260040160006040518083038186803b1580156200165a57600080fd5b62001780604051806040016040528060018152602001600760fc1b8152506200189f565b91935090915050915091565b60006200160c83836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525062001953565b60008262001852575060006200081e565b828202828482816200186057fe5b04146200160c5760405162461bcd60e51b8152600401808060200182810382526021815260200180620032156021913960400191505060405180910390fd5b620018a962001a64565b506040805180820190915281518152602082810190820152919050565b8051825160609182910167ffffffffffffffff81118015620018e757600080fd5b506040519080825280601f01601f19166020018201604052801562001913576020820181803683370190505b5090506000602082019050620019338186602001518760000151620019fa565b8451602085015185516200194b9284019190620019fa565b509392505050565b60008183620019e35760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015620019a75781810151838201526020016200198d565b50505050905090810190601f168015620019d55780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b506000838581620019f057fe5b0495945050505050565b5b6020811062001a1c578151835260209283019290910190601f1901620019fb565b905182516020929092036101000a6000190180199091169116179052565b6108998062001a7f83390190565b610758806200231883390190565b6107a58062002a7083390190565b60405180604001604052806000815260200160008152509056fe608060405234801561001057600080fd5b50604051610899380380610899833981810160405261014081101561003457600080fd5b815160208301516040808501516060860151608087015160a088015160c0890180519551979996989497939692959194830192918464010000000082111561007b57600080fd5b90830190602082018581111561009057600080fd5b82516401000000008111828201881017156100aa57600080fd5b82525081516020918201929091019080838360005b838110156100d75781810151838201526020016100bf565b50505050905090810190601f1680156101045780820380516001836020036101000a031916815260200191505b506040526020018051604051939291908464010000000082111561012757600080fd5b90830190602082018581111561013c57600080fd5b825164010000000081118282018810171561015657600080fd5b82525081516020918201929091019080838360005b8381101561018357818101518382015260200161016b565b50505050905090810190601f1680156101b05780820380516001836020036101000a031916815260200191505b506040908152602082015191015190925090506101cc8161036a565b6101d58961038c565b61035a60008054906101000a90046001600160a01b03168b838b8b8b8b8b8b8b604051602401808a6001600160a01b03168152602001896001600160a01b03168152602001886001600160a01b03168152602001876001600160a01b0316815260200186815260200185815260200180602001806020018460ff168152602001838103835286818151815260200191508051906020019080838360005b8381101561028a578181015183820152602001610272565b50505050905090810190601f1680156102b75780820380516001836020036101000a031916815260200191505b50838103825285518152855160209182019187019080838360005b838110156102ea5781810151838201526020016102d2565b50505050905090810190601f1680156103175780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529190526020810180516001600160e01b0390811663776fce3960e11b17909152909c506103ae169a5050505050505050505050565b5050505050505050505050610470565b600180546001600160a01b0319166001600160a01b0392909216919091179055565b600080546001600160a01b0319166001600160a01b0392909216919091179055565b606060006060846001600160a01b0316846040518082805190602001908083835b602083106103ee5780518252601f1990920191602091820191016103cf565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461044e576040519150601f19603f3d011682016040523d82523d6000602084013e610453565b606091505b50915091506000821415610468573d60208201fd5b949350505050565b61041a8061047f6000396000f3fe6080604052600436106100385760003560e01c80635c60da1b146100c45780637b103999146100f5578063d784d4261461010a5761007c565b3661007c57341561007a5760405162461bcd60e51b81526004018080602001828103825260338152602001806103b26033913960400191505060405180910390fd5b005b34156100b95760405162461bcd60e51b815260040180806020018281038252603581526020018061037d6035913960400191505060405180910390fd5b6100c161014f565b50005b3480156100d057600080fd5b506100d96101d4565b604080516001600160a01b039092168252519081900360200190f35b34801561010157600080fd5b506100d96101e3565b34801561011657600080fd5b5061013d6004803603602081101561012d57600080fd5b50356001600160a01b03166101f2565b60408051918252519081900360200190f35b60008054604051606092916001600160a01b031690829036908083838082843760405192019450600093509091505080830381855af49150503d80600081146101b4576040519150601f19603f3d011682016040523d82523d6000602084013e6101b9565b606091505b505090506040513d6000823e8180156101d0573d82f35b3d82fd5b6000546001600160a01b031681565b6001546001600160a01b031681565b600154604080516303e1469160e61b815290516000926001600160a01b03169163f851a440916004808301926020929190829003018186803b15801561023757600080fd5b505afa15801561024b573d6000803e3d6000fd5b505050506040513d602081101561026157600080fd5b50516001600160a01b031633146102855761027e600160516102ed565b90506102e8565b6000546001600160a01b031661029a8361035a565b600054604080516001600160a01b038085168252909216602083015280517fd604de94d45953f9138079ec1b82d533cb2160c906d1076d1f7ed54befbca97a9281900390910190a160009150505b919050565b60007f45b96fe442630264581b197e84bbada861235052c5a1aadfff9ea4e40a969aa083601081111561031c57fe5b83605181111561032857fe5b604080519283526020830191909152600082820152519081900360600190a182601081111561035357fe5b9392505050565b600080546001600160a01b0319166001600160a01b039290921691909117905556fe5050494544656c656761746f723a66616c6c6261636b3a2063616e6e6f742073656e642076616c756520746f2066616c6c6261636b5050494544656c656761746f723a726563656976653a2063616e6e6f742073656e642076616c756520746f2072656365697665a2646970667358221220bb35f3e3f15832c93e6a4fcd6a3c5318c416fe57c3152477dc70a255f0b32fb864736f6c63430007040033608060405234801561001057600080fd5b50604051610758380380610758833981810160405261012081101561003457600080fd5b815160208301516040808501516060860151608087015160a08801805194519698959793969295919492938201928464010000000082111561007557600080fd5b90830190602082018581111561008a57600080fd5b82516401000000008111828201881017156100a457600080fd5b82525081516020918201929091019080838360005b838110156100d15781810151838201526020016100b9565b50505050905090810190601f1680156100fe5780820380516001836020036101000a031916815260200191505b506040526020018051604051939291908464010000000082111561012157600080fd5b90830190602082018581111561013657600080fd5b825164010000000081118282018810171561015057600080fd5b82525081516020918201929091019080838360005b8381101561017d578181015183820152602001610165565b50505050905090810190601f1680156101aa5780820380516001836020036101000a031916815260200191505b506040908152602082015191015190925090506101c68161034e565b61033f6101d1610370565b8a838b8b8b8b8b8b8b604051602401808a6001600160a01b03168152602001896001600160a01b03168152602001886001600160a01b03168152602001876001600160a01b0316815260200186815260200185815260200180602001806020018460ff168152602001838103835286818151815260200191508051906020019080838360005b8381101561026f578181015183820152602001610257565b50505050905090810190601f16801561029c5780820380516001836020036101000a031916815260200191505b50838103825285518152855160209182019187019080838360005b838110156102cf5781810151838201526020016102b7565b50505050905090810190601f1680156102fc5780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529190526020810180516001600160e01b0390811663776fce3960e11b17909152909c506103f0169a5050505050505050505050565b505050505050505050506104b2565b600080546001600160a01b0319166001600160a01b0392909216919091179055565b60008060009054906101000a90046001600160a01b03166001600160a01b03166382466ff66040518163ffffffff1660e01b815260040160206040518083038186803b1580156103bf57600080fd5b505afa1580156103d3573d6000803e3d6000fd5b505050506040513d60208110156103e957600080fd5b5051905090565b606060006060846001600160a01b0316846040518082805190602001908083835b602083106104305780518252601f199092019160209182019101610411565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d8060008114610490576040519150601f19603f3d011682016040523d82523d6000602084013e610495565b606091505b509150915060008214156104aa573d60208201fd5b949350505050565b610297806104c16000396000f3fe6080604052600436106100225760003560e01c80637b103999146100ae57610066565b366100665734156100645760405162461bcd60e51b81526004018080602001828103825260358152602001806101f66035913960400191505060405180910390fd5b005b34156100a35760405162461bcd60e51b815260040180806020018281038252603781526020018061022b6037913960400191505060405180910390fd5b6100ab6100df565b50005b3480156100ba57600080fd5b506100c3610166565b604080516001600160a01b039092168252519081900360200190f35b606060006100eb610175565b6001600160a01b03166000366040518083838082843760405192019450600093509091505080830381855af49150503d8060008114610146576040519150601f19603f3d011682016040523d82523d6000602084013e61014b565b606091505b505090506040513d6000823e818015610162573d82f35b3d82fd5b6000546001600160a01b031681565b60008060009054906101000a90046001600160a01b03166001600160a01b03166382466ff66040518163ffffffff1660e01b815260040160206040518083038186803b1580156101c457600080fd5b505afa1580156101d8573d6000803e3d6000fd5b505050506040513d60208110156101ee57600080fd5b505190509056fe50457263323044656c656761746f723a726563656976653a2063616e6e6f742073656e642076616c756520746f207265636569766550457263323044656c656761746f723a66616c6c6261636b3a2063616e6e6f742073656e642076616c756520746f2066616c6c6261636ba2646970667358221220895e093bd7e3c322cfda8f1d0aaf34fb1f387204430b227dbc049e9102e27a3164736f6c63430007040033608060405234801561001057600080fd5b506040516107a53803806107a5833981810160405261012081101561003457600080fd5b815160208301516040808501516060860151608087015160a08801805194519698959793969295919492938201928464010000000082111561007557600080fd5b90830190602082018581111561008a57600080fd5b82516401000000008111828201881017156100a457600080fd5b82525081516020918201929091019080838360005b838110156100d15781810151838201526020016100b9565b50505050905090810190601f1680156100fe5780820380516001836020036101000a031916815260200191505b506040526020018051604051939291908464010000000082111561012157600080fd5b90830190602082018581111561013657600080fd5b825164010000000081118282018810171561015057600080fd5b82525081516020918201929091019080838360005b8381101561017d578181015183820152602001610165565b50505050905090810190601f1680156101aa5780820380516001836020036101000a031916815260200191505b506040908152602082015191015190925090506101c681610352565b6101cf89610374565b61034360008054906101000a90046001600160a01b0316828a8a8a8a8a8a8a60405160240180896001600160a01b03168152602001886001600160a01b03168152602001876001600160a01b0316815260200186815260200185815260200180602001806020018460ff168152602001838103835286818151815260200191508051906020019080838360005b8381101561027457818101518382015260200161025c565b50505050905090810190601f1680156102a15780820380516001836020036101000a031916815260200191505b50838103825285518152855160209182019187019080838360005b838110156102d45781810151838201526020016102bc565b50505050905090810190601f1680156103015780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529190526020810180516001600160e01b03908116639ea21c3d60e01b17909152909b50610396169950505050505050505050565b50505050505050505050610458565b600180546001600160a01b0319166001600160a01b0392909216919091179055565b600080546001600160a01b0319166001600160a01b0392909216919091179055565b606060006060846001600160a01b0316846040518082805190602001908083835b602083106103d65780518252601f1990920191602091820191016103b7565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d8060008114610436576040519150601f19603f3d011682016040523d82523d6000602084013e61043b565b606091505b50915091506000821415610450573d60208201fd5b949350505050565b61033e806104676000396000f3fe6080604052600436106100385760003560e01c80635c60da1b146100505780637b10399914610081578063d784d4261461009657610048565b36610048576100456100db565b50005b6100456100db565b34801561005c57600080fd5b50610065610160565b604080516001600160a01b039092168252519081900360200190f35b34801561008d57600080fd5b5061006561016f565b3480156100a257600080fd5b506100c9600480360360208110156100b957600080fd5b50356001600160a01b031661017e565b60408051918252519081900360200190f35b60008054604051606092916001600160a01b031690829036908083838082843760405192019450600093509091505080830381855af49150503d8060008114610140576040519150601f19603f3d011682016040523d82523d6000602084013e610145565b606091505b505090506040513d6000823e81801561015c573d82f35b3d82fd5b6000546001600160a01b031681565b6001546001600160a01b031681565b600154604080516303e1469160e61b815290516000926001600160a01b03169163f851a440916004808301926020929190829003018186803b1580156101c357600080fd5b505afa1580156101d7573d6000803e3d6000fd5b505050506040513d60208110156101ed57600080fd5b50516001600160a01b031633146102115761020a60016051610279565b9050610274565b6000546001600160a01b0316610226836102e6565b600054604080516001600160a01b038085168252909216602083015280517fd604de94d45953f9138079ec1b82d533cb2160c906d1076d1f7ed54befbca97a9281900390910190a160009150505b919050565b60007f45b96fe442630264581b197e84bbada861235052c5a1aadfff9ea4e40a969aa08360108111156102a857fe5b8360518111156102b457fe5b604080519283526020830191909152600082820152519081900360600190a18260108111156102df57fe5b9392505050565b600080546001600160a01b0319166001600160a01b039290921691909117905556fea2646970667358221220c699eeeab1e09afe10d1ac82b01d19752e6fc62f5ad5697451d9e73c06510de964736f6c63430007040033536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77a264697066735822122003dbceee381e28efb3c6bb42d0c0e0a4614cd73ac4c7009f9002ce811f0ce71b64736f6c63430007040033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
0000000000000000000000001135270bbb0627e769a7a2e24f2b2c7f14b3d83a00000000000000000000000000000000000000000000000410d586a20a4c000000000000000000000000000085f6ab4e889bbdd760b61183d3544e77f228d77c00000000000000000000000036de5bbc618a04c9b471208ef52ee2b1f536e92d000000000000000000000000d47d39a66bb4912d127fbfc1b90884fcb354613700000000000000000000000000000000000000000000000000470de4df820000000000000000000000000000000000000000000000000000016345785d8a0000
-----Decoded View---------------
Arg [0] : registry_ (address): 0x1135270BbB0627e769a7a2e24f2b2C7F14B3d83A
Arg [1] : minUniswapLiquidity_ (uint256): 75000000000000000000
Arg [2] : oracle_ (address): 0x85F6ab4e889BbDD760b61183d3544E77F228d77C
Arg [3] : _controller (address): 0x36de5Bbc618A04c9B471208Ef52eE2b1F536E92d
Arg [4] : _interestRateModel (address): 0xd47d39A66bb4912D127fBfC1b90884fCB3546137
Arg [5] : _initialExchangeRateMantissa (uint256): 20000000000000000
Arg [6] : _initialReserveFactorMantissa (uint256): 100000000000000000
-----Encoded View---------------
7 Constructor Arguments found :
Arg [0] : 0000000000000000000000001135270bbb0627e769a7a2e24f2b2c7f14b3d83a
Arg [1] : 00000000000000000000000000000000000000000000000410d586a20a4c0000
Arg [2] : 00000000000000000000000085f6ab4e889bbdd760b61183d3544e77f228d77c
Arg [3] : 00000000000000000000000036de5bbc618a04c9b471208ef52ee2b1f536e92d
Arg [4] : 000000000000000000000000d47d39a66bb4912d127fbfc1b90884fcb3546137
Arg [5] : 00000000000000000000000000000000000000000000000000470de4df820000
Arg [6] : 000000000000000000000000000000000000000000000000016345785d8a0000
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 30 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|
Loading...
Loading
[ Download: CSV Export ]
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.